From hat at se-162.se.wtb.tue.nl Tue Oct 30 08:45:12 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 30 Oct 2007 13:45:12 +0100 Subject: Readline and record separator References: <1193746908.551018.130240@z9g2000hsf.googlegroups.com> Message-ID: On 2007-10-30, Johny wrote: > Is it possible to change record separator when using readline? > As far as I know readline reads characters until found '\n' and it is > the end of record for readline. > My problem is that my record consits several '\n' and when I use > readline it does NOT read the whole my record. > So If I could change '\n' as a record separator for readline, it > would solve my problem. > Any idea? Read large enough blocks of data, then use block.find() (in the string module) to find your delimiter, and split the block. Albert From tchur at optushome.com.au Thu Oct 11 18:09:40 2007 From: tchur at optushome.com.au (Tim Churches) Date: Fri, 12 Oct 2007 08:09:40 +1000 Subject: Web Ontology Language (OWL) parsing In-Reply-To: <1192138731.912438.139580@o3g2000hsb.googlegroups.com> References: <1192138731.912438.139580@o3g2000hsb.googlegroups.com> Message-ID: <470E9F24.7040300@optushome.com.au> Sean Davis wrote: > I would like to parse some OWL files, but I haven't dealt with OWL in > python or any other language for that matter. Some quick google > searches do not turn up much in the way of possibilities for doing so > in python. Any suggestions of available code or using existing > libraries for doing so? I'm not sure whether it is still being maintained, but what about CWM, by Sir Semantic Web himself: http://www.w3.org/2000/10/swap/doc/cwm.html Tim C (If it is written by a Tim it must be good.) From bdesth.quelquechose at free.quelquepart.fr Tue Oct 16 13:31:42 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 16 Oct 2007 19:31:42 +0200 Subject: Why does the message send only once? In-Reply-To: <1192550131.869157.88130@q5g2000prf.googlegroups.com> References: <1192550131.869157.88130@q5g2000prf.googlegroups.com> Message-ID: <4714f5b6$0$21020$426a34cc@news.free.fr> danfolkes a ?crit : You already posted the same question here one hour and a half ago. Please avoid. From timr at probo.com Sun Oct 28 19:22:54 2007 From: timr at probo.com (Tim Roberts) Date: Sun, 28 Oct 2007 23:22:54 GMT Subject: Proposal: Decimal literals in Python. References: <4721ab28$0$1238$e4fe514c@dreader28.news.xs4all.nl> <1193438763.190428.134710@q5g2000prf.googlegroups.com> <87tzodii6i.fsf@benfinney.id.au> <1193494184.618613.81090@50g2000hsm.googlegroups.com> Message-ID: MRAB wrote: >On Oct 27, 12:12 am, Ben Finney >wrote: >> Matimus writes: >> > The trailing L [for 'long' literals] is going away in Python 3.0. >> >> Yes. On the other hand, we are gaining '0bNNNN' for binary literals, >> to go along with '0oNNNN' for octal and '0xNNNN' for hexadecimal. >> >> So, the original poster might get further by proposing an '0dNNN.NNN' >> syntax for 'decimal.Decimal' literals. At least the syntax would be >> consistent and wouldn't add a new punctuation character to the >> language... >> >[snip] >Some languages have or permit 0qNNNN or 0QNNNN for octal to reduce the >chance of confusion of 'O' (oh) with '0' (zero) in uppercase, eg. >0Q123 is clearer than 0O123 (0 oh 123), although lowercase is better, >eg. 0q123 or 0o123. My favorite notation for this comes from Ada, which allows arbitrary bases from 2 to 16, and allows for underscores within numeric literals: x23_bin : constant := 2#0001_0111#; x23_oct : constant := 8#27#; x23_dec : constant := 10#23#; x23_hex : constant := 16#17#; The opportunities for obfuscated coding by writing all constants in base 7 boggle the mind. I'm not convinced you need delimiters on both ends; I think 16'fffe_3777 would be just as good. Although, now that I think about the original thread, this doesn't have a neat solution for the decimal problem... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ttkk1024 at gmail.com Fri Oct 5 22:40:25 2007 From: ttkk1024 at gmail.com (smalltalk) Date: Sat, 06 Oct 2007 02:40:25 -0000 Subject: pypar error Message-ID: <1191638425.609180.175620@g4g2000hsf.googlegroups.com> I want to install pypar,but it always show following errors: D:\pypar_1.9.3>python setup.py build -c mingw32 running build running build_py running build_ext building 'pypar.mpiext' extension D:\MinGWStudio\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -I $MPICH_DIR\SDK.gcc \include -ID:\Python25\include -ID:\Python25\PC -c mpiext.c -o build \temp.win32- 2.5\Release\mpiext.o gcc: mpiext.c: No such file or directory gcc: no input files error: command 'gcc' failed with exit status 1 can you give me a help ? From bignose+hates-spam at benfinney.id.au Mon Oct 29 01:23:48 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 29 Oct 2007 16:23:48 +1100 Subject: PEP 299 and unit testing References: <871wbehef8.fsf@benfinney.id.au> <9tmdnf3x8fMezLjanZ2dnUVZ_oninZ2d@comcast.com> <87k5p6fsxj.fsf@benfinney.id.au> Message-ID: <87bqaifq8r.fsf@benfinney.id.au> Ben Finney writes: > Steven Bethard writes: > > > Ben Finney wrote: > > > What it doesn't allow is for the testing of the 'if __name__ == > > > "__main__":' clause itself. No matter how simple we make that, > > > it's still functional code that can contain errors, be they > > > obvious or subtle; yet it's code that *can't* be touched by the > > > unit test (by design, it doesn't execute when the module is > > > imported), leading to errors that won't be caught as early or > > > easily as they might. > > > > You could always use runpy.run_module. > > Thanks! I was unaware of that module. It does seem to nicely address > the issue I discussed. Thinking about it further: I don't think it does address the issue. Running the *entire* module code again in a single step (as 'run_module' seems to do) would happily overwrite any instrumented faked attributes of the module that were inserted for the purpose of unit testing, rendering it useless for unit test purposes. The issue here is that there is an irreducible amount of functional code inside the module that cannot be unit tested without running the entire program with all its side effects. PEP 299 promises to make that specific small-but-significant code become an implementation detail in the language runtime, which would mean it would no longer be prone to errors in the modules themselves, and thus no longer the topic of a unit test on those modules. I think 100% statement coverage is not possible in Python programs without this, or something that achieves the same thing. -- \ "We spend the first twelve months of our children's lives | `\ teaching them to walk and talk and the next twelve years | _o__) telling them to sit down and shut up." -- Phyllis Diller | Ben Finney From danbrotherston at gmail.com Tue Oct 16 16:34:49 2007 From: danbrotherston at gmail.com (danbrotherston) Date: Tue, 16 Oct 2007 13:34:49 -0700 Subject: Capturing OutputDebugString information in python Message-ID: <1192566889.524862.167030@k35g2000prh.googlegroups.com> Hello, I am trying to get the output from the win32 platform command OutputDebugString. I have used the following C++ code as a guideline: http://groups.google.com/group/microsoft.public.vc.utilities/browse_frm/thread/1434418cb968d053/1a3c957675242c7e?lnk=st&q=DBWIN_BUFFER&rnum=3#1a3c957675242c7e And I have been able to translate most things into python, but I have been unable to get it to work. I use the pywin extensions to call CreateEvent and create the required events. But when I wait on the event using the WaitOnSingleEvent call, it hangs indefinitely even when I make calls to OutputDebugString in other processes, (both python processes using win32api and actual C++ win32 programs). I also used mmap to map a file (using fileno -1) to the "DBWIN_BUFFER" but that buffer appears to be empty all the time no matter the calls to OutputDebugString. I have limited experience with this part of windows, but if anyone had any ideas I'd appreciate it greatly. Thanks, Daniel From dkixk at earthlink.net Mon Oct 8 22:28:12 2007 From: dkixk at earthlink.net (Damien Kick) Date: Mon, 08 Oct 2007 21:28:12 -0500 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <47016899$0$4524$9b4e6d93@newsspool3.arcor-online.net> References: <13frd6vtarbee75@corp.supernews.com> <47016899$0$4524$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <13glppu3hknk597@corp.supernews.com> Wildemar Wildenburger wrote: > Frank Goenninger wrote: >> On 2007-09-29 01:27:04 +0200, Damien Kick said: >> >>> If you were referring to the "free" in "free Mumia Abu Jamal", I >>> would agree with you. I don't think anyone would imagine that this >>> phrase meant that someone was going to get Mumia Abu Jamal gratis. >>> Like it or not, "free software" referring to "free as in beer" is >>> probably the most common interpretation of the phrase for a native >>> English speaker. [...] >> >> Fully true for non-native English speakers as well. Just did the "wife >> test" also - she is a pure software user - and yes, free is "no money, >> do what you want" and that's it. I should have used the phrase "fluent English speaker"... >> I *never* use the term "free" if I don't want to imply "free beer" >> (which is a Good Thing and as such highly valuated - ask any >> Bavarian). Using "free" as by FSF or any other lawyer-style 6 pixel >> font printed phrasing is pure perfidiousness. >> > I appearantly missed a lot of that conversation, but what is your point? > While I agree that the word "free" implies "free of monetary cost" to > many people societies, that is by no means set in stone [...]. For some odd reason, this reminded me of an old episode of Mork & Mindy:
What made Mork think eggs could fly? And yet when he tried to release them from the tyranny of gravity ("Fly, be free!"), flinging them into the air only to have them land with a soft thwack, it seemed like nothing so much as a stroke of loopy brilliance.
The term "free eggs" can only sensibly mean one thing, eggs which can be obtained without an exchange of money. To think of it meaning anything else--"fly, be free!"--is comedy (or not, depending on one's opinion of Mork & Mindy). When Free Software Foundationistas try to insist on the phrase "free software" meaning anything other than the obvious interpretation of the term it is annoying (or not, depending on one's opinion of RMS's skills as a wordsmith). I've got this great mental image of some farcical Free Software Liberation Army running around, removing hard drives from boxen, and throwing them in the air with the moral imperative to "fly, be free!" > But that aside: The word free with respect to the FSF and GPL have a > perfectly well defined meaning. People may misunderstand that from not > knowing the definition but that doesnt make it any less well defined. This thread of conversation also popped into my head when I was waiting in line at the Starbucks in the building in which I work. I've been ordering a lot of Americanos lately. I always ask for a small Americano and the person taking my order always calls out my drink as a "tall". With respect to Starbucks, calling a beverage which comes in the shortest cup used in the store a "tall" has a perfectly well defined meaning. But that doesn't make it any less ridiculous. Of course, it was mentioned elsewhere in this thread that context is important. And it is. To use the Starbucks analogy, for someone to criticize Starbucks because their tall drinks really are actually quite short would be ignoring the significance of the context of Starbucks' abuse of the English language. But, again, that doesn't make Starbuck's use of the word any less ridiculous. However, at least at Starbucks, when I use the "wrong" word, they don't start lecturing me. They know what I mean and simply go ahead and translate it to Starbucks newspeak. > Again, why this discussion? Hello, Pot? This is the kettle. You are so black. From cokofreedom at gmail.com Thu Oct 18 10:09:24 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 18 Oct 2007 07:09:24 -0700 Subject: Best way to generate alternate toggling values in a loop? In-Reply-To: <1192715280.994649.172110@q3g2000prf.googlegroups.com> References: <1192665353.008563.99280@y27g2000pre.googlegroups.com> <13hddo2obghq5c0@corp.supernews.com> <1192715280.994649.172110@q3g2000prf.googlegroups.com> Message-ID: <1192716564.870803.204670@i13g2000prf.googlegroups.com> On Oct 18, 3:48 pm, Iain King wrote: > On Oct 18, 2:29 am, Grant Edwards wrote: > > > > > On 2007-10-17, Debajit Adhikary wrote: > > > > # Start of Code > > > > def evenOdd(): > > > values = ["Even", "Odd"] > > > state = 0 > > > while True: > > > yield values[state] > > > state = (state + 1) % 2 > > > I'd replace the last line with > > > state ^= 1 > > > to save a couple instructions, but I spend too much time > > working with micoroprocessors running on clocks measured in the > > KHz. > > > There are probably other more Pythonic ways... > > I always use: > > state = 1 - state > > for toggles. I doubt it's much more pythonic though :) > > Iain why not do state = not state ? From steve at REMOVE-THIS-cybersource.com.au Sat Oct 20 00:47:31 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 20 Oct 2007 04:47:31 -0000 Subject: class vs type References: <87wstjtfip.fsf@mulj.homelinux.net> Message-ID: <13hj233db0ujid1@corp.supernews.com> On Fri, 19 Oct 2007 12:21:25 -0400, Colin J. Williams wrote: > In this case, why do we continue to use the word class to generate a > type? Because type is a callable, and class is convenient syntactic sugar. class Parrot(object): def speak(self, msg): return "Polly sez %s" % msg is much more convenient than: import new Parrot = type('Parrot', (object,), {'speak': lambda self, msg: 'Polly sez %s' % msg}) particularly for large classes with many methods. -- Steven From chlo.prog at gmail.com Wed Oct 17 11:49:06 2007 From: chlo.prog at gmail.com (rc) Date: Wed, 17 Oct 2007 08:49:06 -0700 Subject: pymssql - insert NULL to int Message-ID: <1192636146.759372.33660@v29g2000prd.googlegroups.com> How to insert NULL values in to int field using params. I'm trying to use pymssql.execute, passing the operation and list of params. One of the values in the params is a NULL value going to int field. The pymssql._quote() puts ' around the NULL which causes an exception to be thrown, is there a way to use the params for this or do I need to build the insert string myself? pymssql.DatabaseError: internal error: SQL Server message 245, severity 16, state 1, line 1: Conversion failed when converting the varchar value 'NULL' to data type int. DB-Lib error message 10007, severity 5: General SQL Server error: Check messages from the SQL Server. From aahz at pythoncraft.com Fri Oct 5 11:16:36 2007 From: aahz at pythoncraft.com (Aahz) Date: 5 Oct 2007 08:16:36 -0700 Subject: Where's the Starship's crew? References: Message-ID: In article , Dick Moores wrote: > > > >I didn't check on all of them, but the only one I found was Mark >Hammond . This is the unfortunate remnant of a system hack; many people who used to have active Starship accounts never bothered bringing them back after Starship was cleaned up. Starship was recently moved to another machine and we're having discussions about the future. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From panguohualove at sina.com Mon Oct 1 01:13:49 2007 From: panguohualove at sina.com (panguohua) Date: Sun, 30 Sep 2007 22:13:49 -0700 Subject: I earn $36800 a month with google adsense Message-ID: <1191215629.384871.280240@o80g2000hse.googlegroups.com> www.space666.com a good website for making money with your blog.more information there From stefan.arentz at gmail.com Thu Oct 4 17:07:51 2007 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 04 Oct 2007 23:07:51 +0200 Subject: Is there a nicer way to do this? Message-ID: <87ejgawpug.fsf@keizer.soze.com> Is there a better way to do the following? attributes = ['foo', 'bar'] attributeNames = {} n = 1 for attribute in attributes: attributeNames["AttributeName.%d" % n] = attribute n = n + 1 It works, but I am wondering if there is a more pythonic way to do this. S. From gosinn at gmail.com Mon Oct 22 04:17:31 2007 From: gosinn at gmail.com (Gosi) Date: Mon, 22 Oct 2007 08:17:31 -0000 Subject: ACM SIGAPL / APL2007 Conference / Montreal / one week away In-Reply-To: References: <47133159.9010204@acm.org> <1192920380.625668.221960@i13g2000prf.googlegroups.com> <1192954949.817248.242120@y27g2000pre.googlegroups.com> Message-ID: <1193041051.719162.94210@q3g2000prf.googlegroups.com> On Oct 21, 10:35 am, "Wade Ward" wrote: > "Gosi" wrote in message > > news:1192954949.817248.242120 at y27g2000pre.googlegroups.com... > > > > > On Oct 20, 10:46 pm, rbe wrote: > >> On Oct 15, 5:22 am, Mike Kent wrote: > > >> > Conference page > >> > // with links to program details // > >> > (updated Friday 10/12) > > >> > http://www.sigapl.org/apl2007.html... > > >> At APL2007, I'll be announcing the release of the APEX APL compiler, > >> version 0.0.0, under GPL Version 2. > >> If you can't wait until then, you can download it for Dyalog Linux > >> atwww.snakeisland.com. > > >> Bob > > > Congratulations on your compiler. > > > I looked through your pages and came across this > > > "[This article originally appeared in the ACM SIGAPL Quote Quad, vol. > > 21, no.1, September 1990.] > > > The APL character set has contributed, more than any other facet of > > the language, to its lack of acceptance in the computing community at > > large. The character set is a metaproblem -- not a problem in and of > > itself, but a creator of other recurring problems of hardware, > > software, ergonomics, and psychology. The adoption of new, ASCII-base > > dialects of APL, such as J, is suggested as one solution to the > > character set problem. " > > > This is also the reason for why I will not be downloading your new > > compiler until there will be a J version of it, something I hope will > > be coming soon. > > > I can not use the APL character set at all. > > It is too mixed up with my national characters. > > witch ones? > -- > wade ward > w... at zaxfuuq.net > "Der Katze tritt die Treppe hoch; Der Kater tritt sie krumm.% > % De Teufel geit um; er bringt de menschen allet dumm." > schau, schau 4 10$a.i.'????????????????????' 195 161 195 176 195 169 195 173 195 179 195 186 195 189 195 190 195 166 195 182 195 129 195 144 195 137 195 141 195 147 195 154 195 157 195 158 195 134 195 150 From Graham.Dumpleton at gmail.com Sun Oct 14 05:20:15 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 14 Oct 2007 09:20:15 -0000 Subject: Paste and WSGI 2.0 [WAS: Yet another comparison of Python Web Frameworks] In-Reply-To: <1192351618.434893.166310@e9g2000prf.googlegroups.com> References: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> <470789c2$0$28579$426a74cc@news.free.fr> <1192323138.960870.251160@i13g2000prf.googlegroups.com> <1192351618.434893.166310@e9g2000prf.googlegroups.com> Message-ID: <1192353615.432726.255850@q3g2000prf.googlegroups.com> On Oct 14, 6:46 pm, Michele Simionato wrote: > Now, since you are here, there is an unrelated question that I want to > ask you, concerning the future of Paste with respect to WSGI 2.0. > I do realize that at this stage WSGI 2.0, is only a draft Hmmm, not sure where people keep getting this idea that there exists a WSGI 2.0 draft. The only thing that exists that I know of is: http://www.wsgi.org/wsgi/WSGI_2.0 This is at this point merely a collection of ideas for change, or areas where the existing WSGI 1.0 is deficient. There are a various things around this where decisions would need to be made or solutions developed before one could even consider calling it a draft. I certainly wouldn't necessarily go off making decisions based on what may or may not be in WSGI 2.0. :-) Graham From jcd at sdf.lonestar.org Mon Oct 8 14:00:28 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Mon, 8 Oct 2007 14:00:28 -0400 Subject: pytz has so many timezones! In-Reply-To: <1191865263.572366.270820@y42g2000hsy.googlegroups.com> References: <1191828739.635927.86590@57g2000hsv.googlegroups.com> <1191865263.572366.270820@y42g2000hsy.googlegroups.com> Message-ID: <20071008180027.GD27158@sdf.lonestar.org> On Mon, Oct 08, 2007 at 10:41:03AM -0700, mensanator at aol.com wrote regarding Re: pytz has so many timezones!: > > On Oct 8, 2:32 am, Sanjay wrote: > > Hi All, > > > > I am using pytz.common_timezones to populate the timezone combo box of > > some user registration form. But as it has so many timezones (around > > 400), > > There are only 25 timezones: -12, -11, ... -1, 0 (GMT), +1, ... +11, > +12. > > A handful of countries set their clocks offset by a half hour, > but those aren't timezones. > I'm sorry. By what even vaguely useful definition of "Timezone" is it not a timezone if it's offset by half an hour? > > The 400 you're seeing are duplications based on locality. Of the 86 > shown in Windows, all but 33 are dulplicate references to the same > timezones. > > For example, Windows has seperate listings for > > Central America > Central Time (US & Canada) > Guadalahara, Mexico City, Monterry - New > Guadalahara, Mexico City, Monterry - Old > Saskatchewan > > but they are all GMT-6 > Those are non-duplicate (and perhaps inaccurate, I'm not sure). US time switches from standard to Daylight Savings earlier than Mexico, and switches back later, as of this year. Reducing them to a single time zone will result in aberrant functionality in one or more locales. Cheers, Cliff From deets at nospam.web.de Fri Oct 19 07:19:54 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 19 Oct 2007 13:19:54 +0200 Subject: dynamic invoke References: <1192790367.342435.243930@v29g2000prd.googlegroups.com> <1192791068.230349.104740@e34g2000pro.googlegroups.com> Message-ID: <5nri6qFji28aU1@mid.uni-berlin.de> lukasz.f24 at gmail.com wrote: > On 19 Oct, 11:45, Jarek Zgoda wrote: >> lukasz.... at gmail.com napisa?(a): >> >> > Is there any way (other then eval) to invoke a method by passing >> > method name in a string. >> > It's very simple in php: >> > $oFoo = new Foo(); >> > $dynamiMethod = "bar"; >> > $oFoo->$dynamiMethod(); >> >> > Unfortunately I can't find a good solution to do the same thing in >> > python. Does it have some build-in function to do it? >> >> foo = getattr(module_or_object, 'function_name') >> foo() >> >> -- >> Jarek Zgoda >> Skype: jzgoda | GTalk: zg... at jabber.aster.pl | voice: +48228430101 >> >> "We read Knuth so you don't have to." (Tim Peters) > > Superb! > I was lookig for something like this. Belive me or not but i spent > lots of time looking for this simple solution :) The above clearly is a solution to your problem. I just wonder if you _need_ it. PHP doesn't have the concept of a function reference. So you need to store/use names. But in Python you can do this: def foo(): print "foo" callback = foo callback() As trivial this code is, it illustrates one thing: passing around functions is as easy as passing around other values. So maybe you don't need a function name. Only a suggestion to ponder about though, it might be that your usecase is not suited for the above. Diez From mail at microcorp.co.za Sat Oct 6 02:47:50 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 6 Oct 2007 08:47:50 +0200 Subject: Please Help me References: <003701c80688$d79738f0$1a02a8c0@ERTF.ERTF.COM> Message-ID: <01ec01c807ed$8f7c7100$03000080@hendrik> Jean-Francois Canac wrote: 8< -------------- duplicate request ------------------- see other answer. - Hendrik From pavlovevidence at gmail.com Thu Oct 11 13:43:29 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 11 Oct 2007 10:43:29 -0700 Subject: "".join(string_generator()) fails to be magic In-Reply-To: References: Message-ID: <1192124609.235260.193490@19g2000hsx.googlegroups.com> On Oct 11, 2:26 am, Matt Mackal wrote: > I have an application that occassionally is called upon to process > strings that are a substantial portion of the size of memory. For > various reasons, the resultant strings must fit completely in RAM. > Occassionally, I need to join some large strings to build some even > larger strings. Do you really need a Python string? Some functions work just fine on mmap or array objects, for example regular expressions: >>> import array >>> import re >>> a = array.array('c','hello, world') >>> a array('c', 'hello, world') >>> m = re.search('llo',a) >>> m <_sre.SRE_Match object at 0x009DCB80> >>> m.group(0) array('c', 'llo') I would look to see if there's a way to use an array or mmap instead. If you have an upper bound for the total size, then you can reserve the needed number of bytes. If you really need a Python string, you might have to resort to a C solution. Carl Banks From bdesth.quelquechose at free.quelquepart.fr Tue Oct 2 04:27:05 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 02 Oct 2007 10:27:05 +0200 Subject: Question on overriding implicit lookups In-Reply-To: <1191338201.762723.72750@22g2000hsm.googlegroups.com> References: <1191338201.762723.72750@22g2000hsm.googlegroups.com> Message-ID: <4702930b$0$8908$426a74cc@news.free.fr> David Ells a ?crit : > In Python we have a wonderful facility for customizing attribute > access by defining __getattr__ or __getattribute__ in our classes. > Unfortunately (or perhaps fortunately, for reasons I don't know), this > facility only works for explicit attribute access, i.e. accessing > foo.bar. What I am in need of, for reasons I'll keep out of the > discussion for now, is a similar facility for implicit attribute > access, such as the call to foo.__len__ when something like len(foo) > is executed. I would like some way to customize access during these > implicit lookups without having to define each one in the class > myself. Essentially what I am looking for is a mechanism like > __getattribute__, only one that will work for these implicit lookups > to functions like __len__, __str__, __getitem__, and so on. Hopefully > my question makes sense. An obvious solution would be to define "each one" of these magic methods in a mixin class. Else, here's a Q&D but working solution : class Test(object): def _get_magic_attribute(self, name): return "YADDA YADDA" for _name in ('__len__', '__str__', '__repr__'): exec "%s = lambda self, _name='%s' : " \ "self._get_magic_attribute(_name)" % (_name, _name) del _name For a cleaner version, you may want to use a custom metaclass, but that seems a bit overkill to me. From jjl at pobox.com Thu Oct 11 14:29:12 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 11 Oct 2007 18:29:12 GMT Subject: urllib.ProxyHandler HTTPS issues References: <1192078997.453819.323390@22g2000hsm.googlegroups.com> Message-ID: <87641d8pzb.fsf@pobox.com> Devraj writes: > Hi everyone, > > I have been reading various documents/posts on the web about handling > proxy options in urllib2. Some of them suggest that urllib2 doesn't > handle HTTPS and others say it does. I have successfully written code > that relays HTTP connections via a proxy but have failed to do the > same for HTTPS connections. urllib2 does not support "HTTPS proxies" (it does not support use of the CONNECT method). > Can anyone confirm if urllib2 can handle HTTPS, Yes, it can. John From grflanagan at yahoo.co.uk Thu Oct 18 03:43:45 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Thu, 18 Oct 2007 00:43:45 -0700 Subject: Best way to generate alternate toggling values in a loop? In-Reply-To: <1192665353.008563.99280@y27g2000pre.googlegroups.com> References: <1192665353.008563.99280@y27g2000pre.googlegroups.com> Message-ID: <1192693425.381102.141680@i38g2000prf.googlegroups.com> On Oct 18, 1:55 am, Debajit Adhikary wrote: > I'm writing this little Python program which will pull values from a > database and generate some XHTML. > > I'm generating a where I would like the alternate 's to be > > > and > > > What is the best way to do this? > from itertools import izip def toggle(start=True): flag = start while 1: flag = not flag yield flag CSS = ("even", "odd") HTML = '' result = [(1, 'One'), (2, 'two'), (3, 'Three'), (4, 'Four'), (5, 'Five')] for flag, (id, name) in izip(toggle(), result): print HTML % (CSS[flag], id, name) From auzaar at gmail.com Tue Oct 30 08:11:07 2007 From: auzaar at gmail.com (auzaar at gmail.com) Date: Tue, 30 Oct 2007 05:11:07 -0700 Subject: Iteration for Factorials In-Reply-To: References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <7xodeouga8.fsf@ruckus.brouhaha.com> <1193396435.916666.277770@50g2000hsm.googlegroups.com> <5oKdncgTz5YBBb_anZ2dnUVZ_obinZ2d@comcast.com> <1193731947.088651.324330@50g2000hsm.googlegroups.com> Message-ID: <1193746267.816210.123140@y42g2000hsy.googlegroups.com> On Oct 30, 3:30 pm, Nick Craig-Wood wrote: > Anurag wrote: > > What about this no map, reduce, mutiplication or even addition > > Its truly interative and You will need to interate till infinity if > > you want correct answer ;) > > > deffactorial(N): > > """ > > Increase I ...and go on increasing... > > """ > > import random > > > myNumer = range(N) > > count = 0 > > I = 10000 #10**(N+1) > > for i in range(I): > > bucket = range(N) > > number = [] > > for i in range(N): > > k = bucket[ random.randrange(0,len(bucket))] > > bucket.remove(k) > > number.append(k) > > > if number == myNumer: > > count+=1 > > > return int(I*1.0/count+.5) > > ;-) > > Note you can write your middle loop as > > for i in range(I): > number = myNumer[:] > random.shuffle(number) > if number == myNumer: > count+=1 > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick- Hide quoted text - > > - Show quoted text - good :) i thinkif go on improving this we will have worlds' best useless factorial function. actually number = myNumer[:] can be moved out of the loop. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Oct 22 08:03:21 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 22 Oct 2007 14:03:21 +0200 Subject: calling a function from string In-Reply-To: References: <1193043242.235837.86590@e34g2000pro.googlegroups.com> Message-ID: <471c9181$0$14475$426a74cc@news.free.fr> Jarek Zgoda a ?crit : > Trent Nelson napisa?(a): >>> i have a function that I could like to call, but to make it more >>> dynamic I am constructing a string first that could equivalent to the >>> name of the function I wish to call. how could I do that? the string >>> could might include name of the module. >>> >>> for example >>> >>> a_string = 'datetime.' + 'today()' >>> >>> how could I call a_string as function? >> Use 'eval' in one of the following fashions: >> >> a_string_1 = 'datetime.' + 'today' >> a_string_2 = 'datetime.' + 'today()' >> >> eval(a_string_1)() >> eval(a_string_2) > > Do not use eval(). Not only it's deprecated, Chapter and verse ??? > it's also unsafe. it's *potentially* unsafe. As long as the eval'd code comes from a trusted source, there should be no security problem. I agree that eval is usually not the solution, but mainly because Python has far better (wrt/ readability and maintainance) options for this kind of things. From lucaberto at libero.it Mon Oct 15 08:24:09 2007 From: lucaberto at libero.it (luca72) Date: Mon, 15 Oct 2007 05:24:09 -0700 Subject: PyQt ProgressBar Message-ID: <1192451049.060044.166830@i13g2000prf.googlegroups.com> Hello i have made anly one test like this: from time import sleep barra = QtGui.QProgressBar() barra.setMinimum(0) barra.setMaximum(10) for a in range(10): sleep(1) barra.setValue(a) app.processEvents() But the bar remain fix to 0% don't increase. can you tell me how to prooced Regards Luca From crcarleRemoveThis at BOGUSsandia.gov Tue Oct 23 20:06:36 2007 From: crcarleRemoveThis at BOGUSsandia.gov (Chris Carlen) Date: Tue, 23 Oct 2007 17:06:36 -0700 Subject: Is this a wx bug? Message-ID: Hi: #!/usr/bin/env python """From listing 3.3 in 'wxPython in Action' Demonstrates that something funny happens when you click&hold in the frame, then drag the mouse over the button window. The wx.EVT_ENTER_WINDOW event is missed. The wx.EVT_LEAVE_WINDOW event is NOT missed when you click&hold the mouse button over the button, and leave the button window.""" import wx class MouseEventFrame(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self, parent, id, title="Listing 3.3", size=(300, 100)) self.panel = wx.Panel(self) self.button = wx.Button(self.panel, label="Not over", pos=(100, 15)) self.Bind(wx.EVT_BUTTON, self.OnButtonClick, self.button) self.button.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow) self.button.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow) # This is not critical to demonstrating the 'bug', but just provides # feedback that the wx.EVT_BUTTON events are working correctly # in relation to entering/leaving the button window. def OnButtonClick(self, event): if self.panel.GetBackgroundColour() == "Green": self.panel.SetBackgroundColour("Red") else: self.panel.SetBackgroundColour("Green") self.panel.Refresh() def OnEnterWindow(self, event): self.button.SetLabel("Over") event.Skip() def OnLeaveWindow(self, event): self.button.SetLabel("Not over") event.Skip() if __name__ == '__main__': app = wx.PySimpleApp() frame = MouseEventFrame(None, id=-1) frame.Show() app.MainLoop() -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From jeremit0 at gmail.com Fri Oct 12 15:53:15 2007 From: jeremit0 at gmail.com (jeremito) Date: Fri, 12 Oct 2007 19:53:15 -0000 Subject: Python module for making Quicktime or mpeg movies from images In-Reply-To: <1192199862.532118.306290@t8g2000prg.googlegroups.com> References: <1192113745.291983.292950@50g2000hsm.googlegroups.com> <5n6r5bFfp4a6U1@mid.uni-berlin.de> <1192115372.754998.270520@o80g2000hse.googlegroups.com> <1192199862.532118.306290@t8g2000prg.googlegroups.com> Message-ID: <1192218795.540056.51700@k35g2000prh.googlegroups.com> On Oct 12, 10:37 am, TYR wrote: > On Oct 11, 4:17 pm, Tim Golden wrote: > > > > > jeremito wrote: > > > On Oct 11, 10:43 am, "Diez B. Roggisch" wrote: > > >> jeremito wrote: > > >>> My Python script makes a bunch of images that I want to use as frames > > >>> in a movie. I've tried searching for a module that will take these > > >>> images and put them together in a Quicktime or mpeg movie, but haven't > > >>> found anything. My images are currently pdfs, but I could make them > > >>> into just about anything if needed. > > >>> Is there a module, or example of how to do this? > > >>http://pymedia.org/ > > > >> Diez > > > > That initially looked promising, but it looks like nobody is working > > > on it anymore and it doesn't compile on Mac. (I should have mentioned > > > I am using a Mac.) Any other suggestions? > > > Not really a Python module but... run them > > through mencoder? (Haven't tried it but it > > seems to be saying it's possible). > > >http://www.mplayerhq.hu/DOCS/man/en/mplayer.1.html#EXAMPLES%20OF%20ME... > > > TJG > > NodeBox; nodebox.org > > GUI application that creates either PDFs or Quicktime vids from python > code. Unix/Linux/MacOS. I actually found NodeBox in my googling. This seems to be a stand alone application. I need to be able to convert my images to a movie from my code I wrote myself. Thanks, Jeremy From bbxx789_05ss at yahoo.com Fri Oct 5 13:09:35 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 05 Oct 2007 10:09:35 -0700 Subject: unit testing In-Reply-To: References: Message-ID: <1191604175.903042.228140@g4g2000hsf.googlegroups.com> What are some strategies for unit testing a function that obtains user input? Thanks. From danfolkes at gmail.com Tue Oct 16 09:41:52 2007 From: danfolkes at gmail.com (danfolkes) Date: Tue, 16 Oct 2007 13:41:52 -0000 Subject: while statements In-Reply-To: References: Message-ID: <1192542112.711284.51530@z24g2000prh.googlegroups.com> On Oct 16, 9:28 am, Shawn Minisall wrote: > I just learned about while statements and get why you place them around > inputs for validation, but I'm a little lost on exactly where to place > it with what condition in this program where the number of fat grams > exceeds the total number of calories so that it loops back and asks you > the two questions again instead of just saying The calories or fat grams > were incorrectly entered. Any idea's? > > thx > > while cal <=0: > #Prompt for calories > cal = input("Please enter the number of calories in your food: ") > if cal <=0: > print "Error. The number of calories must be positive." > > #Prompt for fat > fat = input("Please enter the number of fat grams in your food: ") > if fat <=0: > print "Error. The number of fat grams must be positive." > > #Calculate calories from fat > calfat = float(fat) * 9 > > #Calculate number of calories from fat > caldel = calfat / cal > > #change calcent decimal to percentage > calcent = caldel * 100 > > #evaluate input > if calfat > cal: > print "The calories or fat grams were incorrectly entered." > > elif calcent > 0 and calfat < cal: > > if caldel <= .3: > print "Your food is low in fat." > elif caldel >= .3: > print "Your food is high in fat." > > #Display percentage of calories from fat > print "The percentage of calories from fat in your food is %", > calcent Instead of: if(cal<=0) you could do : cal=0 while cal<=0: cal = int(raw_input("Please enter the number of calories in your food: ")) that would make sure that your input is > 0 From Florian.Lindner at xgm.de Thu Oct 18 16:40:53 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Thu, 18 Oct 2007 13:40:53 -0700 Subject: Problem with format string / MySQL cursor In-Reply-To: References: <1192732348.392303.151430@i38g2000prf.googlegroups.com> <1192736676.035569.188300@e9g2000prf.googlegroups.com> Message-ID: <1192740053.589994.109050@q5g2000prf.googlegroups.com> On 18 Okt., 22:08, Paul McNett wrote: > timar... at gmail.com wrote: > > On Oct 19, 7:32 am, Florian Lindner wrote: > >> Hello, > >> I have a string: > > >> INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`, > >> `gid`, `password`) VALUES (%s, %s, %s, %s, %i, %i, %s) > > >> that is passed to a MySQL cursor from MySQLdb: > > >> ret = cursor.execute(sql, paras) > > >> paras is: > > >> ('flindner', 'te... at florian-lindner.de', '/home/flindner/', '/home/ > >> flindner/Mail/test', 1001, 1001, '123') > > >> But that gives me an error: > > >> Traceback (most recent call last): > >> File "account.py", line 188, in ? > >> main() > >> File "account.py", line 33, in main > >> execute(action, account_type, options) > >> File "account.py", line 129, in execute > >> executeSQL(sql, options.username, options.login, options.home, > >> options.directory, options.uid, options.gid, options.password) > >> File "/home/flindner/common.py", line 29, in executeSQL > >> ret = cursor.execute(sql, paras) > >> File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line > >> 148, in execute > >> query = query % db.literal(args) > >> TypeError: int argument required > > >> I don't see errors in the format string or some other problem.... > > >> What's wrong? > > You should be using '?' for parameter bindings in your sql string not > > python format specifiers (you are after all writing sql here not > > python). > > > INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`, > > `gid`, `password`) VALUES (?, ?, ?, ?, ?, ?, ?) > > Sorry Tim, but that isn't correct: > > >>> import MySQLdb > >>> MySQLdb.paramstyle > > 'format' > > Florian, what happens when you replace your %i with %s? That works! Thanks! But a weird error message for this solution... From deets at nospam.web.de Wed Oct 31 08:16:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 31 Oct 2007 13:16:10 +0100 Subject: Creating a temporary file in Python References: <1193832119.872710.108920@k79g2000hse.googlegroups.com> Message-ID: <5ora0aFo7tsmU1@mid.uni-berlin.de> looping wrote: > Hi, > > I want to create a temporary file, read it in an external command and > finally delete it (in Windows XP). > > I try to use tempfile module but it doesn't work, the file couldn't be > open by my other process (error like: SP2-0310: unable to open file "c: > \docume~1\looping\locals~1\temp\tmpau81-s.sql") > Is there a way to make it work or I have to manually manage > everything ? > > My non working code: > > f = tempfile.NamedTemporaryFile(suffix='.sql') > f.write(txt) > f.flush() > p = subprocess.Popen([SQL_PLUS, '-s', dsn, '@', SQL_PLUS_SCRIPT, > f.name], > stdout=subprocess.PIPE, stderr=subprocess.STDOUT) > p.wait() > f.close() I'm not an expert, but I think you need to close the file first - you under windows here, which can be picky about such stuff AFAIK. Or maybe there is some other mode-specifier. Diez From duncan.booth at invalid.invalid Tue Oct 9 04:32:05 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Oct 2007 08:32:05 GMT Subject: python bytecode questions. References: <1191918011.685441.151180@o3g2000hsb.googlegroups.com> Message-ID: warhero wrote: > First question, I can't seem to get any python bytecode to be > produced. I've tried different techniques from chapter 30.8 to chapter > 31 of the python guide.. I was under the assumption that after > compiling a file, it would output a pyc file, but where does it go? > Any help would be appreciated. Any time you import a python file it will be compiled (if it hasn't already been compiled) and a .pyc file will be generated in the same directory as the source file (so long as you can write a file to that directory). N.B. This only happens when you import a module: when you run a .py file as a script it is still compiled, but no .pyc is output. If this worries you then write a very short .py file which just imports the main program module and calls some startup function. > > Second, Are there any other projects out for bundling python bytecode > files, making it able to use a couple files to distribute an entire > app?? I saw one of the effbot site but it's old as it was written for > 1.4.. For Windows you can make standalone executables with py2exe (http://www.py2exe.org/) More generally, assuming that Python is already installed, the trend seems to be for packaging your code as a Python egg (http://peak.telecommunity.com/DevCenter/PythonEggs). > Third, can distributing code in pyc files, speed up the application? > Or would speed increases only be seen upon application initialization? > As an example, let's say I'm running an application server, would > distributing the source in some pyc files with a bootstrapper be any > faster overall, or just on init?? > No, the only gain is that you save the initial compile. From scott.hendryx.clothes at sbcglobal.net Fri Oct 5 07:31:41 2007 From: scott.hendryx.clothes at sbcglobal.net (MoParMaN) Date: Fri, 5 Oct 2007 06:31:41 -0500 Subject: Dear Hendryx and Leach References: <470541a7$0$47118$892e7fe2@authen.yellow.readfreenews.net> <0llag31er762a2tsdfcs8t1lq9ms1ksghq@4ax.com> Message-ID: "Jay Furr" wrote in message news:Xns99BFC2342C5CDfnord23 at 216.168.3.44... > "MoParMaN" wrote in news:QgeNi.259 > $sm6.23 at nlpi069.nbdc.sbc.com: > >> I will not screw with the cardio doctor again after my stressless stress >> test. Jesus fucking christ, I thought I died for 45 seconds. > > Can I have your liver, then? > AAAHHHHAAAA, it's about the size of a basketball. -- ------MoParMaN------ ---Scud Coordinates 32.61204 North 96.92989 West--- --Remove Clothes to Reply!-- TEDWARD Said: Eggs are really good for you. They have all the nutrition needed to make a chicken. From see at sig.below Tue Oct 9 01:59:28 2007 From: see at sig.below (Barb Knox) Date: Tue, 09 Oct 2007 18:59:28 +1300 Subject: The fundamental concept of continuations References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> Message-ID: In article <1191906949.179197.217470 at 57g2000hsv.googlegroups.com>, gnuist006 at gmail.com wrote: > Again I am depressed to encounter a fundamentally new concept that I > was all along unheard of. Don't be depressed about that. There are countless concepts out there they you haven't yet heard of. > Its not even in paul graham's book where i > learnt part of Lisp. Its in Marc Feeley's video. > > Can anyone explain: > > (1) its origin Lambda calculus. Instead of function A returning to its caller, the caller provides an additional argument (the "continuation") which is a function B to be called by A with A's result(s). In pure "continuation style" coding, nothing ever "returns" a result. It is easy to mechanically transform normal function-style lambda calculus into continuation-style, but the reverse is not so. > (2) its syntax and semantics in emacs lisp, common lisp, scheme > (3) Is it present in python and java ? Java, sort of. For example, the Run interface. Python, I don't know. > (4) Its implementation in assembly. for example in the manner that > pointer fundamentally arises from indirect addressing and nothing new. > So how do you juggle PC to do it. You can have a "spaghetti stack", or keep continuation data-structures in the heap. > (5) how does it compare to and superior to a function or subroutine > call. how does it differ. This sounds like homework. What do you have so far? > Thanks a lot. > > (6) any good readable references that explain it lucidly ? Google? -- --------------------------- | BBB b \ Barbara at LivingHistory stop co stop uk | B B aa rrr b | | BBB a a r bbb | Quidquid latine dictum sit, | B B a a r b b | altum viditur. | BBB aa a r bbb | ----------------------------- From jjl at pobox.com Wed Oct 17 16:13:01 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 17 Oct 2007 20:13:01 GMT Subject: urlgrabber cookie handling? References: <1192593158.188757.129010@i38g2000prf.googlegroups.com> Message-ID: <878x61zeia.fsf@pobox.com> Devraj writes: > Hi everyone, > > I have been battling to make my code work with a HTTPS proxy, current > my code uses urllib2 to to most things and works well, except that > urllib2 doesn't handle HTTPS proxies. > > Urlgrabber (http://linux.duke.edu/projects/urlgrabber/help/ > urlgrabber.grabber.html) looks very promising except that I can find a > way to handle cookies in urlgrabber. Is there a way urlgrabber can use > a HTTPCookieProcess or cookielib.CookieJar object to handle cookies? I don't see a nice way. But then I don't see any HTTPS proxy support in urlgrabber... (I looked at version 3.1.0). There is a recipe or two on ASPN showing how to support HTTPS proxies with urllib2, which gives an idea how to do it, though the code is a bit rough (I'd post some code myself, but I did it for work). John From __peter__ at web.de Thu Oct 25 05:18:17 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Oct 2007 11:18:17 +0200 Subject: local variable referenced before assignment References: <47205ba1$0$515$5a6aecb4@news.aaisp.net.uk> Message-ID: Pete Bartonly wrote: > Quick question, probably quite a simple matter. Take the follow start of > a method: > > > def review(filesNeedingReview): > > for item in filesNeedingReview: > (tightestOwner, logMsg) = item > > if (logMsg != None): > for logInfo in logMsg.changed_paths: > > > This generates the error: > > UnboundLocalError: local variable 'logMsg' referenced before assignment > > I thought I'd assigned it in the "(tightestOwner, logMsg) = item" line - > so in the python interpreter complaining about the fact this assignment > might not go well? My crystal ball tells me that you are not posting the actual code where for... and if... are indented to the same level. This triggers the error when review() is called with an empty sequence. Please remember to copy and paste both code and traceback next time. Peter From python.list at tim.thechases.com Wed Oct 10 16:45:47 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 10 Oct 2007 15:45:47 -0500 Subject: for loop question In-Reply-To: <1192047900.124690.284890@19g2000hsx.googlegroups.com> References: <496954360710101256w2502c99dh5341ade1c0aaa88d@mail.gmail.com> <1192047900.124690.284890@19g2000hsx.googlegroups.com> Message-ID: <470D39FB.8060700@tim.thechases.com> Paul Hankin wrote: > On Oct 10, 9:12 pm, Tim Chase wrote: >> >>> pairs = (test[i:i+2] for i in xrange(len(test)-1)) >> >>> for a,b in pairs: >> ... print a,b > > for a, b in zip(test, test[1:]): > print a, b Very nice! I second this solution as better than my original. The only "improvement" (in quotes, because it might be more work/opacity than the problem merits) might be to use izip/islice from itertools to do the evaluation lazily if "test" gets large: from itertools import izip, islice for a,b in izip(test, islice(test, 1, None)): print a,b [side note/question] What's with islice having the first optional paramenter expand as the stop/third argument by default: islice(test, 1) -> stop at 1 islice(test, 1, 2) -> start at 1, stop at 2 islice (in python2.4) doesn't even take kword params, so you can't force it like islice(test, start=1) but instead must specify a stop parameter, even if it's None: islice(test, 1, None) Seems bogus, IMHO. -tkc From bergv at math.uiuc.edu Fri Oct 19 16:58:21 2007 From: bergv at math.uiuc.edu (Maarten Bergvelt) Date: Fri, 19 Oct 2007 20:58:21 +0000 (UTC) Subject: DIAGNOSIS: Racism moves back to Denmark from South Africa References: <1192661865.485820.253030@v29g2000prd.googlegroups.com> Message-ID: On 2007-10-19, mich wrote: > > wrote in message > news:1192661865.485820.253030 at v29g2000prd.googlegroups.com... >> >> INCISIVE ANALYSIS: The dismantlement of Apartheid Regime in South >> Africa sent the racist Dutch Afrikaners back to Denmark where they are >> spreading their racist ideology -- The Apartheid "Christianity" : > > > The Dutch went back to Denmark? Sure, Copenhagen is the capital of the Netherlands, any American school child knows that. -- Maarten Bergvelt From gneuner2/ at comcast.net Thu Oct 4 01:33:11 2007 From: gneuner2/ at comcast.net (George Neuner) Date: Thu, 04 Oct 2007 01:33:11 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <13frd6vtarbee75@corp.supernews.com> <85ve9ov971.fsf@lola.goethe.zz> <47041303$0$13930$fa0fcedb@news.zen.co.uk> Message-ID: <8sn8g39v75hg114lf3m9m911ib2ajddaui@4ax.com> On Wed, 03 Oct 2007 23:07:32 +0100, dan at telent.net wrote: >George Neuner wrote: >> Symbolism over substance has become the mantra >> of the young. > >"Symbolism: The practice of representing things by means of symbols or >of attributing symbolic meanings or significance to objects, events, or >relationships." > >One might even suggest that all written language is based on the use of >words as symbols. > >"Substance: (2) > a. Essential nature; essence. > b. Gist; heart." > >"Mantra: A sacred verbal formula repeated in prayer, meditation, or >incantation, such as an invocation of a god, a magic spell, or a >syllable or portion of scripture containing mystical potentialities." > >Perhaps the young people you're referring to are not the same young >people that I know, because I've never even heard of a religion whose >object of reverence is meta-level analysis of language. The Christian Bible says "In the beginning was the Word, and the Word was with God, and the Word was God." John 1:1. Theologians and philosophers have been writing about it for quite a few centuries. Or, how about politics? Another example from the Judeo-Christian Bible (that is, from the Old Testament), politicking was the sin that resulted in Lucifer's fall from God's grace. [Yeah, I know the official story is that Lucifer's sin was envy. Trust me ... I was there. God didn't have a clue until Lucifer went and organized the rally to protest God's policy on human souls (back then God trusted his angels and was not in the habit of reading their minds). He didn't find out that Lucifer was behind the protests until after Michael's police units had put down the riots. When it was all over, God didn't care that Lucifer had been envious or prideful or lustful ... He was simply pissed that Lucifer had protested His policies. Shortly after He outlawed beer in Heaven because many of the rioters had been drunk. Then He started a program of wire-tapping without warrants to spy on innocent angels. I was ready to leave when He closed the pubs, the illegal wire-taps just clinched it.] >Tell me, do you know what "hyperbole" means? Yes I do. George -- for email reply remove "/" from address From heikki at osafoundation.org Fri Oct 26 14:26:21 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 26 Oct 2007 11:26:21 -0700 Subject: Eclipse Plugins In-Reply-To: References: <-5528451693797282245@unknownmsgid> Message-ID: Martin Marcher wrote: > 2007/10/26, Robert Rawlins - Think Blue : >> For my other languages, such as HTML, ColdFusion, JAVA etc I make good use >> of the Eclipse SDK, and I'm looking for some advice on the best and most >> popular python plug-ins available, what would you suggest? I downloaded one >> called PyDev which looked ok but nothing too exciting. I'm a very happy user of PyDev. The main reason I got PyDev was to get automatic error reporting in the editor (it uses PyLint for this, you need to install PyLint first). The debugger is also pretty good (supports even multiple threads). Exceptions could perhaps be handled better, and getting a shell in the debugger context is only available in the commercial extension to PyDev I think. Having come from (X)Emacs, perhaps my IDE needs are primitive. I've tried to use some automatic refactoring tools but support that that is pretty primitive for Python at the moment. PyDev is open source, and the developer is pretty responsive, so if you could describe what is missing there is a good chance it would get implemented. I even fixed two bugs myself, my first ever real Java contribution... -- Heikki Toivonen From Scott.Daniels at Acm.Org Thu Oct 25 08:28:00 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 25 Oct 2007 05:28:00 -0700 Subject: Parallel insert to postgresql with thread In-Reply-To: <5obctcFm7sogU1@mid.uni-berlin.de> References: <1193310044.750654.157320@22g2000hsm.googlegroups.com> <5obctcFm7sogU1@mid.uni-berlin.de> Message-ID: <13i12q276igp0df@corp.supernews.com> Diez B. Roggisch wrote: > Abandoned wrote: > >> Hi.. >> I use the threading module for the fast operation. But .... [in each thread] >> def save(a,b,c): >> cursor.execute("INSERT INTO ... >> conn.commit() >> cursor.execute(...) >> How can i insert data to postgresql the same moment ?... > > DB modules aren't necessarily thread-safe. Most of the times, a connection > (and of course their cursor) can't be shared between threads. > > So open a connection for each thread. Note that your DB server will have to "serialize" your inserts, so unless there is some other reason for the threads, a single thread through a single connection to the DB is the way to go. Of course it may be clever enough to behave "as if" they are serialized, but mostly of your work parallelizing at your end simply creates new work at the DB server end. -Scott David Daniels Scott.Daniels at Acm.Org From bignose+hates-spam at benfinney.id.au Wed Oct 3 23:41:25 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 Oct 2007 13:41:25 +1000 Subject: module confusion References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> <874ph8sdhx.fsf@benfinney.id.au> Message-ID: <87hcl7r1ga.fsf@benfinney.id.au> Steve Holden writes: > You and I know that the semantics of Python names are precisely > those of (to use an Algol 68 term, unless I am mistaken) > automatically dereferenced pointers to objects of arbitrary type. Yes. That's exactly why it's wrong to refer to them as pointers. They don't behave like the pointers in other languages, which are *not* "automatically-dereferenced", nor "to objects of arbitrary type". It's misleading to talk about a Python name as a "pointer" without those qualifiers, because they're *not* implicit in programmers' understanding of that term. If you want to continually refer to them as "automatically-dereferenced pointers to objects of arbitrary type", by all means go ahead. That at least *does* fit the semantics. But the simple term "pointer" does *not* describe them in the absence of those necessary and non-default qualifiers, and is misleading. -- \ "I wish there was a knob on the TV to turn up the intelligence. | `\ There's a knob called 'brightness' but it doesn't work." -- | _o__) Eugene P. Gallagher | Ben Finney From martin at marcher.name Fri Oct 26 08:49:38 2007 From: martin at marcher.name (Martin Marcher) Date: Fri, 26 Oct 2007 14:49:38 +0200 Subject: "Standard" Full Text Search Engine Message-ID: <5fa6c12e0710260549y2cf6e1c2y93593f8225a6f662@mail.gmail.com> Hello, is there something like a standard full text search engine? I'm thinking of the equivalent for python like lucene is for java or ferret for rails. Preferrably something that isn't exactly a clone of one of those but more that is python friendly in terms of the API it provides. Things I'd like to have: * different languages are supported (it seems most FTSs do only english) * I'd like to be able to provide an identifier (if I index files in the filesystem that would be the filename, or an ID if it lives in a database, or whatever applies) * I'd like to pass it just some (user defined) keywords with content, the actual content (as string, or list of strings or whatever) and to retrieve the results by search by keyword * something like a priority should be assignable to different fields (like field: title(priority=10, content="My Draft"), keywords(priority=50, list_of_keywords)) Unnecessary: * built-in parsing of different files The "standard" I'm referring to would be something with a large and active user base. Like... WSGI is _the_ thing to refer to when doing webapps it should be something like $FTS-Engine is _the_ engine to refer to. any hints? -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From lasses_weil at klapptsowieso.net Thu Oct 25 11:31:15 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 25 Oct 2007 17:31:15 +0200 Subject: [0..9] list (range) syntax In-Reply-To: References: <471fd26a$0$13110$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4720b6c4$0$27138$9b4e6d93@newsspool1.arcor-online.net> Michal Bozon wrote: > The .. syntax was not meant only as something > which would include the last item, > but also/rather a range list syntactic shortcut: > > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] --> > [0, 1, ... 9, 10] --> > [0..10] > OK, I see. But I still fail to see where this is useful. All these 3 statements create a list from 0 to 10 including. If, however, the ".." operator would recognize patterns before and after itself, I could see your point (e.g. [0, 1, 2, 4, 8, .. 128, 256, 512]). Buts thats pretty academic, maybe good for a specialized computation language. And I feel that my "write a function" argument still holds. /W From google at mrabarnett.plus.com Mon Oct 8 18:46:56 2007 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Oct 2007 15:46:56 -0700 Subject: Variable scoping rules in Python? In-Reply-To: <470a4758$0$9150$426a74cc@news.free.fr> References: <1191853056.970304.209350@k79g2000hse.googlegroups.com> <470a4758$0$9150$426a74cc@news.free.fr> Message-ID: <1191883616.517211.95400@19g2000hsx.googlegroups.com> On Oct 8, 4:06 pm, Bruno Desthuilliers wrote: > joshua.dav... at travelocity.com a ?crit : > > > Ok, I'm relatively new to Python (coming from C, C++ and Java). I'm > > working on a program that outputs text that may be arbitrarily long, > > but should still line up, so I want to split the output on a specific > > column boundary. > > FWIW :http://docs.python.org/lib/module-textwrap.html > > > > > > > Since I might want to change the length of a column, > > I tried defining the column as a constant (what I would have made a > > "#define" in C, or a "static final" in Java). I defined this at the > > top level (not within a def), and I reference it inside a function. > > Like this: > > > COLUMNS = 80 > > > def doSomethindAndOutputIt( ): > > ... > > for i in range( 0, ( len( output[0] ) / COLUMNS ) ): > > print output[0][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ] > > print output[1][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ] > > .. > > > etc. etc. It works fine, and splits the output on the 80-column > > boundary just like I want. > > > Well, I decided that I wanted "COLUMNS = 0" to be a special "don't > > split anywhere" value, so I changed it to look like this: > > > COLUMNS = 80 > > > def doSomethindAndOutputIt( ): > > ... > > if COLUMNS == 0: > > COLUMNS = len( output[ 0 ] ) > > > for i in range( 0, ( len( output[0] ) / COLUMNS ) ): > > print output[0][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ] > > print output[1][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ] > > .. > > Since you don't want to modify a global (and even worse, a CONSTANT), > the following code may be a bit cleaner: > > def doSomethindAndOutputIt( ): > ... > if COLUMNS == 0: > columns = len( output[ 0 ] ) > else: > columns = COLUMNS > for i in range( 0, ( len( output[0] ) / COLUMNS ) ): > print output[0][ i * columns : i * columns + ( columns - 1 ) ] > .. > [snip] range() can accept 3 arguments (start, stop and step) so you could write: for i in range( 0, len( output[0] ), columns ): print output[0][ i : i + columns ] .. From fantus at poczta.fm Tue Oct 9 16:01:47 2007 From: fantus at poczta.fm (Fantus) Date: Tue, 09 Oct 2007 22:01:47 +0200 Subject: tinyp2p - trying to get it to work In-Reply-To: References: Message-ID: Marc Christiansen pisze: > > I had a (not so quick) look. The code proves its point (i.e. writing a > very small p2p application is possible), but it is horrible. With only > one server, the code is broken; maybe it works using multiple servers, I > didn't test. A quick fix seems to be to change the line > pr() and [aug(s) for s in aug(pr()[0])] > to > pr() and [aug(s) for s in aug(pr()[0])] or pr([myU]) > > Please don't take tinyp2p.py as an example on writing python. > > HTH Marc Ok, this seems to work "fine" (as much as a program designed to be minimalistic can do) except it can't download files larger than 10kb. It looks like a problem with SimpleXMLRPCServer (or at least I think so...) While trying to download file larger than 10kb the server itself doesn't crash but generates output like this: ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 44817) Traceback (most recent call last): File "SocketServer.py", line 222, in handle_request self.process_request(request, client_address) File "SocketServer.py", line 241, in process_request self.finish_request(request, client_address) File "SocketServer.py", line 254, in finish_request self.RequestHandlerClass(request, client_address, self) File "SocketServer.py", line 521, in __init__ self.handle() File "BaseHTTPServer.py", line 316, in handle self.handle_one_request() File "BaseHTTPServer.py", line 310, in handle_one_request method() File "SimpleXMLRPCServer.py", line 445, in do_POST self.wfile.write(response) File "socket.py", line 248, in write self.flush() File "socket.py", line 235, in flush self._sock.sendall(buffer) error: (104, 'Connection reset by peer') ---------------------------------------- The client that was trying to make a download generates this: Traceback (most recent call last): File "backup5.py", line 75, in ? (lambda fi:fi.write(proxy(url).f(pw(url),2,fn)) or fi.close())(file(fn,"wc")) File "backup5.py", line 75, in (lambda fi:fi.write(proxy(url).f(pw(url),2,fn)) or fi.close())(file(fn,"wc")) File "/usr/lib/python2.4/xmlrpclib.py", line 1096, in __call__ return self.__send(self.__name, args) File "/usr/lib/python2.4/xmlrpclib.py", line 1383, in __request verbose=self.__verbose File "/usr/lib/python2.4/xmlrpclib.py", line 1147, in request return self._parse_response(h.getfile(), sock) File "/usr/lib/python2.4/xmlrpclib.py", line 1281, in _parse_response p.feed(response) File "/usr/lib/python2.4/xmlrpclib.py", line 527, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 5, column 15 Should I post this in a separate thread or maybe one of experts visiting this group will take a look and hopefully solve my problem? Thank you in advance. From carsten at uniqsys.com Wed Oct 10 17:17:04 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 10 Oct 2007 17:17:04 -0400 Subject: for loop question In-Reply-To: <496954360710101403p6b057a07le3f6dd0fe03d770@mail.gmail.com> References: <496954360710101256w2502c99dh5341ade1c0aaa88d@mail.gmail.com> <1192047136.3388.19.camel@dot.uniqsys.com> <496954360710101327s7ee23520u9bb4d74833110071@mail.gmail.com> <1192048912.3388.27.camel@dot.uniqsys.com> <496954360710101403p6b057a07le3f6dd0fe03d770@mail.gmail.com> Message-ID: <1192051024.3388.40.camel@dot.uniqsys.com> On Wed, 2007-10-10 at 16:03 -0500, Robert Dailey wrote: > I've tried everything to make the original CSV module work. It just > doesn't. I've tried UTF-16 encoding What do you mean, "tried?" Don't you know what the file is encoded in? > (which works fine with codecs.open()) but when I pass in the file > object returned from codecs.open() into csv.reader(), the call to > reader.next() fails because it says something isnt' in the range of > range(128) or something (Not really an expert on Unicode so I'm not > sure of the meaning). I would use CSV if I could! That's because the codec-file object feeds it decoded Unicode strings, but the CSV module wants to work with encoded octet strings, so it tries to encode the unicode string with the default codec. The default codec is ASCII, which can't represent characters with code points greater than 127. Instead of passing the file object directly to the csv parser, pass in a generator that reads from the file and explicitly encodes the strings into UTF-8, along these lines: def encode_to_utf8(f): for line in f: yield line.encode("utf-8") There may be a fundamental problem with this approach that I can't foresee at the moment, but it's worth a try when your alternative is to build a Unicode-aware CSV parser from scratch. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From happyhondje at gmail.com Thu Oct 25 18:33:40 2007 From: happyhondje at gmail.com (happyhondje at gmail.com) Date: Thu, 25 Oct 2007 22:33:40 -0000 Subject: An efficient, pythonic way to calculate result sets In-Reply-To: <1193337893.635877.208050@v3g2000hsg.googlegroups.com> References: <1193326263.917893.266620@e9g2000prf.googlegroups.com> <1193337893.635877.208050@v3g2000hsg.googlegroups.com> Message-ID: <1193351620.822061.194040@50g2000hsm.googlegroups.com> On Oct 25, 8:44 pm, "mensana... at aol.com" wrote: > On Oct 25, 10:31 am, happyhon... at gmail.com wrote: > > > > > Hello everyone, > > > I've got a little issue, both programming and performance-wise. I have > > a set, containing objects that refer to other sets. For example, in a > > simple notation: (, ) (or in a more object-like > > display: set(obj1.choices=set(a, b, c) ). There may be obj1..objN > > objects in the outer set, and the amount of items in the choices sets > > could also reach a high number. The objects in the choices sets might > > overlap. > > > Now I want to have all possible combinations, like this: (a, d), (b, > > d), (c, d), (a, e), (b, e), (c, e). > > > However, I've got a few catches that make an already (icky) recursive > > function worse to use. > > > First of all, I want to be able to only choose things so that the > > outer 'result sets' have the same length. For example, if you'd have > > (, ), you might pick (a, a) with a simple algorythm, the > > basic behaviour of sets reducing it to (a) and thus having an improper > > length. I could add yet another loop after calculating everything to > > throw out any result sets with the improper length, but that would be > > highly inefficient. > > Does this do what you want? > > result_set = set([]) > seta = set(['a','b','c','d','e']) > setb = set(['a','c','f','g','h']) > for i in seta: > temp1 = setb.difference(set([i])) > for j in temp1: > result_set.add(tuple(set([i,j]))) > for i in result_set: > print i > > I figure there should be 4+5+3+5+5 results. > No ('a'), no ('c'). Has ('a','c') but not ('c','a'). > > ## ('c', 'g') > ## ('a', 'd') > ## ('h', 'e') > ## ('a', 'b') > ## ('c', 'f') > ## ('e', 'g') > ## ('c', 'b') > ## ('d', 'f') > ## ('a', 'g') > ## ('a', 'h') > ## ('c', 'e') > ## ('e', 'f') > ## ('d', 'g') > ## ('h', 'b') > ## ('a', 'f') > ## ('b', 'f') > ## ('c', 'd') > ## ('h', 'c') > ## ('a', 'c') > ## ('b', 'g') > ## ('a', 'e') > ## ('h', 'd') > > > > > Second, I'd hope to be able to say that objX should be assumed to have > > made the choice z. In the first example I mentioned, if I said that > > 'obj1 == a', the only result sets that would come out would be (a, d) > > and (a, e). > > Like this? > > result_set = set([]) > seta = set(['a','b','c','d','e']) > setb = set(['a','c','f','g','h']) > target = 'a' > for i in seta: > temp1 = setb.difference(set([i])) > for j in temp1: > temp2 = set([i,j]) > if target in temp2: > result_set.add(tuple(temp2)) > for i in result_set: > print i > > ## ('a', 'f') > ## ('a', 'g') > ## ('a', 'd') > ## ('a', 'e') > ## ('a', 'h') > ## ('a', 'b') > ## ('a', 'c') > > > > > I've been toying with this problem for a while, but I've found out it > > quickly gets slow, so I hope some people here could find a way to > > write code like this that is efficient (and hopefully not rely on > > recursion and 'fix up' loops like I've got mockups with right now). > > > Thank you for any suggestions you can offer. Almost, except for the one big issue that is missing: scalability. I don't have a seta and setb, but rather set1..setN, with N varying while the script is running. That's pretty much where the pain comes in. I have some very (butt-ugly) code that works right now, but it's more a hack than pretty (or efficient) code. Thank you for your effort though, since your usage of set.difference() gave me an idea on another issue I was wrestling with. From tommy.nordgren at comhem.se Mon Oct 29 17:18:20 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Mon, 29 Oct 2007 22:18:20 +0100 Subject: setting variables in outer functions In-Reply-To: References: Message-ID: On 29 okt 2007, at 21.59, brad wrote: > Tommy Nordgren wrote: >> Given the following: >> def outer(arg) >> avar = '' >> def inner1(arg2) >> # How can I set 'avar' here ? > > Try this... works for me... maybe not for you? > > def outer(avar=False): > print avar > if avar == True: > return > > def inner(avar=True): > print avar > return avar > > outer(inner()) > > outer() > -- > http://mail.python.org/mailman/listinfo/python-list This is not a general solution to this problem. What works, though, (I just thought of it) is to do the following: def outer(arg): adict = {} def inner1(arg): adict['avar'] = 'something' #now the value set by inner1 is available to other nested functions ------ What is a woman that you forsake her, and the hearth fire and the home acre, to go with the old grey Widow Maker. --Kipling, harp song of the Dane women Tommy Nordgren tommy.nordgren at comhem.se From paul.hankin at gmail.com Wed Oct 17 19:53:22 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 17 Oct 2007 23:53:22 -0000 Subject: Pull Last 3 Months In-Reply-To: References: <1192638812.176235.232060@z24g2000prh.googlegroups.com> <47167F80.8080208@tim.thechases.com> Message-ID: <1192665202.277171.132880@t8g2000prg.googlegroups.com> On Oct 17, 11:56 pm, Shane Geiger wrote: > A simpler way, imho: > > import datetime > m = { > 1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'} > > month = datetime.date.today().month > if month == 1: > ans = [m[11], m[12], m[1]] > elif month == 2: > ans = [m[11], m[12], m[1]] > else: > ans = [m[month-2], m[month-1], m[month]] > print ans It looks like you copied the month 2 case from the month 1 case because you forgot to edit it afterwards. Anyway, a bit of modulo-12 arithmetic avoids special cases, and allows the number of months to be generalised: import datetime months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split() def last_months(n): month = datetime.date.today().month return [months[(month - i - 1) % 12] for i in range(n)] print last_months(3) -- Paul Hankin From projecktzero at yahoo.com Thu Oct 25 11:51:02 2007 From: projecktzero at yahoo.com (projecktzero) Date: Thu, 25 Oct 2007 08:51:02 -0700 Subject: New to Vim and Vim-Python In-Reply-To: <1193250319.878477.91460@t8g2000prg.googlegroups.com> References: <1193250319.878477.91460@t8g2000prg.googlegroups.com> Message-ID: <1193327462.894091.225670@y42g2000hsy.googlegroups.com> On Oct 24, 12:25 pm, Daniel Folkes wrote: > I am new to using Vim's scripts. > > I was wondering if anyone uses Vim-Python and how to use it? This > includes things like key bindings and such. > > Thanks in advance, > Daniel Folkes > danfol... at gmail.com I'm not exactly sure what you are talking about. Do you mean writing Vim scripts in Python? I googled, Vim-Python and found a presentation about it. http://www.tummy.com/Community/Presentations/vimpython-20070225/vim.html Or do you mean writing Python with Vim? There's this blog entry about it. http://www.petersblog.org/node/461 I enjoy writing python with Vim. The omni-complete works pretty well. The TagList plug-in is pretty helpful: http://www.vim.org/scripts/script.php?script_id=273 Mini-buffer explorer is a good plug-in too: http://www.vim.org/scripts/script.php?script_id=159 SnippetsEmu is useful when I remember to trigger it for function defs and class defs. http://www.vim.org/scripts/script.php?script_id=1318 I also mapped a key to run the existing buffer through Pyflakes. map :new r!c:/Python25/python c:/Python25/scripts/ pyflakes # You could use your favorite syntax checker like Pychecker or Pylint instead of Pyflakes. From tdelaney at avaya.com Mon Oct 8 19:00:03 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 9 Oct 2007 07:00:03 +0800 Subject: NUCULAR fielded text searchable indexing In-Reply-To: <1191875335.134872.302660@d55g2000hsg.googlegroups.com> Message-ID: aaron.watters at gmail.com wrote: > ANNOUNCE: > NUCULAR fielded text searchable indexing Does "NUCULAR" stand for anything? The (apparent) misspelling of "nuclear" has already turned me off wanting to find out more about it. Tim Delaney From kyosohma at gmail.com Tue Oct 30 16:44:32 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 30 Oct 2007 20:44:32 -0000 Subject: python in academics? In-Reply-To: <47278c71$0$29610$426a74cc@news.free.fr> References: <1193715569.261522.219520@i13g2000prf.googlegroups.com> <1193749612.124199.172020@o38g2000hse.googlegroups.com> <47278c71$0$29610$426a74cc@news.free.fr> Message-ID: <1193777072.297513.48340@o80g2000hse.googlegroups.com> On Oct 30, 2:55 pm, Bruno Desthuilliers wrote: > kyoso... at gmail.com a ?crit : > > > On Oct 29, 10:39 pm, sandipm wrote: > > >>seeing posts from students on group. I am curious to know, Do they > >>teach python in academic courses in universities? > > >>in undergrad comp science courses, We had scheme language as scheme > >>is neat and beautiful language to learn programming. We learnt other > >>languages ourselve with basics set right by scheme.. > > >>sandip > > > They didn't at either of the colleges I went to. They seemed to be > > focused on C++, COBOL and Visual Basic. All are used all over the > > place, but only Visual Basic is easy for complete newbs. > > And alas one of the worst languages for a beginner - because you'll > probably need years to unlearn it. which language? I listed 3...and since you don't actually "learn" a language at all in a beginner's class, I don't really have anything to unlearn. All you get in those STUPID classes is a taste of programming...if you're lucky. > > > I hope more > > colleges adopt Python or Ruby as a teaching language, but I don't > > think it's a good idea to ignore COBOL or C++ since their used so > > extensively in big business. > > being widely used doesn't imply being a good language for teaching CS > (nor even being a good language for anything). I wasn't implying that they were good or bad, but that if you go to work for most big businesses, than it would probably be beneficial to know the language(s). For example, most insurance, financial and government jobs use COBOL to some degree or another. Mike From steven.bethard at gmail.com Mon Oct 29 19:31:56 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 29 Oct 2007 17:31:56 -0600 Subject: setting variables in outer functions In-Reply-To: <87myu1k4rm.fsf@mulj.homelinux.net> References: <87myu1k4rm.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > Tommy Nordgren writes: > >> Given the following: >> def outer(arg) >> avar = '' >> def inner1(arg2) >> # How can I set 'avar' here ? > > I don't think you can, until Python 3: > http://www.python.org/dev/peps/pep-3104/ But it definitely does work in Python 3 if you use 'nonlocal':: Python 3.0a1+ (py3k:58681, Oct 26 2007, 19:44:30) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(): ... x = 1 ... def g(): ... nonlocal x ... x = 2 ... print(x) ... g() ... print(x) ... >>> f() 1 2 That said, I'd like to see the reason you think you want to do this. STeVe From lew at lewscanon.com Sun Oct 21 11:04:39 2007 From: lew at lewscanon.com (Lew) Date: Sun, 21 Oct 2007 11:04:39 -0400 Subject: Distributed RVS, Darcs, tech love In-Reply-To: <1192978570.098588.276310@v23g2000prn.googlegroups.com> References: <1192850894.310464.89070@e9g2000prf.googlegroups.com> <1192978570.098588.276310@v23g2000prn.googlegroups.com> Message-ID: OMouse wrote: > For the love of the Perl, Python, Lisp, Java and functional > programmers, please just give an abstract of what you've written and > link to it? I expect you'll be ignored on that. Xah Lee reposts and reposts these essays from years agone. I don't even read his posts, just the responses. -- Lew From deets at nospam.web.de Sat Oct 20 12:52:29 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 20 Oct 2007 18:52:29 +0200 Subject: Noob: Loops and the 'else' construct In-Reply-To: <1192837344.623098.186960@k35g2000prh.googlegroups.com> References: <1192761867.254928.115300@i38g2000prf.googlegroups.com> <1192837344.623098.186960@k35g2000prh.googlegroups.com> Message-ID: <5nuq2oFkaj33U1@mid.uni-berlin.de> MRAB schrieb: > On Oct 19, 4:11 am, "Gabriel Genellina" > wrote: >> En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus >> escribi?: >> >>> I have just come across a site that discusses Python's 'for' and >>> 'while' loops as having an (optional) 'else' structure. >>> At first glance I interpreted it as being a bit like the 'default' >>> structure in PHP's switch block... But the switch block isn't a loop, >>> so, I am now confused as to the reason for using 'else' with the for >>> and while loops... >>> A few quick tests basically show that statements in the else structure >>> are executed at the fulfillment of the loop's expression (ie, no >>> break). >> A `while` loop tests a condition: if it evaluates to true, keep cycling; >> if it is false, stop. The `else` clause is executed when the condition is >> false, as in any `if` statement. If you exit the loop by using `break`, >> the `else` part is not executed (because you didn't get out of the loop by >> determining the condition falseness) >> >> You can think of a `for` loop as meaning `while there are remaining >> elements to be iterated, keep cycling` and the `else` clause applies when >> there are no more elements. A `break` statement does not trigger the else >> clause because the iteration was not exhausted. >> >> Once you get the idea, it's very simple. >> > It's useful when you want to search for an item and to do something if > you don't find it, eg: > > for i in items: > if is_wanted(i): > print "Found it" > break > else: > print "Didn't find ir" Wrong. It's not: for i in []: print i else: print "I'm reached, too" prints out "I'm reached, too" The else will ONLY not get executed when the loop is left prematurely through a break: for i in [1]: print i break else: print "I'm reached, too" won't print the "I'm ..." Diez From bruno.42.desthuilliers at wtf.websiteburo.oops.com Sun Oct 7 10:24:33 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Sun, 07 Oct 2007 16:24:33 +0200 Subject: Newbie packages Q In-Reply-To: <1191763497.852128.130710@k79g2000hse.googlegroups.com> References: <1191755440.850529.288860@o3g2000hsb.googlegroups.com> <1191763497.852128.130710@k79g2000hse.googlegroups.com> Message-ID: <4708ebfc$0$21561$426a74cc@news.free.fr> MarkyMarc a ?crit : (snip) > And the atest and btest, shouldn't they be able to import each > other?? import is a statement. It's executed, like any other top-level code, when the module is imported (or the script loaded into the interpreter if it's called directly). So if A.py imports B.py and B.py imports A.py, you do have a circular reference that can't be solved. Anyway, circular dependencies are Bad(tm), so you *don't* want such a situation. From steve at REMOVE-THIS-cybersource.com.au Mon Oct 8 13:09:14 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 08 Oct 2007 17:09:14 -0000 Subject: Variable scoping rules in Python? References: <1191853056.970304.209350@k79g2000hse.googlegroups.com> Message-ID: <13gkp1qr0hp9i5e@corp.supernews.com> On Mon, 08 Oct 2007 07:17:36 -0700, joshua.davies wrote: > I went back and re-read chapter 13 of "Learning Python", which talks > about variable scoping rules, and I can't figure out why Python is > saying this variable in Unbound. It works if I insert: > > global COLUMNS > > before the "if" statement... but I don't understand why. Is the > interpreter scanning my entire function definition before executing it, > recognizing that I *might* assign COLUMNS to a value, and deciding that > it's a local on that basis? Almost right, but not quite. You are right that Python decides that COLUMNS is local, but you're wrong about when that decision gets made. Python does not re-scan your function every time you execute it, but only once, when it is compiled. Compiling the function might take one pass of the source code, or two, or a thousand for all we know; that's an irrelevant detail of interest only to compiler designers and the chronically curious. What's important is that once the function is compiled, the decision is already made about whether COLUMNS is local or not, and the virtual machine that executes your function only needs to interpret the byte-code in a single pass. -- Steven. From kyosohma at gmail.com Wed Oct 10 10:35:35 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 10 Oct 2007 14:35:35 -0000 Subject: Building Binary Packages Message-ID: <1192026935.627151.160810@19g2000hsx.googlegroups.com> I am trying to figure out how to build binaries for Python packages and I've done it with MinGW. However, in my research, I've noticed that some of the programmers out there think that you should use the compiler that is used to compile the official Python distributions, which appears to be Visual Studio 2003. None of these programmers has really given their reasons for this though. Does compiling with a different compiler introduce subtle issues of some sort? If so, what are they (in general)? If you don't use VS2003, what compiler do you use? Here are the some links to what I've been reading: http://boodebr.org/main/python/build-windows-extensions http://www.z3lab.org/sections/blogs/philipp-weitershausen/2007_07_26_cheap-binary-windows http://www.gooli.org/blog/building-m2crypto-on-windows/ Thank you for your time. Mike From phil at freehackers.org Fri Oct 12 06:59:01 2007 From: phil at freehackers.org (BlueBird) Date: Fri, 12 Oct 2007 03:59:01 -0700 Subject: EasyMock for python ? In-Reply-To: References: <1192034695.321302.26580@o3g2000hsb.googlegroups.com> Message-ID: <1192186741.935636.35740@v23g2000prn.googlegroups.com> On Oct 11, 4:26 pm, "Simon Brunning" wrote: > On 10/10/07, BlueBird wrote: > > > Does anybody know where to find a library like EasyMock for python ? I > > searched quickly but could not find anything. > > > I found python-mocks on sourceforge but form quickly reading the docs, > > it is not an EasyMock style mock. Actually, according to > >http://martinfowler.com/articles/mocksArentStubs.htmlI don't think it > > is even a mock library. More a stub. > > python-mock is more jMock than EasyMock in style, it's true, and the > fact that you define expectations *after* the test invocation rather > than before does feel a bit odd. But it does indeed check against the > defined expectations, so that makes it a mock library in my book. > > A record-playback EasyMock style mock library would be nice, it's true... It should not be that hard to do, given that python-mocks already has the notion of recording and expectation verifiation. I may give it a stab. Philippe From rob.mcmullen at gmail.com Sat Oct 27 12:26:24 2007 From: rob.mcmullen at gmail.com (Rob McMullen) Date: Sat, 27 Oct 2007 16:26:24 -0000 Subject: multi-protocol url-based IO -- pure python kioslave-like module? Message-ID: <1193502384.553887.30370@i38g2000prf.googlegroups.com> Wheel reinvention preemption question: is there an existing pure- python library with functionality similar to KDE's kio/kioslave implementation? A multi-protocol, extensible library based on URLs that abstracts directory listing and file read/write? I'm looking to use it in client code, not server, so it doesn't have to be asynchronous like kio; ideally it would be small and only depend on the standard python library. Here's what I'm aware of: * urllib2 doesn't handle opening URLs for writing, meaning that it's incapable of supporting WebDAV or e.g. the fish:// protocol * twisted is built to handle multiple protocols, but is an extremely large package aiming to simplify low-level server and client code * Boa Contstructor has something called Explorers which support multiple protocols, but seems pretty tied to its gui implementation * PyKDE can interface with the KDE shared libraries, but obviously that's not pure python. (Or standalone or small. :) * the somewhat related PEP-268 for WebDAV support, but that was withdrawn. My google-fu doesn't show much else. Any pointers would be appreciated! Thanks, Rob From steve at REMOVE-THIS-cybersource.com.au Sun Oct 14 18:22:31 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 14 Oct 2007 22:22:31 -0000 Subject: pydev code completion problem References: <1192394167.058669.117830@q5g2000prf.googlegroups.com> Message-ID: <13h55l7bk542o92@corp.supernews.com> On Sun, 14 Oct 2007 21:57:12 +0000, Lukasz Mierzejewski wrote: > On Sun, 14 Oct 2007 20:36:07 +0000, cyberco wrote: > >> Confirmed (with exactly the same software). >> >> Please discuss this issue at the PyDev discussion forum: >> http://sourceforge.net/forum/forum.php?forum_id=293649 > > > Thank you for replay, but I'm still not sure what to think about it... > Marc 'BlackJack' Rintsch in his replay to my post says that it would be > to complicated for IDE to keep track of all objects... isn't he right? *shakes head sadly* Young programmers today, with your IDEs and code completion and syntax highlighting... when I was your age, we used "ed" and liked it! http://www.gnu.org/fun/jokes/ed.msg.html -- Steven From cuongvt at fpt.vn Tue Oct 2 20:16:09 2007 From: cuongvt at fpt.vn (cuongvt) Date: Tue, 2 Oct 2007 17:16:09 -0700 (PDT) Subject: Django for database driven web application is OK? Message-ID: <13010756.post@talk.nabble.com> Hello I'm new to both Django and Python. I'm mainly developing on PHP. I tend to move to Django. But I want to confirm as below: I heard that Django is mainly used for something like content management, CMS or something like that and Rails is mainly for web applications. So my question: is it true or not? For rapid web application development, can I use Django to create intranet database web driven application in my company for example: empoyees time management, goods import/export management, salary management etc? Tnx in advance. -- View this message in context: http://www.nabble.com/Django-for-database-driven-web-application-is-OK--tf4559120.html#a13010756 Sent from the Python - python-list mailing list archive at Nabble.com. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Oct 5 03:31:15 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 05 Oct 2007 09:31:15 +0200 Subject: Is there a nicer way to do this? In-Reply-To: <87ejgawpug.fsf@keizer.soze.com> References: <87ejgawpug.fsf@keizer.soze.com> Message-ID: <4705e82b$0$19642$426a74cc@news.free.fr> Stefan Arentz a ?crit : > Is there a better way to do the following? > > attributes = ['foo', 'bar'] > > attributeNames = {} > n = 1 > for attribute in attributes: > attributeNames["AttributeName.%d" % n] = attribute > n = n + 1 > > It works, but I am wondering if there is a more pythonic way to > do this. There is: attributeNames = dict( ("AttributeName.%d" % n, attr) \ for n, attr in enumerate(attributes) ) From gnewsg at gmail.com Mon Oct 22 15:28:50 2007 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Mon, 22 Oct 2007 12:28:50 -0700 Subject: Adding idle timeout capabilities to asyncore Message-ID: <1193081330.701282.149040@v29g2000prd.googlegroups.com> Hi there. We're talking about an asyncore-based server. Just for the heck of it I'd like to set a timeout which will disconnects the clients if they're inactive (i.e., no command or data transfer in progress) for a long period of time. I was thinking about putting the timeout value into an attribute: def settimeout(self, secs): self.timeout = time.time() + secs And then have the readable method call time.time() at every loop to check if time has passed or not: def readable(self): if time.time() >= self.timeout: self.send("Timeout") self.close() return 1 My only concern is if it's a good idea calling time.time() so often. Since A LOT of clients could be connected simultaneously, couldn't it be a too much resource-intensive operation? I'd also be curious to know how Twisted implemented this kind of stuff. By calling time.time() at every loop? Thanks in advance. From exarkun at divmod.com Mon Oct 15 15:12:59 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 15 Oct 2007 15:12:59 -0400 Subject: Automatically organize module imports In-Reply-To: Message-ID: <20071015191259.8162.2131787714.divmod.quotient.23330@ohm> On Mon, 15 Oct 2007 20:52:11 +0200, Thomas Wittek wrote: >Hi! > >Is there any possibility/tool to automatically organize the imports at >the beginning of a module? > >I don't mean automatic imports like autoimp does as I like seeing where >my objects/functions really come from. >For the same reason I don't like "from foo import *". > >The downside is that you have a rather verbose import section at the >beginning of your code. >That's very bad if you reorganize your code and some imports are not >needed anymore or new imports are needed. >In Eclipse/Java there is a nice feature that automatically organizes >your imports, meaning that it removes unneded imports and even adds >missing imports automatically. > >Unfortunately, this PyDev doesn't have an equally powerful feature. >As of the current version it only sorts the imports alphabetically, what >isn't very useful. > >So, is there anything I can do about my imports? >Is there a tool that can organize my import section? >Shall I fall back to ambiguous imports like *? >Shall I write out the module name for every class/function that I use >(quite unhandy)? > Pyflakes will tell you which imports aren't being used (among other things). I don't know if an existing tool which will automatically rewrite your source, though. Jean-Paul From besturk at gmail.com Sun Oct 28 09:00:19 2007 From: besturk at gmail.com (Abandoned) Date: Sun, 28 Oct 2007 06:00:19 -0700 Subject: Which index can i use ? Message-ID: <1193576419.825167.144400@50g2000hsm.googlegroups.com> Hi.. I want to do index in postgresql & python. My table: id(int) | id2(int) | w(int) | d(int) My query: select id, w where id=x and id2=y (sometimes and d=z) I have too many insert and select operation on this table. And which index type can i use ? Btree, Rtree, Gist or Hash ? Also I want to unique (id, id2).. Now this is my index. is it give me good performance ? CREATE UNIQUE INDEX ind1 ON test USING btree (id, id2) CREATE INDEX ind2 ON test USING btree (id) CREATE INDEX ind3 ON test USING btree (id2) CREATE INDEX ind4 ON test USING btree (w) CREATE INDEX ind5 ON test USING btree (d) I'm too sorry my bad english. King regards.. From cjw at sympatico.ca Sun Oct 7 09:36:43 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 07 Oct 2007 09:36:43 -0400 Subject: ANN: Pyrex 0.9.6 In-Reply-To: References: Message-ID: Greg Ewing wrote: > Pyrex 0.9.6 is now available: > > http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ > > There is a *lot* of new stuff in this version, too much > to fit into this announcement. Read all about it here: > > http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/changes-0.9.6.html > > What is Pyrex? > -------------- > > Pyrex is a language for writing Python extension modules. > It lets you freely mix operations on Python and C data, with > all Python reference counting and error checking handled > automatically. Some of the doc\Manual files seem to be missing eg source_files. I was browsing hoping to find an answer to the question "Do I need a C compiler to use Pyrex, if so, which one? Colin W. From orsenthil at gmail.com Mon Oct 22 05:36:27 2007 From: orsenthil at gmail.com (Phoe6) Date: Mon, 22 Oct 2007 02:36:27 -0700 Subject: package import question In-Reply-To: References: <1193040634.402343.127660@y27g2000pre.googlegroups.com> Message-ID: <1193045787.107713.75030@e9g2000prf.googlegroups.com> On Oct 22, 1:24 pm, Peter Otten <__pete... at web.de> wrote: > Phoe6 wrote: > > Hi all, > > I have the following directory structure: > > > wallpaper/ > > -main.py > > -ng/ > > -- __init__.py > > -- setdesktop.py > > -yb/ > > -- __init__.py > > -- setdesktop.py > > >>From main.py, I would like to do: > > import ng > > import yb > > ng.setdesktop.run() > > yb.setdesktop.run() > > > But it is not working! when I import the package, the modules present > > inside the package are getting imported. > > > However, following the python document if I do > > import ng.setdesktop > > import yb.setdesktop > > > ng.setdesktop.run() > > yb.setdesktop.run() > > Works fine. > > > I would like to use the notation. > > import > > and use the modules inside the package in the dotted module notation. > > What should I do the enable such a kind of imports. > > Put the line > > from . import setdesktop > > into both __init__.py files. Importing the package will then trigger the > submodule to be imported. > Thanks a lot for your replies. I had a thought that I can do this way, but as Python Documentation did not mention it, I was 'thinking' that submodules will automatically get imported and __init__.py usually blank. Thanks again, Senthil From patrick.waldo at gmail.com Sat Oct 27 08:19:18 2007 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Sat, 27 Oct 2007 12:19:18 -0000 Subject: Regular Expression In-Reply-To: <1193322969.306956.233960@d55g2000hsg.googlegroups.com> References: <1193092178.791023.163840@v29g2000prd.googlegroups.com> <5o4o43FktnthU7@mid.uni-berlin.de> <1193322969.306956.233960@d55g2000hsg.googlegroups.com> Message-ID: <1193487558.210986.176090@o80g2000hse.googlegroups.com> Finally I solved the problem, with some really minor things to tweak. I guess it's true that I had two problems working with regular expressions. Thank you all for your help. I really learned a lot on quite a difficult problem. Final Code: #For text files in a directory... #Analyzes a randomly organized UTF8 document with EINECS, CAS, Chemical, and Chemical Formula #into a document structured as EINECS|CAS|Chemical|Chemical Formula. import os import codecs import re path = "C:\\text_samples\\text\\" path2 = "C:\\text_samples\\text\\output\\" EINECS = re.compile(r'^\d\d\d-\d\d\d-\d$') CAS = re.compile(r'^\d*-\d\d-\d$') FORMULA = re.compile(r'([A-Z][A-Za-z0-9]+\.?[A-Za-z0-9]+/?[A-Za- z0-9]+)') def iter_elements(tokens): product = [] for tok in tokens: if EINECS.match(tok) and len(product) >= 4: match = re.match(FORMULA,product[-1]) if match: product[2:-1] = [' '.join(product[2:-1])] yield product product = [] else: product[2:-1] = [' '.join(product[2:])] del product[-1] yield product product = [] product.append(tok) yield product for text in os.listdir(path): input_text = os.path.join(path,text) output_text = os.path.join(path2,text) input = codecs.open(input_text, 'r','utf8') output = codecs.open(output_text, 'w', 'utf8') tokens = input.read().split() for element in iter_elements(tokens): output.write('|'.join(element)) output.write("\r\n") input.close() output.close() From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Oct 30 04:54:22 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 30 Oct 2007 09:54:22 +0100 Subject: A class question In-Reply-To: <87d4uxk08l.fsf@mulj.homelinux.net> References: <87ejfe457k.fsf@mulj.homelinux.net> <4725c510$0$4627$426a74cc@news.free.fr> <874pga3zo7.fsf@mulj.homelinux.net> <4725ea41$0$8018$426a74cc@news.free.fr> <87hcka2d76.fsf@mulj.homelinux.net> <47260805$0$5155$426a34cc@news.free.fr> <87d4uxk08l.fsf@mulj.homelinux.net> Message-ID: <4726f139$0$11586$426a34cc@news.free.fr> Hrvoje Niksic a ?crit : > Bruno Desthuilliers > writes: > >>> It seems to me that in recent times more Python beginners come from >>> a Java background than from a C one. >> Java does have "container" variables for primitive types, and even >> for "references", Java's variables are more than names - they do >> hold type informations too. Now I don't pretend to know how this is >> really implemented, but AFAICT, and at least from a cognitive POV, >> Java's variables model looks very close to the C/C++ model. > > While Java's variable declarations bear a superficial (syntactical) > similarity to C, their semantics is in fact equivalent to the > object-reference semantics we know in Python. They implicitly refer > to objects allocated on the heap and, just like in Python, the same > object can be referenced by multiple variables. You're talking about reference types here - not primitive types. And even then, from what I remember (not having done any Java these last 4 years at least), Java's reference types are much closer to C++ references than to Python. > If Java's model were > close to C/C++, that would not be possible without explicit > pointers/references The reference is implicit for non-primitive types. > since an object would be "contained" by the > variable. > > Variables holding primitive types don't really influence the > variable/object relationship, since the values they hold are by nature > immutable and without identity. Python's immutable types instances does have an identity, and follow the same rules as mutable types instances - mutability set aside of course. Which is not the case with Java, where primitive types and reference types follow distinct rules. I'll check this out (not having done Java for a couple years) and come back, but I certainly remember Java's model as being way closer to C++ than to Python. From joostkremers at yahoo.com Mon Oct 8 07:32:13 2007 From: joostkremers at yahoo.com (Joost Kremers) Date: 8 Oct 2007 11:32:13 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> <13frd6vtarbee75@corp.supernews.com> <13gj0neh59oks91@corp.supernews.com> <1191819894.369786.130300@v3g2000hsg.googlegroups.com> Message-ID: bbound at gmail.com wrote: > Don't both "man" and those words for measurement come ultimately from > words for "hand" (similarly to words like "manual", as in labor)? no. "manual" is derived from latin "manus" meaning "hand". the word "man" is related to (though not directly derived from) "mind", and the latin word "mens", which means "mind". -- Joost Kremers joostkremers at yahoo.com Selbst in die Unterwelt dringt durch Spalten Licht EN:SiS(9) From deets at nospam.web.de Tue Oct 2 09:16:14 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Oct 2007 15:16:14 +0200 Subject: Inheriting from int or long References: <1191329955.229829.259130@22g2000hsm.googlegroups.com> Message-ID: <5meukuFcvp4nU1@mid.uni-berlin.de> snorble at hotmail.com wrote: > I started creating a simple "bits" class, intended to act like a array > of bits. This was my initial idea, basically just overriding the > string representation to display the bitmask (so far): > > class bits(long): > def __str__ (self): > s = '' > if self == 0L: > s += '-' > else: > x = self > while x >= 1: > if x & 1L: s = '#' + s > else: s = '-' + s > x >>= 1 > return s > > My thought was this will act like a Long, and so should act like an > array of bits with arbitrary precision, supporting the standard > bitwise operations, along with others I may add. > >>>> import bits >>>> b = bits.bits(32) >>>> b > 32L >>>> print b > #----- >>>> b = bits.bits(35) >>>> print b > #---## >>>> b = bits.bits(36) >>>> print b > #--#-- >>>> b <<= 1 >>>> print b > 72 > > So obviously when I attempt a bitwise operation (ex. b <<= 1), b is > being assigned the result of b << 1, which is a Long. > >>>> b = bits.bits(36) >>>> type(b) > >>>> type (b << 1) > > > Is there any way around this without reimplementing all of the bitwise > operators? It's not the biggest deal to reimplement the operators, but > it kind of defeats the benefit of inheriting from an integer type. No, there isn't. How is the existing operation of the operator going to know that you want an instance of bits instead of long? It can't possibly know that, even if it looked at the class of one or even both of it's operands: it could be that instantiating a bits-object needed a reference to TheCommonApplicationContextThingy or so.... > If there isn't a way around this, then I am curious in what situations > it would be beneficial to inherit from an int or long. This issue > seems more related to numeric types, since they are so centered around > operations that involve assignment, as opposed to, say, a List, which > has some operators (ex. +=), but does not depend on them (ex. use > append() instead). It's beneficial if you want special behavior - but I don't see how the requirement of overloading the methods to make thinks work affect the grade of "beneficiality". Diez From arkanes at gmail.com Mon Oct 15 13:27:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 15 Oct 2007 12:27:54 -0500 Subject: Newbi Q: Recursively reverse lists but NOT strings? In-Reply-To: <13h6nlmd8aku2ea@corp.supernews.com> References: <53396d9e0710141406p6182bdat789fe1706225f345@mail.gmail.com> <471308FA.3070705@islandtraining.com> <53396d9e0710150238v2ccd3df7y42f89e776c31e524@mail.gmail.com> <13h6nlmd8aku2ea@corp.supernews.com> Message-ID: <4866bea60710151027m517e8bablfb210eaf5cc88693@mail.gmail.com> On 10/15/07, Steven D'Aprano wrote: > On Mon, 15 Oct 2007 13:13:48 +0200, paul wrote: > > > Dmitri O.Kondratiev schrieb: > >> Gary, thanks for lots of info! > >> Python strings are not lists! I got it now. That's a pity, I need two > >> different functions: one to reverse a list and one to reverse a string: > > Not necessarily, you can handle both cases in one function: > > > > def reverse(xs): > > if xs in [[], '']: > > return xs > > return (reverse (xs[1:])) + [xs[0], [xs[0]]][isinstance(list, xs)] > > > > but this is evil(tm) and violates Rule #1, #2 of "import this" and > > several others. > > > I'm not sure if you consider the Zen of Python to be numbered from 1 or > 0, so here are the first three: > > > Beautiful is better than ugly. > Explicit is better than implicit. > Simple is better than complex. > > I'm not sure why you say that function violates two of those three. Well, > okay, it's a bit ugly. > > I would say it violates this rule: > > There should be one-- and preferably only one --obvious way to do it. > > Have I missed something? Nobody seems to have pointed out the existence > of reversed(), which works on both lists and strings. > > > >>> ''.join(reversed("abc")) > 'cba' > >>> list(reversed(range(3))) > [2, 1, 0] > > It doesn't take much to make a more user-friendly version: > > > def myreversed(sequence): > if isinstance(sequence, basestring): > return type(sequence)().join(reversed(sequence)) > else: > return type(sequence)(reversed(sequence)) > > (in fact, that's so simple I wonder why the built-in reversed() doesn't > do that). > > Probably because reversed()'s primary use case is iteration, and it doesn't make sense to do the magic to return full objects there. The use case where you need to reverse a string or a list, with no context about what it will be, and where you're not iterating over the result (so a simple reversed() isn't practical) seems to be pretty obscure to me, so that there's not an obvious answer isn't surprising. There is the slightly non-obvious answer of sequence[::-1], though, which I think is perfectly satisfactory. From ldo at geek-central.gen.new_zealand Thu Oct 4 23:06:10 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Oct 2007 16:06:10 +1300 Subject: module confusion References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> <874ph8sdhx.fsf@benfinney.id.au> Message-ID: In message , Neil Cerutti wrote: > On 2007-10-03, Lawrence D'Oliveiro > wrote: >> In message <874ph8sdhx.fsf at benfinney.id.au>, Ben Finney wrote: >> >>> Lawrence D'Oliveiro writes: >>> >>>> On my Gentoo system: >>>> >>>> >>> import os >>>> >>> os.path >>>> >>>> >>>> It's just a variable that happens to point to the posixpath module. >>> >>> There's no "pointing" going on. It's another name bound to the >>> same object, of equal status to the 'posixpath' name. >>> >>> Python doesn't have pointers, and even "variable" is a >>> misleading term in Python. Best to stick to "name" and "bound >>> to". >> >> In Python, all names _are_ variables. They are not "bound" to >> objects. The value of os.path is a pointer. It's implemented as >> a pointer, it has all the semantics of a pointer. > > No. A pointer is also an iterator. > > void duplicate(char *d, const char *s) > { > while (*d++ = *s++) > ; > } So if you can't do pointer arithmetic, then it's not a pointer? Trying this: void duplicate(void *d, const void *s) { while (*d++ = *s++) ; } I get: test.c: In function 'duplicate': test.c:3: warning: dereferencing 'void *' pointer test.c:3: warning: dereferencing 'void *' pointer test.c:3: error: invalid use of void expression So you can't do arithmetic or iterate with a void * pointer. Does that mean it's not really a pointer? From Glich.Glich at googlemail.com Sun Oct 28 20:05:55 2007 From: Glich.Glich at googlemail.com (Glich) Date: Sun, 28 Oct 2007 17:05:55 -0700 Subject: Getting callfunc from ast code. In-Reply-To: <1193597572.850216.42300@19g2000hsx.googlegroups.com> References: <1193594968.334939.289710@57g2000hsv.googlegroups.com> <1193597572.850216.42300@19g2000hsx.googlegroups.com> Message-ID: <1193616355.997307.278980@v3g2000hsg.googlegroups.com> Your help is very useful. I would not be able to progress without you! Thanks. From bj_666 at gmx.net Wed Oct 10 07:42:15 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Oct 2007 11:42:15 GMT Subject: function wrappers References: Message-ID: <5n3s4mFfu79fU3@mid.uni-berlin.de> On Wed, 10 Oct 2007 12:39:24 +0200, Ramon Crehuet wrote: > def require_int(func): > def wrapper(arg): > assert isinstance(arg, int) > return func(arg) > return wrapper > p1(a): > print a > > p2=require_int(p1) > > My question is: why do p2 arguments become wrapper arguments? What is > the flux of the arguments in the program when you pass functions as > arguments? The function `p1` is passed into `require_int`. It is bound to the local name `func` in `require_int`. Everytime `require_int` is called a new function object is created and bound to the local name `wrapper`. The name `func` in that new function object refers to the object bound to `func` in the `require_int` namespace. Then the new function is returned still carrying a reference to the `func` object that was passed into `require_int`. Ciao, Marc 'Blackjack' Rintsch From zyzhu2000 at gmail.com Tue Oct 23 13:02:48 2007 From: zyzhu2000 at gmail.com (beginner) Date: Tue, 23 Oct 2007 17:02:48 -0000 Subject: Life-time of temporary variables in list comprehensions Message-ID: <1193158968.578330.204710@t8g2000prg.googlegroups.com> Hi All, If I have a list comprehension: ab=["A","B"] c = "ABC" [1.0 if c=='A' else c='B' for c in ab] print c >>"B" My test shows that if c is not defined before the list comprehension, it will be created in the list comprehension; if it is defined before the list comprehension, the value will be overwritten. In other words, temp variables are not local to list comprehensions. My question is why is this and is there any way to make c local to list comp? Thanks, Geoffrey From rkmr.em at gmail.com Tue Oct 23 01:27:06 2007 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Mon, 22 Oct 2007 22:27:06 -0700 Subject: decorator for a function without argument Message-ID: hi: i have a decorator given below. def checkdb(web): def decorator(func): def proxyfunc(self, args=(), kw=None): #DO STUFF with web return func(self, *args, **kw) return proxyfunc return decorator but if i use it to decorate function without any arguments I get this error: Traceback (most recent call last): File "", line 1, in TypeError: proxyfunc() takes at least 1 argument (0 given) how to fix this? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From lorna.burns at gmail.com Mon Oct 22 08:37:27 2007 From: lorna.burns at gmail.com (Py-Fun) Date: Mon, 22 Oct 2007 05:37:27 -0700 Subject: Iteration for Factorials In-Reply-To: <5o3jalFl0n43U1@mid.uni-berlin.de> References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <5o3jalFl0n43U1@mid.uni-berlin.de> Message-ID: <1193056647.416562.36150@q3g2000prf.googlegroups.com> On 22 Oct, 13:28, "Diez B. Roggisch" wrote: > Py-Fun wrote: > > I'm stuck trying to write a function that generates a factorial of a > > number using iteration and not recursion. Any simple ideas would be > > appreciated. > > Show us your attempts, and we might suggest a fix. Because otherwise this > sounds suspiciously like homework. > > Diez Here is my futile attempt. Be careful with this though, I just ran something similar and it was never ending... def itforfact(n): while n<100: print n n+1 n = input("Please enter a number below 100") itforfact(n) From tjreedy at udel.edu Mon Oct 29 17:49:59 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Oct 2007 17:49:59 -0400 Subject: A Python 3000 Question References: Message-ID: "brad" wrote in message news:fg5fku$5c1$1 at solaris.cc.vt.edu... | Will len(a_string) become a_string.len()? No. I was just reading | http://docs.python.org/dev/3.0/whatsnew/3.0.html which says nothing about such a change, except for one in the opposite direction: o.next() changes to next(o) which in turn calls o.__next__(), just as len(o) calls o.__len__() | One of the criticisms of Python compared to other OO languages is that | it isn't OO enough or as OO as others or that it is inconsistent. Python is object-based and has a nice user-defined type (class) system, but I do not believe Guido has ever called it object oriented. So the comparision is besides the point even if true. | Is there a reason that len cannot be a method? It corresponds to and calls method .__len__ , when such exists. Yes, Python could have been designed differently, with no builtin functions, but is was not. Python is also a functional language with first-class generic functions. | why not a_string.len()? You are free to bypass builtins and call methods directly if you like: a_string.__len__(). But consider rewriting the following: def table(func, seq): return zip(seq, map(func,seq)) table(len, ('', (), [])) If you *really* want to be super-OO, like functionless OO languages, you can also call methods instead of using operator symbols, which in effect are names of builtin functions. Instead of a+b, write a.__add__(b). And so on. Terry Jan Reedy From ldo at geek-central.gen.new_zealand Thu Oct 4 07:39:25 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Oct 2007 00:39:25 +1300 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <13frd6vtarbee75@corp.supernews.com> <85ve9ov971.fsf@lola.goethe.zz> <47041303$0$13930$fa0fcedb@news.zen.co.uk> <8sn8g39v75hg114lf3m9m911ib2ajddaui@4ax.com> Message-ID: In message , Steve Holden wrote: > Lawrence D'Oliveiro wrote: > >> In message <8sn8g39v75hg114lf3m9m911ib2ajddaui at 4ax.com>, George Neuner >> wrote: >> >>> The Christian Bible says "In the beginning was the Word..." >> >> Which is an English mistranslation from the Greek "logos". > > So, now you're telling me that the Garden of Eden was actually a > *marketing campaign*? Different Bible book, different author, different original language. From chowroc.z+l at gmail.com Tue Oct 16 22:52:17 2007 From: chowroc.z+l at gmail.com (Roc Zhou) Date: Wed, 17 Oct 2007 10:52:17 +0800 Subject: A near realtime file system mirror application written in Python Message-ID: <7847e5160710161952t7a22881ei1ba0d70b69dec883@mail.gmail.com> Hello: Recently I started an open source project "cutils" on the sourceforge: https://sourceforge.net/projects/crablfs/ The document can be found at: http://crablfs.sourceforge.net/#ru_data_man This project's mirrord/fs_mirror is a near realtime file system mirroring application across 2 or more hosts, now it can work for me. I hope this tool can be useful to you. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From goon12 at gmail.com Fri Oct 19 23:46:14 2007 From: goon12 at gmail.com (Joe Riopel) Date: Fri, 19 Oct 2007 23:46:14 -0400 Subject: C++ version of the C Python API? In-Reply-To: <496954360710191537r62ab6f28p3f61ca459fdc2116@mail.gmail.com> References: <496954360710191537r62ab6f28p3f61ca459fdc2116@mail.gmail.com> Message-ID: <6a2ccd190710192046l7fbf6748qb1f0cc71525af267@mail.gmail.com> On 10/19/07, Robert Dailey wrote: > Is there a C++ version of the C Python API packaged with python 2.5? > It would be nice to have a OOP approach to embedding python in C++. It > would also be a bonus if this C++ Python API cleaned up a lot of the > messy code involved in embedding python. C++ is object orientated? I heard it was, but I don't buy it. From ldo at geek-central.gen.new_zealand Thu Oct 4 00:44:38 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Oct 2007 17:44:38 +1300 Subject: module confusion References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> <874ph8sdhx.fsf@benfinney.id.au> Message-ID: In message , Carsten Haese wrote: > On Thu, 2007-10-04 at 11:11 +1300, Lawrence D'Oliveiro wrote: > >> In Python, all names _are_ variables. They are not "bound" to objects. >> The value of os.path is a pointer. > > No. "os.path" refers to the object that's known as the "path" attribute > of the object known as "os". That object, in turn, is a module. No, it's a variable. It just happens to contain a pointer to a module. >> It's implemented as a pointer, > > While it is true that namespaces are implemented in CPython as > collections of pointers to PyObject structures, that's an irrelevant > implementation detail. I doubt that they are implemented as pointers in > Jython, PyPy, or IronPython. I'll bet they are. >> it has all the semantics of a pointer. > > No, it doesn't. A pointer means the physical address of a memory > location, which implies that you can overwrite that memory location. Can > you do that in Python? Yes. Look up the definition of "mutable objects". From gnuist006 at gmail.com Tue Oct 9 02:24:05 2007 From: gnuist006 at gmail.com (gnuist006 at gmail.com) Date: Tue, 09 Oct 2007 06:24:05 -0000 Subject: The fundamental concept of continuations In-Reply-To: References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> Message-ID: <1191911045.604596.50110@19g2000hsx.googlegroups.com> On Oct 8, 10:59 pm, Barb Knox wrote: > > Lambda calculus. Instead of function A returning to its caller, the > caller provides an additional argument (the "continuation") which is a > function B to be called by A with A's result(s). In pure "continuation > style" coding, nothing ever "returns" a result. > > It is easy to mechanically transform normal function-style lambda > calculus into continuation-style, but the reverse is not so. > Explanation and reference please > > You can have a "spaghetti stack", or keep continuation data-structures > in the heap. A picture, diagram? a picture is worth a thousand words From comp.lang.scheme at ancell-ent.com Tue Oct 9 07:28:00 2007 From: comp.lang.scheme at ancell-ent.com (Harold Ancell) Date: Tue, 09 Oct 2007 06:28:00 -0500 Subject: why did MIT drop scheme for python in intro to computing? References: <1191432204.361780.129850@d55g2000hsg.googlegroups.com> <1191863837.105036.45510@22g2000hsm.googlegroups.com> <1191900533.823209.252590@o3g2000hsb.googlegroups.com> Message-ID: <2fomg3hkekk99kgcjag280hgb02np9hngt@4ax.com> On Tue, 09 Oct 2007 03:28:53 -0000, gnuist006 at hotmail.com wrote: >On Oct 8, 1:23 pm, b... at cs.berkeley.edu (Brian Harvey) wrote: >> "Kjetil S. Matheussen" writes: >> >I don't think your speculations makes very much sence. >> Amen. >> And, in any case, there's no need to speculate. >> MIT has published, on their web site, pages and >> pages of rationale for the new curriculum. >> The most important point, imho, is that the >> programming language was the /least/ important >> aspect of the decision. The most important >> aspect was the move to an application-based >> (rather than topic-based) organization of the >> curriculum. The details flow out of that big >> shift of focus. >[ much snipped. ] >Does scheme have a gui library? >I really dont follow the logic. I really REALLY hope that not a single GUI is constructed in 6.01-2; adding that to the load would be stark raving mad (look and you'll agree). As Brian points out, languages are a means to the end of teaching stuff, and I wouldn't be surprised if not a single GUI is constructed in the entire required/restricted elective curriculum. That's just not to the point of an EECS education that has to be squeezed into 4/5 years (most students take the combined MEng path, where the MS degree is terminal and leads straight to industry). If any library was a consideration in choosing Python, it was the robots one for 6.01. Note also that Hal helped design and teach 6.01, and fully supports the new curriculum. As a total LISP/Scheme fanatic who finds parts of Python's syntax to be too hard for his brain (not the indentation, that's weird but useful and cool, much like S-expressions in LISP), I looked hard at the beginning of 6.01 where they're only teaching SICP. For that purpose, Python is not "awful" (remember, I believe LISP is the One True Way of Computing). For that initial bit of SICP material, I do not believe the students will be handicapped. Beyond that initial bit of material, I have no informed opinions. - Harold From aahz at pythoncraft.com Fri Oct 26 20:09:03 2007 From: aahz at pythoncraft.com (Aahz) Date: 26 Oct 2007 17:09:03 -0700 Subject: Good Book References: <1192556250.936548.255060@i13g2000prf.googlegroups.com> Message-ID: In article <1192556250.936548.255060 at i13g2000prf.googlegroups.com>, wrote: > >The Python Cookbook would probably be another good resource. While I >don't like the Dummies series' name, the Python Dummies book is a good >introduction, although it doesn't have enough examples, in my opinion. Could you explain what examples you would have liked more of in _Python for Dummies_? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From __peter__ at web.de Tue Oct 16 04:14:44 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Oct 2007 10:14:44 +0200 Subject: Simple Text Processing Help References: <1192369731.561036.31010@i38g2000prf.googlegroups.com> <1192396632.736910.134070@q5g2000prf.googlegroups.com> <1192445236.310797.91160@z24g2000prh.googlegroups.com> <1192482484.987399.112620@k35g2000prh.googlegroups.com> Message-ID: patrick.waldo wrote: > manipulation? Also, I conceptually get it, but would you mind walking > me through >> for key, group in groupby(instream, unicode.isspace): >> if not key: >> yield "".join(group) itertools.groupby() splits a sequence into groups with the same key; e. g. to group names by their first letter you'd do the following: >>> def first_letter(s): return s[:1] ... >>> for key, group in groupby(["Anne", "Andrew", "Bill", "Brett", "Alex"], first_letter): ... print "--- %s ---" % key ... for item in group: ... print item ... --- A --- Anne Andrew --- B --- Bill Brett --- A --- Alex Note that there are two groups with the same initial; groupby() considers only consecutive items in the sequence for the same group. In your case the sequence are the lines in the file, converted to unicode strings -- the key is a boolean indicating whether the line consists entirely of whitespace or not, >>> u"\n".isspace() True >>> u"alpha\n".isspace() False but I call it slightly differently, as an unbound method: >>> unicode.isspace(u"alpha\n") False This is only possible because all items in the sequence are known to be unicode instances. So far we have, using a list instead of a file: >>> instream = [u"alpha\n", u"beta\n", u"\n", u"gamma\n", u"\n", u"\n", u"delta\n"] >>> for key, group in groupby(instream, unicode.isspace): ... print "--- %s ---" % key ... for item in group: ... print repr(item) ... --- False --- u'alpha\n' u'beta\n' --- True --- u'\n' --- False --- u'gamma\n' --- True --- u'\n' u'\n' --- False --- u'delta\n' As you see, groups with real data alternate with groups that contain only blank lines, and the key for the latter is True, so we can skip them with if not key: # it's not a separator group yield group As the final refinement we join all lines of the group into a single string >>> "".join(group) u'alpha\nbeta\n' and that's it. Peter From anandology at gmail.com Wed Oct 31 21:25:22 2007 From: anandology at gmail.com (Anand) Date: Thu, 01 Nov 2007 01:25:22 -0000 Subject: Method needed for skipping lines In-Reply-To: <1193875491.983722.239270@y42g2000hsy.googlegroups.com> References: <1193875491.983722.239270@y42g2000hsy.googlegroups.com> Message-ID: <1193880322.994494.322970@i38g2000prf.googlegroups.com> On Nov 1, 5:04 am, Paul Hankin wrote: > On Oct 31, 5:02 pm, Gustaf wrote: > > > Hi all, > > > Just for fun, I'm working on a script to count the number of lines in source files. Some lines are auto-generated (by the IDE) and shouldn't be counted. The auto-generated part of files start with "Begin VB.Form" and end with "End" (first thing on the line). The "End" keyword may appear inside the auto-generated part, but not at the beginning of the line. I think we can take help of regular expressions. import re rx = re.compile('^Begin VB.Form.*^End\n', re.DOTALL|re.MULTILINE) def count(filename) text = open(filename).read() return rx.sub('', text).count('\n') From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Oct 4 04:26:31 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 04 Oct 2007 10:26:31 +0200 Subject: migrating to packages In-Reply-To: <87hcl7jsn0.fsf@mulj.homelinux.net> References: <4703C661.50009@fmed.uba.ar> <27E2B61D-3D3E-466D-9650-69E0DA27E952@myemma.com> <87hcl7jsn0.fsf@mulj.homelinux.net> Message-ID: <4704a3a5$0$5110$426a34cc@news.free.fr> Hrvoje Niksic a ?crit : > gherzig at fmed.uba.ar writes: > >> I will expose my case quicly. >> The MYCLASES.py file contains the A class, so i can use >> from MYCLASES import A >> a = () >> >> Using the "package mode" (wich looks fine BTW), having the simple >> MYCLASES/ >> __init__.py >> A.py >> >> forces my (i guess) to use the >> from MYCLASES.A import A > > Exactly. Using mypackage.mymodule instead of just mymodule is the > entire *point* of a package. Nope. The "entire point" of packages is to let you organize your code and namespace. And it's quite common to use the __init__.py of the package (as explained by Ben) as a facade to the internal organization of the package, so you can change this internal organization without breaking client code. > That way, if someone creates another > module with using the same name (mymodule), it won't conflict with > yours. If you don't want to change mymodule to mypackage.mymodule, > why use a package in the first place? Because you have too much code to keep it in a single file. From jwkenne at attglobal.net Thu Oct 11 17:40:48 2007 From: jwkenne at attglobal.net (John W. Kennedy) Date: Thu, 11 Oct 2007 17:40:48 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1191978311.987341.271000@r29g2000hsg.googlegroups.com> References: <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> <13frd6vtarbee75@corp.supernews.com> <13gj0neh59oks91@corp.supernews.com> <1191819894.369786.130300@v3g2000hsg.googlegroups.com> <1191978311.987341.271000@r29g2000hsg.googlegroups.com> Message-ID: nebulous99 at gmail.com wrote: > Do not bluntly contradict me in public. You are in grave need of professional psychiatric help. Seek it now, if you do not wish your life to be ended three or four years down the line by a police sniper. -- John W. Kennedy Read the remains of Shakespeare's lost play, now annotated! http://pws.prserv.net/jwkennedy/Double%20Falshood/index.html From daniel_nolan at msn.com Mon Oct 29 21:40:04 2007 From: daniel_nolan at msn.com (daniel) Date: Mon, 29 Oct 2007 18:40:04 -0700 Subject: trouble with PAMIE Message-ID: <1193708404.650144.316150@50g2000hsm.googlegroups.com> I'm using PAMIE to automate some web browsing. My problem is with the buttonClick() method. It seems to work unless the button is supposed to open a new window, in which case nothing happens. There is no error message. Any ideas? Daniel From bj_666 at gmx.net Sat Oct 13 04:38:19 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Oct 2007 08:38:19 GMT Subject: raw_input() and utf-8 formatted chars References: <1192197233.824215.301890@e9g2000prf.googlegroups.com> <1192216685.923198.279040@v29g2000prd.googlegroups.com> <1192220315.602812.155810@z24g2000prh.googlegroups.com> <5na4jvFh28v6U2@mid.uni-berlin.de> <1192241386.568665.140500@y27g2000pre.googlegroups.com> Message-ID: <5nbefrFh5md2U1@mid.uni-berlin.de> On Fri, 12 Oct 2007 19:09:46 -0700, 7stud wrote: > On Oct 12, 2:43 pm, Marc 'BlackJack' Rintsch wrote: >> You mean literally!? Then of course I get A\xcc\x88 because that's what I >> entered. In string literals in source code the backslash has a special >> meaning but `raw_input()` does not "interpret" the input in any way. >> > > Then why don't I end up with the same situation as this: > >> >> > s = 'A\xcc\x88' #capital A with umlaut >> >> > print s #displays capital A with umlaut I don't get the question!? In string literals in source code the backslash has a special meaning, like I wrote above. When Python compiles that above snippet you end up with a string of three bytes, one with the ASCII value of an 'A' and two bytes where you typed in the byte value in hexadecimal: In [191]: s = 'A\xcc\x88' In [192]: len(s) Out[192]: 3 In [193]: map(ord, s) Out[193]: [65, 204, 136] In [194]: print s ? The last works this way only if the receiving/displaying program expected UTF-8 as encoding. Otherwise something other than an ? would have been shown. If you type in that text when asked by `raw_input()` then you get exactly what you typed because there is no Python source code compiled: In [195]: s = raw_input() A\xcc\x88 In [196]: len(s) Out[196]: 9 In [197]: map(ord, s) Out[197]: [65, 92, 120, 99, 99, 92, 120, 56, 56] In [198]: print s A\xcc\x88 >> > And what is it that your keyboard enters to produce an 'a' with an >> > umlaut? >> >> *I* just hit the key. The one right next to the ? key. ;-) >> > ...and what if you don't have an a-with-umlaut key? I find other means to enter it. + some magic number on the numeric keypad in windows, or , , <"> on Unix/Linux. Some text editors offer special sequences too. If all fails there are character map programs that show all unicode characters to choose from and copy'n'paste them. Ciao, Marc 'BlackJack' Rintsch From stargaming at gmail.com Fri Oct 12 09:59:39 2007 From: stargaming at gmail.com (Stargaming) Date: 12 Oct 2007 13:59:39 GMT Subject: Declarative properties References: <1192103298.065386.243670@o3g2000hsb.googlegroups.com> <5n6j5nFghr61U4@mid.uni-berlin.de> <1192107893.492826.233730@d55g2000hsg.googlegroups.com> <470e5606$0$29825$426a34cc@news.free.fr> Message-ID: <470f7dca$0$8814$9b622d9e@news.freenet.de> On Thu, 11 Oct 2007 18:58:44 +0200, Bruno Desthuilliers wrote: [snip] Your implementation seems particularly broken. You do not return anything from `name()`, hereby removing name as an attribute (or: replacing it with its return value -- None). You should return ``property(**locals()) `` (or ``property(fget=fget, fset=fset, ...)``, whatever you like). I'm going to point out a few other mistakes first: > class Toto(object): > def __iinit__(self, name): Typo here: __init__ > self.name = name > @apply > def name(): > def fget(self): > print "getting %s.name" % self > return self._name > def fset(self, val): > print "setting %s.name to %s" % (self, val) > self._name = name It should be `val`, not `name`, huh? And, as mentioned above, the return value is missing. > def say_hello(self): > print "Hello, my name is %s" % self.name A fixed implementation could be something along these lines:: >>> class Toto(object): ... def __init__(self, name): ... self.name = name ... @apply ... def name(): ... def fget(self): ... print "getting %s.name" % self ... return self._name ... def fset(self, val): ... print "setting %s.name to %s" % (self, val) ... self._name = val ... return property(**locals()) ... def say_hello(self): ... print "Hello, my name is %s" % self.name ... >>> t = Toto("bruno") setting <__main__.Toto object at 0xb792f66c>.name to bruno >>> t.say_hello() getting <__main__.Toto object at 0xb792f66c>.name Hello, my name is bruno >>> t.name getting <__main__.Toto object at 0xb792f66c>.name 'bruno' >>> t.name = "jon" setting <__main__.Toto object at 0xb792f66c>.name to jon >>> t.say_hello() getting <__main__.Toto object at 0xb792f66c>.name Hello, my name is jon Cheers, Stargaming From sjmachin at lexicon.net Sun Oct 14 19:01:00 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 14 Oct 2007 16:01:00 -0700 Subject: Order of tuples in dict.items() In-Reply-To: <13h55uj8pogd4ea@corp.supernews.com> References: <47122790$0$8421$db0fefd9@news.zen.co.uk> <13h55uj8pogd4ea@corp.supernews.com> Message-ID: <1192402860.365074.241070@i38g2000prf.googlegroups.com> On Oct 15, 8:27 am, Steven D'Aprano wrote: > I've never seen the point of a sorted dictionary, it's easy to just say: > > for key, value in sorted(D.items()) There are several applications that involve finding i such that key[i] <= query < key[i+1] where the keys are sorted and unique ... perhaps with a huge sentinel key at the end. Examples include sliding-scale taxes, and looking up prices for shares or managed funds. The code to do this in Python using the bisect module is about as clear as the equivalent SQL :-) From Jiandong.Ge at gmail.com Wed Oct 3 12:46:20 2007 From: Jiandong.Ge at gmail.com (JD) Date: Wed, 03 Oct 2007 16:46:20 -0000 Subject: A question about subprocess Message-ID: <1191429980.784610.39020@22g2000hsm.googlegroups.com> Hi, I want send my jobs over a whole bunch of machines (using ssh). The jobs will need to be run in the following pattern: (Machine A) (Machine B) (Machine C) Job A1 Job B1 Job C1 Job A2 Job B2 etc Job A3 etc etc Jobs runing on machine A, B, C should be in parallel, however, for each machine, jobs should run one after another. How can I do it with the subprocess? Thanks, JD From steven.bethard at gmail.com Tue Oct 23 13:30:20 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 23 Oct 2007 11:30:20 -0600 Subject: Automatic Generation of Python Class Files In-Reply-To: <5o5mimFld8c9U1@mid.uni-berlin.de> References: <1193073156.493809.184110@z24g2000prh.googlegroups.com> <1193076352.576143.123260@z24g2000prh.googlegroups.com> <1193078577.129883.317680@k35g2000prh.googlegroups.com> <471d06e2$0$12275$426a74cc@news.free.fr> <5o5mimFld8c9U1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 22 Oct 2007 17:31:51 -0600, Steven Bethard wrote: > >> Bruno Desthuilliers wrote: >>> Computed attributes are IMHO not only a life-saver when it comes to >>> refactoring. There are cases where you *really* have - by 'design' I'd >>> say - the semantic of a property, but know from the start you'll need >>> computation (for whatever reason). Then what would be the rationale for >>> using explicit getters/setters ? >> I'd be interested to hear what these use cases are. > > Stupid little example: A circle object with `radius` and `diameter` > attributes. It doesn't make sense to store both a as normal attributes > because they will eventually get out of sync. One can be implemented as a > property. Could be. But I'd tend to define a get_diameter() method here. As a user of your class, I'd like to know which one is doing the computation. What if I'm using ridiculously large ints, and I care about the multiplication? > Another one is delegation of attribute access. I'm thinking of a wrapper > class around an object with an attribute, say `is_active`, and a wrapper > that has a property with the same name that returns the value of the > wrapped objects attribute. This is retrofitting to an API, so it already falls under the only time I think you *should* be using property(). Although in this case, it might be that __getattr__ is more appropriate. > Or lazy computation of an attribute. Breaks expectations for the first > access -- long calculation for simple attribute access -- but meets it for > every subsequent access. There are descriptors better than property() at achieving this behavior. See for example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363602 My personal experience is that every time I write stuff this way (and I have many times), I end up re-writing it later as a method because it's less confusing for a method to take a long time than it is for an attribute access. STeVe From michele.simionato at gmail.com Sun Oct 7 08:49:13 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sun, 07 Oct 2007 12:49:13 -0000 Subject: Yet another comparison of Python Web Frameworks In-Reply-To: <4708d28f$0$21569$426a34cc@news.free.fr> References: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> <1i5kbfo.xq3fut1f7ouujN%raims@dot.com> <1i5kk06.enf7ws1juj4zkN%raims@dot.com> <4708d28f$0$21569$426a34cc@news.free.fr> Message-ID: <1191761353.306980.121410@22g2000hsm.googlegroups.com> On Oct 7, 8:36 am, Bruno Desthuilliers > Indeed. But AFAICT, Lawrence and Michele problems is not to port an > existing web application, but to choose a web framework that will play > well with their existing *system* (RDBMS, existing apps and libs etc). > Which is quite another problem, and may eliminate some otherwise pretty > good frameworks for compatibility reasons (DBMS support and other issues). > > (please Michele or Lawrence correct me if I'm wrong...) Yes, our main concern is compatibility with the existing system: for instance, one constraint is the MS SQL database. Having said that, we would like to port parts of a Zope application to the new framework, but I do not expect this to be particularly difficult for the parts we want to migrate since they are not really using Zope features. Other parts instead would require a very substantial rewrite so for the moment I think they will stay in Zope. Michele Simionato From robert.kern at gmail.com Sun Oct 21 23:11:05 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 21 Oct 2007 22:11:05 -0500 Subject: parallel NumPy: PyMPI, myMPI or something else? In-Reply-To: <1193001446.939761.122290@t8g2000prg.googlegroups.com> References: <1193001446.939761.122290@t8g2000prg.googlegroups.com> Message-ID: smithken04 at yahoo.com wrote: > Hi! > > I am trying to find my way to a running parallel NumPy installation. > Can you help me getting started wihtout losing my way several times? > > PyMPI and myMPI are apperently not too actively developed. Is this > true? Are they mature enough so that they don't need any more updates? > Have they been replaced by more recent modules? The people who I know who use MPI and Python have been using mpi4py. I haven't used it myself, though. http://mpi4py.scipy.org/ > Then, if I have NumPy running with PyMPI or whatever, is NumPy already > optimized for a MPI environment so that for example matrix > multiplication, iterative solvers etc. are automatically distributed? No. > Or do I have to split each problem myself to make use of the > parallelism? Pretty much. -- 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 gneuner2/ at comcast.net Wed Oct 3 23:30:08 2007 From: gneuner2/ at comcast.net (George Neuner) Date: Wed, 03 Oct 2007 23:30:08 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <13frd6vtarbee75@corp.supernews.com> <85ve9ov971.fsf@lola.goethe.zz> Message-ID: <8gn8g35m3rtb4n4l2ouk55vv54bsfbga4r@4ax.com> On Wed, 3 Oct 2007 18:20:38 +0000 (UTC), bcd at pvv.ntnu.no (Bent C Dalager) wrote: >In article , >George Neuner wrote: >>On Wed, 3 Oct 2007 09:36:40 +0000 (UTC), bcd at pvv.ntnu.no (Bent C >>Dalager) wrote: >> >>> >>>Only if you're being exceedingly pedantic and probably not even >>>then. Webster 1913 lists, among other meanings, >>> >>>Free >>>(...) >>>"Liberated, by arriving at a certain age, from the control >>>of parents, guardian, or master." >>> >>>The point presumably being that having been "liberated", you are now >>>"free". >> >> (...) >> >>The English language has degenerated significantly in the last 30 >>years. >> (...) >> >>Dictionaries used to be the arbiters of the language - any word or >>meaning of a word not found in the dictionary was considered a >>colloquial (slang) use. Since the 1980's, an entry in the dictionary >>has become little more than evidence of popularity as the major >>dictionaries (OED, Webster, Cambridge, etc.) will now consider any >>word they can find used in print. > >Apparantly, you missed the part where I referred to the 1913 edition >of Webster. I have kept it in the quoted text above for your >convenience. I can assure you that 1913 is both more than 30 years ago >/and/ it is before 1980, in case that was in doubt. > >Cheers > Bent D I didn't miss it. Your post was just an opportunity to rant. George -- for email reply remove "/" from address From juan at juanreyero.com Thu Oct 18 04:32:07 2007 From: juan at juanreyero.com (juan at juanreyero.com) Date: Thu, 18 Oct 2007 10:32:07 +0200 Subject: ANN: magnitude 0.9.1 References: <873awb5wgw.fsf@benfinney.id.au> <87k5pn4efu.fsf@benfinney.id.au> Message-ID: > A further issue, that requires a change of interface: Please comply > with PEP 8 for your > module interface. In particular, please name classes with TitleCase, > and functions, methods, and instance names with > lower_case. Done, almost. I should have seen that document before. I think magnitude is compliant now, both in its API and its innards. The only thing missing is to raise objects instead of strings. > Also: "precision" is the correct spelling of that word. Now that's embarrassing. Thanks. jm From donn.ingle at gmail.com Mon Oct 29 16:43:32 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Mon, 29 Oct 2007 22:43:32 +0200 Subject: A class question References: <87ejfe457k.fsf@mulj.homelinux.net> <1193666679.216514.248300@o3g2000hsb.googlegroups.com> Message-ID: > for humans: Sweet. Thanks, I'll give it a go. It's only for debugging and will make life easier. \d From Josef.Robert.Novak at gmail.com Wed Oct 24 06:31:01 2007 From: Josef.Robert.Novak at gmail.com (kettle) Date: Wed, 24 Oct 2007 10:31:01 -0000 Subject: japanese encoding iso-2022-jp in python vs. perl In-Reply-To: <1193210435.469081.168360@v29g2000prd.googlegroups.com> References: <1193135850.030196.31170@i38g2000prf.googlegroups.com> <1193210435.469081.168360@v29g2000prd.googlegroups.com> Message-ID: <1193221861.332351.188960@e9g2000prf.googlegroups.com> Thanks Leo, and everyone else, these were very helpful replies. The issue was exactly as Leo described, and I apologize for not being aware of it, and thus not quite reporting it correctly. At the moment I don't care about round-tripping between half-width and full-width kana, rather I need only be able to rely on any particular kana character be translated correctly to its half-width or full-width equivalent, and I need the Japanese I send out to be readable. I appreciate the 'implicit versus explicit' point, and have read about it in a few different python mailing lists. In this instance it seems that perl perhaps ought to flash a warning notification regarding what it is doing, but as this conversion between half-width and full-width characters is by far the most logical one available, it also seems reasonable that python might perhaps include such capabilities by default, just as it currently includes the 'replace' option for mapping missed characters generically to '?'. I still haven't worked out the entire mapping routine, but Leo's hint is probably sufficient to get it working with a bit more effort. Again, thanks for the help. -Joe > Thanks that I have my crystal ball working. I can see clearly that the > forth > character of the input is 'HALFWIDTH KATAKANA LETTER ME' (U+FF92) > which is > not present in ISO-2022-JP as defined by RFC 1468 so python converts > it into > question mark as you requested. Meanwhile perl as usual is trying to > guess what > you want and silently converts that character into 'KATAKANA LETTER > ME' (U+30E1) > which is present in ISO-2022-JP. > > > Why can't python properly encode some of these > > characters? > > Because "Explicit is better than implicit". Do you care about > roundtripping? > Do you care about width of characters? What about full-width " (U > +FF02)? Python > doesn't know answers to these questions so it doesn't do anything with > your > input. You have to do it yourself. Assuming you don't care about > roundtripping > and width here is an example demonstrating how to deal with narrow > characters: > > from unicodedata import normalize > iso2022_squeezing = dict((i, normalize('NFKC',unichr(i))) for i in > range(0xFF61,0xFFE0)) > print repr(u'\uFF92'.translate(iso2022_squeezing)) > > It prints u'\u30e1'. Feel free to ask questions if something is not > clear. > > Note, this is just an example, I *don't* claim it does what you want > for any character > in FF61-FFDF range. You may want to carefully review the whole unicode > block:http://www.unicode.org/charts/PDF/UFF00.pdf > > -- Leo. From devnew at gmail.com Tue Oct 16 03:05:56 2007 From: devnew at gmail.com (devnew at gmail.com) Date: Tue, 16 Oct 2007 07:05:56 -0000 Subject: PIL and getpixel() Message-ID: <1192518356.021602.276860@y27g2000pre.googlegroups.com> i am trying to get the pixel data using im.getpixel() i am getting a tuple like (152,118,106) for a pixel in a RGB jpeg image . what i really want is an integer value representing a pixel ,like waht i can get from java's BufferedImage.getRGB(x,y) .. i am wondering if someone can advise me on how i can do this thanx dn From ritu2cool.85 at gmail.com Tue Oct 9 01:01:58 2007 From: ritu2cool.85 at gmail.com (ritu sharma) Date: Tue, 9 Oct 2007 10:31:58 +0530 Subject: Query Message-ID: Hi , I am using linked server to fetch data from Oracle database. Now ,I have to use FPN_STATUS='A' in the query. Kindly tell me if there is an escape sequence for ' . FROM OPENQUERY(FPDWH, 'SELECT WGFP_OWN.GRS_FILE_PLAN_VERSION.FVN_STATUS FPN_STAT_CODE, WGFP_OWN.GRS_FILE_PLAN_STATUS.FPS_NAME FPN_STAT_NAME, WGFP_OWN.GRS_FILE_PLAN_VERSION.FVN_STAT_UPD_BY FPN_STAT_UPD_BY, FROM WGFP_OWN.GRS_FILE_PLAN_VERSION, WGFP_OWN.GRS_FILE_PLAN, WGFP_OWN.GRS_FILE_PLAN_STATUS, WGFP_OWN.GRS_SECTOR, (SELECT A.FVN_FPN_ID AS FPN_NO, A.FVN_ID AS FVN_ID FROM WGFP_OWN.GRS_FILE_PLAN_VERSION A, WGFP_OWN.GRS_FILE_PLAN B WHERE B.FPN_ID = A.FVN_FPN_ID AND A.FVN_VERSION=1 AND (A.FVN_FPN_ID) NOT IN (SELECT C.FVN_FPN_ID AS FPN_NO_A FROM WGFP_OWN.GRS_FILE_PLAN_VERSION C, WGFP_OWN.GRS_FILE_PLAN D WHERE D.FPN_ID = C.FVN_FPN_ID AND C.FVN_STATUS ='A') UNION SELECT A.FVN_FPN_ID AS FPN_NO, A.FVN_ID AS FVN_ID FROM WGFP_OWN.GRS_FILE_PLAN_VERSION A, WGFP_OWN.GRS_FILE_PLAN B WHERE B.FPN_ID = A.FVN_FPN_ID AND *A.FVN_STATUS ='A' --- Any alternative for ' character * --GROUP BY A.FVN_FPN_ID ) FVN_MAX Now ,I have to use FPN_STATUS='A' in the query. Kindly tell me if there is an escape sequence for ' . Hoping for an early reply. *Thanks * *Ritu *** -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Wed Oct 31 18:13:46 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 31 Oct 2007 22:13:46 -0000 Subject: A Python 3000 Question References: <1193761000.248965.139690@y42g2000hsy.googlegroups.com> <1193836481.203103.111400@22g2000hsm.googlegroups.com> Message-ID: <13ihvgqk7klhb9@corp.supernews.com> On Wed, 31 Oct 2007 13:14:41 +0000, George Sakkis wrote: > On Oct 31, 8:44 am, Neil Cerutti wrote: >> On 2007-10-30, George Sakkis wrote: >> >> >> >> > On Oct 30, 11:25 am, Neil Cerutti wrote: >> >> On 2007-10-30, Eduardo O. Padoan wrote: >> >> >> > This is a FAQ: >> >> >http://effbot.org/pyfaq/why-does-python-use-methods-for-some- function... >> >> >> Holy Airy Persiflage Batman! >> >> >> 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 timeit >> >> >>> timeit.Timer('len(seq)', 'seq = range(100)').timeit() >> >> 0.20332271187463391 >> >> >>> timeit.Timer('seq.__len__()', 'seq = range(100)').timeit() >> >> >> 0.48545737364457864 >> >> > Common mistake; try this instead: >> >> > timeit.Timer('seqlen()', >> > 'seq = range(100); seqlen=seq.__len__').timeit() >> >> Why would I want to do that? > > > To realize that __len__ is actually faster than len in this case; your > second timing is dominated by the time to do attribute lookup. What Neil has done is the correct thing to measure in this case. What you have measured is a local optimization that is only useful when you have a tight loop with lots of calls to the same len(): Len = sequence.__len__ while Len() < 100000: foo(sequence) But what Neil is measuring is relevant for the more general case of calling len() on arbitrary objects at arbitrary times: x = len(sequence) y = 42 + len("xyz") if len(records) == 12: print "twelve!" To get the benefit of the micro-optimization you suggested, you would need to write this: Len = sequence.__len__ x = Len() Len = "xyz".__len__ y = 42 + Len() Len = records.__len__ if Len() == 12: print "twelve!" Not only is that an especially ugly, confusing piece of code, it is also counter-productive as you still have to do the method lookup every single time. Taking the method lookup is an apple-and-oranges comparison. It is useful to know for the times when you don't want an apple, you want an orange (i.e. the tight loop example above). This is an apples-and-apples comparison: >>> import timeit >>> timeit.Timer("Len = seq.__len__; Len()", "seq = range(12)").repeat() [1.3109469413757324, 0.7687380313873291, 0.55280089378356934] >>> timeit.Timer("len(seq)", "seq = range(12)").repeat() [0.60111594200134277, 0.5977931022644043, 0.59935498237609863] The time to do the lookup and call the method is about 0.6 microseconds whether you do it manually or let len() do it. The logic behind the micro-optimization trick is to recognize when you can avoid the cost of repeated method lookups by doing it once only. That is not relevant to the question of whether len() should be a function or a method. -- Steven. From marco at sferacarta.com Tue Oct 23 11:24:26 2007 From: marco at sferacarta.com (Marco Mariani) Date: Tue, 23 Oct 2007 17:24:26 +0200 Subject: Iteration for Factorials In-Reply-To: <1193149619.244514.325360@t8g2000prg.googlegroups.com> References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <5o3jalFl0n43U1@mid.uni-berlin.de> <1193056647.416562.36150@q3g2000prf.googlegroups.com> <1193057676.680959.71780@v23g2000prn.googlegroups.com> <1193064348.526006.183080@q5g2000prf.googlegroups.com> <1193149619.244514.325360@t8g2000prg.googlegroups.com> Message-ID: Roberto Bonvallet wrote: > import urllib > import re > urllib.URLopener.version = "Mozilla/4.0" > > def fact(x): > r = re.compile(r"%d ! = (\d+)" % x) > for line in urllib.urlopen("http://www.google.cl/search?q=%d%%21" % x): > m = r.search(line) > if m: > return int(m.group(1)) You solution reminds me the web-based WTF calculator. http://worsethanfailure.com/Articles/OMGWTF-Finalist-05-WTF-Web-Calc.aspx From gagsl-py2 at yahoo.com.ar Wed Oct 31 23:23:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Nov 2007 00:23:49 -0300 Subject: capturing output of command line in an array References: <1193842906.058058.29080@t8g2000prg.googlegroups.com> <1193847249.528264.270150@k35g2000prh.googlegroups.com> Message-ID: En Wed, 31 Oct 2007 19:20:56 -0300, escribi?: > I am looking to just get the node name from that info. > I dont need all other info > so my list would be just > alist=[node13,node12,node8,node1 ....] > is it possible?? > >> > node13 2 ( 0/ 56) [ 0.00, 0.00, 0.00] [ 0.0, 0.0, >> > 0.1, 99.9, 0.0] OFF >> > node12 2 ( 1/ 63) [ 0.99, 0.97, 0.91] [ 46.6, 0.0, >> > 3.7, 49.8, 0.0] OFF >> > node8 2 ( 1/ 59) [ 0.99, 0.97, 0.91] [ 47.5, 0.0, >> > 2.8, 49.7, 0.0] OFF Try this: import subprocess p = subprocess.Popen( ["your","command","+args"], stdout=subprocess.PIPE) lines = p.stdout.readlines() p.wait() If you are only interested in the first word in each line, you may replace the lines = ... above with this: nodes = [line.split(' ', 1)[0] for line in p.stdout] -- Gabriel Genellina From arnodel at googlemail.com Tue Oct 2 12:42:24 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 02 Oct 2007 09:42:24 -0700 Subject: Using fractions instead of floats In-Reply-To: References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> <1191254961.729631.256760@22g2000hsm.googlegroups.com> <1191272365.225974.41660@w3g2000hsg.googlegroups.com> Message-ID: <1191343344.454133.46790@n39g2000hsh.googlegroups.com> On Oct 2, 12:42 pm, Neil Cerutti wrote: > On 2007-10-01, Arnaud Delobelle wrote: > > Scheme has prefix numeric operators, so that 1/2 is > > unambiguously (for the interpreter and the user) a litteral for > > 'the fraction 1/2'. You can't avoid the confusion in python, as > > binary operators are infix. Of course, we could create a new > > kind of litteral. Let's see, / and // are already operators, > > so why not use /// ? ;) > > But you wouldn't actually need a literal rational represention. In which case rationals are better off in a module than in the language! > But I'm just playing Devil's Advocate here; I like rationals in > Scheme and Lisp, but I don't see a need for them in Python. > On the other hand, Python has had complex numbers a long time, > and it doesn't need those more than rationals, does it? My guess > is that it got complex numbers but not rationals because > rationals just aren't very efficient. Another guess could be that real numbers being closed under the four arithmetic operations, there is no danger to accidentally step into complex numbers. OTOH floats and rationals are two (conflicting) ways of extending integers. > But as a programmer, I'm mostly just a data-twiddler, and don't > generally need either of those numeric type in my day-to-day > work. So I'm not the guy to ask. ;) I use rationals a lot, and I don't want them in the language :) -- Arnaud From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Oct 24 08:27:55 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 24 Oct 2007 14:27:55 +0200 Subject: Python Windows Installation References: <1193195493.086681.40570@t8g2000prg.googlegroups.com> Message-ID: <5o8s2bFlhd8uU2@mid.individual.net> TheFlyingDutchman wrote: > I am trying to install Python 2.5 on Windows XP. It installs into > the root directory on C:\ instead of C:\Python25 BTW, what exactly is behind the idea to install to c:\python25 instead of %PROGRAMFILES%\python25? Regards, Bj?rn -- BOFH excuse #339: manager in the cable duct From deets at nospam.web.de Wed Oct 10 04:41:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Oct 2007 10:41:10 +0200 Subject: Problem with argument parsing References: <1191940442.108905.292810@50g2000hsm.googlegroups.com> <5n1keaFfoj0eU1@mid.uni-berlin.de> <1191995876.142576.242160@50g2000hsm.googlegroups.com> Message-ID: <5n3hh6Ffsul2U1@mid.uni-berlin.de> lgwe wrote: > On 9 Okt, 17:18, "Diez B. Roggisch" wrote: >> lgwe wrote: >> > I have a python-script: myscript, used to start a program on another >> > computer and I use OptionParser in optpars. >> > I use it like this: myscript -H host arg1 -x -y zzz >> > I would like OptionParser to ignore all arguments after arg1, because >> > these are options that should be used by the program started on the >> > oter computer arg1 -x -y zzz. >> > One solution is to write: myscript -H host "arg1 -x -y zzz" >> > But is it in some way possible to instruct OptionParser to ignore -x - >> > y zzz without the "..."? >> >> Use -- to separate arguments to be parsed by OptionParser from the >> to-be-ignored-ones, which is documented btw. >> >> Diez > > Thanks! > I understand that this must be documented. > But I can't find if anywhere in > http://docs.python.org/lib/module-optparse.html. (maybee I just cant see > it, but it is there) It's general unix-commandline-knowledge... but you are right of course. It should be documented. Maybe you can file a documentation-bug or something? Diez From patrick.waldo at gmail.com Thu Oct 25 10:36:09 2007 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Thu, 25 Oct 2007 14:36:09 -0000 Subject: Regular Expression In-Reply-To: <5o4o43FktnthU7@mid.uni-berlin.de> References: <1193092178.791023.163840@v29g2000prd.googlegroups.com> <5o4o43FktnthU7@mid.uni-berlin.de> Message-ID: <1193322969.306956.233960@d55g2000hsg.googlegroups.com> Marc, thank you for the example it made me realize where I was getting things wrong. I didn't realize how specific I needed to be. Also http://weitz.de/regex-coach/ really helped me test things out on this one. I realized I had some more exceptions like C18H34O2.1/2Cu and I also realized I didn't really understand regular expressions (which I still don't but I think it's getting better) FORMULA = re.compile(r'([A-Z][A-Za-z0-9]+\.?[A-Za-z0-9]+/?[A-Za- z0-9]+)') This gets all Chemical names like C14H28 C18H34O2.1/2Cu C8H17ClO2, ie a word that begins with a capital letter followed by any number of upper or lower case letters and numbers followed by a possible . followed by any number of upper or lower case letters and numbers followed by a possible / followed by any number of upper or lower case letters and numbers. Say that five times fast! So now I want to tell the program that if it finds the formula at the end then continue, otherwise if it finds C.I. 75240 or any other type of word that it should not be broken by a | and be lumped into the whole line. But now I get: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\Patrick Waldo\My Documents\Python \WORD\try5-2-file-1-1.py", line 32, in ? input = codecs.open(input_text, 'r','utf8') File "C:\Python24\lib\codecs.py", line 666, in open file = __builtin__.open(filename, mode, buffering) IOError: [Errno 13] Permission denied: 'C:\\Documents and Settings\ \Patrick Waldo\\Desktop\\decernis\\DAD\\EINECS_SK\\text\\output' Ideas? #For text files in a directory... #Analyzes a randomly organized UTF8 document with EINECS, CAS, Chemical, and Chemical Formula #into a document structured as EINECS|CAS|Chemical|Chemical Formula. import os import codecs import re path = "C:\\text" path2 = "C:\\text\output" EINECS = re.compile(r'^\d\d\d-\d\d\d-\d $') FORMULA = re.compile(r'([A-Z][A-Za-z0-9]+\.?[A-Za-z0-9]+/?[A-Za- z0-9]+)') def iter_elements(tokens): product = [] for tok in tokens: if EINECS.match(tok) and len(product) >= 4: if product[-1] == FORMULA.findall(tok): product[2:-1] = [' '.join(product[2:-1])] yield product product = [] else: product[2:-1] = [' '.join(product[2:])] yield product product = [] product.append(tok) yield product for text in os.listdir(path): input_text = os.path.join(path,text) output_text = os.path.join(path2,text) input = codecs.open(input_text, 'r','utf8') output = codecs.open(output_text, 'w', 'utf8') tokens = input.read().split() for element in iter_elements(tokens): output.write('|'.join(element)) output.write("\r\n") input.close() output.close() From daniel_nolan at msn.com Mon Oct 29 11:56:05 2007 From: daniel_nolan at msn.com (daniel) Date: Mon, 29 Oct 2007 08:56:05 -0700 Subject: IEC - cannot find button In-Reply-To: <1193663081.249282.106150@50g2000hsm.googlegroups.com> References: <1193637535.413630.252960@22g2000hsm.googlegroups.com> <1193663081.249282.106150@50g2000hsm.googlegroups.com> Message-ID: <1193673365.693804.63460@y27g2000pre.googlegroups.com> On Oct 29, 6:04 am, kyoso... at gmail.com wrote: > On Oct 29, 12:58 am, daniel_no... at msn.com wrote: > > > > > I'm brand new to Python--and programming in general. I'm trying to use > > IEC to control Internet Explorer. I've navigated to a page, and now > > I'm trying to click a button. The button appears to be called 'PDF > > Preview' but I honestly do not know whether that's the name or the > > caption. Here is my code: > > > from win32com.client import Dispatch > > import IEC > > > . > > . > > . > > > ie = IEC.IEController(window_num = 1) > > ie.Navigate(URL_part_1 + x + URL_part_2) > > ie.ClickButton(name='PDF Preview') > > > (I've also tried replacing name w/ caption but I get a similar error > > message.) I get this error message: > > > Traceback (most recent call last): > > File "C:\Program Files\Python25\experiment", line 14, in > > ie.ClickButton(name='PDF Preview') > > File "C:\Program Files\Python25\lib\IEC.py", line 126, in > > ClickButton > > elem = elemcoll.item(i) > > File ">", line 3, in item > > com_error: (-2147024891, 'Access is denied.', None, None) > > > I really have no idea how to interpret this. I'm pasting the button > > tag below: > > > > > You might want to look at PAMIE instead. It sounds like a Python > project that's aimed at automating Internet Explorer:http://sourceforge.net/projects/pamie/ > > But if you really like COM, I found this tutorial: > > http://www.evilbitz.com/2006/10/22/python-ie-automation-thorough-tuto... > > I'm not very good with COM, but I would recommend that you do some > research on it. From the traceback, I would guess that you don't have > administrator privileges (of some sort) on the machine you're running > the script on. > > Mike Thanks for the input, Mike. Since I don't have much experience w/ either, I don't have a strong preference for COM over PAMIE. I'm just frustrated my script isn't working. I guess it could have to do w/ privileges. I'm using a VPN connection. I tried turning off my antivirus software before running the module. I can click on the button I want manually, and get the page I need, so I wonder if I can adjust some settings to allow Python to take control of certain things? That or I thought it might have to do w/ a javascript error. By looking at the tag, does 'PDF Preview' look like the name of the button or the button caption? Let me know what you think. Daniel From java.oke at gmail.com Thu Oct 18 16:36:02 2007 From: java.oke at gmail.com (j.oke) Date: Thu, 18 Oct 2007 13:36:02 -0700 Subject: Elisp Tutorial: HTML Syntax Coloring Code Block In-Reply-To: <1192680926.420317.16630@v29g2000prd.googlegroups.com> References: <1192680926.420317.16630@v29g2000prd.googlegroups.com> Message-ID: <1192739762.151628.132800@i38g2000prf.googlegroups.com> On 18 Ott, 06:15, Xah Lee wrote: > [...] Half lost on my firmness gains to more glad heart, Or violent and from forage drives A glimmering of all sun new begun Both harp thy discourse they march'd, Forth my early, is not without delay; For their soft with whirlwind; and balm. Undoubtedly he scornful turn'd round ninefold, Though doubled now what redounds, And chains these a lower world devote, yet inflicted? Till body or rare, and best things else enjoy'd in heav'n To stand divided light at ev'n and poise their eyes, Or nourish, lik'ning spiritual, I have thou appear. -Henley From mensanator at aol.com Wed Oct 24 19:09:38 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Wed, 24 Oct 2007 16:09:38 -0700 Subject: Python and Combinatorics In-Reply-To: <471fc476$1@news.bezeqint.net> References: <471fc476$1@news.bezeqint.net> Message-ID: <1193267378.171825.233770@e34g2000pro.googlegroups.com> On Oct 24, 5:20 pm, none <""atavory\"@(none)"> wrote: > Hello, > > Is there some package to calculate combinatorical stuff like (n over > k), i.e., n!/(k!(n - k!) ? Sure, the gmpy module. >>> import gmpy >>> for m in xrange(10): for n in xrange(m+1): print '%4d' % (gmpy.comb(m,n)), print 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 > > I know it can be written in about 3 lines of code, but still... > > Thanks, > > Ami From pavlovevidence at gmail.com Wed Oct 31 10:59:58 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 31 Oct 2007 07:59:58 -0700 Subject: A Python 3000 Question In-Reply-To: References: <1193761000.248965.139690@y42g2000hsy.googlegroups.com> Message-ID: <1193842798.085242.22690@t8g2000prg.googlegroups.com> On Oct 31, 8:44 am, Neil Cerutti wrote: > On 2007-10-30, George Sakkis wrote: > > > > > On Oct 30, 11:25 am, Neil Cerutti wrote: > >> On 2007-10-30, Eduardo O. Padoan wrote: > > >> > This is a FAQ: > >> >http://effbot.org/pyfaq/why-does-python-use-methods-for-some-function... > > >> Holy Airy Persiflage Batman! > > >> 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 timeit > >> >>> timeit.Timer('len(seq)', 'seq = range(100)').timeit() > >> 0.20332271187463391 > >> >>> timeit.Timer('seq.__len__()', 'seq = range(100)').timeit() > > >> 0.48545737364457864 > > > Common mistake; try this instead: > > > timeit.Timer('seqlen()', > > 'seq = range(100); seqlen=seq.__len__').timeit() > > Why would I want to do that? If your point is to measure the time of just the operation as accurately as possible, you don't want the extra dict lookup in seq.__len__ affecting things. Though it seems to me that if your intention is to determine if builtin or method style is faster, it's not such a great idea to replace the method call with a builtin call. As for what benefit there is for len to be a builtin: Python considers len to be an operator for all intents and purposes. Python chose to spell this operator like a regular function, but it could easily have given a special syntax to the length operation (for instance, $#x). Do you think that, if the length operation had its own syntax, people would be saying "No, length shouldn't be an operator, it should be a method"? I don't think so; length is a fundamental and ubiquitous operation and it wouldn't be unreasonable to give it its own syntax. That suggests to me that, when people complain that len should be a method, their complaint is a superficial complaint about spelling. They are not considering whether len is important enough to be an operator or not. Carl Banks From steven.bethard at gmail.com Mon Oct 22 14:48:21 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 22 Oct 2007 12:48:21 -0600 Subject: Automatic Generation of Python Class Files In-Reply-To: <1193078577.129883.317680@k35g2000prh.googlegroups.com> References: <1193073156.493809.184110@z24g2000prh.googlegroups.com> <1193076352.576143.123260@z24g2000prh.googlegroups.com> <1193078577.129883.317680@k35g2000prh.googlegroups.com> Message-ID: Sunburned Surveyor wrote: > I also intended to add statements creating properties from the getter > and setter methods. I understand that getters and setters aren't > really necessary if you aren't making a property. I just forgot to add > the property statements to my example. You still don't want to define the getters and setters if they're just going to set an attribute. Just use an attribute itself. Java makes you define getters and setters because there's no way to make method calls look like an attribute access. So in Java if you start with a public attribute, you can never adjust the API later. In Python, you can use property() to make method calls look like attribute access. This could be necessary if you have an existing API that used public attributes, but changes to your code require those attributes to do additional calculations now. But if you're creating a class for the first time, it should *never* use property(). There's no need to retrofit anything. STeVe From deets at nospam.web.de Thu Oct 11 03:40:37 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Oct 2007 09:40:37 +0200 Subject: "".join(string_generator()) fails to be magic In-Reply-To: References: Message-ID: <5n62boFgcod7U1@mid.uni-berlin.de> Matt Mackal schrieb: > I have an application that occassionally is called upon to process > strings that are a substantial portion of the size of memory. For > various reasons, the resultant strings must fit completely in RAM. > Occassionally, I need to join some large strings to build some even > larger strings. > > Unfortunately, there's no good way of doing this without using 2x the > amount of memory as the result. You can get most of the way there with > things like cStringIO or mmap objects, but when you want to actually > get the result as a Python string, you run into the copy again. > > Thus, it would be nice if there was a way to join the output of a > string generator so that I didn't need to keep the partial strings in > memory. would be the obvious way to do this, but it of > course converts the generator output to a list first. You can't built a contiguous string of bytes without copying them. The question is: what do you need the resulting strings for? Depending on the use-case, it might be that you could spare yourself the actual concatenation, but instead use a generator like this: def charit(strings): for s in strings: for c in s: yield c Diez From bbound at gmail.com Mon Oct 8 01:04:54 2007 From: bbound at gmail.com (bbound at gmail.com) Date: Mon, 08 Oct 2007 05:04:54 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <13gj0neh59oks91@corp.supernews.com> References: <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> <13frd6vtarbee75@corp.supernews.com> <13gj0neh59oks91@corp.supernews.com> Message-ID: <1191819894.369786.130300@v3g2000hsg.googlegroups.com> On Oct 7, 9:07 pm, Damien Kick wrote: > Perhaps our word "man" (manas) still expresses something of precisely > this feeling of self-satisfaction: man designated himself as the > creature that measures values, evaluates and measures, as the "valuating > animal as such".[1] Don't both "man" and those words for measurement come ultimately from words for "hand" (similarly to words like "manual", as in labor)? Our clever hands with their opposable thumbs being considered a defining characteristic. And our tool use thus derived. Handspans also having been a common (if imprecise) early unit of measurement (along with forearm-spans, as in cubits, strides, and foot-length, from which the measurement in feet still derives its name). From kaaveland at gmail.com Sat Oct 13 07:50:02 2007 From: kaaveland at gmail.com (=?iso-8859-1?q?Robin_K=E5veland?=) Date: Sat, 13 Oct 2007 11:50:02 -0000 Subject: Last iteration? In-Reply-To: References: Message-ID: <1192276202.151145.306050@z24g2000prh.googlegroups.com> On Oct 12, 12:58 pm, Florian Lindner wrote: > Hello, > can I determine somehow if the iteration on a list of values is the last > iteration? > > Example: > > for i in [1, 2, 3]: > if last_iteration: > print i*i > else: > print i > > that would print > > 1 > 2 > 9 > > Can this be acomplished somehow? > > Thanks, > > Florian If you want to do this over a list or a string, I'd just do: for element in iterable[:-1]: print iterable print iterable[-1] * iterable[-1] No need for it to get more advanced than that :) From http Thu Oct 4 15:39:19 2007 From: http (Paul Rubin) Date: 04 Oct 2007 12:39:19 -0700 Subject: unit testing References: Message-ID: <7xlkaifz4o.fsf@ruckus.brouhaha.com> brad writes: > Does anyone else feel that unittesting is too much work? Not in > general, just the official unittest module for small to medium sized > projects? Yeah, unittest is sort of a Java-ism. You might try the newer doctest module instead. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Oct 18 13:30:54 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 18 Oct 2007 19:30:54 +0200 Subject: Convert string to command.. In-Reply-To: <1192722090.740342.60950@i13g2000prf.googlegroups.com> References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> <5npa5cFj5bvfU1@mid.uni-berlin.de> <1192720007.177063.194550@i13g2000prf.googlegroups.com> <5npbjbFio7g9U1@mid.uni-berlin.de> <1192720659.272611.320900@v29g2000prd.googlegroups.com> <873aw830lc.fsf@mulj.homelinux.net> <1192722090.740342.60950@i13g2000prf.googlegroups.com> Message-ID: <4717984e$0$439$426a74cc@news.free.fr> Abandoned a ?crit : (snip) > import cPickle as pickle > a="{2:3,4:6,2:7}" > s=pickle.dumps(a, -1) > g=pickle.loads(s); > print g > '{2:3,4:6,2:7}' > > Thank you very much for your answer but result is a string ?? > Of course it's a string. That's what you pickled. What did you hope ? If you want a dict back, then pickle a dict. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Oct 1 11:13:29 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 01 Oct 2007 17:13:29 +0200 Subject: Select as dictionary... In-Reply-To: References: <1191245527.228745.17100@r29g2000hsg.googlegroups.com> <4700fb42$0$18288$426a74cc@news.free.fr> Message-ID: <47010e97$0$7777$426a74cc@news.free.fr> J. Clifford Dyer a ?crit : > On Mon, Oct 01, 2007 at 03:50:59PM +0200, Bruno Desthuilliers wrote regarding Re: Select as dictionary...: >> IIRC, postgres' db-api connector (well, at least one of them - I don't >> know which one you're using) has a DictCursor. You should find all you >> want to know in the relevant doc. >> > > Correct me if I'm wrong, but I think the DictCursor would output the following: > > [{'id': 1, 'value': 5}, {'id': 2, 'value': 5}, ...] > > But the OP wanted one dict with IDs as keys: > > {1: 5, 2: 5, ...} Hmmm... I did answer too fast, indeed. Thanks for pointing that out. From bj_666 at gmx.net Thu Oct 25 02:49:06 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Oct 2007 06:49:06 GMT Subject: Regular Expression question References: <1193294043.936217.54090@q5g2000prf.googlegroups.com> Message-ID: <5oasj2Fm1hl5U2@mid.uni-berlin.de> On Thu, 25 Oct 2007 06:34:03 +0000, looping wrote: > Hi, > It's not really a Python question but I'm sure someone could help me. > > When I use RE, I always have trouble with this kind of search: > > Ex. > > I've a text file: > """ > create or replace package XXX > ... > > create or replace package body XXX > ... > """ > now I want to search the position (line) of this two string. > > for the body I use: > s = re.search(r'create\s+or\s+replace\s+package\s+body\s+', txt, > re.IGNORECASE) > > but how to search for the other line ? > I want the same RE but explicitly without "body". The write the same RE but explicitly without "body". But I guess I didn't understand your problem when the answer is that obvious. Maybe you want to iterate over the text file line by line and match or search within the line? Untested: needle = re.compile(r'create\s+or\s+replace\s+package(\s+body)?\s+', re.IGNORECASE) for i, line in enumerate(lines): if needle.match(line): print 'match in line %d' % (i + 1) Ciao, Marc 'BlackJack' Rintsch From alia_khouri at yahoo.com Tue Oct 2 03:16:25 2007 From: alia_khouri at yahoo.com (Alia Khouri) Date: Tue, 02 Oct 2007 00:16:25 -0700 Subject: Python 3.0 migration plans? In-Reply-To: References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <%q0Li.725$ih1.539@nlpi068.nbdc.sbc.com> <1i555ag.9ez4uvf4583jN%aleax@mac.com> Message-ID: <1191309385.404530.292880@r29g2000hsg.googlegroups.com> Couldn't agree with you more. What would be fantastic is if I could drop into the Pypi (and/or use easy_install) and download automatically compiled versions of extension modules for different versions of python. I'm sure the community at large would be happy to chip in an annual fee to help build/maintain this infrastructure: I know my firm would. PS: IMHO The growth of Ruby is, to a large extent, due to easy installation of modules via its gem system... On Sep 28, 6:53 pm, John Nagle wrote: > Insofar as Python has an organization, it's not adequately managing > extension modules. Each extension module has its own infrastructure, > with its own build procedures, its own bug list, and its own maintainers. > There's not even an archive. Unlike CPAN, Cheese Shop is just a directory of > URLs. > > Take a look at how Perl does it. Here are the instructions on > how to contribute to CPAN: > > http://www.cpan.org/modules/04pause.html > > There's a way to get your module into the system, a standardized format, > build, and installation procedure, and an archive which is mirrored. > There's a common bug reporting system. Modules abandoned by their > original developers are not lost, and can be "adopted" by someone else. > > Python doesn't have any of this. And that's far more of a problem > than Python 3.x. > > John Nagle From nogradi at gmail.com Wed Oct 3 14:08:30 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 3 Oct 2007 20:08:30 +0200 Subject: python autoconf macro for building ming extension Message-ID: <5f56302b0710031108x65675b94kcc4bed884c3643c7@mail.gmail.com> It might be slightly off topic here but couldn't find a more suitable place for this question: I'm trying to build the python binding for ming -- http://ming.sf.net -- but for some reason the python macro for autoconf -- python.m4 -- doesn't seem to detect my python installation correctly. The strange thing is that it seemingly detects everything correctly, but a final check still fails. I have the python 2.5 source distribution installed to /usr/local the standard location. Configuring ming fails with: checking for python... /usr/local/bin/python checking for python2.5... (cached) /usr/local/bin/python checking for a version of Python >= '2.1.0'... yes checking for the distutils Python package... yes checking for Python include path... -I/usr/local/include/python2.5 checking for Python library path... -L/usr/local/lib/python2.5 -lpython2.5 checking for Python site-packages path... /usr/local/lib/python2.5/site-packages checking python extra libraries... -lpthread -ldl -lutil checking python extra linking flags... -Xlinker -export-dynamic checking consistency of all components of python development environment... no configure: error: Could not link test program to Python. Maybe the main Python library has been installed in some non-standard library path. If so, pass it to configure, via the LDFLAGS environment variable. Example: ./configure LDFLAGS="-L/usr/non-standard-path/python/lib" ============================================================================ ERROR! You probably have to install the development version of the Python package for your distribution. The exact name of this package varies among them. ============================================================================ and all variables above are correct. It apparently found PYTHON_CPPFLAGS=-I/usr/local/include/python2.5 PYTHON_LDFLAGS=-L/usr/local/lib/python2.5 -lpython2.5 PYTHON_SITE_PKG=/usr/local/lib/python2.5/site-packages PYTHON_EXTRA_LIBS=-lpthread -ldl -lutil PYTHON_EXTRA_LDFLAGS=-Xlinker -export-dynamic all correctly, yet the final check fails. I even tried configuring with PYTHON_NOVERSIONCHECK and LDFLAGS=-L/usr/local/lib/python2.5 and gave the above environment variables manually but still the same final check fails. Apparently it's not a ming but an autoconf issue. Anyone familiar with python.m4? From robert.rawlins at thinkbluemedia.co.uk Mon Oct 22 05:56:52 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 22 Oct 2007 10:56:52 +0100 Subject: Check File Change Every 10 Seconds Message-ID: <002701c81491$e09eb510$a1dc1f30$@rawlins@thinkbluemedia.co.uk> Hello Chaps, I've got a requirement to check a file for a change every 10 seconds or so, and if the file has been modified since the last time I parsed its content into the application then I need to parse it in again. However, I need this process to not interrupt the rest of my application flow. What is the best way to handle this? Is there some form of file watcher module for python which can watch the file for me and then parse any changes into the application memory? Or should I be spawning and unjoined thread which contains and infinite loop which checks a date/time the file was modified against an internal date/time variable for when the application last parsed the file into memory? I'll be interested to hear your ideas guys, Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From piyush.subscription at gmail.com Fri Oct 26 03:25:33 2007 From: piyush.subscription at gmail.com (Piyush Jain) Date: Fri, 26 Oct 2007 12:55:33 +0530 Subject: modifying __class__ Message-ID: <19ac19520710260025w4a871cfekcc8f01a6d6143f17@mail.gmail.com> Hi, Itis possible to change the class of an object by assigning new value to __class__ Is it possible to call my module when it is done. For example, object = ClassA() object.__class__ = classB # I want to call my method when this statement is executed. I want to do it in a general way. For ex. , whenever __class__ is changed for any object instance (of different classes), my own function is called. How should I do it ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From MrJean1 at gmail.com Tue Oct 30 00:15:06 2007 From: MrJean1 at gmail.com (MrJean1) Date: Tue, 30 Oct 2007 04:15:06 -0000 Subject: Solaris 10 + Sun Studio 12 Pyrhon 2.4.4 64-bit build problem In-Reply-To: <1193684775.643350.208230@y27g2000pre.googlegroups.com> References: <1193637835.936397.307160@e9g2000prf.googlegroups.com> <1193684775.643350.208230@y27g2000pre.googlegroups.com> Message-ID: <1193717706.876266.78150@v23g2000prn.googlegroups.com> Here is one way to build a 64-bit Python binary on Solaris 10 using SUN's compilers**. This is probably not the recommended procedure but it does create a partial, expected result. Here are the 4 steps I used: 1 - Run ./configure --without-gcc --with-cxx-main=CC --enable-64- bit .... 2 - Edit the generated Makefile and change 3 lines CC = cc -xtarget=opteron -xarch=amd64 CXX = CC -xtarget=opteron -xarch=amd64 MAINCC = CC -xtarget=opteron -xarch=amd64 The -xtarget and -xarch flags must be adjusted for UltraSparc. 3 - Edit python source file ./Include/pyport.h before line 728 (in Python 2.5.1) as follows. Add these 3 lines: #ifndef __GNUC__ /* non-GNU C/C++, like SUN */ # undef LONG_BIT #endif such that LONG_BIT is #define'd next #ifndef LONG_BIT #define LONG_BIT (8 * SIZEOF_LONG) #endif before this error message can occur #if LONG_BIT != 8 * SIZEOF_LONG /* 04-Oct-2000 LONG_BIT is apparently (mis)defined as 64 on some recent * 32-bit platforms using gcc. We try to catch that here at compile-time * rather than waiting for integer multiplication to trigger bogus * overflows. */ #error "LONG_BIT definition appears wrong for platform (bad gcc/ glibc config?)." #endif 4 - Run make and check the resulting Python binary with file ./ python. However, make test still fails and that will require further investigation. /Jean Brouwers **) Sun C/C++ 5.8 2005/10/14 on an Ultra 20 Opteron machine On Oct 29, 12:06 pm, MrJean1 wrote: > Building 64-bit Python is still elusive. I tried various ways to add - > xtarget=opteron -xarch-amd64 to the C/C++ flags but that still fails > to produce a 64-bit build. Changing the Makefile is not sufficient > since that causes compilation errors. > > It looks like the ./configure command must run with those additional > flags. Passing the flags in environment variables defining CC and CXX > only works for CXX. The additional flags do not appear on the C > compiler command lines. > > /Jean Brouwers > > On Oct 28, 11:03 pm, plumb and tree wrote: ..... From kirby.urner at gmail.com Sun Oct 28 09:14:38 2007 From: kirby.urner at gmail.com (kirby urner) Date: Sun, 28 Oct 2007 06:14:38 -0700 Subject: fclient project seeking co-coders In-Reply-To: <1193568557.720305.82380@50g2000hsm.googlegroups.com> References: <1193568557.720305.82380@50g2000hsm.googlegroups.com> Message-ID: Another Urner, that's interesting. Not many of us. Kirby Urner Portland, Oregon USA On 10/28/07, J?rgen Urner wrote: > > Hello all, > > I Just recently registered a project fclient to sourceforge.net > [http://sourceforge.net/projects/fclient]. fclient is intended to > become desktop client for the freenet [freenetproject.org] > network written in python and Qt4. > > fclient is very alpha, in fact only parts of the freenet client > protocol > are curently implementated and loads of work ahead. But I would > appreciate very much finding interested co-coders to take part in the > project. > > Me, I am no professional coder, but an enthusiast with one or the > other year > of python (and Qt) experience. If interested in the project (and > freenet), feel free > to drop a mail to the users mailing list at the project page. > > > Have fun, Juergen > > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ricaraoz at gmail.com Mon Oct 8 10:35:27 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 08 Oct 2007 11:35:27 -0300 Subject: Really basic problem In-Reply-To: <1191836371.296466.137780@22g2000hsm.googlegroups.com> References: <1191836371.296466.137780@22g2000hsm.googlegroups.com> Message-ID: <470A402F.4070108@bigfoot.com> tomamil wrote: > i know this example is stupid and useless, but that's not the answer > to my question. > here it goes: > > status = 0.0 > for i in range(10): > status = status + 0.1 > > if status == 0.1: > print status > elif status == 0.2: > print status > elif status == 0.3: > print status > elif status == 0.4: > print status > elif status == 0.5: > print status > elif status == 0.6: > print status > elif status == 0.7: > print status > elif status == 0.8: > print status > elif status == 0.9: > print status > elif status == 1.0: > print status > > the expected output: > 0.1 > 0.2 > 0.3 > 0.4 > 0.5 > 0.6 > 0.7 > 0.8 > 0.9 > 1.0 > > but it gives me instead: > 0.1 > 0.2 > 0.4 > 0.5 > 0.6 > 0.7 > > why? > > thanks, > > m. > Replace : status = status + 0.1 with : status = round(status + 0.1, 1) From sjmachin at lexicon.net Wed Oct 10 06:48:31 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Oct 2007 20:48:31 +1000 Subject: Mixing Python and C classes in a module In-Reply-To: <1191985376.434309.128620@g4g2000hsf.googlegroups.com> References: <87wstwibfl.fsf@keizer.soze.com> <4866bea60710090802s1ac3fde4vb3a4d17693448383@mail.gmail.com> <1191985376.434309.128620@g4g2000hsf.googlegroups.com> Message-ID: <470cae03@news.eftel.com.au> On 10/10/2007 1:02 PM, timaranz at gmail.com wrote: > > It is easier to do it the other way around. > Create module.py and _module.so and in module.py write: > > from _module.so import * It is even easier to type from _module import * and somewhat more productive, too :-) From joesox at gmail.com Sat Oct 27 12:27:35 2007 From: joesox at gmail.com (JoeSox) Date: Sat, 27 Oct 2007 09:27:35 -0700 Subject: Event for multithread help advice Message-ID: <785694cd0710270927m3934d2deqae2c9c1a14a3cb66@mail.gmail.com> I have two threads going class guiThread(threading.Thread) class mainThread(threading.Thread) Within the guiThread, I have an instance of class GUIFramework(Frame) in this Tkinter instance I have a ListBox. The second thread, mainThread, has an instance of a custom class the will need to send out text or other objects to the gui. What is the best or easiest way to send, let's say text, from mainThread to the guiThread ListBox? Should I use a custom Event class, pubsub, or Queue? This is the way I have things right now (not in its entirety): ----- start.py import threading import thread import time import GUIFramework import myFoo class guiThread(threading.Thread): def __init__(self, threadID, name): self.threadID = threadID self.name = name self.guiFrame = GUIFramework(master=None) threading.Thread.__init__(self) def run(self): print "Starting " + self.name self.guiFrame.mainloop() print "Exiting " + self.name class mainThread(threading.Thread): def __init__(self, threadID, name): self.threadID = threadID self.name = name self.myFoo = myFoo() threading.Thread.__init__(self) def run(self): print "Starting " + self.name self.myFoo.alive() print "Exiting " + self.name def start(): """ Start """ #Create new threads threadgui = guiThread(1, "threadgui") threadmain= carlThread(2, "threadmain") #Start new Threads threadgui.start() threadmain.run() while threadmain.isAlive(): if not threadgui.isAlive(): doExit = 1 pass print "Exiting Main Thread" if __name__ == '__main__': start() ----- I've tried a fews things but I really haven't had any luck. -- Thanks, Joe From dokondr at gmail.com Tue Oct 16 07:20:47 2007 From: dokondr at gmail.com (Dmitri O.Kondratiev) Date: Tue, 16 Oct 2007 15:20:47 +0400 Subject: Newbi Q: What is a rational for strings not being lists in Python? In-Reply-To: <9e95df10710151303s117658a5xde18c577d929f9ae@mail.gmail.com> References: <53396d9e0710150805n6e2cfa53je05d24ec51190aa0@mail.gmail.com> <9e95df10710151303s117658a5xde18c577d929f9ae@mail.gmail.com> Message-ID: <53396d9e0710160420l3055fea5u69cf7bfa1e3ec01d@mail.gmail.com> On 10/16/07, Matt McCredie wrote: [quote] > The example you posted won't work with tuples either because they, > like strings, are also immutable. So, the best way to get the posted > code to work (which is a bad way to go about reversing a string, but I > digress) > [end-quote] I agree, my first example: def reverse1(xs): if xs == []: return xs else: return (reverse1 (xs[1:])) + [xs[0]] is very inefficient. I posted it just to illustrate my question about strings and lists in Python. The cost of reverse1() is proportional to: (N - 1) + (N -2) + ...+1 = N(N - 1) /2, which in turn is ~ square(N), where N is the number of elements in the list. For example, reverse2() demonstrates a better algorithm, with cost proportional to N: def head(xs) : if xs == []: return [] else: return xs[0] def tail(xs) : if xs == []: return [] else: return xs[1:] def addHead (acc, xs): if xs == []: return acc else: return addHead ([head(xs)] + acc, tail(xs)) def reverse2 (xs): if xs == []: return [] else: return addHead([], xs) [quote] > is to cast the input parameter to a list first. The returned > value will always be a list, but you will simply have to convert it > back to the appropriate type when you are done. [end-quote] Casting and writing wrapper classes is not interesting. Life becomes much easier when String is a subtype of List, and when you have polymorphic functions making no difference between String and List. [quote] > What is the purpose if immutability? It allows a value to be hashed. I > don't want to get into a discussion about methods for hashing mutable > types, if you are interested just do a search on the list archives. > Hashing allows for quick comparisons of values, but more importantly > it allows for values to be used as keys for the dict type. This is > very important because, as you will soon find out if you keep learning > the language, all namespaces in python are implemented as dicts. [end-quote] As for me, I am perfectly happy with immutable types, I would rather do without mutable ones. And thanks, everybody, for reminding me that Python is a 'side effect' language, from which by definition follows that it should have mutable lists along with immutable strings. So answer to my question "What is a rational for strings not being lists in Python?" is quite trivial, as Simon B. (simon at brunningonline.net) wrote: "Lists are mutable, strings are not, so so strings can't support all a list's methods." Sorry again for trivial question :(worked too much with Haskell recently and mostly forgot about mutable types , I guess ) ... [quote] So... if you want a mutable string, just cast it to a list, do your > operations and cast it back to a string. > > Incidentally, the proper method for converting a list of characters to > a string is by using the join method on an empty string. > > >>> s = "I am a string" > >>> x = list(s) > >>> x > ['I', ' ', 'a', 'm', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g'] > >>> "".join(x) > 'I am a string' > > > Matt > [end-quote] -- Dmitri O. Kondratiev dokondr at gmail.com http://www.geocities.com/dkondr -------------- next part -------------- An HTML attachment was scrubbed... URL: From sanxiyn at gmail.com Mon Oct 15 09:38:54 2007 From: sanxiyn at gmail.com (Sanghyeon Seo) Date: Mon, 15 Oct 2007 22:38:54 +0900 Subject: [ANN] IronPython Community Edition r7 Message-ID: <5b0248170710150638r7f405bb2l2a32d334e7ad4478@mail.gmail.com> This is the seventh release of IronPython Community Edition (IPCE). Download from SourceForge: http://sourceforge.net/projects/fepy FePy project aims to provide enhancements and add-ons for IronPython. http://fepy.sourceforge.net/ This work was in part supported by Mozilla Corporation. FePy project got a blog! http://fepy.blogspot.com/ FePy blog documents two developments not included in this release. Files under trunk/pyprof/, which tries to implement sys.setprofile with Mono profiler API. (Thanks to Miguel de Icaza and Paolo Molaro for help.) Files under bench/, which benchmarks simple IronPython programs to measure progress of Mono runtime. This release comes with both IronPython 1.1 and IronPython 2.0 Alpha 5. IronPython 1.x is stable on Mono. IronPython 2.x isn't. For example, importing string module will crash runtime for Mono 1.2.5. (But os module works fine, which is much more complex. It's a bit of hit and miss.) This release is built with Mono 1.2.5.1. The minimum Mono version needed to compile and run for IronPython 1.x is 1.2.3. For IronPython 2.x it's 1.2.5. Mono 1.2.5 and 1.2.5.1 are same except for ASP.NET bugfixes. DLR-based languages won't work with Mono versions before 1.2.5. Please check your Mono version before reporting any problems. Changes in this release follow. Contributions are credited in parentheses. IronPython IronPython 2.0 Alpha 5. Libraries dbapi module handles DBNull correctly. (Carsten Haese) pyexpat module handles DTD. (Shozo Arai) Bundles Following modules are now included: decimal, modulefinder, pkgutil, smtplib. pystone benchmark. (It's under Lib/test.) irclib, which works great. Try this example as a sanity test. https://fepy.svn.sourceforge.net/svnroot/fepy/trunk/example/irc_test.py Patches Patches are documented here. http://fepy.sourceforge.net/patches.html New in this release: For 1.x patch-ironpython-option-s For 2.x patch-{325478,328022,333647} # Numbers refer to Mono bugs patch-console patch-cs0177 patch-debug-define patch-initialize-builtins Build system Use NAnt to build IronPython 2.x. Use quilt to manage patches. Patches to build all IronPython 2 Alpha releases. - AssemblyVersion.cs was missing in Alpha 3. (Miguel de Icaza) Include both IronPython 1.x and 2.x, but share the library using site.py. Misc Ms-PL is now included in licenses. -- Seo Sanghyeon From rcdailey at gmail.com Mon Oct 8 16:39:23 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 8 Oct 2007 15:39:23 -0500 Subject: csv module and Unicode In-Reply-To: <496954360710051510u4150742cyf1268444c3760862@mail.gmail.com> References: <496954360710051510u4150742cyf1268444c3760862@mail.gmail.com> Message-ID: <496954360710081339g56254317ye6afd558154a437c@mail.gmail.com> Wow; I guess this is a REAL problem! I would have thought that something as common as Unicode CSV would have been supported by SOMEONE. On 10/5/07, Robert Dailey wrote: > > Hi, > > According to the Python 2.5 documentation, Unicode is not supported > through the CSV module. Is there some third-party CSV module I can use that > has Unicode support? Thanks. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Oct 7 10:47:57 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 07 Oct 2007 14:47:57 -0000 Subject: Override 'and' and 'or' References: <1191765135.493040.176500@d55g2000hsg.googlegroups.com> <4708eb82$0$30379$9b4e6d93@newsspool4.arcor-online.net> <4708ec23$0$30379$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <13ghsctf6ksfaa9@corp.supernews.com> On Sun, 07 Oct 2007 16:24:35 +0200, Wildemar Wildenburger wrote: > Wildemar Wildenburger wrote: >> [whate everyone else wrote :(] >> >> /W > > Dangit! 4th of 4. > Gotta type quicker. That's okay, in two weeks time there will be 139 messages in this thread, it will have devolved into an argument about whether Python's truth- testing semantics are better or worse than whatever Java/Lisp/Haskell/ Ruby does, and *then* somebody will respond to the Original Poster with "customize the __and__ and __or__ methods of your class". Happens every time. -- Steven. From arkanes at gmail.com Mon Oct 22 14:23:19 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 22 Oct 2007 13:23:19 -0500 Subject: Automatic Generation of Python Class Files In-Reply-To: <1193076352.576143.123260@z24g2000prh.googlegroups.com> References: <1193073156.493809.184110@z24g2000prh.googlegroups.com> <1193076352.576143.123260@z24g2000prh.googlegroups.com> Message-ID: <4866bea60710221123g4170a722vd70af3c97dbc0681@mail.gmail.com> On 10/22/07, Sunburned Surveyor wrote: > On Oct 22, 10:26 am, "Chris Mellon" wrote: > > On 10/22/07, Sunburned Surveyor wrote: > > > > > > > > > > > > > I was thinking of a way I could make writing Python Class Files a > > > little less painful. I was considering a Ptyhon script that read a > > > file with a list of property names and method names and then generated > > > a skeleton class file. > > > > > I was even thinking of automatically generating the shell for doc > > > strings and epydoc tags. > > > > > Is there existing scripts that do something like this? If not, I will > > > try to come up with something. If I'm sucessful I'll release the code > > > under the GPL and will report back to the list. > > > > > However, I thought I would check here first so that I don't reinvent > > > the wheel. > > > > > Thanks, > > > > > Scott Huey > > > > I can't think of a single reason why you would ever want to do this, > > since your "list of method and property names" would be just as > > verbose as just typing the actual python code. > > > > Auto generated documentation stubs are considered harmful because they > > take the place of real documentation.- Hide quoted text - > > > > - Show quoted text - > > Chris, > > You wrote: " can't think of a single reason why you would ever want to > do this, > since your "list of method and property names" would be just as > verbose as just typing the actual python code." > > I don't think I understand how this would be the same amount of > typing. Consider the following example that would generate a Monster > class file from an input text file (I only did one property and method > in generated class file.): > > Contents of input text file: > > [Name] > Fire Breathing Dragon > > [Properties] > Strength > Scariness > Endurance > > [Methods] > eatMaiden argMaiden > fightKnight argKnight > > Generated Python Class File: > > def class FireBreathingDragon: > > def getStrength(self): > """ > Docstring goes here. > > @return > @rtype > """ > return self.strength > > def setStrength(self, argStrength): > """ > Docstring goes here. > > @param argStrength > @ptype > """ > return self.strength > > def eatMaiden(self, argMaiden): > """ > Docstring goes here. > > @param argMaiden > @ptype > """ > Your getters/setters are useless (Python isn't Java) and so are the docstrings, because you have to write them over again anyway. Removing them results in 3 lines of code, quite a bit shorter than your input file, and it doesn't have any of the quite well known issues with this sort of boiler plate code generation. From larry.bates at websafe.com Wed Oct 10 08:26:01 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 10 Oct 2007 07:26:01 -0500 Subject: Exceptions: Logging TB and local variables? In-Reply-To: <1191989030.598822.283420@50g2000hsm.googlegroups.com> References: <1191989030.598822.283420@50g2000hsm.googlegroups.com> Message-ID: <470CC4D9.3010401@websafe.com> allen.fowler wrote: > Hi, > > My code looks like this: > > for item in bigset: > self.__sub1(item) > self.__sub2(item) > self.__sub3(item) > > # the subX functions, in turn, use various 3rd party modules. > > > Now, I would like to do this: > > for item in bigset: > try: > self.__sub1(item) > self.__sub2(item) > self.__sub3(item) > except StandardError: > # Log error and continue to next item in set. > log_error_to_file() > > > In the error log, I would like to record various local variables that > existed in subX at the time the Exception was thrown... (even though > the actuall exception may have been thrown from deep inside some 3rd > party module that subX called) > > How can I do this? > > Thank you, > Allen > Two possibilieies: You will need to determine ALL the exceptions that the 3rd party party modules can raise. If they are custom exceptions you will need to import them into your application from their modules. example: say that 3rd party modules raise TransientError, IOError, and ValueError exceptions. TransientError is a custom exception from module foo from foo import TransientError for item in bigset: try: self.__sub1(item) self.__sub2(item) self.__sub3(item) except (TransientError, IOError, ValueError): # Log error and continue to next item in set. log_error_to_file() 2) Hook exception traceback handler def myTraceBackHandler(type, value, tb): global # # This function allows the user to redefine what happens if the program # aborts due to an uncaught exception. # This provides a way to get a "partial" session log if the program # aborts"as well as some information about what caused the program to # abort. # import traceback # # Get traceback lines # tblines=traceback.format_exception(type, value, tb) # # Write some lines to log # log_error_to_file() # # Always write the exceptions to screen # sys.exit('\n'.join(tblines)) Hope this helps. -Larry From Scott.Daniels at Acm.Org Wed Oct 24 23:45:57 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 24 Oct 2007 20:45:57 -0700 Subject: Test for a unicode string In-Reply-To: <1193252964.441263.179350@e9g2000prf.googlegroups.com> References: <1193252964.441263.179350@e9g2000prf.googlegroups.com> Message-ID: <13i04776fvf559@corp.supernews.com> goldtech wrote: > I have a regular expression test in a script. When a unicode character > get tested in the regex it gives an error: > > UnicodeError: ASCII decoding error: ordinal not in range(128) > > Question: Is there a way to test a string for unicode chars (ie. test > if a string will throw the error cited above). How about: if ord(max(thestring)) >= 128: print 'whatever you want' -Scott David Daniels Scott.Daniels at Acm.Org From stefan.behnel-n05pAM at web.de Tue Oct 23 02:38:17 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 23 Oct 2007 08:38:17 +0200 Subject: ignoring chinese characters parsing xml file In-Reply-To: References: <5o4evvFktnthU5@mid.uni-berlin.de> Message-ID: <471D96D9.6070107@web.de> Fabian L?pez wrote: > Thanks Mark, the code is like this. The attrib name is the problem: > > from lxml import etree > > context = etree.iterparse("file.xml") > for action, elem in context: > if elem.tag == "weblog": > print action, elem.tag , elem.attrib["name"],elem.attrib["url"], The problem is the print statement. Looks like your terminal encoding (that Python needs to encode the unicode string to) can't handle these unicode characters. Stefan From stefan.arentz at gmail.com Tue Oct 9 03:28:16 2007 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 09 Oct 2007 09:28:16 +0200 Subject: Accessing 'Package Data' Message-ID: <87bqb8wxv3.fsf@keizer.soze.com> At http://docs.python.org/dist/node12.html it is described how to add package data to a module. This was pretty easy to do, but now how do I access this data from my module? Is there an API to load a 'package resource' ala Java's classloader? S. From arkanes at gmail.com Tue Oct 9 11:00:43 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 9 Oct 2007 10:00:43 -0500 Subject: List loops In-Reply-To: References: Message-ID: <4866bea60710090800u5c871c04ldd964fcac36ecc63@mail.gmail.com> On 10/9/07, Tommy Grav wrote: > Hi everyone, > > I have a list of objects where I have want to do two loops. > I want to loop over the list and inside this loop, work on all > the elements of the list after the one being handled in the outer > loop. I can of course do this with indexes: > > >>> alist = range(3) > >>> for i in xrange(len(alist)): > ... for j in xrange(i+1,len(alist)): > ... print i,j,alist[i],alist[j] > ... > 0 1 0 1 > 0 2 0 2 > 1 2 1 2 > >>> > > > Is there a way to do this without using indexes? > >>> for idx, i in enumerate(alist): ... for jdx, j in enumerate(range(1,4)): ... print idx, jdx, i, j ... 0 0 0 1 0 1 0 2 0 2 0 3 1 0 1 1 1 1 1 2 1 2 1 3 2 0 2 1 2 1 2 2 2 2 2 3 >>> From amdescombes at spad.eu Mon Oct 15 05:31:59 2007 From: amdescombes at spad.eu (amdescombes) Date: Mon, 15 Oct 2007 11:31:59 +0200 Subject: Memory Problems in Windows 2003 Server In-Reply-To: <6b63h3p842g6ggafqbc5d4f8n4o48ramdm@4ax.com> References: <470f7857$0$27795$426a74cc@news.free.fr> <4710a5ad$0$26731$426a74cc@news.free.fr> <6b63h3p842g6ggafqbc5d4f8n4o48ramdm@4ax.com> Message-ID: <4713338b$0$20269$426a74cc@news.free.fr> Yes, I think that might be the issue, perhaps I could implement the solution using several dictionaries instead of just one. Are there any classes that implement disk based dictionaries? Thanks, Andre > > I don't know whether Python dictionaries must live in a contiguous piece of > memory, but if so, that could be the issue. The system DLLs in Server 2003 > have been "rebased" in such a way that they chop up the virtual address > space more than XP. Even though there is more virtual memory available, it > is fragmented. From beema.shafreen at gmail.com Mon Oct 29 12:20:51 2007 From: beema.shafreen at gmail.com (Beema shafreen) Date: Mon, 29 Oct 2007 21:50:51 +0530 Subject: two files into an alternate list Message-ID: hi everybody , i have a file : file 1: 1 2 3 4 5 6 file2: a b c d e f how do i make the two files into list like this = [1,a,2,b,3,c,4,d,5,e,6,f] regards shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Oct 24 00:47:47 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Oct 2007 01:47:47 -0300 Subject: How to find out which functions exist? References: <1193173804.937071.278110@e9g2000prf.googlegroups.com> Message-ID: En Tue, 23 Oct 2007 18:10:04 -0300, mrstephengross escribi?: > Let's say I have a python file with a base class, and a few derived > classes: > > class Base: > pass > > class Derived1(Base): > pass > > class Derived2(Base): > pass > > Is there a way I can find out the classes that have been derived from > Base? If Base were a new-style class, you could use Base.__subclasses__() -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Wed Oct 24 20:54:04 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 25 Oct 2007 00:54:04 -0000 Subject: list (range) syntax References: <1193268500.077940.182790@y27g2000pre.googlegroups.com> Message-ID: <13hvq9cj6k9hf18@corp.supernews.com> On Wed, 24 Oct 2007 16:28:20 -0700, mensanator at aol.com wrote: > On Oct 24, 5:44 pm, Michal Bozon wrote: >> many Python newcomers are confused why range(10), does not include 10. > > How can they be confused? Because in common English, counting starts at 1 and ranges normally include both end points (that is, it is a "closed" interval). If you say "I'll be away from the 4th to the 7th" and then turn up on the 7th, nearly everyone will wonder why you're back a day early. > Does base 10 have a digit ten? > Does base 2 have a digit two? > Does base 16 have a digit sixteen? > > Haven't you stopped counting on your fingers when you leave grade > school? range(N) is not designed to return the digits used in base N strings, and any connection is weak (what base does range(3, 25, 4) correspond to?). What little correspondence there is is an accidental coincidence of how we write numbers, not a fundamental fact about half-open intervals like range(). Having said that, and regardless of common English usage, using half-open intervals almost always leads to simpler programming and fewer errors. Creating syntax support for beginners to make extra off-by-one bugs is a terrible idea, no matter how seductive it seems for newbies. I know Ruby has (to my mind confusing!) support for both closed and half-open intervals, but I wonder how useful it is in practice? Ruby expression => Python equivalent 1..5 => range(1, 6) 1...5 => range(1, 5) -- Steven. From http Fri Oct 12 23:13:58 2007 From: http (Paul Rubin) Date: 12 Oct 2007 20:13:58 -0700 Subject: The fundamental concept of continuations References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> <85zlyrutux.fsf@lola.goethe.zz> <85lka8p2h4.fsf@lola.goethe.zz> Message-ID: <7xy7e7yadl.fsf@ruckus.brouhaha.com> David Kastrup writes: > There is a Scheme implementation (I keep forgetting the name) which > actually does both: it actually uses the call stack but never returns, > and the garbage collection includes the stack. That would be Chicken Scheme. http://en.wikipedia.org/wiki/Chicken_(Scheme_implementation) From carsten at uniqsys.com Wed Oct 10 19:40:13 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 10 Oct 2007 19:40:13 -0400 Subject: How to "dereference" an iterator? In-Reply-To: <496954360710101601s5cc774dby16f01ba532ef096e@mail.gmail.com> References: <496954360710101601s5cc774dby16f01ba532ef096e@mail.gmail.com> Message-ID: <1192059613.3385.18.camel@localhost.localdomain> On Wed, 2007-10-10 at 18:01 -0500, Robert Dailey wrote: > Hi, > > Suppose I wanted to manually iterate over a container, for example: > > mylist = [1,2,3,4,5,6] > > it = iter(mylist) > while True: > print it > it.next() > > In the example above, the print doesn't print the VALUE that the > iterator currently represents, it prints the iterator itself. How can > I get the value 'it' represents so I can either modify that value or > print it? Thanks. I have the feeling that you're not telling us the actual problem you're trying to solve. Python iterators do not, in general, have a notion of a "current" value. The only have a notion of a next value, which is returned by next(). If you need to use that value multiple times, you need to store it somewhere. If you really must use a while loop, it'll have to look something like this (add handling of StopIteration to taste): while True: current = it.next() print current HTH, -- Carsten Haese http://informixdb.sourceforge.net From sakradevanamindra at gmail.com Mon Oct 15 23:55:45 2007 From: sakradevanamindra at gmail.com (Shoryuken) Date: Mon, 15 Oct 2007 20:55:45 -0700 Subject: use lines as argument to a command In-Reply-To: References: <1192420069.166779.55230@y27g2000pre.googlegroups.com> Message-ID: <1192506945.018694.289000@t8g2000prg.googlegroups.com> > I guess that you want to loop over a file and for each line in the > file you want to call some > external program with the line as the argument. > > Have a look at subprocess module > http://docs.python.org/lib/module-subprocess.html > > If there is some else that you meant, please specify . > > Cheers, > > -- > -- > Amit Khemka Thanks alot, its working now. But I have another question (sorry I'm so noob), how can I redirect a command's output to a file (just like executing a linux command "dmesg>>stat.txt")? From chris.lyon at spritenote.co.uk Wed Oct 31 12:24:56 2007 From: chris.lyon at spritenote.co.uk (wyleu) Date: Wed, 31 Oct 2007 09:24:56 -0700 Subject: _tkinter installation in python 2.5 on mandriva with a default 2.4 In-Reply-To: <47288E4D.6010301@v.loewis.de> References: <1193775761.764547.148730@i38g2000prf.googlegroups.com> <4727b1e6$0$13390$9b622d9e@news.freenet.de> <1193813238.978699.154830@57g2000hsv.googlegroups.com> <47288E4D.6010301@v.loewis.de> Message-ID: <1193847896.441329.315560@o80g2000hse.googlegroups.com> > So where it tk.h located? tk.h is now in just about every directory called include that could in anyway be connected with this and indeed it does appear in the make file printout: /usr/bin/install -c -m 644 ./Include/sysmodule.h /usr/local/include/ python2.5 /usr/bin/install -c -m 644 ./Include/timefuncs.h /usr/local/include/ python2.5 /usr/bin/install -c -m 644 ./Include/tk.h /usr/local/include/python2.5 /usr/bin/install -c -m 644 ./Include/token.h /usr/local/include/ python2.5 /usr/bin/install -c -m 644 ./Include/traceback.h /usr/local/include/ python2.5 however it still generates the same error message, I've tried debugging setup.py in the distribution directory with idle ( python2.4.3 versions ) but not surprisingly that doesn't do anything too impressive, as you would expect. Short of stuffing lots of print statements in there to actual try and locate the file names it's failing on I'm at a loss to see where to go next. From bignose+hates-spam at benfinney.id.au Tue Oct 16 18:49:12 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 Oct 2007 08:49:12 +1000 Subject: why doesn't have this list a "reply-to" ? References: <471530E3.9090602@gmail.com> Message-ID: <87ejfu3cbb.fsf@benfinney.id.au> Robert Kern writes: > It's not universal. Many people consider it harmful. Google > "reply-to considered harmful" for a variety of opinions, for and > against. The arguments in support of munging have been defeated, since 2001. Munging the "Reply-To" field is in violation of standards, and completely unnecessary. Any remaining lack is for the mail user agent provider to fix, in accordance with standards. -- \ "I wrote a song, but I can't read music so I don't know what it | `\ is. Every once in a while I'll be listening to the radio and I | _o__) say, 'I think I might have written that.'" -- Steven Wright | Ben Finney From raims at dot.com Sat Oct 27 20:37:01 2007 From: raims at dot.com (Lawrence Oluyede) Date: Sun, 28 Oct 2007 02:37:01 +0200 Subject: A lib to build query string... References: Message-ID: <1i6o9uy.b021j815ll3zxN%raims@dot.com> durumdara at gmail.com wrote: > Is anybody knows about a function that can build query string from > parameter list? I very need that! urllib.urlencode? -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From chris.monsanto at gmail.com Sun Oct 21 19:49:13 2007 From: chris.monsanto at gmail.com (chris.monsanto at gmail.com) Date: Sun, 21 Oct 2007 16:49:13 -0700 Subject: Problem with regexp and text injection In-Reply-To: <1193005376.777299.154860@z24g2000prh.googlegroups.com> References: <1193005376.777299.154860@z24g2000prh.googlegroups.com> Message-ID: <1193010553.039899.318990@q3g2000prf.googlegroups.com> On Oct 21, 6:22 pm, Panagiotis Atmatzidis wrote: > Hello, > > I want to create a script in python that search for .html files in the > predefined directory and subdirectories. Then it checks if a specific > snippet of code exists in the .html file, if not it injects/adds the > code right below the string otherwise bypasses the file. > > I wrote the first part, I managed to write search function and I'm > trying to find my way out of regular expressions reading the manuals. > However I don't know what kind of function and module to use in order > to write this function, re.search(), re.string() or re.match() or > maybe re.compile() ? > > I have not much programming experience. Programming is not my cup of > tea. > > Can someone help by pointing me to a sample code with comments if > possible. > > Regards, > > atma import glob glob.glob("*.html") # returns a list of all filenames you are looking for --------- import re m = re.search(regular_expression_testing_for_string_of_code, string_with_contents_of_page) # checks if your snippet is there if m is None: new_contents = re.sub(r"(?xis) ", lambda m: m.group() + your_snippet_of_code, string_with_contents_of_page) # Add the snippet to the body. I use a function as the replacement in case your snippet has backreferences in it for some reason. If it doesn't, feel free to use r"\0" + snippet_of_code. From theller at ctypes.org Fri Oct 5 07:54:09 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 05 Oct 2007 13:54:09 +0200 Subject: Where's the Starship's crew? In-Reply-To: <20071005083806.61D811E4002@bag.python.org> References: <20071005083806.61D811E4002@bag.python.org> Message-ID: Dick Moores schrieb: > > > I didn't check on all of them, but the only one I found was Mark > Hammond . > > Dick Moores > There are more. Think of it as a game you have to solve. From bj_666 at gmx.net Thu Oct 11 09:46:12 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Oct 2007 13:46:12 GMT Subject: Declarative properties References: <1192103298.065386.243670@o3g2000hsb.googlegroups.com> <5n6j5nFghr61U4@mid.uni-berlin.de> <1192107893.492826.233730@d55g2000hsg.googlegroups.com> Message-ID: <5n6np4Fghr61U6@mid.uni-berlin.de> On Thu, 11 Oct 2007 13:04:53 +0000, Artur Siekielski wrote: > On Oct 11, 2:27 pm, Marc 'BlackJack' Rintsch wrote: >> But why? Default getters and setters are unnecessary and if you need >> something other than the default you need to write it anyway more >> explicitly. > > I see some problems with your approach: > > 1. If I use instance field 'name' which is accessed directly by other > classes, > and later I decide to implement nonstandard getter, I must refactor > 'Person' class > and in some places change 'name' to '_name' (assuming this is now the > field's name). > The problem is that I cannot automatically change 'name' to '_name' > everywhere, because > in some places I want public property value (eg. validated and > formatted), and in other > places raw property value. So what? Otherwise you carry *always* the baggage of a public property and a private attribute whether you need this or not. At least for me it would be unnecessary in most cases. > 2. Properties define (a part of) public interface of a class. When > using fields for public > access, you must tell this explicitly in documentation, or use name > convention. And public > fields definition is mixed with private fields, which doesn't happen > when using properties. Attributes are public unless you start the name with an underscore which is by convention a warning to not use that attribute unless you know what you are doing. With properties all over the place you use that convention anyway because the "real" value for `name` is bound as `_name`. So you clutter your API with two attributes for non-method-attributes. And a property is not automatically part of the public API, just if the name does not start with an underscore. > 3. Using properties as first-class objects gives possibilities to use > declarative approaches for constructing them. No idea what you mean here. Everything in Python is an object. Ciao, Marc 'BlackJack' Rintsch From Graham.Dumpleton at gmail.com Thu Oct 18 19:16:26 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 18 Oct 2007 23:16:26 -0000 Subject: Is there a way to tell if a script has been run by Pythonw.exe instead of Python.exe? In-Reply-To: <1192744576.899687.93650@k35g2000prh.googlegroups.com> References: <1192744576.899687.93650@k35g2000prh.googlegroups.com> Message-ID: <1192749386.683238.216390@t8g2000prg.googlegroups.com> On Oct 19, 7:56 am, Metalone wrote: > In particular I want to know how to tell if reading and writing to the > console can occur. > Something like > sys.isConsolePresent() Have you tried: sys.stdin.isatty() sys.stdout.isatty() Graham From martin at marcher.name Mon Oct 29 05:56:45 2007 From: martin at marcher.name (Martin Marcher) Date: Mon, 29 Oct 2007 10:56:45 +0100 Subject: sharing vars with different functions In-Reply-To: <5fa6c12e0710290211j1eb4fef0n81d8b8be94500789@mail.gmail.com> References: <1193648594.380143.153450@o38g2000hse.googlegroups.com> <5fa6c12e0710290211j1eb4fef0n81d8b8be94500789@mail.gmail.com> Message-ID: <5fa6c12e0710290256ocae982bi97f94ca4a5cffe40@mail.gmail.com> I hate gmail, always forgetting to set the right recipient... ---------- Forwarded message ---------- From: Martin Marcher Date: 29.10.2007 10:11 Subject: Re: sharing vars with different functions To: "scripteaze at gmail.com" 2007/10/29, scripteaze at gmail.com : > Im tryin to call a var thats sitting in a function, example: > > i guess im not graspng the whole global or local var topic.. does this help? >>> class Foo(object): ... somevar = ["a", "b"] ... def __init__(self): ... self.another_var = ["c", "d"] ... >>> Foo.somevar ['a', 'b'] >>> f = Foo() >>> f.somevar ['a', 'b'] >>> f.another_var ['c', 'd'] >>> Foo.somevar = "New Value" >>> f.somevar 'New Value' >>> Foo.another_var Traceback (most recent call last): File "", line 1, in AttributeError: type object 'Foo' has no attribute 'another_var' -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From martin at v.loewis.de Sun Oct 21 13:06:25 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Oct 2007 19:06:25 +0200 Subject: C++ version of the C Python API? In-Reply-To: References: Message-ID: <471B8711.1020509@v.loewis.de> > Is there a C++ version of the C Python API packaged with python 2.5? Stargaming has already mentioned the fine points; the first answer is: yes, the API packaged python 2.5 can be used with C++. It is a C++ version of the same API as it adds proper extern "C" declarations around all prototypes, and it was specifically cleaned up (ten years ago) to work with C++. This API does not make use of many of the C++ features, including classes, templates, or overloading. Regards, Martin From Frank.Aune at broadpark.no Fri Oct 19 07:01:30 2007 From: Frank.Aune at broadpark.no (Frank Aune) Date: Fri, 19 Oct 2007 13:01:30 +0200 Subject: ConfigParser preserving file ordering In-Reply-To: References: <200710190123.39177.Frank.Aune@broadpark.no> Message-ID: <200710191301.30573.Frank.Aune@broadpark.no> On Friday 19 October 2007 03:42:16 Joshua J. Kugler wrote: > > Have you taken a look at ConfigObj? > > http://www.voidspace.org.uk/python/configobj.html > Yes, but as I said I need functionality present in the standard-library, so sub-classing ConfigParser is the last option really. I was hoping preserve ordering for ConfigParser would find its way into a release soon. -Frank From edreamleo at charter.net Tue Oct 23 12:10:29 2007 From: edreamleo at charter.net (Edward K Ream) Date: Tue, 23 Oct 2007 11:10:29 -0500 Subject: Leo 4.4.4 beta 3 released Message-ID: Leo 4.4.4 beta 3 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo 4.4.4 contains many important features originally planned for later releases. It's been a good month :-) 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.4.4: ---------------------------- - The Great Graph Aha (tm): simple scripts allow Leo outlines to represent arbitrary directed graphs. There is no need for a separate 'graph world'. The graphed.py plugin is a direct result of this Aha. The graphed.py plugin allows you to create general graphs from Leo outlines. - @menus trees in settings files create all of Leo's menus. It is now dead easy to make Leo's menus look the way you want. - @buttons trees in settings files create common @button nodes created in all Leo outlines. - @auto nodes eliminate sentinels in derived files, thereby allowing people to collaborate using Leo more easily. - New commands for resolving cvs conflicts. - A threading_colorizer plugin replaces the __jEdit_colorizer__ plugin. This plugin features much better performance and a new, elegant algorithm. - Leo is now compatible with jython. - The usual assortment of bug fixes and other minor improvements. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ 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 jzgoda at o2.usun.pl Mon Oct 22 06:46:03 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 22 Oct 2007 12:46:03 +0200 Subject: calling a function from string In-Reply-To: References: <1193043242.235837.86590@e34g2000pro.googlegroups.com> Message-ID: Trent Nelson napisa?(a): >> i have a function that I could like to call, but to make it more >> dynamic I am constructing a string first that could equivalent to the >> name of the function I wish to call. how could I do that? the string >> could might include name of the module. >> >> for example >> >> a_string = 'datetime.' + 'today()' >> >> how could I call a_string as function? > > Use 'eval' in one of the following fashions: > > a_string_1 = 'datetime.' + 'today' > a_string_2 = 'datetime.' + 'today()' > > eval(a_string_1)() > eval(a_string_2) Do not use eval(). Not only it's deprecated, it's also unsafe. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From grante at visi.com Fri Oct 12 16:48:51 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 12 Oct 2007 20:48:51 -0000 Subject: test if email References: Message-ID: <13gvndj3ebgfh98@corp.supernews.com> On 2007-10-12, brad wrote: > Florian Lindner wrote: >> Hello, >> is there a function in the Python stdlib to test if a string is a valid >> email address? > > Nope, most any string with an @ in it could be a valid email addy. Send > a message to the addy, if it doesn't bounce, then it's valid. Just because it doesn't bounce, that doesn't mean it's "valid". Some servers don't bounce e-mail to invalid addresses, they just drop them into the bit bucket in an effort to prevent spammers from harvesting valid e-mail addresses using dictionary attacks. If you send an e-mail to an address and you get a response, then it's valid. -- Grant Edwards grante Yow! BARRY ... That was at the most HEART-WARMING visi.com rendition of "I DID IT MY WAY" I've ever heard!! From adurdin at gmail.com Thu Oct 18 08:47:31 2007 From: adurdin at gmail.com (Andrew Durdin) Date: Thu, 18 Oct 2007 13:47:31 +0100 Subject: Inheriting automatic attributes initializer considered harmful? In-Reply-To: <1i64bxc.7f41mi1tsdr45N%aleax@mac.com> References: <1i64bxc.7f41mi1tsdr45N%aleax@mac.com> Message-ID: <59e9fd3a0710180547y47319f43n6cae0bede5f58a66@mail.gmail.com> On 10/17/07, Alex Martelli wrote: > > fake_str is not called, because special-method lookup occurs on the > TYPE, *NOT* on the instance. So it does; I'd forgotten that. I need to remember to actually check that the code does what I think it does before posting it on c.l.p :-| Andrew From nachogomez at gmail.com Tue Oct 23 10:35:07 2007 From: nachogomez at gmail.com (=?UTF-8?Q?Ra=C3=BAl_G=C3=B3mez_C.?=) Date: Tue, 23 Oct 2007 10:35:07 -0400 Subject: Bidirectional communication over unix socket (named pipe) In-Reply-To: <684b0a740710172159v4da8cc4fi813c53d3bfd7ee1@mail.gmail.com> References: <684b0a740710171411t2c30822ew2309254f39b53898@mail.gmail.com> <684b0a740710171420k72c27080mb5402d37d5a81a9c@mail.gmail.com> <684b0a740710172143o4ddd60fn15da73991f76130c@mail.gmail.com> <684b0a740710172159v4da8cc4fi813c53d3bfd7ee1@mail.gmail.com> Message-ID: <684b0a740710230735w25fc3d1o94592fe8d2be2d60@mail.gmail.com> Hi list, I've been looking around and I found a very interesting solution to this problem, but instead of using a file for communication the author (Eduardo Fleury) uses a reference to the abstract namespace, chek it out... http://blog.eduardofleury.com/archives/2007/09/13/ Raul -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Tue Oct 30 03:58:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Oct 2007 07:58:38 GMT Subject: A Python 3000 Question References: <1193712614.592262.114790@e34g2000pro.googlegroups.com> Message-ID: <5oo6heFliu6sU2@mid.uni-berlin.de> On Mon, 29 Oct 2007 19:50:14 -0700, George Sakkis wrote: > On Oct 29, 5:49 pm, "Terry Reedy" wrote: > >> | why not a_string.len()? >> >> You are free to bypass builtins and call methods directly if you like: >> a_string.__len__(). >> >> But consider rewriting the following: >> >> def table(func, seq): >> return zip(seq, map(func,seq)) >> >> table(len, ('', (), [])) > > table(lambda x:x.__len__(), ('',[],())) > > What was the point again ? Beautiful is better than ugly!? ;-) Ciao, Marc 'BlackJack' Rintsch From robert.kern at gmail.com Sun Oct 28 19:47:55 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 28 Oct 2007 18:47:55 -0500 Subject: Pari Python In-Reply-To: References: <1193593529.388263.211930@z9g2000hsf.googlegroups.com> Message-ID: Anton Mellit wrote: >> Have you looked at SAGE at all? They already have wrappers for Pari. > > Well :) I expected that question. I tried. But the distribution for > windows is so big :( (2GB) and I could not build it on cygwin, where > it is also pretty big. And I so much like pari - it is so light and > simple and still can do almost everything. So my idea is to make > simple module for python so that you don't need to install 2GB program > with 2000 functions where it is difficult to find the one you need, > but just type 'import pari', and then help(pari), and then find a > function like 'ellinit' and create an elliptic curve, or type some > polynomial and factor, or expand some function into power series, or > integrate numerically... > > I heard from some people that SAGE is good but i somehow don't > appreciate the approach. > >> I don't recommend continuing to modify core parts of Python just for your >> module. It means that you will break other Python modules. If you can't use >> other Python modules with your module, what's the point of using Python at all? > > Of course you don't have to replace ** with ^ or making that hack with > division. The module would work with or without these changes. But I > think every mathematician agrees that x**2 is really ugly. So? There is no reason to make alterations to the core to achieve what you want. You just need to parse your almost-Python code yourself before executing it. That's what SAGE does. You really should take a closer look at it. It is possible to take just part of SAGE and not install the whole thing. -- 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 trekker182 at comcast.net Mon Oct 22 18:17:56 2007 From: trekker182 at comcast.net (Shawn Minisall) Date: Mon, 22 Oct 2007 18:17:56 -0400 Subject: for loop Message-ID: <471D2194.7030607@comcast.net> #Intro print "*********************************************" print "WELCOME TO THE POPULATION GROWTH CALCULATOR" print "*********************************************" print "This program will predict the size of a population of organisms." print print organisms=input("Please enter the starting number of organisms: ") increase=input("Please enter the average daily population increase as a percentage (20% = .20): ") days=input("Please enter the number of days that they will multiply: ") print " Day Population" print "----------------------------------------------------------" for p in range (days): population = organisms * population * increase print days, print "\t\t\t\t",population I'm having problems with my for loop here to calculate estimated population output to a table. Instead of knowing how much I want to loop it, the loop index is going to be whatever number of days the user enters. When I run my program, it asks the 3 questions above but then just dead stops at a prompt which leads me to believe there's something wrong with my loop. I have the exact same setup in another program, but the loop index has a specific value. I tried (0,days), (1,days) ect. and I don't think for loops need accumulators, I've tried it with one anyways and it still stops. Any idea's? thx From deets at nospam.web.de Thu Oct 25 02:44:20 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Oct 2007 08:44:20 +0200 Subject: about functions question In-Reply-To: <1193293696.450188.108330@q3g2000prf.googlegroups.com> References: <1193293696.450188.108330@q3g2000prf.googlegroups.com> Message-ID: <5oasakFm35phU1@mid.uni-berlin.de> NoName schrieb: > I try it: > > def b(): > ... > a() > ... > > def a(): > ... > b() > ... > > b() > it's not work. It works. def a(): print "a" b() def b(): print "b" print a # not calling! b() But if you really call a in b, you create an endless loop. In all programming languages, btw. > Is it possible pre-define function like in c++ No. > or place functions code > after main block? Yes. From russandheather at gmail.com Wed Oct 3 10:32:41 2007 From: russandheather at gmail.com (Russell Warren) Date: Wed, 03 Oct 2007 14:32:41 -0000 Subject: logging module and trailing newlines In-Reply-To: References: <1191362837.501929.127520@22g2000hsm.googlegroups.com> Message-ID: <1191421961.911729.101520@w3g2000hsg.googlegroups.com> Both are very good responses... thanks! I had forgotten the ease of "monkey-patching" in python and the Stream class is certainly cleaner than the way I had been doing it. On Oct 3, 3:15 am, Peter Otten <__pete... at web.de> wrote: > Russell Warren wrote: > > All I'm after is the ability to log things like... > > > Compiling 'shrubbery.c'... [DONE] > > > where the "[DONE]" was added later in time than the "Compiling...", and > > the output goes to both stdout and to a log file. ie: I want to tee my > > print statements and keep the ability to skip the trailing newline. I had > > rolled my own primitive version than decided to try the logging module for > > kicks. > > > Anyone have a suggestion on how to get logging to work like this? Or know > > of a way to tee in Windows without forcing other users to install a tee > > package? > > (1) Logging > > If you are too lazy to subclass you can monkey-patch: > > >>> import logging > >>> def emit(self, record): > > ... msg = self.format(record) > ... fs = "%s" if getattr(record, "continued", False) else "%s\n" > ... self.stream.write(fs % msg) > ... self.flush() > ...>>> logging.StreamHandler.emit = emit > >>> continued = dict(continued=True) > >>> logging.error("Compiling... ", extra=continued); logging.error("[Done]") > > ERROR:root:Compiling... ERROR:root:[Done] > > (2) Teeing > > "Primitive", but should work: > > >>> class Stream(object): > > ... def __init__(self, *streams): > ... self.streams = streams > ... def write(self, s): > ... for stream in self.streams: > ... stream.write(s) > ... def flush(self): > ... for stream in self.streams: > ... stream.flush() > ...>>> import sys > >>> stream = Stream(sys.stdout, sys.stderr) > >>> print >> stream, "Compiling...", > > Compiling...Compiling...>>> > > I'd probably go with the latter. > > Peter From thomas.weholt at gmail.com Tue Oct 9 08:22:29 2007 From: thomas.weholt at gmail.com (Thomas W) Date: Tue, 09 Oct 2007 12:22:29 -0000 Subject: Virtual filesystem in python ( Fuse or WebDav ? ) Message-ID: <1191932549.616430.285240@22g2000hsm.googlegroups.com> I want to create a virtual filesystem based on a relational database. It might run as a server on a different machine, but it has to be available like a normal filesystem, either shared using SAMBA or windows filesharing or thru something else like WebDav. The idea is that I scan a local filesystem and then create relations between those files stored in a relational database, eg. a create a group called family, add a bunch of files related to my family in that virtual group/folder. When the user accesses the virtual filesystem and types ls or dir the result is a list of groups, in my case ., .. and family. The user types "cd family" and dir/ls in that virtual folder will show all files in that group. How can this be done? I've looked at dav, especially mod_dav and fuse. I want to be able to access the files ( and even add files, like if I copy a file into the family-folder, a relation in the relational database will be created, but the newly added file itself might be stored some other place on the filesystem, based on extension or perhaps EXIF-info if it's an image being added ) using standard filesystem tools, like explorer on win32 or the shell on linux. I don't think I can use WebDav directly, because I want to control what happens if somebody copies a file into a virtual folder, but I don't know much about webdav so I might be wrong. Any hint or clue would be appreciated. From lasses_weil at klapptsowieso.net Wed Oct 3 16:21:48 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Wed, 03 Oct 2007 22:21:48 +0200 Subject: Class design question In-Reply-To: References: <1191436021.775375.324010@r29g2000hsg.googlegroups.com> <1191437225.918592.193010@o80g2000hse.googlegroups.com> Message-ID: <4703f9dc$0$30375$9b4e6d93@newsspool4.arcor-online.net> Adam Lanier wrote: >> class Foo(object): >> def __init__(self, *args): >> self.params = [arg if isinstance(arg, Bar) else Bar(arg) for >> arg in args] >> > > Interesting, I'm not familiar with this idiom... > > These are two idioms actually: 1. a "list comprehension": >>> newlist = [return_something(item) for item in some_iterable] 2. where return_something(item) is a "conditional assignment": >>> result = a if condition_is_true else b /W From facundobatista at gmail.com Tue Oct 23 16:44:27 2007 From: facundobatista at gmail.com (Facundo Batista) Date: Tue, 23 Oct 2007 17:44:27 -0300 Subject: Python tickets summary In-Reply-To: References: Message-ID: 2007/9/13, Facundo Batista : > All the listings are accesible from the same pages, start here: > > http://www.taniquetil.com.ar/facundo/py_tickets.html > > (remember to refresh) > > Any idea to improve these pages is welcomed. Following an idea of John Lenton, now every page shows a graph of the activity per day of all open tickets. Look at the bottom: http://www.taniquetil.com.ar/facundo/py_tickets.html Regards, -- . Facundo Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From bj_666 at gmx.net Thu Oct 18 11:51:24 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Oct 2007 15:51:24 GMT Subject: Convert string to command.. References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> <5npa5cFj5bvfU1@mid.uni-berlin.de> <1192720007.177063.194550@i13g2000prf.googlegroups.com> <5npbjbFio7g9U1@mid.uni-berlin.de> <1192720659.272611.320900@v29g2000prd.googlegroups.com> <873aw830lc.fsf@mulj.homelinux.net> <1192722090.740342.60950@i13g2000prf.googlegroups.com> Message-ID: <5npdnsFj14e6U3@mid.uni-berlin.de> On Thu, 18 Oct 2007 08:41:30 -0700, Abandoned wrote: > import cPickle as pickle > a="{2:3,4:6,2:7}" > s=pickle.dumps(a, -1) > g=pickle.loads(s); > print g > '{2:3,4:6,2:7}' > > Thank you very much for your answer but result is a string ?? In Python terms yes, strings in Python can contain any byte value. If you want to put this into a database you need a BLOB column or encode it as base64 or something similar more ASCII safe. Ciao, Marc 'BlackJack' Rintsch From robert.kern at gmail.com Wed Oct 17 20:27:08 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 17 Oct 2007 19:27:08 -0500 Subject: Appending a list's elements to another list using a list comprehension In-Reply-To: <1192664785.093927.305050@q5g2000prf.googlegroups.com> References: <1192652834.150718.205050@t8g2000prg.googlegroups.com> <1192655036.279184.255720@q3g2000prf.googlegroups.com> <1192657240.005464.35770@z24g2000prh.googlegroups.com> <1192664785.093927.305050@q5g2000prf.googlegroups.com> Message-ID: Debajit Adhikary wrote: > On Oct 17, 5:40 pm, Paul Hankin wrote: >> To answer your question though: a += b is *not* the same as a = a + b. >> The latter would create a new list and assign it to a, whereas a += b >> updates a in-place. > > I know I'm being a little finicky here, but how would someone know > that a+=b is not the same as a=a+b? > Any documentation or reference that mentions this? http://docs.python.org/ref/augassign.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From schmidt_florian at gmx.de Thu Oct 4 14:04:32 2007 From: schmidt_florian at gmx.de (Florian Schmidt) Date: Thu, 4 Oct 2007 20:04:32 +0200 Subject: Import PY file not included in py2exe executable In-Reply-To: <1191518159.408503.258070@19g2000hsx.googlegroups.com> References: <1191518159.408503.258070@19g2000hsx.googlegroups.com> Message-ID: <20071004180432.GA1709@mail.gmx.de> On Thu, Oct 04, 2007 at 10:15:59AM -0700, ward.david at comcast.net wrote: > ... because they are used for program configuration ... not sure if i completely understood but i guess you do something like that: my_config.py: db_host = "mydbserver" db_user = "root" ... and in your program.py you have: import my_config ... DB.Connect(my_config.db_host, my_config.db_user...) and your problem is that py2exe will package that my_config.py so that "noone" can change it afterwards... one possibility i often use is execfile: same my_config as above, but: program.py: class config_class: pass my_config = config_class() my_config.db_host = "localhost" # default config... def read_config(): execfile("my_config.py", globals(), my_config.__dict__) ... DB.Connect(my_config.db_host, my_config.db_user...) so you can always call read_config() to re-read the configuration and have all python features in that config file. (additionally you can catch exceptions and check the config files' mtime if it has changed...) that way py2exe won't care about your config file... hope it helps... -- Florian Schmidt From bdesth.quelquechose at free.quelquepart.fr Fri Oct 5 12:47:35 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 05 Oct 2007 18:47:35 +0200 Subject: weakrefs and bound methods In-Reply-To: <4708f45d$0$11868$3b214f66@tunews.univie.ac.at> References: <4708f276$0$11868$3b214f66@tunews.univie.ac.at> <4708f45d$0$11868$3b214f66@tunews.univie.ac.at> Message-ID: <470a818a$0$14499$426a74cc@news.free.fr> Mathias Panzenboeck a ?crit : About the lost weakref problem: in Python, methods are just tiny wrappers around the object, class and function created at lookup time (yes, on *each* lookup) (and WWAI, they are by the function object itself, which implements the descriptor protocol). > When I change the class Wrapper to following, the class Foo works: > > class Wrapper(object): > def __init__(self,x): > self.func_name = x.func_name > self.x = weakref.ref(x.im_self) > def __call__(self,*args,**kwargs): > x = self.x() > if x is None: > print "lost reference" > else: > return getattr(x,self.func_name)(*args,**kwargs) Anyway, the whole thing looks quite baroque to me - and I'm known for my immoderate appetite for brain-melting features.... If I understand correctly, you're doing all this to avoid circular references while keeping track of a list of methods to call ? If yes, then you're thru much pain for nothing. Mostly because there are other much more simpler solutions. The first one is obviously to use names and getattr. In it's most na?ve implementation, this would look like: class Foo(object): def __init__(self): self._methods = set() self._methods.add('_foo') def _foo(self): print "_foo" def callMethods(self): for name in self._methods: meth = getattr(self, name, None) if callable(meth): meth() Now if _methods is supposed to have the same content class-wise (which is the case in your exemple), no need to have it as an instance method: class Foo(object): _methods = set('_foo') def _foo(self): print "_foo" def callMethods(self): for name in self._methods: meth = getattr(self, name, None) if callable(meth): meth() We could go further, like using a decorator to mark methods to add to _methods, and a metaclass to set the whole thing up, but this would probably be overkill. Unless there are other requirements, I'd personnaly stop here. Oh, and yes, while we're at it : Python usually knows how to deal with circular references.... > But that's ugly. Indeed. > Any better idea? Yes. KISS. From stef.mientki at gmail.com Sat Oct 20 06:21:57 2007 From: stef.mientki at gmail.com (stef mientki) Date: Sat, 20 Oct 2007 12:21:57 +0200 Subject: how to iterate over sequence and non-sequence ? In-Reply-To: <13hj34cgdvkdc80@corp.supernews.com> References: <1192779222.618164.321910@y27g2000pre.googlegroups.com> <2e539$4718bcf4$83aef404$17711@news1.tudelft.nl> <13hhicd14jrt5e3@corp.supernews.com> <13hj34cgdvkdc80@corp.supernews.com> Message-ID: <4719D6C5.7020603@gmail.com> Steven D'Aprano wrote: > On Fri, 19 Oct 2007 18:38:06 +0200, stef mientki wrote: > > >> I don't have pointers, I've just names (at least I think). Let me >> explain a little bit more, >> I want to simulate / debug a user program, the user program might look >> like this: >> >> x = 5 >> for i in xrange(10): >> x = x + 1 >> > > > I thought you were writing a JAL interpreter: > > http://en.wikipedia.org/wiki/JAL_(compiler) > > hi Steven, you're completely right, in fact I want to some more: also taken hardware and physics into account. You can see one of my first demo's here, to see what I mean: http://stef.mientki.googlepages.com/jalspy_demo_robot1a.html and some more demos can be found over here: http://oase.uci.kun.nl/~mientki/data_www/pic/jalspy/jalspy_animated_demos.html In fact we already used the simulator a number of times in real applications with great success, but didn't release it yet, because you still need Python knowledge to run it reliable. > but the code above is Python. > Yes, right again ;-) The simulator translates JAL into Python, In the beginning I thought that was the easiest, I'm not sure about that anymore at the moment, but on the other hand that's just replacing one module. > Python already has a debugger. Try this: > > import pdb > help(pdb) > > Yes, Paul also pointed me into that direction, and to be honest, I expected there would be such a module, but I never searched for it, because .... If I see that I can cook dinner, when I (very seldom) test the program (I'm writing) in the debug mode, (assuming the IDE uses the same pdb), then this is far too slow :-( I'll report back what my experiences are with pdb. cheers, Stef Mientki From python at rcn.com Thu Oct 25 20:37:31 2007 From: python at rcn.com (Raymond Hettinger) Date: Thu, 25 Oct 2007 17:37:31 -0700 Subject: An efficient, pythonic way to calculate result sets In-Reply-To: <1193358833.133666.253680@k35g2000prh.googlegroups.com> References: <1193326263.917893.266620@e9g2000prf.googlegroups.com> <1193358833.133666.253680@k35g2000prh.googlegroups.com> Message-ID: <1193359051.336992.230920@v23g2000prn.googlegroups.com> > Easy exercise of transforming recursion to iteration left to the > reader. Ack! That part was already done. Raymond From kf9150 at gmail.com Thu Oct 4 14:33:22 2007 From: kf9150 at gmail.com (Kelie) Date: Thu, 04 Oct 2007 11:33:22 -0700 Subject: using regular express to analyze lisp code In-Reply-To: References: <1191518039.676797.290620@22g2000hsm.googlegroups.com> Message-ID: <1191522802.565729.144530@n39g2000hsh.googlegroups.com> On Oct 4, 7:50 am, Tim Chase wrote: > Use a parsing lib. I've tinkered a bit with PyParsing[1] which > is fairly easy to pick up, but powerful enough that you're not > banging your head against limitations. There are a number of > other parsing libraries[2] with various domain-specific features > and audiences, but I'd go browsing through them only if PyParsing > doesn't fill the bill. > > As you don't detail what you want to do with the content or how > pathological the input can be, but you might be able to get away > with just skimming through the input and counting open-parens and > close-parens, stopping when they've been balanced, skipping lines > with comments. thanks Tim. following you and Dan's advice i visited http://python.fyxm.net/topics/parsing.html and i picked up pyparsing after brief reading of descriptions for couple of packages. now that you recommended it, seems that i made a good choice. btw, the content found will be copied to a new text file. From deets at nospam.web.de Mon Oct 15 11:28:31 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Oct 2007 17:28:31 +0200 Subject: A Python way to get MS Access table column information? References: <1192461377.629580.287370@i38g2000prf.googlegroups.com> Message-ID: <5nhf8vFi1p52U1@mid.uni-berlin.de> goldtech wrote: > Using Python and OBDC in MS-Access DBs. So, I'm able to run SQL > statements from Python on an Access DB. > > Is there an SQL statement that will give me column information? For a > table I want to know the data type and of course colum/Attribute name > for each column. > > So far the answer has been "no". VB or some other tool is needed to do > that I'm told. Who said that? Did you check the cursor objects description-property, as described in http://www.python.org/dev/peps/pep-0249/ That at least for other DBs gives the needed info, and it seems it's required. Diez From deets at nospam.web.de Wed Oct 10 18:22:55 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Oct 2007 00:22:55 +0200 Subject: PYTHONPATH on OS X In-Reply-To: <1192053645.223787.320580@y42g2000hsy.googlegroups.com> References: <1192053645.223787.320580@y42g2000hsy.googlegroups.com> Message-ID: <5n51m2Fg7ceoU2@mid.uni-berlin.de> mhearne808[insert-at-sign-here]gmail[insert-dot-here]com schrieb: > I'm missing something major here. I'm trying to add a directory to my > python path using the PYTHONPATH environment variable, and it's being > ignored by the Python interactive shell. > > Below is a capture of what I did. Note that my newfolder appears > nowhere on the list of directories in sys.path. How do I get Python > to pay attention to my shell variables? > > Using bash on OS X 10.4.10. > > %:~ user$ echo $PYTHONPATH > > %:~ user$ PYTHONPATH=/Users/user/newfolder > %:~ user$ echo $PYTHONPATH > /Users/user/newfolder > %:~ user$ python > Python 2.5.1 (r251:54863, Aug 10 2007, 10:46:58) > [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.path > ['', '/usr/local/lib/python2.5/site-packages/ > setuptools-0.7a1dev_r56320-py2.5.egg', '/usr/local/lib/python2.5/site- > packages/ipython1-0.9alpha2-py2.5.egg', '/usr/local/lib/python2.5/site- > packages/SQLAlchemy-0.4.0beta5-py2.5.egg', '/usr/local/lib/python2.5/ > site-packages/MySQL_python-1.2.2-py2.5-macosx-10.3-i386.egg', '/usr/ > local/lib/python25.zip', '/usr/local/lib/python2.5', '/usr/local/lib/ > python2.5/plat-darwin', '/usr/local/lib/python2.5/plat-mac', '/usr/ > local/lib/python2.5/plat-mac/lib-scriptpackages', '/usr/local/lib/ > python2.5/lib-tk', '/usr/local/lib/python2.5/lib-dynload', '/usr/local/ > lib/python2.5/site-packages', '/usr/local/lib/python2.5/site-packages/ > PIL'] Use export PYTHONPATH=.... to pass environment vars to subprocesses. Basic unix shell knowledge :) $ man bash ... export -p The supplied names are marked for automatic export to the envi- ronment of subsequently executed commands. If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed. The -n option causes the export property to be removed from the named variables. export returns an exit status of 0 unless an invalid option is encoun- tered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function. ... Diez From e0427417 at student.tuwien.ac.at Sun Oct 7 10:59:40 2007 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Sun, 07 Oct 2007 16:59:40 +0200 Subject: weakrefs and bound methods In-Reply-To: <4708f276$0$11868$3b214f66@tunews.univie.ac.at> References: <4708f276$0$11868$3b214f66@tunews.univie.ac.at> Message-ID: <4708f45d$0$11868$3b214f66@tunews.univie.ac.at> When I change the class Wrapper to following, the class Foo works: class Wrapper(object): def __init__(self,x): self.func_name = x.func_name self.x = weakref.ref(x.im_self) def __call__(self,*args,**kwargs): x = self.x() if x is None: print "lost reference" else: return getattr(x,self.func_name)(*args,**kwargs) But that's ugly. Any better idea? From Florian.Lindner at xgm.de Fri Oct 12 06:58:28 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Fri, 12 Oct 2007 12:58:28 +0200 Subject: Last iteration? Message-ID: Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i that would print 1 2 9 Can this be acomplished somehow? Thanks, Florian From paul at boddie.org.uk Sat Oct 27 13:13:06 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 27 Oct 2007 10:13:06 -0700 Subject: multi-protocol url-based IO -- pure python kioslave-like module? In-Reply-To: <1193502384.553887.30370@i38g2000prf.googlegroups.com> References: <1193502384.553887.30370@i38g2000prf.googlegroups.com> Message-ID: <1193505186.813473.108330@o80g2000hse.googlegroups.com> On 27 Okt, 18:26, Rob McMullen wrote: > Wheel reinvention preemption question: is there an existing pure- > python library with functionality similar to KDE's kio/kioslave > implementation? A multi-protocol, extensible library based on URLs > that abstracts directory listing and file read/write? I'm looking to > use it in client code, not server, so it doesn't have to be > asynchronous like kio; ideally it would be small and only depend on > the standard python library. Something like itools.vfs, perhaps? http://www.ikaaro.org/itools http://download.ikaaro.org/doc/itools/Chapter--VFS.html Paul From surekap at gmail.com Wed Oct 24 06:55:16 2007 From: surekap at gmail.com (Prateek) Date: Wed, 24 Oct 2007 03:55:16 -0700 Subject: building a linux executable Message-ID: <1193223316.020001.77940@i13g2000prf.googlegroups.com> Hello, I'm trying to package my python program into a linux executable using cx_freeze. The goal is that the user should require python on their system. I've managed to make the binaries on Fedora Core 6 and they run fine. However, when I move to Ubuntu (tested on Ubuntu Server 7.04 and xUbuntu Desktop 7.04), the program fails to run with the following error: ImportError: no module named _md5 _md5 being imported by the hashlib module because the import of _hashlib.so failed. When I try to import the _hashlib module manually, I see that it cannot find libssl.so.6 (The _hashlib module in the standard python installation which came with Ubuntu works just fine). If I manually copy the libssl.so.6 file from FC6 (its really a symlink pointing to libssl.so.0.9.8b) to Ubuntu and make the symlink in /lib, it works fine (the next error is related to libcrypto, libxslt and libjpeg (i'm also using libxml, libxsl and PIL in my application). I've scoured the net and it seems that _hashlib.so is dynamically linked to libssl which is not being "integrated" into the build by cx_Freeze. Similarly, there are other files with the same problem. Does anyone have any idea how to make cx_Freeze make a linux executable which is portable across *nix distros? Thanks in advance, -Prateek Sureka From paul.hankin at gmail.com Tue Oct 2 07:34:25 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 02 Oct 2007 11:34:25 -0000 Subject: problem with special built-in method __contains__, In-Reply-To: <1191323678.609701.258550@y42g2000hsy.googlegroups.com> References: <1191323678.609701.258550@y42g2000hsy.googlegroups.com> Message-ID: <1191324865.979298.107430@d55g2000hsg.googlegroups.com> On Oct 2, 12:14 pm, "ebo... at gmail.com" wrote: > if i have a dictionary name number ....and i want to ask the list > whether a particular key already > exists. > > >>> print number > > {'octal': '1234567', 'binary': '10100101', 'decimal': '1234567890', > 'hexadecimal': '1-9,a-f'} > > i got error..after execute > > >>>number._contains_("test") It's __contains__ and not _contains_. But better is just: 'test' in number -- Paul Hankin From jcd at sdf.lonestar.org Mon Oct 22 06:47:49 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 22 Oct 2007 06:47:49 -0400 Subject: Failure to connect in SimpleXMLRPCServer/xmlrpclib In-Reply-To: <1193034835.803633.121600@z24g2000prh.googlegroups.com> References: <1193034835.803633.121600@z24g2000prh.googlegroups.com> Message-ID: <471C7FD5.3040104@sdf.lonestar.org> iu2 wrote: > Hi all, > > I've copied the example of RPC usage from the Python's doc. > When the client and server were on the same PC ("localhost") (I use > Windows) > it worked ok. But putting the server on a different PC raised the > error: > > gaierror: (11001, 'getaddrinfo failed') > The error was raised upion accessing some function of the server, > i.e., > print s.add_nums(1, 2, 3) # server registered function > > PCs in our organization are accessed by "\\" so I used > > s = xmlrpclib.Server(r'http://\\pc_name:8000') > I got the same error when I put some non-existing name. > Trying to remove the double-backslash from the PC's name raised the > error: > error: (10061, 'Connection refused') > > I'll appreciate your help on this. > > Thanks > iu2 > > Don't use the \\. That's a windows networking convention, and it does not apply if you are using http. Your error messages tell you this. The first one (r'http://\\pc_name:8000') could not resolve the address. The second one reached the server just fine, but the server rejected the client's request. So now the issue is why is the request being rejected? Did you check your firewall to see if it is blocking access to port 8000 on the ethernet adapter? Cheers, Cliff From goldtech at worldpost.com Fri Oct 5 08:16:14 2007 From: goldtech at worldpost.com (goldtech) Date: Fri, 05 Oct 2007 05:16:14 -0700 Subject: tkinter question In-Reply-To: References: <1191554174.490449.251400@50g2000hsm.googlegroups.com> Message-ID: <1191586574.410311.142230@k79g2000hse.googlegroups.com> > > try to change listbox.pack() to listbox.pack(expand=True, fill=BOTH) > .. is it that you want ? Yes. > > -mykhal Worked with TRUE all uppercase. Exactly what I needed. Thank you. From tommy.nordgren at comhem.se Mon Oct 22 18:21:49 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Tue, 23 Oct 2007 00:21:49 +0200 Subject: Check File Change Every 10 Seconds In-Reply-To: <005001c814ba$3d09bca0$b71d35e0$@rawlins@thinkbluemedia.co.uk> References: <27459.1491478079$1193048158@news.gmane.org> <005001c814ba$3d09bca0$b71d35e0$@rawlins@thinkbluemedia.co.uk> Message-ID: <70AF4D02-E15C-4EA5-AB68-5C0428DBBD51@comhem.se> On 22 okt 2007, at 16.45, Robert Rawlins - Think Blue wrote: > Thanks for your time Gabriel, > > That certainly looks to be the type of thing that I'm looking to > achieve, however, I forgot to mention I'm running this on a Linux > platform and not a Win32 one :-( Sorry. > > I'm sure similar things are achievable, I've used os.stat before > now to get the time stamp for when a file was last changed, if I > perhaps combine this with the while 1: inside a thread I can > achieve the same end result? Sound like a good idea? > > I just wasn?t sure how safe it was to spawn a thread like this > which contains an infinite loop. > > Thanks again for your time, > > Rob > Don't use os.stat Use os.fstat instead on the open filedescriptor associated with your file. If you use stat on a portable, and poll too often, your hard drive will never go to sleep when idle. fstat works on the cached, in memory, directory info of the file. When it's changed, rewind the file and reparse. > ------ What is a woman that you forsake her, and the hearth fire and the home acre, to go with the old grey Widow Maker. --Kipling, harp song of the Dane women Tommy Nordgren tommy.nordgren at comhem.se From Eric_Dexter at msn.com Tue Oct 9 07:18:27 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Tue, 09 Oct 2007 04:18:27 -0700 Subject: embedding error in python example In-Reply-To: <1191928299.360986.304070@22g2000hsm.googlegroups.com> References: <1191928299.360986.304070@22g2000hsm.googlegroups.com> Message-ID: <1191928707.133203.227830@o3g2000hsb.googlegroups.com> On Oct 9, 6:11 am, "Eric_Dex... at msn.com" wrote: > I compiled the comand line example and I am getting an error when I > try to use the program when the program is cleaning up (I don't know > that it would prevent the program from running though I will run more > tests)... ebedpython test testt > result of call: -1 > exception exceptions.TypeError: 'an integer is required' in ' 'garbage > collection' ignored > Fatal Python error: unexpected exception during garbage collection... > > the program is just > test.py > > def testt(): > x = 'test' > > doesn't realy do anything it was my first test of the program.. > > I would be thankfull for any help.. > > tagline I don't need no stinken tagline... def testt(): v = open('file.txt','w') v.write('test') v.close() #x := 'test' #print x This seems to work but gives me the annoying looking error.. I now have a file with the word test in it... This is done with xp, with python 2.5 dll and the example that you find when you look up python + embed in google.. I copied all the .dll's in the root (msvcrt exc) and python25.dll to the directory.. any help would be apreaceated.. From steve at REMOVE-THIS-cybersource.com.au Wed Oct 31 17:59:05 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 31 Oct 2007 21:59:05 -0000 Subject: A Python 3000 Question References: Message-ID: <13ihul9dsov4h8c@corp.supernews.com> On Wed, 31 Oct 2007 14:45:59 +0000, Duncan Booth wrote: >> Thanks for the interesting note. I didn't know that tuples originally >> had no methods. That made len mandatory, I suppose. >> > Only if you think tuples are a sequence rather than a record. Even records have a length. The length of a record is the number of fields it has. -- Steven. From patrick.waldo at gmail.com Mon Oct 15 06:43:19 2007 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Mon, 15 Oct 2007 10:43:19 -0000 Subject: Simple Text Processing Help In-Reply-To: <1192396632.736910.134070@q5g2000prf.googlegroups.com> References: <1192369731.561036.31010@i38g2000prf.googlegroups.com> <1192396632.736910.134070@q5g2000prf.googlegroups.com> Message-ID: <1192444999.825194.268930@v23g2000prn.googlegroups.com> > lines = open('your_file.txt').readlines()[:4] > print lines > print map(len, lines) gave me: ['\xef\xbb\xbf200-720-7 69-93-2\n', 'kyselina mo\xc4\x8dov \xc3\xa1 C5H4N4O3\n', '\n', '200-001-8\t50-00-0\n'] [28, 32, 1, 18] I think it means that I'm still at option 3. I got the line by line part. My code is a lot cleaner now: import codecs path = "c:\\text_samples\\chem_1_utf8.txt" path2 = "c:\\text_samples\\chem_2.txt" input = codecs.open(path, 'r','utf8') output = codecs.open(path2, 'w', 'utf8') for line in input: tokens = line.strip().split() tokens[2:-1] = [u' '.join(tokens[2:-1])] #this doesn't seem to combine the files correctly file = u'|'.join(tokens) #this does put '|' in between print file + u'\n' output.write(file + u'\r\n') input.close() output.close() my sample input file looks like this( not organized,as you see it): 200-720-7 69-93-2 kyselina mocov? C5H4N4O3 200-001-8 50-00-0 formaldehyd CH2O 200-002-3 50-01-1 guanid?nium-chlorid CH5N3.ClH etc... and after the program I get: 200-720-7|69-93-2| kyselina|mocov?||C5H4N4O3 200-001-8|50-00-0| formaldehyd|CH2O| 200-002-3| 50-01-1| guanid?nium-chlorid|CH5N3.ClH| etc... So, I am sort of back at the start again. If I add: tokens = line.strip().split() for token in tokens: print token I get all the single tokens, which I thought I could then put together, except when I did: for token in tokens: s = u'|'.join(token) print s I got ?|2|0|0|-|7|2|0|-|7, etc... How can I join these together into nice neat little lines? When I try to store the tokens in a list, the tokens double and I don't know why. I can work on getting the chemical names together after...baby steps, or maybe I am just missing something obvious. The first two numbers will always be the same three digits-three digits-one digit and then two digits-two digits-one digit. My intuition tells me that I need to add an if statement that says, if the first two numbers follow the pattern, then continue, if they don't (ie a chemical name was accidently split apart) then the third entry needs to be put together. Something like if tokens.startswith('pattern') == true Again, thanks so much. I've gone to http://gnosis.cx/TPiP/ and I have a couple O'Reilly books, but they don't seem to have a straightforward example for this kind of text manipulation. Patrick On Oct 14, 11:17 pm, John Machin wrote: > On Oct 14, 11:48 pm, patrick.wa... at gmail.com wrote: > > > > > Hi all, > > > I started Python just a little while ago and I am stuck on something > > that is really simple, but I just can't figure out. > > > Essentially I need to take a text document with some chemical > > information in Czech and organize it into another text file. The > > information is always EINECS number, CAS, chemical name, and formula > > in tables. I need to organize them into lines with | in between. So > > it goes from: > > > 200-763-1 71-73-8 > > n?trium-tiopent?l C11H18N2O2S.Na to: > > > 200-763-1|71-73-8|n?trium-tiopent?l|C11H18N2O2S.Na > > > but if I have a chemical like: kyselina mo?ov? > > > I get: > > 200-720-7|69-93-2|kyselina|mo?ov? > > |C5H4N4O3|200-763-1|71-73-8|n?trium-tiopent?l > > > and then it is all off. > > > How can I get Python to realize that a chemical name may have a space > > in it? > > Your input file could be in one of THREE formats: > (1) fields are separated by TAB characters (represented in Python by > the escape sequence '\t', and equivalent to '\x09') > (2) fields are fixed width and padded with spaces > (3) fields are separated by a random number of whitespace characters > (and can contain spaces). > > What makes you sure that you have format 3? You might like to try > something like > lines = open('your_file.txt').readlines()[:4] > print lines > print map(len, lines) > This will print a *precise* representation of what is in the first > four lines, plus their lengths. Please show us the output. From rbonvall at gmail.com Wed Oct 31 16:50:48 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Wed, 31 Oct 2007 20:50:48 -0000 Subject: 3 number and dot.. In-Reply-To: <1193860737.687984.13400@k79g2000hse.googlegroups.com> References: <1193860737.687984.13400@k79g2000hse.googlegroups.com> Message-ID: <1193863848.080615.191090@v3g2000hsg.googlegroups.com> On 31 oct, 16:58, Abandoned wrote: > Hi.. > I want to do this: > for examle: > 12332321 ==> 12.332.321 > > How can i do? >>> x = 12332321 >>> '.'.join(''.join(i for n, i in g) for k, g in groupby(enumerate(reversed(str(x))), lambda (n, i): n//3))[::-1] '12.332.321' >>> -- Roberto Bonvallet From wbrehaut at mcsnet.ca Fri Oct 5 16:56:44 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Fri, 05 Oct 2007 14:56:44 -0600 Subject: Python Magazine: Issue 1 Free! References: <13gcjeqbhmh152c@corp.supernews.com> <13gcogrm9uloj4b@corp.supernews.com> <47069e40$0$16410$426a74cc@news.free.fr> Message-ID: On Thu, 04 Oct 2007 04:12:04 +0200, Bruno Desthuilliers wrote: >J. Clifford Dyer a ?crit : >> On Fri, Oct 05, 2007 at 04:11:07PM -0000, Grant Edwards wrote >> regarding Re: Python Magazine: Issue 1 Free!: >> >>> On 2007-10-05, Steve Holden wrote: >>> >>>>>> I've just been told by the editors at Python Magazine that >>>>>> the first issue is out. >>>>> >>>>> The first issue is issue number 10? >>>>> >>>>> That's a bit silly. >>>> >>>> It's the October edition. They obviously decided to make sure the >>>> month numbering was consistent across the volumes. >>> >>> I presumed that was the reasoning. It just seems counter-intuitive >>> (and sort of un-Pythonic) to start numbering a sequence of objects >>> at 10. ;) >>> >> >> >> Well, it's also unpythonic to start numbering a sequence at 1, but >> it's clearly the right thing to do in this case. > >As far as I'm concerned, if I had to number a magazine about >programming, I'd obviously start with 0. And since the "first" issue is free that would be best here too. >Then it would be n?1, n?10, >n?11, n?100 etc !-) But probably with enough leading zeros to last the expected lifetime (8 bits should about do it?) so they'd sort properly: 0000 0000 0000 0001 etc. wwwayne From haraldarminmassa at gmail.com Wed Oct 10 08:45:44 2007 From: haraldarminmassa at gmail.com (GHUM) Date: Wed, 10 Oct 2007 05:45:44 -0700 Subject: Yet another comparison of Python Web Frameworks In-Reply-To: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> References: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> Message-ID: <1192020344.600656.300770@50g2000hsm.googlegroups.com> Michele, > At work we are shopping for a Web framework, so I have been looking at > the available options on the current market. just because you were involved in creating an own version of Python does NOT free you from the social obligation to create your own Python web framework. So stop shopping and start announcing your own pwf like all other Python programmers do. Harald From ncoghlan at gmail.com Mon Oct 1 17:42:34 2007 From: ncoghlan at gmail.com (NickC) Date: Mon, 01 Oct 2007 14:42:34 -0700 Subject: Python 3.0 migration plans? In-Reply-To: <1191083377.191358.303320@d55g2000hsg.googlegroups.com> References: <1191083377.191358.303320@d55g2000hsg.googlegroups.com> Message-ID: <1191274954.862049.299800@r29g2000hsg.googlegroups.com> On Sep 30, 2:29 am, John Roth wrote: > I was thinking of starting work on converting Python FIT to 3.0, and > then they posted PEP 3137. I think it's a real good idea, but it shows > that 3.0a1 isn't ready for a conversion effort. > > http://www.python.org/dev/peps/pep-3137/ > > I'll look at it again in a year or so. > > John Roth When 3.0b1 comes out is probably the time to start looking seriously at conversion. Until then, major course corrections (like PEP 3137) will still be a possibility. Before the first beta, the best idea is probably just to keep a watchful eye on the development to see if you spot any show-stopper problems that might lead to the need for such a course correction :) Regards, Nick. From drcolombes at yahoo.com Fri Oct 12 20:34:16 2007 From: drcolombes at yahoo.com (Dr. Colombes) Date: Fri, 12 Oct 2007 17:34:16 -0700 (PDT) Subject: How to modify EVDEV.py to record Keyboard Key RELEASE times? Message-ID: <996305.22470.qm@web38712.mail.mud.yahoo.com> I'm using a modified EVDEV.py program (see below) to record inter-keystroke times for Keystroke triples and doubles (t2 - t1, t3 -t1). These times are key PRESS times. How - where can EVDEV.py be modified (without too much trouble) to record Keystroke RELEASE times also ? Thanks for your help. --------------------------------------------------------------------------------------- #!/usr/bin/env python """ evdev.py This is a Python interface to the Linux input system's event device. Events can be read from an open event file and decoded into spiffy python objects. The Event objects can optionally be fed into a Device object that represents the complete state of the device being monitored. Copyright (C) 2003-2004 Micah Dowty This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import struct, sys, os, time from socket import gethostname from fcntl import ioctl __all__ = ["Event", "Device"] def demo(): """Open the event device named on the command line, use incoming events to update a device, and show the state of this device. """ dev = Device(sys.argv[1]) try: while 1: dev.poll() except: dev.log.close() return dev.get_filename() class BaseDevice: """Base class representing the state of an input device, with axes and buttons. Event instances can be fed into the Device to update its state. """ def __init__(self): self.axes = {} self.buttons = {} self.name = None self.next2last = None self.next2lasttime = None self.next2lastpress = 'NONE' self.last = None self.lasttime = None self.lastpress = 'NONE' self.echo = {} #make log directory if not os.path.isdir("./logs"): os.mkdir("./logs") #new filename hostname = str(gethostname()) filename = str(hostname) + "_log_" + str(time.asctime()).replace(":", "_").replace(" ", "_") #open log file self.log = open("./logs/" + filename, "w") self.filename = "./logs/" + filename #self.log.write("\n\n\n\nHOSTNAME: " + str(hostname) + "\n" + ("_" * 60) + "\n") def get_filename(self): return self.filename def __repr__(self): return "" % ( self.name, self.axes, self.buttons) def update(self, event): f = getattr(self, "update_%s" % event.type, None) if f: f(event) def update_EV_KEY(self, event): if event.code not in self.echo: self.echo[event.code] = 0 if self.echo[event.code] >= 1: self.echo[event.code] = 0 return else: self.echo[event.code] += 1 now = time.time() if self.lasttime == None: #self.lasttime = time.time() self.lasttime = now if self.next2lasttime == None: self.next2lasttime = now #now = time.time() newtime = now - self.lasttime new3time = now - self.next2lasttime #self.log.write(repr(self.lastpress) + "_" + repr(event.code) + "\t\t" + str(newtime) + "\n") self.log.write(self.lastpress + "_" + event.code + "\t\t" + str(newtime) + "\n") self.log.write(self.next2lastpress + "_" + self.lastpress + "_" + event.code + "\t\t" + str(new3time) + "\n") self.next2lastpress = self.lastpress self.lastpress = event.code self.next2lasttime = self.lasttime self.lasttime = now def update_EV_ABS(self, event): self.axes[event.code] = event.value def update_EV_REL(self, event): self.axes[event.code] = self.axes.get(event.code, 0) + event.value def __getitem__(self, name): """Retrieve the current value of an axis or button, or zero if no data has been received for it yet. """ if name in self.axes: return self.axes[name] else: return self.buttons.get(name, 0) # evdev ioctl constants. The horrible mess here # is to silence silly FutureWarnings EVIOCGNAME_512 = ~int(~0x82004506L & 0xFFFFFFFFL) EVIOCGID = ~int(~0x80084502L & 0xFFFFFFFFL) EVIOCGBIT_512 = ~int(~0x81fe4520L & 0xFFFFFFFFL) EVIOCGABS_512 = ~int(~0x80144540L & 0xFFFFFFFFL) class Device(BaseDevice): """An abstract input device attached to a Linux evdev device node""" def __init__(self, filename): BaseDevice.__init__(self) self.fd = os.open(filename, os.O_RDONLY) self.packetSize = struct.calcsize(Event.format) self.readMetadata() def poll(self): """Receive and process all available input events""" while 1: try: buffer = os.read(self.fd, self.packetSize) except OSError: print "Could not open event device" return self.update(Event(unpack=buffer)) def readMetadata(self): """Read device identity and capabilities via ioctl()""" buffer = "\0"*512 # Read the name self.name = ioctl(self.fd, EVIOCGNAME_512, buffer) self.name = self.name[:self.name.find("\0")] # Read info on each absolute axis absmap = Event.codeMaps['EV_ABS'] buffer = "\0" * struct.calcsize("iiiii") self.absAxisInfo = {} for name, number in absmap.nameMap.iteritems(): values = struct.unpack("iiiii", ioctl(self.fd, EVIOCGABS_512 + number, buffer)) values = dict(zip(( 'value', 'min', 'max', 'fuzz', 'flat' ),values)) self.absAxisInfo[name] = values def update_EV_ABS(self, event): """Scale the absolute axis into the range [-1, 1] using absAxisInfo""" try: info = self.absAxisInfo[event.code] except KeyError: return range = float(info['max'] - info['min']) self.axes[event.code] = (event.value - info['min']) / range * 2.0 - 1.0 class EnumDict: """A 1:1 mapping from numbers to strings or other objects, for enumerated types and other assigned numbers. The mapping can be queried in either direction. All values, by default, map to themselves. """ def __init__(self, numberMap): self.numberMap = numberMap self.nameMap = {} for key, value in numberMap.iteritems(): self.nameMap[value] = key def toNumber(self, name): return self.nameMap.get(name, name) def fromNumber(self, num): return self.numberMap.get(num, num) class Event: """Represents one linux input system event. It can be encoded and decoded in the 'struct input_event' format used by the kernel. Types and codes are automatically encoded and decoded with the #define names used in input.h """ format = "LLHHl" typeMap = EnumDict({ 0x00: "EV_RST", 0x01: "EV_KEY", 0x02: "EV_REL", 0x03: "EV_ABS", 0x04: "EV_MSC", 0x11: "EV_LED", 0x12: "EV_SND", 0x14: "EV_REP", 0x15: "EV_FF", }) codeMaps = { "EV_KEY": EnumDict({ 0: "RESERVED", 1: "ESC", 2: "1", 3: "2", 4: "3", 5: "4", 6: "5", 7: "6", 8: "7", 9: "8", 10: "9", 11: "0", 12: "-", 13: "=", 14: "BACKSPACE", # "\\b", 15: "TAB", # "\\t", 16: "q", 17: "w", 18: "e", 19: "r", 20: "t", 21: "y", 22: "u", 23: "i", 24: "o", 25: "p", 26: "[", 27: "]", 28: "NEWLINE", # "\\n", 29: "LEFTCTRL", 30: "a", 31: "s", 32: "d", 33: "f", 34: "g", 35: "h", 36: "j", 37: "k", 38: "l", 39: "SEMICOLON", # ";", 40: "'", 41: "`", 42: "LEFTSHIFT", 43: "\\", 44: "z", 45: "x", 46: "c", 47: "v", 48: "b", 49: "n", 50: "m", 51: "COMMA", # ",", 52: "PERIOD", # ".", 53: "/", 54: "RIGHTSHIFT", 55: "*", 56: "LEFTALT", 57: "BLANK", # " ", 58: "CAPSLOCK", 59: "F1", 60: "F2", 61: "F3", 62: "F4", 63: "F5", 64: "F6", 65: "F7", 66: "F8", 67: "F9", 68: "F10", 69: "NUMLOCK", 70: "SCROLLLOCK", 71: "NK7", # "7", 72: "NK8", # "8", 73: "NK9", # "9", 74: "NKMINUS", # "-", 75: "NK4", # "4", 76: "NK5", # "5", 77: "NK6", # "6", 78: "NK+", # "+", 79: "NK1", # "1", 80: "NK2", # "2", 81: "NK3", # "3", 82: "NK0", # "0", 83: "NKPERIOD", # ".", 84: "103RD", 85: "F13", 86: "102ND", 87: "F11", 88: "F12", 89: "F14", 90: "F15", 91: "F16", 92: "F17", 93: "F18", 94: "F19", 95: "F20", 96: "NEWLINE", # "\\n", 97: "RIGHTCTRL", 98: "/", 99: "SYSRQ", 100: "RIGHTALT", 101: "LINEFEED", 102: "HOME", 103: "UP", 104: "PAGEUP", 105: "LEFT", 106: "RIGHT", 107: "END", 108: "DOWN", 109: "PAGEDOWN", 110: "INSERT", 111: "DELETE", 112: "MACRO", 113: "MUTE", 114: "VOLUMEDOWN", 115: "VOLUMEUP", 116: "POWER", 117: "=", 118: "KPPLUSMINUS", 119: "PAUSE", 120: "F21", 121: "F22", 122: "F23", 123: "F24", 124: "COMMA", # ",", 125: "LEFTMETA", 126: "RIGHTMETA", 127: "COMPOSE", 128: "STOP", 129: "AGAIN", 130: "PROPS", 131: "UNDO", 132: "FRONT", 133: "COPY", 134: "OPEN", 135: "PASTE", 136: "FIND", 137: "CUT", 138: "HELP", 139: "MENU", 140: "CALC", 141: "SETUP", 142: "SLEEP", 143: "WAKEUP", 144: "FILE", 145: "SENDFILE", 146: "DELETEFILE", 147: "XFER", 148: "PROG1", 149: "PROG2", 150: "WWW", 151: "MSDOS", 152: "COFFEE", 153: "DIRECTION", 154: "CYCLEWINDOWS", 155: "MAIL", 156: "BOOKMARKS", 157: "COMPUTER", 158: "BACK", 159: "FORWARD", 160: "CLOSECD", 161: "EJECTCD", 162: "EJECTCLOSECD", 163: "NEXTSONG", 164: "PLAYPAUSE", 165: "PREVIOUSSONG", 166: "STOPCD", 167: "RECORD", 168: "REWIND", 169: "PHONE", 170: "ISO", 171: "CONFIG", 172: "HOMEPAGE", 173: "REFRESH", 174: "EXIT", 175: "MOVE", 176: "EDIT", 177: "SCROLLUP", 178: "SCROLLDOWN", 179: "(", 180: ")", 181: "INTL1", 182: "INTL2", 183: "INTL3", 184: "INTL4", 185: "INTL5", 186: "INTL6", 187: "INTL7", 188: "INTL8", 189: "INTL9", 190: "LANG1", 191: "LANG2", 192: "LANG3", 193: "LANG4", 194: "LANG5", 195: "LANG6", 196: "LANG7", 197: "LANG8", 198: "LANG9", 200: "PLAYCD", 201: "PAUSECD", 202: "PROG3", 203: "PROG4", 205: "SUSPEND", 206: "CLOSE", 220: "UNKNOWN", 224: "BRIGHTNESSDOWN", 225: "BRIGHTNESSUP", 0x100: "BTN_0", 0x101: "BTN_1", 0x102: "BTN_2", 0x103: "BTN_3", 0x104: "BTN_4", 0x105: "BTN_5", 0x106: "BTN_6", 0x107: "BTN_7", 0x108: "BTN_8", 0x109: "BTN_9", 0x110: "BTN_LEFT", 0x111: "BTN_RIGHT", 0x112: "BTN_MIDDLE", 0x113: "BTN_SIDE", 0x114: "BTN_EXTRA", 0x115: "BTN_FORWARD", 0x116: "BTN_BACK", 0x120: "BTN_TRIGGER", 0x121: "BTN_THUMB", 0x122: "BTN_THUMB2", 0x123: "BTN_TOP", 0x124: "BTN_TOP2", 0x125: "BTN_PINKIE", 0x126: "BTN_BASE", 0x127: "BTN_BASE2", 0x128: "BTN_BASE3", 0x129: "BTN_BASE4", 0x12a: "BTN_BASE5", 0x12b: "BTN_BASE6", 0x12f: "BTN_DEAD", 0x130: "BTN_A", 0x131: "BTN_B", 0x132: "BTN_C", 0x133: "BTN_X", 0x134: "BTN_Y", 0x135: "BTN_Z", 0x136: "BTN_TL", 0x137: "BTN_TR", 0x138: "BTN_TL2", 0x139: "BTN_TR2", 0x13a: "BTN_SELECT", 0x13b: "BTN_START", 0x13c: "BTN_MODE", 0x13d: "BTN_THUMBL", 0x13e: "BTN_THUMBR", 0x140: "BTN_TOOL_PEN", 0x141: "BTN_TOOL_RUBBER", 0x142: "BTN_TOOL_BRUSH", 0x143: "BTN_TOOL_PENCIL", 0x144: "BTN_TOOL_AIRBRUSH", 0x145: "BTN_TOOL_FINGER", 0x146: "BTN_TOOL_MOUSE", 0x147: "BTN_TOOL_LENS", 0x14a: "BTN_TOUCH", 0x14b: "BTN_STYLUS", 0x14c: "BTN_STYLUS2", }), "EV_REL": EnumDict({ 0x00: "REL_X", 0x01: "REL_Y", 0x02: "REL_Z", 0x06: "REL_HWHEEL", 0x07: "REL_DIAL", 0x08: "REL_WHEEL", 0x09: "REL_MISC", }), "EV_ABS": EnumDict({ 0x00: "ABS_X", 0x01: "ABS_Y", 0x02: "ABS_Z", 0x03: "ABS_RX", 0x04: "ABS_RY", 0x05: "ABS_RZ", 0x06: "ABS_THROTTLE", 0x07: "ABS_RUDDER", 0x08: "ABS_WHEEL", 0x09: "ABS_GAS", 0x0a: "ABS_BRAKE", 0x10: "ABS_HAT0X", 0x11: "ABS_HAT0Y", 0x12: "ABS_HAT1X", 0x13: "ABS_HAT1Y", 0x14: "ABS_HAT2X", 0x15: "ABS_HAT2Y", 0x16: "ABS_HAT3X", 0x17: "ABS_HAT3Y", 0x18: "ABS_PRESSURE", 0x19: "ABS_DISTANCE", 0x1a: "ABS_TILT_X", 0x1b: "ABS_TILT_Y", 0x1c: "ABS_MISC", }), "EV_MSC": EnumDict({ 0x00: "MSC_SERIAL", 0x01: "MSC_PULSELED", }), "EV_LED": EnumDict({ 0x00: "LED_NUML", 0x01: "LED_CAPSL", 0x02: "LED_SCROLLL", 0x03: "LED_COMPOSE", 0x04: "LED_KANA", 0x05: "LED_SLEEP", 0x06: "LED_SUSPEND", 0x07: "LED_MUTE", 0x08: "LED_MISC", }), "EV_REP": EnumDict({ 0x00: "REP_DELAY", 0x01: "REP_PERIOD", }), "EV_SND": EnumDict({ 0x00: "SND_CLICK", 0x01: "SND_BELL", }), } def __init__(self, timestamp=0, type=0, code=0, value=0, unpack=None, readFrom=None): self.timestamp = timestamp self.type = type self.code = code self.value = value if unpack is not None: self.unpack(unpack) if readFrom is not None: self.readFrom(readFrom) def __repr__(self): return "" % ( self.timestamp, self.type, self.code, self.value) def pack(self): """Pack this event into an input_event struct in the local machine's byte order. """ secs = int(self.timestamp) usecs = int((self.timestamp - secs) * 1000000) packedType = self.typeMap.toNumber(self.type) if self.type in self.codeMaps: packedCode = self.codeMaps[self.type].toNumber(self.code) else: packedCode = self.code return struct.pack(self.format, secs, usecs, packedType, packedCode, self.value) def unpack(self, s): """Unpack ourselves from the given string,, an input_event struct in the local byte order. """ secs, usecs, packedType, packedCode, self.value = struct.unpack(self.format, s) self.timestamp = secs + (usecs / 1000000.0) self.type = self.typeMap.fromNumber(packedType) if self.type in self.codeMaps: self.code = self.codeMaps[self.type].fromNumber(packedCode) else: self.code = packedCode def readFrom(self, stream): """Read the next event from the given file-like object""" self.unpack(stream.read(struct.calcsize(self.format))) if __name__ == "__main__": filename = demo() print "\nReturned file name = %s " % filename text = open(filename).read() L = text.splitlines() L.sort() os.remove(filename) filename_sorted = filename + "_s" output = open (filename_sorted, "www") #filename_unsorted = filename + "_u" #output = open (filename_unsorted, "www") for line in L: line = line + "\n" output.write(line) #os.chmod(output, 0777) output.close() print " Created sorted file %s " % filename_sorted #print " Created UNsorted file %s " % filename_unsorted ### The End ### --------------------------------- Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. -------------- next part -------------- An HTML attachment was scrubbed... URL: From beema.shafreen at gmail.com Wed Oct 31 11:08:11 2007 From: beema.shafreen at gmail.com (Beema shafreen) Date: Wed, 31 Oct 2007 20:38:11 +0530 Subject: dictionary Message-ID: hi everybody, I have a file 2709852 2709911 A_16_P21360207 405 -59 2710316 2710367 A_14_P136880 -42 -51 2710325 2710384 A_16_P21360209 876 -59 2711260 2711319 A_16_P21360210 -22 -59 2711297 2711356 A_16_P03641959 254 -59 2711610 2711659 A_16_P03641960 982 -49 2712641 2712696 A_16_P03641962 1011 -55 2713707 2713765 A_16_P41563648 43 -58 2713808 2713861 A_16_P03641963 -16 -53 2713845 2713893 A_16_P41563649 3460 -48 2717353 2717412 A_16_P03641964 214 -59 2717626 2717685 A_16_P41563655 25 -59 2717710 2717754 A_16_P03641965 1250 -44 2719004 2719063 A_16_P03641966 -36 -59 I need the result like this A_16_P21360207 [405 , -59 , -42] A_14_P136880 [42 , -51, 876] A_16_P21360209 [876 , -59, -22] That is the list has an overlapping with the next lines ..... My script: d = {} fh = open('final_lenght_probe_span','r') while fh: a, b, c, span,len = fh.readline().strip().split('\t') a1,b1,c1,span1,len1 = fh.readline().strip().split('\t') probe_id = c d[probe_id] = [] d[probe_id] = [span,len,span1] for key in d.keys(): print key, d[key] but i am not able to achive at my result what should i do for it..... -------------- next part -------------- An HTML attachment was scrubbed... URL: From istvan.albert at gmail.com Tue Oct 9 08:46:34 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Tue, 09 Oct 2007 12:46:34 -0000 Subject: NUCULAR fielded text searchable indexing In-Reply-To: <1191929178.103375.308840@50g2000hsm.googlegroups.com> References: <1191875335.134872.302660@d55g2000hsg.googlegroups.com> <1191929178.103375.308840@50g2000hsm.googlegroups.com> Message-ID: <1191933994.473730.73100@22g2000hsm.googlegroups.com> On Oct 9, 7:26 am, aaron.watt... at gmail.com wrote: > No, it doesn't stand for anything. It also reminds me of someone we all know, and I wish it didn't. As the latin proverb says "Nomen est omen". Calling your package "docindexer" would draw a lot more people. It is hard to justify to a third party that a project named "nucular" actually does something useful. It looks like a great piece of work otherwise. Congrats. ps. there is a python project named "The Devil Framework", I cringe every time I hear about it. Nucular is not as bad, but it is close. From gneuner2/ at /comcast.net Mon Oct 22 11:30:51 2007 From: gneuner2/ at /comcast.net (George Neuner) Date: Mon, 22 Oct 2007 11:30:51 -0400 Subject: TeX pestilence (was Distributed RVS, Darcs, tech love) References: <1192914246.208743.94870@y27g2000pre.googlegroups.com> <471afd4c.179297746@news.readfreenews.net> <1192972158.250126.203980@v23g2000prn.googlegroups.com> <471b6714$0$90276$14726298@news.sunsite.dk> <1192981349.181197.308610@q5g2000prf.googlegroups.com> <1193037849.011136.282480@y27g2000pre.googlegroups.com> <1193057430.359962.68820@v29g2000prd.googlegroups.com> Message-ID: <1pfph3dqfvhka2b6t5isv39po183ppp5ha@4ax.com> On Mon, 22 Oct 2007 05:50:30 -0700, Xah Lee wrote: >TeX, in my opinion, has done massive damage to the computing world. > >i have written on this variously in emails. No coherent argument, but >the basic thoughts are here: >http://xahlee.org/cmaci/notation/TeX_pestilence.html Knuth did a whole lot more for computing than you have or, probably, ever will. Your arrogance is truly amazing. >1. A typesetting system per se, not a mathematical expressions >representation system. So? >2. The free nature, like cigeratte given to children, contaminated the >entire field of math knowledge representation into 2 decades of >stagnation. What the frac are you talking about? >3. Being a typesetting system, brainwashed entire generation of >mathematicians into micro-spacing doodling. Like they wouldn't be doodling anyway. At least the TeX doodling is likely to be readable (as if anyone cared). >4. Inargurated a massive collection of documents that are invalid >HTML. (due to the programing moron's ingorance and need to idolize a >leader, and TeX's inherent problem of being a typesetting system that >is unsuitable of representing any structure or semantics) HTML is unsuitable for representing most structure and semantics. And legions of fumbling idiots compose brand new invalid HTML every day. >5. This is arguable and trivial, but i think TeX judged as a computer >language in particular its syntax, on esthetical grounds, sucks in >major ways. No one except you thinks TeX is a "computer language". >Btw, a example of item 4 above, is Python's documentation. Fucking >asses and holes. Watch your language, there are children present. George -- for email reply remove "/" from address From Afro.Systems at gmail.com Thu Oct 4 00:49:44 2007 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Thu, 04 Oct 2007 04:49:44 -0000 Subject: Having fun with python In-Reply-To: References: <1191396497.374407.262600@y42g2000hsy.googlegroups.com> Message-ID: <1191473384.349002.9660@o80g2000hse.googlegroups.com> > However, one point you have shown very clearly: the second one is much > easier to tear apart and reassemble. Sure. Zen Of Python: Readbility Counts From python.list at tim.thechases.com Mon Oct 1 13:41:19 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 01 Oct 2007 12:41:19 -0500 Subject: Combine two dictionary... In-Reply-To: <1191259479.116112.104550@w3g2000hsg.googlegroups.com> References: <1191259479.116112.104550@w3g2000hsg.googlegroups.com> Message-ID: <4701313F.7080606@tim.thechases.com> > dict1={1: 4, 3: 5}... and 2 millions element > dict2={3: 3, 8: 6}... and 3 millions element > > I want to combine dict1 and dict2 and i don't want to use FOR because > i need to performance. If you combine your dict1 and dict2 to become result_dict, what should the result of result_dict[3] be? 3 or 5? It sounds like the .update() method on a dict. You can do something like dict2.update(dict1) or disc1.update(dict2) depending on your answer to the above question about what result_dict[3] should be. If you need to preserve dict1 and dict2, rather than update one of them, you can make a copy first: result_dict = dict(dict1) result_dict.update(dict2) this will produce result_dict[3] = 3 whereas if you want it to return 5, swap the order of dict1 and dict. -tkc From nagle at animats.com Thu Oct 11 22:17:55 2007 From: nagle at animats.com (John Nagle) Date: Thu, 11 Oct 2007 19:17:55 -0700 Subject: M2Crypto possible intermittent bug In-Reply-To: References: <%tcPi.58508$YL5.4581@newssvr29.news.prodigy.net> Message-ID: John Nagle wrote: > Heikki Toivonen wrote: >> John Nagle wrote: >>> Still having trouble reproducing the problem. But somewhere, >>> something raised that bogus no-error exception three times. >>> Anything that returns "(0, 'Error')" as exception data is a bug. >> >> If you can, build python and m2crypto with debug symbols, and place >> breakpoints in |case SSL_ERROR_SYSCALL| blocks (from _ssl.i). Then rerun >> the tests. That would be my first guess as to where these might be >> coming from. > > I don't have the right compiler to build it on Windows, and it > doesn't seem to be failing on Linux. It failed three times during > one test run and hasn't failed since. That makes me suspect an > uninitialized data problem in C code. I'll try to reproduce the > problem. > > John Nagle I'm unable to reproduce the problem at this time. Even re-installingM2Crypto doesn't make it recur. I've been rerunning my regression test over and over, and it's not repeatable. I suspect that for some reason Windows networking was generating a local error, and the Windows error status to UNIX-like error status conversion is wrong somewhere. John Nagle From patrick.waldo at gmail.com Sun Oct 21 14:32:57 2007 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Sun, 21 Oct 2007 18:32:57 -0000 Subject: Problem Converting Word to UTF8 Text File In-Reply-To: References: <1192984543.240902.3790@t8g2000prg.googlegroups.com> Message-ID: <1192991577.355854.264410@v29g2000prd.googlegroups.com> Indeed, the shutil.copyfile(doc,txt_doc) was causing the problem for the reason you stated. So, I changed it to this: for doc in glob.glob(input): txt_split = os.path.splitext(doc) txt_doc = txt_split[0] + '.txt' txt_doc_dir = os.path.join(input_dir,txt_doc) doc_dir = os.path.join(input_dir,doc) shutil.copy(doc_dir,txt_doc_dir) However, I still cannot read the unicode from the Word file. If take out the first for-statement, I get a bunch of garbled text, which isn't helpful. I would save them all manually, but I want to figure out how to do it in Python, since I'm just beginning. My intuition says the problem is with FileFormat=win32com.client.constants.wdFormatText because it converts fine to a text file, just not a utf-8 text file. How can I modify this or is there another way to code this type of file conversion from *.doc to *.txt with unicode characters? Thanks On Oct 21, 7:02 pm, "Gabriel Genellina" wrote: > En Sun, 21 Oct 2007 13:35:43 -0300, escribi?: > > > Hi all, > > > I'm trying to copy a bunch of microsoft word documents that have > > unicode characters into utf-8 text files. Everything works fine at > > the beginning. The word documents get converted and new utf-8 text > > files with the same name get created. And then I try to copy the data > > and I keep on getting "TypeError: coercing to Unicode: need string or > > buffer, instance found". I'm probably copying the word document > > wrong. What can I do? > > Always remember to provide the full traceback. > Where do you get the error? In the last line: shutil.copyfile? > If the file already contains the text in utf-8, and you just want to make > a copy, use shutil.copy as before. > (or, why not tell Word to save the file using the .txt extension in the > first place?) > > > for doc in glob.glob(input): > > txt_split = os.path.splitext(doc) > > txt_doc = txt_split[0] + '.txt' > > txt_doc = codecs.open(txt_doc,'w','utf-8') > > shutil.copyfile(doc,txt_doc) > > copyfile expects path names as arguments, not a > codecs-wrapped-file-like-object > > -- > Gabriel Genellina From trekker182 at comcast.net Mon Oct 29 16:31:52 2007 From: trekker182 at comcast.net (Shawn Minisall) Date: Mon, 29 Oct 2007 16:31:52 -0400 Subject: clear shell screen In-Reply-To: References: <47254E9E.3040008@comcast.net> Message-ID: <47264338.8060607@comcast.net> Hmm...it works fine within the command line but then when I import os in python and then try os.system("cls"), i get that very fast opening/closing window and 0 inside the shell. Gabriel Genellina wrote: > En Mon, 29 Oct 2007 00:08:14 -0300, Shawn Minisall > escribi?: > > >> Does anyone know how to clear the shell screen completely ? I tried >> import os and then os.system("clear") was said to have worked in Windows >> XP, but it's just bringing up another window, then it turns black and >> then it closes in within about a second moving the prompt at the >> os.system("clear") line . I've also tried os.system("cls") with the >> same results. >> > > Try running cls from a command prompt. If it works, it should work from > inside Python, using os.system("cls") > > > From deets at nospam.web.de Fri Oct 5 07:28:37 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Oct 2007 13:28:37 +0200 Subject: WebBased Vector 2D Graphics References: <1191579966.073025.168980@50g2000hsm.googlegroups.com> Message-ID: <5mmlf5FeagctU1@mid.uni-berlin.de> cjt22 at bath.ac.uk wrote: > Hi there > > I currently have a Python program outputing to the command line, > durations of 'completed Steps' and 'data items' in relation to time > i.e. > > > --------------jfh > ---------kl //kl started after jfh finished > % Ds //new data arrived at this point in time > -------pl (1) //Details error with finsihed Step > *kl // This step is now outputed but > due to error with pl is cancelled (no duration) > > I am new to doing any web based development and don't have a clue > where to start! I just wondered what is the best way to output this > program to a web page graphically. > > I want to be able to represent these durations "-----" as rectangles > and as the program runs the page will refresh every 10 seconds, thus > the boxes will expand with time until they have finished. New data > will also be represented in boxes with a different colour. I believe > some kind of script will have to be run which constantly updates the > html page after x seconds which then causes the web page to refresh > with the updated data. > > Is there any way this web programming can be done in python. Or > perhaps I can use soemthing such as ajax? > > As mentioned previously, I have never done any web based development > so don't really know what I'm talking about when trying to understand > how I can go from this Python program output to producing some > graphical output on a web page. You certainly need to get on speed with webdevelopment. Otherwise you will fail miserably. There are several options here: - rendering a server-side image, deliver that embedded in a html-page - render using html tags like DIV and the like, which allow for positioned colored rectangles and text, in pixel coordinates - canvas tag, to render 2D-drawing-commands - embedded SVG All that can be enriched with AJAX to have that fancy realtime-update-thingy. Diez From aaron.watters at gmail.com Wed Oct 31 09:45:00 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Wed, 31 Oct 2007 13:45:00 -0000 Subject: marshal vs pickle In-Reply-To: References: Message-ID: <1193838300.998229.33380@v3g2000hsg.googlegroups.com> On Oct 31, 3:31 am, "Evan Klitzke" wrote: > Can anyone elaborate more on the difference between marshal and > pickle. In what conditions would using marshal be unsafe? If one can > guarantee that the marshalled objects would be created and read by the > same version of Python, is that enough? Yes, I think that's enough. I like to use marshal a lot because it's the absolutely fastest way to store and load data to/from Python. Furthermore because marshal is "stupid" the programmer has complete control. A lot of the overhead you get with the pickles which make them generally much slower than marshal come from the cleverness by which pickle will recognized shared objects and all that junk. When I serialize, I generally don't need that because I know what I'm doing. For example both gadfly SQL http://gadfly.sourceforge.net and nucular full text/fielded search http://nucular.sourceforge.net use marshal as the underlying serializer. Using cPickle would probably make serialization worse than 2x slower. This is one of the 2 or 3 key tricks which make these packages as fast as they are. -- Aaron Watters === http://www.xfeedme.com/nucular/gut.py/go?FREETEXT=halloween From zorg724 at yahoo.fr Sat Oct 20 15:10:34 2007 From: zorg724 at yahoo.fr (sccs cscs) Date: Sat, 20 Oct 2007 21:10:34 +0200 (CEST) Subject: Get the instance name from a list by Reflection Message-ID: <57045.94694.qm@web90513.mail.mud.yahoo.com> Hello, I cannot find into documentation how to get the instance name. I found the attributes __dict__,__class__ ,__bases__ __name__ , but if i have the code: class A :pass a1 = A () a2 = A () aList = [a1,a2] for elem in aList : print elem.__instance_name__ ??? I expect to have "a1" "a2" ... But it does not work ... help please Zorgi --------------------------------- Ne gardez plus qu'une seule adresse mail ! Copiez vos mails vers Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.hankin at gmail.com Sun Oct 14 10:41:52 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Sun, 14 Oct 2007 14:41:52 -0000 Subject: Order of tuples in dict.items() In-Reply-To: <47122790$0$8421$db0fefd9@news.zen.co.uk> References: <47122790$0$8421$db0fefd9@news.zen.co.uk> Message-ID: <1192372912.572289.260920@k35g2000prh.googlegroups.com> On Oct 14, 3:28 pm, Will McGugan wrote: > If I have two dictionaries containing identical values, can I be sure > that the items() method will return tuples in the same order? > ... > Can I rely on this behavior? No. To quote the python documentation: > Keys and values are listed in an arbitrary order which is > non-random, varies across Python implementations, and > depends on the dictionary's history of insertions and deletions. In general, looking at documentation is better than experimenting when you want to know if something is either always true or mostly true. -- Paul Hankin From steve at holdenweb.com Tue Oct 2 16:16:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 02 Oct 2007 16:16:46 -0400 Subject: Mysqldb printing sql and params ... NEVER MIND In-Reply-To: <0A53725C4A497848A7B3A0874B2598313D38C6@acesxch01.ADVENTISTCORP.NET> References: <0A53725C4A497848A7B3A0874B2598313D38C4@acesxch01.ADVENTISTCORP.NET> <0A53725C4A497848A7B3A0874B2598313D38C6@acesxch01.ADVENTISTCORP.NET> Message-ID: Sells, Fred wrote: > el stupido here "accidently" put a couple of print statements into a > mysqldb module when eclipse opened it from the link in the stacktrace; > :-) -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From juan at juanreyero.com Tue Oct 16 04:33:07 2007 From: juan at juanreyero.com (juan at juanreyero.com) Date: Tue, 16 Oct 2007 10:33:07 +0200 Subject: ANN: magnitude 0.9.1 References: <873awb5wgw.fsf@benfinney.id.au> Message-ID: Ben Finney writes: > Please don't ever recommend 'from foo import *' in end-user > documentation. It's generally a bad practice and should only be done > when the individual programmer understands the tradeoffs involved; > putting it in the documentation for a module is setting a poor > example. Got it, and solved. Thanks. I have been carelessly using it like that for a long time (I was, after all, guilty of any name it imported into my namespace) and I didn't think about the implications for others in the documentation. jm From steve at REMOVE-THIS-cybersource.com.au Wed Oct 10 09:39:29 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 10 Oct 2007 13:39:29 -0000 Subject: Singleton References: <1192009016.858568.58430@50g2000hsm.googlegroups.com> Message-ID: <13gplgh75hot354@corp.supernews.com> On Wed, 10 Oct 2007 09:36:56 +0000, pythoncurious wrote: > So how do people solve this? Is there an obvious way that I missed? Mostly by avoiding singletons. Why do you need only one instance? Perhaps you should consider the Borg pattern instead. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 -- Steven From python at rcn.com Wed Oct 3 13:22:03 2007 From: python at rcn.com (Raymond Hettinger) Date: Wed, 03 Oct 2007 10:22:03 -0700 Subject: enumerate overflow In-Reply-To: <7xmyv0nn7f.fsf@ruckus.brouhaha.com> References: <1191411991.165082.19010@o80g2000hse.googlegroups.com> <5mheq7Fd78r2U2@mid.uni-berlin.de> <7xmyv0nn7f.fsf@ruckus.brouhaha.com> Message-ID: <1191432123.619871.226360@g4g2000hsf.googlegroups.com> [Paul Rubin] > I hope in 3.0 there's a real fix, i.e. the count should promote to > long. In Py2.6, I will mostly likely put in an automatic promotion to long for both enumerate() and count(). It took a while to figure-out how to do this without killing the performance for normal cases (ones used in real programs, not examples contrived to say, "omg, see what *could* happen"). Raymond From stargaming at gmail.com Mon Oct 1 10:21:52 2007 From: stargaming at gmail.com (Stargaming) Date: 01 Oct 2007 14:21:52 GMT Subject: Fwd: Using fractions instead of floats References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> <1191206183.441075.167450@57g2000hsv.googlegroups.com> <52c50880709302007g4103c6c6h9b09ee376fa77998@mail.gmail.com> Message-ID: <47010280$0$11466$9b622d9e@news.freenet.de> On Sun, 30 Sep 2007 20:10:05 -0700, Andres Riofrio wrote: [snip] >>From what I've read, seems that the principal reason for rejecting the > PEP is that there was not much need (enthusiasm)... Well, then I have a > question: Is there a way to make 5/2 return something other than an > integer? I can do: > class int(int): > def __add__(self, other): > pass > but that will only work if I do int(5)/int(2)... > > (setting __builtin__.int=int doesn't work, either) > > What I'd like is to be able to implement what I put in the proposal, as > I don't think it's a really big language change... [snip] You could make up an example implementation by using fractionizing_int (1) / fractionizing_int(3) (or whatever name you come up with). I don't know of any particularly nice way to Just Let It Work anywhere in python (perhaps some ugly byte code hacks, automatically wrapping ints). So, you would have to implement it in C if you want to propose this for CPython. And that's no 5 minute task, I guess. Still, having this `int` behaviour working globally would include those previously mentioned irrational numbers (but Pi is rational in any visualization anyways, so FWIW that wouldn't be too much of a blockade). But where would you put normal integer division then? Introducing a new type seems best to me. You could, as well, try to implement this in PyPy. If this would hit the broad masses is another question, though. ;) Regards, stargaming From erik at myemma.com Tue Oct 23 13:10:13 2007 From: erik at myemma.com (Erik Jones) Date: Tue, 23 Oct 2007 12:10:13 -0500 Subject: greatest and least of these... In-Reply-To: <471E19B1.2040909@comcast.net> References: <471E19B1.2040909@comcast.net> Message-ID: On Oct 23, 2007, at 10:56 AM, Shawn Minisall wrote: > I just wrote a program to let the user input a series of whole numbers > and tell them which is least and which is greatest based off of a > menu. > However, the menu isn't kicking in after they pick a number. I > included > a while statement for a loop just for the menu and compared it to my > other programs that have a similar setup and are working, but I'm > stumped. Here's the program... > > def main(): > > #define and initialize variables > #choice as int > choice = 0 > #number as int > number = 0 > > #intro > print "WELCOME TO THE GREATEST AND LEAST NUMBER PROGRAM!" > print > > #Menu loop > while choice != 2: > #display menu > print "Please choose from the following menu: " > print "1. Enter a number" > print "2. Exit" > print > > #prompt user for their menu choice > choice = input("Enter your choice here: ") > > #if statements to determine which choice > if choice == 1: > nums = [] > while number >=0: > nums.append(number) > number = input("Please enter a number.") You're telling the script to continue asking for numbers until a non- positive number is entered. Enter a negative number and you'll see your menu again. What you probably want is to change this. > > > elif choice == 2: > print "Have a great day!" > > if len(nums) > 0: > print "The smallest number that you entered > was:",min(nums) > print "The largest number that you entered was:",max > (nums) > > else: > #invalid > print "Invalid selection. Enter either one or two." > print > > Also, if they quit the program with choice #2 and entered numbers, it > should display the greatest and least of them. If they just > started and > didn't enter anything and want to quit, I get an error message saying > UnboundLocalError: local variable 'nums' referenced before assignment. > Isn't the if statement supposed to keep python from going there > since if > they didn't enter any input, the length of the list should just be > zero. The exception is because you're not ensure that nums is ever initialized. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From panguohualove at sina.com Tue Oct 9 01:47:21 2007 From: panguohualove at sina.com (panguohua) Date: Mon, 08 Oct 2007 22:47:21 -0700 Subject: more information for making money Message-ID: <1191908841.319307.177990@22g2000hsm.googlegroups.com> www.space666.com good!!!!!!!!!!! From martin at v.loewis.de Sun Oct 21 16:57:57 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Oct 2007 22:57:57 +0200 Subject: C++ version of the C Python API? In-Reply-To: <496954360710211349p4278f4f3g675c657f7740980f@mail.gmail.com> References: <471B8711.1020509@v.loewis.de> <496954360710211250x1389a594m1551b3389cc9d5dd@mail.gmail.com> <471BB1FA.1020704@v.loewis.de> <496954360710211349p4278f4f3g675c657f7740980f@mail.gmail.com> Message-ID: <471BBD55.9030601@v.loewis.de> > Could you emphasize a little more? I haven't worked much at all with > the Python C API, so I may be misunderstanding. First of all, you say > that the "Python C API is object oriented", which is contradictory > because it should read "Python C++ API is object oriented". Perhaps > this is a typo, or maybe you're referencing some C++ wrapper for the > Python C API that you failed to mention the name of. No, I literally meant that the Python C API is object-oriented. You don't need an object-oriented language to write object-oriented code. > You also mentioned that there are "multiple C++ wrappers arround the > Python C API Available"... could you provide names for a few of the > popular ones? The most popular ones are Boost.Python, CXX, and PySTL. Regards, Martin From carsten at uniqsys.com Thu Oct 11 09:42:10 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 11 Oct 2007 09:42:10 -0400 Subject: Problem with MySQL cursor In-Reply-To: References: Message-ID: <1192110130.3387.5.camel@dot.uniqsys.com> On Thu, 2007-10-11 at 15:14 +0200, Florian Lindner wrote: > Hello, > I have a function that executes a SQL statement with MySQLdb: > > def executeSQL(sql, *args): > print sql % args > cursor = conn.cursor() > cursor.execute(sql, args) > cursor.close() > > it's called like that: > > sql = "INSERT INTO %s (%s) VALUES (%s)" > executeSQL(sql, DOMAIN_TABLE, DOMAIN_FIELD, domainname) You can't use parameter binding to substitute table names and column names, or any other syntax element, into a query. You can only bind parameters in places where a literal value would be allowed (more or less, the real rules are more complicated, but this rule of thumb gets you close enough). You have to construct the query string like this, for example: sql = "INSERT INTO "+DOMAIN_TABLE+"("+DOMAIN_FIELD+") VALUES (%s)" executeSQL(sql, domainname) HTH, -- Carsten Haese http://informixdb.sourceforge.net From deets at nospam.web.de Thu Oct 25 17:41:41 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Oct 2007 23:41:41 +0200 Subject: threading problem.. In-Reply-To: <1193346037.742074.16730@z9g2000hsf.googlegroups.com> References: <1193346037.742074.16730@z9g2000hsf.googlegroups.com> Message-ID: <5ocgt5Fm7ku1U1@mid.uni-berlin.de> Abandoned schrieb: > Hi.. > I want to threading but i have a interesting error.. > ========== > class SelectAll(threading.Thread): > def __init__(self, name): > threading.Thread.__init__(self) > self.name = name #kelime > > def run(self): > .... > .... > self.result=... > nglist=[] > current = SelectAll(name) > nglist.append(current) > current.start() > for aaa in nglist: > aaa.join() > > ============= > > and it gives me this error: > aaa.join() > > AttributeError: 'dict' object has no attribute 'join' > > > What is the problem i can't understand this error :( that you have an attribute join on you SelectAll-objects that shadows the Thread.join Diez From grante at visi.com Tue Oct 16 23:38:04 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 17 Oct 2007 03:38:04 -0000 Subject: why doesn't have this list a "reply-to" ? References: <471530E3.9090602@gmail.com> Message-ID: <13hb0ss1oamhr14@corp.supernews.com> On 2007-10-16, Robert Kern wrote: > It's not universal. Many people consider it harmful. Google "reply-to considered > harmful" for a variety of opinions, for and against. > > I use GMane to read and post to this list because I like my lists to act like > USENET. > > http://gmane.org Since "this list" is just mirroring a Usenet news group, wouldn't it be more straight-forward to just use a real Usenet news server? -- Grant Edwards grante Yow! You should all JUMP at UP AND DOWN for TWO HOURS visi.com while I decide on a NEW CAREER!! From trekker182 at comcast.net Sun Oct 28 21:02:02 2007 From: trekker182 at comcast.net (Shawn Minisall) Date: Sun, 28 Oct 2007 21:02:02 -0400 Subject: while within while In-Reply-To: <13i88bo9djpu279@corp.supernews.com> References: <13i88bo9djpu279@corp.supernews.com> Message-ID: <4725310A.7080500@comcast.net> Thanks a lot for your suggestions. Unfortunately, a lot of the issues brought up were simply the way I was taught by my professor and the way she wants things done,having to use a numbered menu as opposed to entering r, p or s, being taught just to use one main function for the entire program, having to init all variables in the program b4 the actual program starts or else points off for each program, while statements surrounding every input statement for input validation purposes... Going beyond those things, would look like someone else wrote my program since we didn't talk about or ever cover them in class. I think we get to true statements in the next chapter next week. It turns out that my problem was with indentation, as soon as I fixed it, it's working perfectly now. thx Dennis Lee Bieber wrote: > On Sat, 27 Oct 2007 15:11:37 -0400, Shawn Minisall > declaimed the following in comp.lang.python: > > Smells like homework -- so this week I won't be supplying a working > program (even one with no documentation -- requiring the student to > study the reference manuals to figure out what is being done) I'm going > to more focus on some stylistic features. > >> import random >> >> >> def main(): >> >> #define and initialize variables >> #choice as int >> choice = 0 >> > > Please note that one cannot define /type/ for a variable NAME. the > name is just a name that is attached to an object, and can be attached > to some other object later... It is the object on the RHS of the > assignment that has a type. > > The above binds the name "choice" to an object of type integer -- a > 0... The type is part of the 0, not of the name. > > >> #play again loop >> again = "no" >> > > > >> >> #Menu loop >> while choice != 4: >> #display menu >> print "Please choose from the following menu: " >> print "1. See the rules" >> print "2. Play against the computer" >> print "3. Play a two player game" >> print "4. Exit" >> >> #prompt user for their menu choice >> choice = input("Please enter your choice here: ") >> print >> >> > Rather than having to pre-initialize your loop conditional (and > notice that you can use ANY value EXCEPT 4 to initialize it) just for > the pleasure of using a while loop (I'm guessing being taught from the > "go to is forbidden" crowd, and not knowing of structured loop exits..) > that you go out of your way to avoid duplicating code (Pardon my > phrasing -- I'm not quite sure what my point was trying to be...) Let me > just mention that in Ada, what you are trying would be formulated as: > > loop > --display menu > -- prompt for choice > exit when choice = 4 > -- process other choices > end loop > > No need to preload the condition variable, since the first time it > is used is when it receives a value from the user. > > Python can produce the same formulation... (hint: the naked "loop" > in Ada is "while True" in Python). > > >> >> >> #if statements to determine which choice >> if choice == 1: >> print >> print "The rules of the game are as follows: " >> print >> print "Rock Covers Rock" >> print >> print "Rock Smashes Scissors" >> print >> print "Scissors Cuts Paper" >> print >> print >> >> > Python triple quoted strings can be split over multiple lines: > > print """ > The rules of the game are as follows: > > Paper Covers Rock > > Scissors Cut Paper > > Rock Breaks Scissors > > """ > even better -- This should be an initialized item at the start of the > program: > > rules = """ > The rules... etc. > """ > and then you just use one > > print rules > > > >> >> elif choice == 2: >> while again[0] == "y": >> > > I'd suggest same concern as prior while loop... don't preload > choices when the real determination can only be made after first > entering the loop. > > Secondly... If you are taking user input, you should probably expect > things like case changes.... > > while again.lower().startswith("y") > > >> #display menu >> print "Please choose a weapon from the following menu: " >> print "1. Rock" >> print "2. Paper" >> print "3. Scissors" >> >> while weaponchoice != 1 and weaponchoice != 2 and >> weaponchoice != 3: >> > > A third preloaded nested while loop... And why require numeric > input? Why not allow the user to enter, say "r" for rock? > > >> weaponchoice = input("Please choose a weapon: ") >> > > Don't use input()... input() will evaluate whatever the user types > as Python statements... the user could enter a one-liner that attempts > to delete all the files on your machine. > > USE raw_input() -- this gives you a string which you can then pass > to a conversion function that will only return what is valid... > > ... = int(raw_input(...)) > > > >> if weaponchoice != 1 and weaponchoice != 2 and >> weaponchoice != 3: >> print >> print "Error. Please enter a number from 1-3." >> >> decision = (1, 2, 3) >> > > Presuming this tuple will never change, this is another candidate > for initialization at the top of the file... > > DECISION = (1, 2, 3) #all caps is a convention to indicate a > "constant" > > >> ai = str((random.choice(decision))) >> >> > Why are you taking a random integer, converting it to a string, and > then... > > >> if ai == "1": >> ai = "rock" >> > > ... comparing the stringified value to a character literal -- only to > then assign a text string to the variable? > > >> if ai == "2": >> ai = "paper" >> if ai == "3": >> ai = "scissors" >> >> > > ai = ["rock", "paper", "scissors"][random.choice(decision)] > > replaces all the above... > > >> if weaponchoice == 1: >> weaponchoice = "rock" >> >> elif weaponchoice == 2: >> weaponchoice = "paper" >> >> else: >> weaponchoice = "scissors" >> >> > > Another "use the same variable name but change it from numeric input > to text string" > > wc = ["rock", "paper", "scissors"][weaponchoice] > > > >> print "=====================" >> print "you choose " + weaponchoice >> print >> print "I choose " + ai >> print >> >> if weaponchoice == "rock" and ai == "scissors": >> win += 1 >> print "You WIN by SMASHING those SCISSORS!" >> >> elif weaponchoice == "paper" and ai == "rock": >> win += 1 >> print "You WIN by COVERING that ROCK!" >> >> elif weaponchoice == "scissors" and ai == "paper": >> win += 1 >> print "You WIN by CUTTING that PAPER!" >> >> elif weaponchoice == ai: >> tie += 1 >> print "YOU TIE!" >> >> else: >> lose += 1 >> print "YOU LOSE!" >> >> > > I'd suggest converting the above to a decision table, though that > may be getting too fancy for an intro homework assignment... > > DTable = { "rock" : { "rock" : ("TIE", ""), > "paper" : ("LOSE", "Covers"), > "scissors" : ("WIN", "Breaks") }, > "paper" : { "rock" : ("WIN", "Covers"), > "paper" : ("TIE", ""), > "scissors" : ("LOSE", "Cut") }, > "scissors" : { "rock" : ("LOSE", "Breaks"), > "paper" : ("WIN", "Cut"), > "scissors" : ("TIE, "") } } > > used by: > > (result, means) = DTable[ai][wc] > if result == "TIE": > print "It is a tie" > tie += 1 > elif result == "LOSE": > print "You lose: %s %s %s" % (ai, means, wc) > lose += 1 > elif result == "WIN": > print "You win: %s %s %s" % (wc, means, ai) > win += 1 > > > >> elif choice == 4: >> print "Have a great day!" >> print >> print "Thanks for playing!" >> >> > Note how you are still processing the exit choice here which means > you have two places in the code that have to check for choice 4 > > > > If I haven't confused you enough with the above, and you still are > enamored of numeric menu choices... > > def getNumChoice(menu, minvalue, maxvalue): > while True > print menu > c = int(raw_input("\nEnter your choice [by number] => ")) > if minvalue <= c <= maxvalue: return c > print "\n*** %s is not valid, please try again\n\n" % c > > usage... > > MAINMENU = """ > Please select from the following choices: > > 1: See the rules > 2: Play against the computer > 3: Play against another player > 4: Exit > """ > > WEAPONMENU = """ > Please select from the following choices: > > 1: Rock > 2: Paper > 3: Scissors > """ > > WEAPONLIST = [ "rock", "paper", "scissors" ] > > while True: > mc = getNumChoice(MAINMENU, 1, 4) != 4 > if mc == 1: > #do stuff > elif mc == 2: > wc = WEAPONLIST[getNumChoice(WEAPONMENU, 1, 3) - 1] > ai = random.choice(WEAPONLIST) > > etc... > From kadeko at gmail.com Mon Oct 15 07:01:49 2007 From: kadeko at gmail.com (looping) Date: Mon, 15 Oct 2007 04:01:49 -0700 Subject: Twisted (or for loops ?) madness In-Reply-To: <1192444397.510886.48990@i13g2000prf.googlegroups.com> References: <1192434369.994950.33940@v29g2000prd.googlegroups.com> <1192443010.957983.81970@q3g2000prf.googlegroups.com> <1192444397.510886.48990@i13g2000prf.googlegroups.com> Message-ID: <1192446109.954833.322080@v29g2000prd.googlegroups.com> On Oct 15, 12:33 pm, Michele Simionato wrote: > is a design decision, in the sense that Python always do late binding. > If you > you will get funclist[0]() == funclist[1]() == funclist[2]() == 3 (you > get the latest > binding of "i"). As you see, it has nothing to do with lambdas. > Thanks Diez, replacing my addCallback with d.addCallback(lambda result, comp=c: comp.compile()) do the trick. So if I understand what Michele wrote (thanks too), when a function is defined (with def), no scope is saved and every variable value not passed in parameter is lost ? It means that variable value come from the outer scope when the function is called ? From steve at REMOVE-THIS-cybersource.com.au Sat Oct 20 21:01:51 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 21 Oct 2007 01:01:51 -0000 Subject: what is the difference between the two kinds of brackets? References: <1192875315.887877.210550@y27g2000pre.googlegroups.com> Message-ID: <13hl97vnvqui6df@corp.supernews.com> On Sat, 20 Oct 2007 12:43:31 +0000, Steve Lamb wrote: > The quick answer is that tuples can be indexes into directories > while lists cannot. A note on terminology: the things inside curly brackets {} are called dictionaries, or dicts, not directories. And the things you use to store data in dictionaries are called keys, not indexes: # Lists have indexes: L = ['x', 'y', 'z'] L[0] # returns the item in position 0 # Dicts have keys: D = {'a': 'x', 2: 'y', 7.8: 'z'} D['a'] # returns the item with key 'a' -- Steven. From pavlovevidence at gmail.com Wed Oct 3 23:00:20 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 3 Oct 2007 23:00:20 -0400 Subject: migrating to packages References: <4703C661.50009@fmed.uba.ar> <27E2B61D-3D3E-466D-9650-69E0DA27E952@myemma.com> Message-ID: <47045b29$0$11005$4c368faf@roadrunner.com> On Wed, 03 Oct 2007 22:28:57 -0300, gherzig wrote: >> On Oct 3, 2007, at 11:42 AM, Gerardo Herzig wrote: >> >>> Hi all. I have a single file with several classes, wich i want to >>> separate into several packages. >>> The big file is named, say MYCLASES, and contains a class named >>> A(object), and B(A). >>> >>> We have been using this MYCLASES in the from MYCLASES import B syntax, >>> but i cant reproduce this syntax using packages. Im forced to write >>> from PACKAGE.B import *, and if that means >>> i have to touch so many files, that would really be a problem to me. >>> There is (i cant find it yet) a place where i can read about that kind >>> of package 'migration' situation? >>> >>> Because i *really* want to keep the FROM PACKAGE import B syntax. >> >> http://www.python.org/doc/current/tut/ >> node8.html#SECTION008400000000000000000 > I have already read those files (and i just read it again), but still > cant find the solution. Maybe i just do not explain myself in the > correct way (or i am very very stupid :) > I will expose my case quicly. > The MYCLASES.py file contains the A class, so i can use from MYCLASES > import A > a = () > > Using the "package mode" (wich looks fine BTW), having the simple > MYCLASES/ > __init__.py > A.py > > forces my (i guess) to use the > from MYCLASES.A import A > > which is not what i want, because the big amount of files i will have to > modify (and im not alones, there is a group of dudes who use this > MYCLASES) > > Im i missing something in that docs you post? Thanks!! Add these lines in __init__.py: from MYCLASSES.A import A from MYCLASSES.B import B Carl Banks From schaefer.mp at gmail.com Tue Oct 16 17:48:52 2007 From: schaefer.mp at gmail.com (schaefer.mp at gmail.com) Date: Tue, 16 Oct 2007 21:48:52 -0000 Subject: negative base raised to fractional exponent Message-ID: <1192571332.470809.279160@v23g2000prn.googlegroups.com> Does anyone know of an approximation to raising a negative base to a fractional exponent? For example, (-3)^-4.11111 since this cannot be computed without using imaginary numbers. Any help is appreciated. From grante at visi.com Fri Oct 12 11:51:07 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 12 Oct 2007 15:51:07 -0000 Subject: Cross-platform GUI development References: <1192176809.756259.316980@v29g2000prd.googlegroups.com> <1192178193.734126.253610@z24g2000prh.googlegroups.com> <13gv5jj9u5hege8@corp.supernews.com> Message-ID: <13gv5vb9u7fqg21@corp.supernews.com> On 2007-10-12, Grant Edwards wrote: > I use wxPython, because it uses Gtk on Linux, and Gtk is > "native" for both me and for my Windows users. I didn't state that very well. What I meant was that wxPython uses Gtk under Linux (which is native for me) so wxPython looks native for both me and my Windows users. -- Grant Edwards grante Yow! I demand IMPUNITY! at visi.com From bignose+hates-spam at benfinney.id.au Sun Oct 28 23:15:04 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 29 Oct 2007 14:15:04 +1100 Subject: coverage.py: "Statement coverage is the weakest measure of code coverage" References: <87bqaihmq7.fsf@benfinney.id.au> <1193624413.723453.71700@22g2000hsm.googlegroups.com> Message-ID: <87odeifw7b.fsf@benfinney.id.au> Kay Schluehr writes: > I used to write once a coverage tool ( maybe I can factor this out > of my tool suite some time ) That'd be wonderful. I'd like to see comparisons between different test-coverage tools, just as we have the different but comparable 'pyflakes' and 'pylint' code inspection tools. > Given it's nature it might act transformative. So a statement: > > if a and b: > BLOCK > > can be transformed into > > if a: > if b: > BLOCK I don't see that this actually helps in the cases described in the original post. The lack of coverage checking isn't "are both sides of an 'and' or 'or' expression evaluated", since that's the job of the language runtime, and is outside the scope of our unit test. what needs to be tested is "do the tests execute both the 'true' and 'false' branches of this 'if' statement", or "do the tests exercise the 'no iterations' case for this loop", et cetera. That is, whether all the functional branches are exercised by tests, not whether the language is parsed correctly. -- \ "Know what I hate most? Rhetorical questions." -- Henry N. Camp | `\ | _o__) | Ben Finney From paul.hankin at gmail.com Wed Oct 31 20:12:26 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 01 Nov 2007 00:12:26 -0000 Subject: a few questions. In-Reply-To: References: Message-ID: <1193875946.806750.211150@o38g2000hse.googlegroups.com> On Oct 31, 10:10 pm, Larry Bates wrote: > for i in xrange(0,5): > hundreds, remainder=divmod(stores[i], 100) > print "Store: %i %s" % (i+1, hundreds*"*") Yes, or since you don't need 'remainder'... for i in range(5): hundreds = stores[i] // 100 print "Store: %i %s" % (i + 1, '*' * hundreds) -- Paul Hankin From arnodel at googlemail.com Thu Oct 25 05:30:29 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 25 Oct 2007 09:30:29 -0000 Subject: about functions question In-Reply-To: <1193293696.450188.108330@q3g2000prf.googlegroups.com> References: <1193293696.450188.108330@q3g2000prf.googlegroups.com> Message-ID: <1193304629.429307.50980@v3g2000hsg.googlegroups.com> On Oct 25, 7:28 am, NoName wrote: > I try it: > > def b(): > ... > a() > ... > > def a(): > ... > b() > ... > > b() > it's not work. Probably all those dots! > Is it possible pre-define function like in c++ or place functions code > after main block? Python binds names to objects dynamically: this means that when a() is compiled, the "b()" line in its definition is compiled to something that says "look for the object currently bound to the name 'b' in the global dictionary, and execute the __call__ method of that object with no arguments". It doesn't make any difference what object 'b' is bound to at this time. HTH -- Arnaud From mail at timgolden.me.uk Fri Oct 12 06:38:55 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 12 Oct 2007 11:38:55 +0100 Subject: Script to Remove Attachments in Exchange Mailbox In-Reply-To: <470F2FC4.8020908@timgolden.me.uk> References: <1192110265.529187.48770@y42g2000hsy.googlegroups.com> <1192118025.085938.283610@19g2000hsx.googlegroups.com> <470F2FC4.8020908@timgolden.me.uk> Message-ID: <470F4EBF.2020309@timgolden.me.uk> Tim Golden wrote: > [KDawg44] > >>>> I am frustrated with my users who send large files around the office >>>> instead of using the network shares. > > [Tim Golden] >>> I have something v. similar, ... >>> It's a while since they were last run to they're probably quite >>> dusty but it sounds like the kind of thing you're after. > > Well, here's[1] the first part -- running through folders and replacing > big attachments with links. ... and here's [1] the second part -- running through folders on disk and replacing duplicate files with a link to the first one found. For obvious reasons, be careful with this: it deletes files and replaces them with hardlinks, but there's no rollback. Nor is it so well commented as the other, I'm afraid, but I think it is still fairly clear what's going on. You call it with a space-separated list of directories to search (usually one in my own experience) and it walks down those directory trees looking for files of type INCLUDE_EXTENSIONS except for files called IGNORE_FILES. Its comparison is very simple: comparing md5 hashes with no optimisations; obviously a lot of work could be done there if it were an issue. It ends up with nested dictionaries, the outer one keyed by filename, the inner one by size and containing a list of directories where files of that name/size are found. The first in the list is considered the master and all the others are deleted and replaced by NTFS hardlinks. Probably safer to hardlink first to an alias, *then* delete and then rename the alias, but I leave that up to you if you want to use the script at all. TJG [1] http://timgolden.me.uk/python/downloads/find_duplicate_files.py From brunovianarezende at gmail.com Sat Oct 6 08:37:04 2007 From: brunovianarezende at gmail.com (Bruno Rezende) Date: Sat, 06 Oct 2007 12:37:04 -0000 Subject: my Python lib is broken In-Reply-To: References: <1191672177.389263.185790@g4g2000hsf.googlegroups.com> Message-ID: <1191674224.334287.159280@o3g2000hsb.googlegroups.com> Thanks for the information! Indeed, I was geting an error when trying to do: from xml.dom import minidom but it was because there is a xml.py file inside the same package, so it happens a conflict... On Oct 6, 9:22 am, "Guilherme Polo" wrote: > 2007/10/6, Bruno Rezende : > > > Hi, > > > I think I've broken my python installation (don't know how). All the > > packages that are under 'lib' in python installation doesn't work the > > way expected: > > > >>> import xml > > >>> xml.dom > > Traceback (most recent call last): > > File "", line 1, in > > AttributeError: 'module' object has no attribute 'dom' > > This is not broken. It is how packages works. > xml is a package, dom is a package inside xml. If you want to check > the attributes that you get importing xml you do dir(xml) > > > but, if I import * from xml, it starts to work again: > > > >>> from xml import * > > Doing that will cause the __init__.py inside package xml to check its > __all__ list and import them all, including dom > > > >>> xml.dom > > > > > Does someone know why is this happening? (I can reinstall my python > > 2.5, but would like to know how the python lib got broken). > > This is hapenning because you have installed Python, congratulations =) > > > > > regards, > > Bruno > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves From gregturn at mindspring.com Thu Oct 11 16:08:15 2007 From: gregturn at mindspring.com (Goldfish) Date: Thu, 11 Oct 2007 13:08:15 -0700 Subject: determining fully qualified package & class name In-Reply-To: <5n78g6Fghr61U8@mid.uni-berlin.de> References: <5n78g6Fghr61U8@mid.uni-berlin.de> Message-ID: <1192133295.392180.213400@19g2000hsx.googlegroups.com> import myPackage f = myPackage.foo() print f.__module__ + "." + f.__class__.__name__ That should do it! From mail at microcorp.co.za Thu Oct 4 03:43:49 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Oct 2007 09:43:49 +0200 Subject: racism kontrol References: <1191430790.537383.115880@r29g2000hsg.googlegroups.com> <1191435296.523842.160230@g4g2000hsf.googlegroups.com> <4703f631$0$7692$9b4e6d93@newsspool2.arcor-online.net> <47041be6$0$30382$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <017701c8065a$d284c900$03000080@hendrik> "Wildemar Wildenburger" wrote: > (By the way: Accusing a German of racism is almost too easy an insult. > Not that I had taken any, just saying.) I always thought that it would be insulting to a German if you accused him or her of not being a racist... - Hendrik From nagle at animats.com Tue Oct 2 11:00:19 2007 From: nagle at animats.com (John Nagle) Date: Tue, 02 Oct 2007 15:00:19 GMT Subject: Why doesn't Python's "robotparser" like Wikipedia's "robots.txt" file? In-Reply-To: References: Message-ID: <72tMi.30611$eY.26756@newssvr13.news.prodigy.net> Lawrence D'Oliveiro wrote: > In message , John Nagle > wrote: > >> For some reason, Python's parser for "robots.txt" files >> doesn't like Wikipedia's "robots.txt" file: >> >> >>> import robotparser >> >>> url = 'http://wikipedia.org/robots.txt' >> >>> chk = robotparser.RobotFileParser() >> >>> chk.set_url(url) >> >>> chk.read() >> >>> testurl = 'http://wikipedia.org' >> >>> chk.can_fetch('Mozilla', testurl) >> False >> >>> > > >>> chk.errcode > 403 > > Significant? > Helpful. Also an undocumented feature. See http://docs.python.org/lib/module-robotparser.html John Nagle From nagle at animats.com Wed Oct 31 11:26:06 2007 From: nagle at animats.com (John Nagle) Date: Wed, 31 Oct 2007 08:26:06 -0700 Subject: Python bug tracker now secret? In-Reply-To: References: Message-ID: <47289e6e$0$14147$742ec2ed@news.sonic.net> Jean-Paul Calderone wrote: > On Wed, 31 Oct 2007 07:53:01 -0700, John Nagle wrote: >> I'm now getting messages like this from the Python bug tracker on >> SourceForge: >> >> Artifact: This Artifact Has Been Made Private. Only Group Members Can >> View Private ArtifactTypes. >> >> I'm being denied access to bug reports I submitted, such as >> >> https://sourceforge.net/tracker/?func=detail&aid=1651995&group_id=5470&atid=105470 >> >> >> This is only happening for Python bugs; bugs in non-Python areas are >> still >> accessable. So it's not a general SourceForge bug. >> >> Is this a dumb policy change or a dumb administrator action? >> > > I don't know why they chose to make the sf tracker private. Maybe that > was the only way to remove write access. Python bugs are now tracked > at http://bugs.python.org/. > > Jean-Paul There are bug reports in the SourceForge tracker that aren't in the "bugs.python.org" tracker, so that move was botched. John Nagle From chris.monsanto at gmail.com Wed Oct 31 16:12:24 2007 From: chris.monsanto at gmail.com (Chris M) Date: Wed, 31 Oct 2007 20:12:24 -0000 Subject: Namespace question In-Reply-To: References: Message-ID: <1193861544.658554.30760@o38g2000hse.googlegroups.com> On Oct 31, 10:06 am, Frank Aune wrote: > Hello, > > Is it possible writing custom modules named the same as modules in the > standard library, which in turn use the same module from the standard > library? > > Say I want my application to have a random.py module, which in turn must > import the standard library random.py module also, to get hold of the randint > function for example. > > My attempts so far only causes my random.py to import itself instead of the > standard library random.py > > Receipt for disaster? :) > > Regards, > Frank Read up on absolute imports (In Python 2.5, from __future__ import absolute_imports) is required. You can load your random.py with import .random, which can import the standard lib with import random. From rdm at rcblue.com Fri Oct 5 08:21:38 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 05 Oct 2007 05:21:38 -0700 Subject: Where's the Starship's crew? In-Reply-To: References: <20071005083806.61D811E4002@bag.python.org> Message-ID: <20071005122652.935DB1E4003@bag.python.org> At 04:54 AM 10/5/2007, Thomas Heller wrote: >Dick Moores schrieb: > > > > > > I didn't check on all of them, but the only one I found was Mark > > Hammond . > > > > Dick Moores > > > >There are more. Think of it as a game you have to solve. Yeah, a mind numbing game! http://starship.python.net/crew/ewalstad/ Eric Walstad http://starship.python.net/crew/piers/ Piers Lauder http://starship.python.net/crew/jae/ --> http://zhar.net/ John Eikenberry http://starship.python.net/crew/mwh/ http://starship.python.net/crew/manus/ Manus Hand http://starship.python.net/crew/bhoel/ Berthold H?llmann http://starship.python.net/crew/marduk/ ("Server Error") http://starship.python.net/crew/schorsch/ http://starship.python.net/crew/dni/ David Niergarth http://starship.python.net/crew/jcooley/ James Cooley http://starship.python.net/crew/sdrees/ Stefan Drees http://starship.python.net/crew/jwt/ Jim Tittsler http://starship.python.net/crew/theller/ Thomas Heller http://starship.python.net/crew/gherman/ Dinu Gherman http://starship.python.net/crew/mhammond/ Mark Hammond http://starship.python.net/crew/atuining/ http://starship.python.net/crew/hooft/ Rob W.W. Hooft http://starship.python.net/crew/lemburg/ --> http://www.egenix.com/ http://starship.python.net/crew/goodger/ David Goodger http://starship.python.net/crew/mmuller/ Mike Muller http://starship.python.net/crew/skippy/ same as http://starship.python.net/crew/mhammond/ Mark Hammond BTW How could I have done this with Python script? Dick Moores From zyzhu2000 at gmail.com Wed Oct 24 11:38:30 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 24 Oct 2007 15:38:30 -0000 Subject: Speed of Nested Functions & Lambda Expressions In-Reply-To: References: <1193154050.424718.298030@i13g2000prf.googlegroups.com> Message-ID: <1193240310.191260.212990@k35g2000prh.googlegroups.com> On Oct 24, 2:52 am, Duncan Booth wrote: > beginner wrote: > > It is really convenient to use nested functions and lambda > > expressions. What I'd like to know is if Python compiles fn_inner() > > only once and change the binding of v every time fn_outer() is called > > or if Python compile and generate a new function object every time. If > > it is the latter, will there be a huge performance hit? Would someone > > give some hint about how exactly Python does this internally? > > You can use Python's bytecode disassembler to see what actually gets > executed here: > > >>> def fn_outer(v): > > a=v*2 > def fn_inner(): > print "V:%d,%d" % (v,a) > > fn_inner() > > >>> import dis > >>> dis.dis(fn_outer) > > 2 0 LOAD_DEREF 1 (v) > 3 LOAD_CONST 1 (2) > 6 BINARY_MULTIPLY > 7 STORE_DEREF 0 (a) > > 3 10 LOAD_CLOSURE 0 (a) > 13 LOAD_CLOSURE 1 (v) > 16 BUILD_TUPLE 2 > 19 LOAD_CONST 2 ( 01177218, file "", line 3>) > 22 MAKE_CLOSURE 0 > 25 STORE_FAST 1 (fn_inner) > > 6 28 LOAD_FAST 1 (fn_inner) > 31 CALL_FUNCTION 0 > 34 POP_TOP > 35 LOAD_CONST 0 (None) > 38 RETURN_VALUE > > > > When you execute the 'def' statement, the two scoped variables a and v > are built into a tuple on the stack, the compiled code object for the > inner function is also pushed onto the stack and then the function is > created by the 'MAKE_CLOSURE' instruction. This is then stored in a > local variable (STORE_FAST) which is then loaded and called. > > So the function definition is pretty fast, BUT notice how fn_inner is > referenced by STORE_FAST/LOAD_FAST whereas a and v are referenced by > LOAD_DEREF/STORE_DEREF and LOAD_CLOSURE. > > The code for fn_inner also uses LOAD_DEREF to get at the scoped > variables: > > 4 0 LOAD_CONST 1 ('V:%d,%d') > 3 LOAD_DEREF 1 (v) > 6 LOAD_DEREF 0 (a) > 9 BUILD_TUPLE 2 > 12 BINARY_MODULO > 13 PRINT_ITEM > 14 PRINT_NEWLINE > 15 LOAD_CONST 0 (None) > 18 RETURN_VALUE > > (its a bit harder to disassemble that one, I stuck a call to dis.dis > inside fn_outer to get that) > > If you do some timings you'll find that LOAD_DEREF/STORE_DEREF are > rather slower than LOAD_FAST/STORE_FAST, so while the overhead for > creating the function is minimal you could find that if you access the > variables a lot (even in fn_outer) there may be a measurable slow-down. > > If timings show that it is a code hotspot then you might find it better > to nest the function but pass any required values in as parameters (but > if you don't have evidence for this just write whatever is clearest). Thanks for the detailed analysis, Duncan. Also thanks for showing how the disassembler can be used to figure this out. I was just looking for a tool like this. This is great. Thanks again. From sjmachin at lexicon.net Tue Oct 9 17:18:38 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Oct 2007 07:18:38 +1000 Subject: Mixing Python and C classes in a module In-Reply-To: <87wstwibfl.fsf@keizer.soze.com> References: <87wstwibfl.fsf@keizer.soze.com> Message-ID: <470bf032$1@news.eftel.com.au> On 10/10/2007 12:56 AM, Stefan Arentz wrote: > Is it possible to mix classes defined in both Python and C in the same > module? Ideally I would like to be able to do: > > from some.module import MyPythonClass, MyCClass > > I guess that would mean that this would look like this on disk: > > some/ > __init__.py > module.py (contains MyPythonClass) > module.so (contains MyCClass) > Alternative to other suggestions: Instead of module.so, call it _module.so. Then down the end of module.py: try: from _module import * except ImportError: # either panic or shrug as appropriate Note: the "shrug" response would be appropriate for the use case where "module" contains all necessary functionality, and the optionally-present "_module" contains replacement classes/types and/or functions that are better in some sense e.g. more memory/CPU efficient. HTH, John From erik at myemma.com Mon Oct 22 23:43:35 2007 From: erik at myemma.com (Erik Jones) Date: Mon, 22 Oct 2007 22:43:35 -0500 Subject: Can't Write to PostGIS PostGreSQL database via psycopg2 In-Reply-To: <1193102391.608145.136960@k35g2000prh.googlegroups.com> References: <1193102391.608145.136960@k35g2000prh.googlegroups.com> Message-ID: On Oct 22, 2007, at 8:19 PM, David Michael Schruth, wrote: > Hi, > > I am sort of in a jam here. I am using the PsycoPG2 library to read > data out of a windows XP based PostGIS / PostGreSQL database but I am > apparently unable to write (update or insert) even though I am able to > read (select) > > I am using PsycoPG2 2.0.6 (psycopg2-2.0.6.win32-py2.5-pg8.2.4- > release.exe ) > with Python 2.5 (python-2.5.msi) > and PostGres 8.2.5.-1 (postgresql-8.2.5-1.zip) > and PostGIS 8.2 (postgis-pg82-setup-1.3.1-1.exe) > > I can use PGadminIII to paste the same SQL queries and execute just > fine, but when I try to execute them via python code like > > import psycopg2 > conn = psycopg2.connect("dbname='postgis' user='postgres' > host='localhost' password='12345'") > c=conn.cursor() > c.execute("""INSERT INTO thetable (name) VALUES ('asdf');""") > c.execute("""UPDATE thetable SET name = 'somename' WHERE id = 321;""") > print(c.statusmessage) > #returns "INSERT 0 1" and "UPDATE 0" respectively > > It gives me very specialized table specific error messages if the > query is wrong, but when it's correct, it does nothing and doesn't > update. The only way I can update is pasting the query into the > PgAdminIII query window. > > This is a problem on two separate machines (XP and Windows 2003 > server) with all of the above components installed by two different > people.'' The return value of the insert of 'INSERT 0 1' indicates that one row was inserted so the insert certainly worked. If you're not seeing the results when you look at the database after the script has run it's probably because you need to call conn.commit() after your execute statements in order to commit your transaction as psycopg does not, by default, run in "autocommit" mode. The update's return value of 'UPDATE 0' indicates that the where condition of your update query did not, in fact, match any existing rows in your table. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From kyosohma at gmail.com Fri Oct 19 11:26:30 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 19 Oct 2007 15:26:30 -0000 Subject: Please Help !!! In-Reply-To: References: Message-ID: <1192807590.612544.303830@q3g2000prf.googlegroups.com> On Oct 17, 4:32 am, Heiko Schlierkamp wrote: > I need to update the virus program every day with the new dat file from > mcafee > I would like to us a Bat file to go to the web page and download the dat > file automatically to a specific Directory, that I have created, but my > problem lays in that the bat file will open the file to be downloaded but > the bat file does not confirm the save button so that it start to download > the file, that I still need to do manual. Please advice me with what still > need to be done!! > Your help will be very appreciated!!! > > I have added the file so you can see what it does exactly!! > > > Heiko Schlierkamp > > SENSE OF AFRICA - Namibia > > E-mail: hschlierk... at sense-of-africa.com.na > > Website:www.sense-of-africa.com > > Tel: +264 61 275300 > > Fax: +264 61 263417 > > PO Box 2058, Windhoek, Namibia > > <> > > Superdat.rar > 1KDownload Besides all the other answers, why not just have McAfee do it? Hello? McAfee is a mature product that should auto-download and auto-update itself, if set up properly. Mike From ldo at geek-central.gen.new_zealand Fri Oct 5 00:43:57 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Oct 2007 17:43:57 +1300 Subject: gui toolkits: the real story? (Tkinter, PyGTK, etc.) References: <1191287053.541506.88530@d55g2000hsg.googlegroups.com> <1191370407.188678.86820@n39g2000hsh.googlegroups.com> <13g7itvdl8m3870@corp.supernews.com> Message-ID: In message <13g7itvdl8m3870 at corp.supernews.com>, Grant Edwards wrote: > You've got to admit that Tk "just works", although as a result > it looks ugly and foreign on all platforms. Sort of a "pidgin GUI". :) From has.temp3 at virgin.net Mon Oct 15 09:35:19 2007 From: has.temp3 at virgin.net (has) Date: Mon, 15 Oct 2007 06:35:19 -0700 Subject: Python on imac In-Reply-To: <03tQi.7629$fd2.4411@newsfe07.phx> References: <8ocQi.24253$054.21605@newsfe14.phx> <03tQi.7629$fd2.4411@newsfe07.phx> Message-ID: <1192455319.920331.275650@k35g2000prh.googlegroups.com> On 14 Oct, 19:19, John Velman wrote: > Thanks to all. I'll look into wx before I get too much further. - For prebuilt binaries of the Python framework and various third- party packages, including wxPython, see: http://www.pythonmac.org/packages/py25-fat/index.html (Note that some of the packages provided there may not be the very latest versions, so you might want to check their respective sites as well.) - Also check out py2app for building standalone executables: http://cheeseshop.python.org/pypi/py2app/ http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html - If you're going to be writing Mac-only applications, you might want to consider using PyObjC, which provides a two-way bridge between Python and ObjC, giving you full access to OS X's Cocoa APIs: http://pyobjc.sourceforge.net/ - The PythonMac-SIG mailing list is the main forum for Python-on-Mac discussions: http://mail.python.org/mailman/listinfo/pythonmac-sig HTH has -- http://appscript.sourceforge.net http://rb-appscript.rubyforge.org From ptmcg at austin.rr.com Fri Oct 5 11:02:41 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 05 Oct 2007 08:02:41 -0700 Subject: Boolean parser.. In-Reply-To: <1191528039.339381.47220@d55g2000hsg.googlegroups.com> References: <1191526196.866591.322950@r29g2000hsg.googlegroups.com> <1191528039.339381.47220@d55g2000hsg.googlegroups.com> Message-ID: <1191596561.259263.98930@k79g2000hse.googlegroups.com> On Oct 4, 3:00 pm, timar... at gmail.com wrote: > On Oct 5, 7:29 am, Abandoned wrote: > > > Hi.. > > I try a boolean parser in python since 1 weak.. But i can't do this > > because this is very complicated :( > > Do you know any blooean parser script in python or how do i write a > > boolean parser ? > > example query: ((google or yahoo) or (live msn)) not web > > I'm sorry my bad english. > > King Regards.. > > Try the pyparsing module (google it) > They have several examples. The pyparsing wiki has this online example: http://pyparsing.wikispaces.com/space/showimage/searchparser.py. -- Paul From duncan.booth at invalid.invalid Mon Oct 1 03:46:32 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Oct 2007 07:46:32 GMT Subject: question about for cycle References: <1191079144.724699.250470@o80g2000hse.googlegroups.com> Message-ID: "fdu.xiaojf at gmail.com" wrote: >>> Sometime it maybe a waste to generate all possible combinations of >>> i,j first. >> >> It doesn't; read about generator expressions at >> http://www.python.org/dev/peps/pep-0289/ >> >> George >> > Thanks, I didn't realize that. > > However, I still think labeled break and continue is a valuable > feature, which is easier to understand and to use. > Can you come up with a realistic example where you think a labelled break would be easier to understand and use? A concrete example would really help if you hope to persuade anyone that your way is better. I find that Python's ability to extract the control part of a loop into a generator is an extremely powerful way to make loops much clearer for several reasons: you separate completely the 'what we are looping over', and 'when do we stop' from the 'what do we then do with each item'; also you have an opportunity to give the code controlling the loop a separate (and meaningful) name. From bborcic at gmail.com Tue Oct 30 07:43:09 2007 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 30 Oct 2007 12:43:09 +0100 Subject: Need some help... In-Reply-To: <1193560272.637389.315680@e34g2000pro.googlegroups.com> References: <1193560272.637389.315680@e34g2000pro.googlegroups.com> Message-ID: <47271907$1_6@news.bluewin.ch> hyozan.ux3 at gmail.com wrote: > I want to create a program that I type in a word. > > for example... > > chaos > > each letter equals a number.... > > A=1 > B=20 > > and so on. > > So Chaos would be > > C=13 H=4 A=1 O=7 S=5 > > I want to then have those numbers > 13+4+1+7+5 added together to be 30. > > How can I do that? > > Also, just curious, but, how could I then have the 3 and 0 added > together to be 3? > > Please help me out. > > Thank you..... > >>> sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS') 30 >>> sum(eval(ch) for ch in str(_)) 3 From mogmios at mlug.missouri.edu Tue Oct 9 04:17:53 2007 From: mogmios at mlug.missouri.edu (Michael) Date: Tue, 9 Oct 2007 02:17:53 -0600 Subject: picture filter In-Reply-To: <5mn8klFegvqqU1@mid.uni-berlin.de> References: <1191600265.590444.239110@57g2000hsv.googlegroups.com> <5mn8klFegvqqU1@mid.uni-berlin.de> Message-ID: <58d0a7010710090117o6451157qcfa0d6a0a37eb645@mail.gmail.com> You can do do some kinds of image filtering to get a good idea but it's a lot of work and not a simple script you can throw together. I've tagged and processed millions of photos through my system to train it and I'm still constantly finding ways to improve it. > hii my friends > > ? want to a filter for porn picture > > if you know , please help me :S:S > > how do ? separate porn form not porn > > I don't want my web site porn;) > > (my english bad I hope understant it. very very thans ) > > If anybody know how to do that, he or she would immediatly become > incredibly rich, selling this magic filter to concerned parents as well > as eager porn enthusiasts, to help them filter away the noise or dirt, > from their respective viewpoints that is of course... > > So - you're out of luck buddy. Nobody will be able to help you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Mon Oct 1 08:30:11 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 01 Oct 2007 07:30:11 -0500 Subject: Using fractions instead of floats References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> <1191206183.441075.167450@57g2000hsv.googlegroups.com> Message-ID: Gabriel Genellina wrote: > And gmpy: http://www.aleax.it/gmpy.html And a concrete example >>> from gmpy import mpq >>> mpq(1,3)+mpq(0.4) mpq(11,15) >>> mpq(1,3)+mpq(4,10) mpq(11,15) >>> mpq(1,3)+mpq(6,10) mpq(14,15) >>> mpq(1,3)+0.6 mpq(14,15) >>> mpq(5,2) mpq(5,2) >>> mpq(1,3)*mpq(6,10)*mpq(4,10)+mpq(7,8) mpq(191,200) >>> -- Nick Craig-Wood -- http://www.craig-wood.com/nick From R.Brodie at rl.ac.uk Thu Oct 18 13:22:45 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 18 Oct 2007 18:22:45 +0100 Subject: Convert string to command.. References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> <5npa5cFj5bvfU1@mid.uni-berlin.de> <1192720007.177063.194550@i13g2000prf.googlegroups.com> <5npbjbFio7g9U1@mid.uni-berlin.de> <1192720659.272611.320900@v29g2000prd.googlegroups.com> <5npcq3Fjgi5nU1@mid.uni-berlin.de> <1192722434.921870.112350@k35g2000prh.googlegroups.com> <5npe2qFjhdjpU1@mid.uni-berlin.de> <1192723746.476620.244430@e34g2000pro.googlegroups.com> <1192725702.690339.302300@q5g2000prf.googlegroups.com> Message-ID: "Matimus" wrote in message news:1192725702.690339.302300 at q5g2000prf.googlegroups.com... > I think several people have given you the correct answer, but for some > reason you aren't getting it. Instead of saving the string > representation of a dictionary to the database... Mind you, if this were Jeopardy, "Store a binary pickle of a denormalized table back in the database" would be a tough one. From deets at nospam.web.de Fri Oct 12 08:18:22 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Oct 2007 14:18:22 +0200 Subject: Problem with MySQL cursor References: Message-ID: <5n970eFgifhuU1@mid.uni-berlin.de> Florian Lindner wrote: > Carsten Haese wrote: > >> On Thu, 2007-10-11 at 15:14 +0200, Florian Lindner wrote: >>> Hello, >>> I have a function that executes a SQL statement with MySQLdb: >>> >>> def executeSQL(sql, *args): >>> print sql % args >>> cursor = conn.cursor() >>> cursor.execute(sql, args) >>> cursor.close() >>> >>> it's called like that: >>> >>> sql = "INSERT INTO %s (%s) VALUES (%s)" >>> executeSQL(sql, DOMAIN_TABLE, DOMAIN_FIELD, domainname) >> >> You can't use parameter binding to substitute table names and column >> names, or any other syntax element, into a query. You can only bind >> parameters in places where a literal value would be allowed (more or >> less, the real rules are more complicated, but this rule of thumb gets >> you close enough). You have to construct the query string like this, for >> example: >> >> sql = "INSERT INTO "+DOMAIN_TABLE+"("+DOMAIN_FIELD+") VALUES (%s)" >> executeSQL(sql, domainname) > > Ok, I understand it and now it works, but why is limitation? Why can't I > just the string interpolation in any playes and the cursor function > escapes any strings so that they can't do harm to my query? Because the function doesn't know that you wanted select * from user where email = 'foo at bar' instead of select * from user where email = 'foo'; drop table user where '' = '' And of course you don't gain anything from using USER INPUT in the string-interpolation for creating the sql statement!!! Diez From grante at visi.com Tue Oct 9 10:50:48 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 09 Oct 2007 14:50:48 -0000 Subject: Virtual filesystem in python ( Fuse or WebDav ? ) References: <1191932549.616430.285240@22g2000hsm.googlegroups.com> Message-ID: <13gn5a8e5q0nkec@corp.supernews.com> On 2007-10-09, Thomas W wrote: > I want to create a virtual filesystem based on a relational > database. [...] http://en.wikipedia.org/wiki/Filesystem_in_Userspace http://fuse.sourceforge.net/ -- Grant Edwards grante Yow! I'm a nuclear at submarine under the visi.com polar ice cap and I need a Kleenex! From martin at v.loewis.de Thu Oct 11 15:33:16 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 11 Oct 2007 21:33:16 +0200 Subject: Python SVN down? In-Reply-To: <1192094652.913626.171650@v3g2000hsg.googlegroups.com> References: <1192094652.913626.171650@v3g2000hsg.googlegroups.com> Message-ID: <470E7A7C.90806@v.loewis.de> > Are all the real ( ;-) ) developers using ssh+svn and not noticing > this? As Terry said, some noticed. But yes, many use svn+ssh, plus we live in different time zones, so we may be asleep when it breaks. Regards, Martin From attackwarningred at yahoo.co.uk Wed Oct 24 01:32:49 2007 From: attackwarningred at yahoo.co.uk (attackwarningred) Date: Wed, 24 Oct 2007 06:32:49 +0100 Subject: Using arrays in Python - problems. In-Reply-To: References: <1193181270.396191.291130@i38g2000prf.googlegroups.com> Message-ID: <471ED901.3020304@yahoo.co.uk> Thanks very much to those who sent me a reply to my array problem! Its now working brilliantly! Best wishes, Gareth. -- eclipsing.binary at virgin.net attackwarningred at yahoo.co.uk 665.9238429876 - Number of the Pentium Beast From aahz at pythoncraft.com Mon Oct 15 11:40:34 2007 From: aahz at pythoncraft.com (Aahz) Date: 15 Oct 2007 08:40:34 -0700 Subject: Don't use __slots__ (was Re: Problem of Readability of Python) References: <1191780456.833563.173080@57g2000hsv.googlegroups.com> <2tqdncU0D6K8v5TanZ2dnUVZ_hGdnZ2d@comcast.com> Message-ID: In article , Steven Bethard wrote: >Aahz wrote: >> In article <2tqdncU0D6K8v5TanZ2dnUVZ_hGdnZ2d at comcast.com>, >> Steven Bethard wrote: >>> >>> You can use __slots__ [...] >> >> Aaaugh! Don't use __slots__! >> >> Seriously, __slots__ are for wizards writing applications with huuuge >> numbers of object instances (like, millions of instances). > >You clipped me saying that __slots__ are for performance tweaks: > > You can use __slots__ to make objects consume less memory and have > slightly better attribute-access performance. Classes for objects > that need such performance tweaks should start like... > >I fully agree that __slots__ are for applications with huge numbers of >instances. But if you have that situation, you really do want to be >using __slots__. Well, then, just make sure to put big honking warnings up whenever you mention __slots__. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From hat at se-162.se.wtb.tue.nl Tue Oct 23 09:52:46 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 23 Oct 2007 15:52:46 +0200 Subject: Set operations on object attributes question References: <1193147226.862501.97240@v23g2000prn.googlegroups.com> Message-ID: On 2007-10-23, TheSeeker wrote: > Hi, > > I have run into something I would like to do, but am not sure how to > code it up. I would like to perform 'set-like' operations (union, > intersection, etc) on a set of objects, but have the set operations > based on an attribute of the object, rather than the whole object. > > For instance, say I have (pseudo-code): > > LoTuples1 = [(1,1,0),(1,2,1),(1,3,3)] > Set1=set(LoTuples1) > LoTuples2 = [(2,1,3),(2,2,4),(2,3,2)] > Set2=set(LoTuples2) > > What I would like to be able to do is: > > Set3 = Set1union(Set2) > Set3.intersection(Set2, ) > > to return: > set([(2,1,3), (1,3,3)]) > > How can one do this operation? Put your data in a class, and implement __hash__ and __eq__ Finally, put your objects in sets. Albert From korovev76 at gmail.com Fri Oct 26 15:58:39 2007 From: korovev76 at gmail.com (korovev76 at gmail.com) Date: Fri, 26 Oct 2007 12:58:39 -0700 Subject: tuples within tuples In-Reply-To: <13i48kmfbjstm53@corp.supernews.com> References: <1193394394.235504.273390@y42g2000hsy.googlegroups.com> <1193403264.666264.113710@o38g2000hse.googlegroups.com> <5oe73cFmh2htU1@mid.uni-berlin.de> <1193407191.002389.17680@v3g2000hsg.googlegroups.com> <13i48kmfbjstm53@corp.supernews.com> Message-ID: <1193428719.253120.207320@22g2000hsm.googlegroups.com> On 26 Ott, 19:23, Dennis Lee Bieber wrote: > > (A,B,C,D) > > that could be > > ('tagA', None, [('tagB', None, ['bobloblaw], None)], None) > > "C" isn't a tuple in your example either. It is a one-element list > (the single element INSIDE the list is a tuple whose third element is a > list containing a non-terminated string -- so the entire structure is > invalid) > i'm not sure what u mean with "the entire structure is invalid"... that's exactly what I got while parsing... From duncan.booth at invalid.invalid Mon Oct 29 14:45:22 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Oct 2007 18:45:22 GMT Subject: Built-in functions and keyword arguments References: <1193665924.886459.20710@v3g2000hsg.googlegroups.com> <4725ec3a$0$6623$426a74cc@news.free.fr> Message-ID: "J. Clifford Dyer" wrote: >> I think you are being a little bit unfair here: help(len) says: >> >> len(...) >> len(object) -> integer >> >> Return the number of items of a sequence or mapping. >> >> which implies that the argument to len has the name 'object' >> (although in fact it doesn't have a name). The OP was simply asking >> about the difference in calling conventions, not proposing to write >> code using 'object' as the argument name. > > Hmm.... To my mind, that just implies that the *type* of the expected > input is an object. Just like the "-> integer" tells you that the > type of the output is an integer. If the documentation read > "len(s=object) -> integer", then I would expect a keyword argument s > typed as an object. > How do you interpret: >>> help(__import__) Help on built-in function __import__ in module __builtin__: __import__(...) __import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module ... >>> help(int) Help on class int in module __builtin__: class int(object) | int(x[, base]) -> integer ... Can you find any case (other than a single parameter identified as 'object') where you can interpret the help string as telling you the types of the parameters? From rosreddee at gmail.com Wed Oct 31 06:53:47 2007 From: rosreddee at gmail.com (rosreddee at gmail.com) Date: Wed, 31 Oct 2007 10:53:47 -0000 Subject: ###FREE SEX #STILL FREE##WORLD SEX FREE### Message-ID: <1193828027.915970.216310@v29g2000prd.googlegroups.com> ###SEX LIVE SHOW FREE INDIAN SEX #### LISPINA SEX GARLS SEX FREEE ##TO NIGHT SEX IN LIVE FREE## http://gopitty.googlepages.com/ From deets at nospam.web.de Wed Oct 10 18:21:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Oct 2007 00:21:10 +0200 Subject: RMI with Pyro et al In-Reply-To: References: Message-ID: <5n51ipFg7ceoU1@mid.uni-berlin.de> Sells, Fred schrieb: > I need a simple client/server architecture with clients on linux and servers on windows. There is no UI in this part, just business rules and access control. > > Pyro seems pretty cool for this due to it's simplicity. I'm just starting with it and have not been able to get the server side to "see" changes to a module. The only way I can stop the server is with the Task Manager. Can anyone offer some insight into > 1. stopping/starting the server - perhaps as a windows service. > 2. getting the server to recognize new modules "on the fly", i.e. when the .py file is changed. That can be done, but isn't supported out-of-the-box. Essentially, you have to create a watch-thread that checks timestamps on python-files and then restarts some service if some change. However, it might be difficult to make that play nicely with pyro - after all, it stores some state, reloading stuff makes that go away. So - I wouldn't advice to really implement that. Why do you want that anyway? Does startuptime of a script really bother you? shouldn't take more than a few seconds. Diez From timr at probo.com Wed Oct 31 03:06:59 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Oct 2007 07:06:59 GMT Subject: why did these companies choose Tcl over Python References: <1193779506.643321.216030@z9g2000hsf.googlegroups.com> Message-ID: chewie54 wrote: > >As an electronics engineer I use some very expensive EDA CAD tool >programs that are scriptable using Tcl. I was wondering why these >companies have choose to use Tcl instead of Python. Some of these >are: > > Mentor Graphics ModelTech VHDL and Verilog simulator > Synopsys Design Compiler and Primetime Static Timing Analyzer > Actel FPGA tools. Well, I recently did a development contract for Mentor, and the RFQ gave me the choice of doing the library binding and diagnostic GUI in either Tcl or Python. Naturally, I chose Python (and wxPython), and both the client and I are quite happy with the result. (Actually, I did a Tcl binding for them as well, and just writing the text scripts reinforced my dislike for it...) -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sgeiger at ncee.net Tue Oct 16 10:17:41 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 16 Oct 2007 09:17:41 -0500 Subject: confused on calculating date difference in days. In-Reply-To: References: <5nj8b8FiilfrU3@mid.uni-berlin.de> <87odez4gz5.fsf@benfinney.id.au> <5njb0uFiilfrU4@mid.uni-berlin.de> Message-ID: <4714C805.2080903@ncee.net> # Example import datetime def days_old(birth_year=1974,birth_month=12,birth_day=7): return (datetime.date.today() - datetime.date(birth_year,birth_month,birth_day) ).days >>> days_old() 12000 krishnakant Mane wrote: > hello, > thanks all of you for providing valuable help. > right now I am confused about the delta object. > how can I extract the difference between two dates in terms of day > using the delta object? > I tried reading the python docs but did not understand the concept of > delta object and how can I measure the difference in terms of days > between two dates. > I expect that the days would be integers. > secondly the format of my date is actually "16/10/2007", and this is > all in varchar field inside a postgresql database. > I understand that datetime.datetime.strptime would convert this string > "16/10/2007" into a date object which I can then compare with the > current date created by datetime.now(). > is that right? > if yes then please explain me how I can get the delta object to give > me results in days. > regards, > Krishnakant. > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From gandalf at shopzeus.com Wed Oct 3 10:40:14 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 03 Oct 2007 16:40:14 +0200 Subject: gdbm objects not iterable? In-Reply-To: References: <47039B0B.7080301@shopzeus.com> Message-ID: <4703A9CE.3030608@shopzeus.com> >> >> I know that this is a very small change, but it can make gdbm objects >> look more like dictionaries. >> >> Please make comments. :-) >> >> > What you would need is a method to *create and return* a generator, and > it's the generator that should have the next() method. Otherwise you > can't have two independent iterations over the same gdbm object (and you > don't have a way of ensuring iteration starts at the beginning). > Yes, of course, you are right. I should have returned a newly created generator. Still I wonder why we do not have this? Would it be a good idea to make gdbm objects iterable by default? Thanks, Laszlo From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Oct 1 11:11:47 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 01 Oct 2007 17:11:47 +0200 Subject: How popular is Django ? In-Reply-To: <5mcb9jFcotijU2@mid.uni-berlin.de> References: <1191245034.626711.306380@19g2000hsx.googlegroups.com> <5mcb9jFcotijU2@mid.uni-berlin.de> Message-ID: <47010e31$0$7777$426a74cc@news.free.fr> Diez B. Roggisch a ?crit : > seb.haase at gmail.com wrote: > >> Hi! >> >> I was surprised when I did a google-groups search for python, >> ( >> http://groups.google.com/groups/search?q=python&qt_s=Search+Groups >> ) >> it shows these groups: >> comp.lang.python with about 11000 users, >> and second, >> Django users >> Discussion group for Django users. Django is a high-level Python >> Web ... >> >> with 6500 members !!!! >> >> I cannot believe that django is *that* popular ... where am I going >> wrong ? > > By assuming that readers of this group (or ML) are a superset of the > django-users. And by assuming that the (estimated AFAICT) number of c.l.py readers is representative of the number of Python users... But Django *is* popular indeed. From 3wbl at qlink.queensu.ca Thu Oct 25 13:37:01 2007 From: 3wbl at qlink.queensu.ca (Brent Lievers) Date: 25 Oct 2007 17:37:01 GMT Subject: print vs sys.stdout.write, and UnicodeError Message-ID: Greetings, I have observed the following (python 2.5.1): >>> import sys >>> print sys.stdout.encoding UTF-8 >>> print(u'\u00e9') ?? >>> sys.stdout.write(u'\u00e9\n') Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128) Is this correct? My understanding is that print ultimately calls sys.stdout.write anyway, so I'm confused as to why the Unicode error occurs in the second case. Can someone explain? Thanks, Brent From jstroud at mbi.ucla.edu Fri Oct 12 18:57:54 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 12 Oct 2007 15:57:54 -0700 Subject: decorating container types (Python 2.4) In-Reply-To: <1192148551.690908.111090@q5g2000prf.googlegroups.com> References: <1192138976.165419.25820@19g2000hsx.googlegroups.com> <1192148551.690908.111090@q5g2000prf.googlegroups.com> Message-ID: I was thinking that only one longmeta is really needed and its not necessary to make a new metaclass at each go: from types import MethodType class longmeta(type): def __new__(cls, *args, **kwargs): if len(args) == 2: newcls = type.__new__(cls, args[1], (), {}) len_func = args[0].__len__.im_func newcls.len_dlgt = MethodType(len_func, newcls, cls) return newcls else: return type.__new__(cls, *args, **kwargs) def __len__(cls): return cls.len_dlgt() E.g.: py> from types import MethodType py> py> class longmeta(type): ... def __new__(cls, *args, **kwargs): ... if len(args) == 2: ... newcls = type.__new__(cls, args[1], (), {}) ... len_func = args[0].__len__.im_func ... newcls.len_dlgt = MethodType(len_func, newcls, cls) ... return newcls ... else: ... return type.__new__(cls, *args, **kwargs) ... def __len__(cls): ... return cls.len_dlgt() ... py> class A(object): ... value = 5 ... def __len__(self): ... return A.value ... py> a = A() py> len(a) 5 py> B = longmeta(A, 'B') py> len(B) 5 py> A.value = 16 py> len(B) 16 py> class C(B): pass ... py> len(C) 16 py> A.value = 42 py> len(C) 42 James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From Eric_Dexter at msn.com Tue Oct 9 04:07:07 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Tue, 09 Oct 2007 01:07:07 -0700 Subject: embedding python.. In-Reply-To: References: <1191627640.676114.319430@22g2000hsm.googlegroups.com> Message-ID: <1191917227.061034.96610@o3g2000hsb.googlegroups.com> That sounds to easy I will give it a shot.. On Oct 6, 11:08 pm, "Gabriel Genellina" wrote: > En Fri, 05 Oct 2007 20:40:40 -0300, Eric_Dex... at msn.com > escribi?: > > > I compiled the c program that is supposed to allow you to call a > > procedure from the command line promt.. (it is from the embeding > > example).. I am a little confused as to what all I am supposed to > > distribute to make it work.. Do I just need the python .dll for the > > version I compiled or is it working with the installed version of > > python.. (I don't want to start deleting stuff to find out).. Any > > help on this question would be apreaceated.. > > If you only provide pythonXX.dll (and probably msvcr71.dll), any Python > code that tries to import any module apart from builtin modules will fail. > If you provide the Python standard library in full, almost any program > could be run. > It's up to you to decide how much you require/allow/want to provide. > > -- > Gabriel Genellina From kay.schluehr at gmx.net Thu Oct 11 02:11:08 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 10 Oct 2007 23:11:08 -0700 Subject: Duck Typing and **kwds In-Reply-To: References: Message-ID: <1192083068.540363.252000@57g2000hsv.googlegroups.com> On 11 Okt., 06:05, Luis Zarrabeitia wrote: > Is that behavior expected? Is there any reason (performance, perhaps?) to break > duck-typing in this situation? I guess it wasn't considered to be relevant writing a coercion function since there aren't too many dict like types that are not dicts. You can examine what happens in the relevant code fragment in ceval.c if (flags & CALL_FLAG_KW) { kwdict = EXT_POP(*pp_stack); if (!(kwdict && PyDict_Check(kwdict))) { PyErr_Format(PyExc_TypeError, "%s%s argument after ** " "must be a dictionary", PyEval_GetFuncName(func), PyEval_GetFuncDesc(func)); goto ext_call_fail; } } if (flags & CALL_FLAG_VAR) { stararg = EXT_POP(*pp_stack); if (!PyTuple_Check(stararg)) { PyObject *t = NULL; t = PySequence_Tuple(stararg); if (t == NULL) { if (PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Format(PyExc_TypeError, "%s%s argument after * " "must be a sequence", PyEval_GetFuncName(func), PyEval_GetFuncDesc(func)); } goto ext_call_fail; I paralleled this with the subsequent clause for tuples where some coercion function is applied ( PySequence_Tuple ). It would be cleaner to implement a simple conversion function PyDictlike_Dict which seeks for a __dictionary__ method providing the following interface __dictionary__(self) -> dict and is called when being available. Maybe you can suggest this at python-dev? It might not require a PEP. From arkanes at gmail.com Thu Oct 25 12:12:22 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 25 Oct 2007 11:12:22 -0500 Subject: about functions question In-Reply-To: References: <1193293696.450188.108330@q3g2000prf.googlegroups.com> <1193304629.429307.50980@v3g2000hsg.googlegroups.com> <1193305621.987689.24060@o80g2000hse.googlegroups.com> <1193314722.985517.252220@d55g2000hsg.googlegroups.com> <47209ba3$0$4804$426a74cc@news.free.fr> Message-ID: <4866bea60710250912g435361c9hd85103de8fbfe9f4@mail.gmail.com> On 10/25/07, Neil Cerutti wrote: > On 2007-10-25, Bruno Desthuilliers > wrote: > > The canonical case for small scripts is to have first all > > functions and globals defined, then the main code protected by > > a guard, ie: > > There's no reason to "protect" your main code in a small script. > There's also not much reason not to, and it prevents disaster or at least unwanted side effects when you accidentally run pychecker or pydoc over it. Also, debugging scripts is a lot easier when you can import them into a shell. > > if __name__ == '__main__': > > print SOME_CONST > > if not do_something(): > > try_somethin_else() > > That idiom is useful in modules for launching tests or examples > that should not be run when the module is imported. > I use it whenever there's any code I don't want run unless I'm explicitly trying to do so. From mccredie at gmail.com Mon Oct 29 19:15:15 2007 From: mccredie at gmail.com (Matimus) Date: Mon, 29 Oct 2007 23:15:15 -0000 Subject: "and" and "or" on every item in a list In-Reply-To: <1193698678.288593.314870@k79g2000hse.googlegroups.com> References: <1193698678.288593.314870@k79g2000hse.googlegroups.com> Message-ID: <1193699715.567745.101340@e9g2000prf.googlegroups.com> On Oct 29, 3:57 pm, GHZ wrote: > Is this the best way to test every item in a list? > > def alltrue(f,l): > return reduce(bool.__and__,map(f,l)) > > def onetrue(f,l): > return reduce(bool.__or__,map(f,l)) > > > > >>> alltrue(lambda x:x>1,[1,2,3]) > False > > >>> alltrue(lambda x:x>=1,[1,2,3]) > True > > Thanks If you are using python 2.5 the best way would be something like this: >>> all(x > 1 for x in [1,2,3]) False >>> any(x > 1 for x in [1,2,3]) True If you are using an earlier version you are still discouraged from using reduce in place of a more readable construct. In most cases list comprehension is encouraged over map also. If `all' and `any' aren't defined you can use something like the following. One advantage of these over what you posted is that they will return as soon as an exit condition is reached as opposed to processing the entire list. [code] if not all: def all(seq): for val in seq: if not val: return False return True if not any: def any(seq): for val in seq: if val: return True return False [/code] Matt From odalrick at hotmail.com Sat Oct 20 10:46:30 2007 From: odalrick at hotmail.com (Odalrick) Date: Sat, 20 Oct 2007 07:46:30 -0700 Subject: weakref pitfall In-Reply-To: <1192890068.447688.129180@y27g2000pre.googlegroups.com> References: <1192888078.740427.222640@t8g2000prg.googlegroups.com> <1192890068.447688.129180@y27g2000pre.googlegroups.com> Message-ID: <1192891590.794386.211150@v23g2000prn.googlegroups.com> On 20 Okt, 16:21, Paul Hankin wrote: > The next stage in debugging is to think of a test that will prove your > guess right or wrong. I'd remove weakrefs from your event manager and > see if your code starts working. > > I'd suggest you're a bit confused about your event manager's API: you > have register/deregister methods and are also using weakrefs to > provide auto-deregistering. I don't know your code, but this looks > like a mistake to me - can you justify (to yourself) that you need > both ways? > > -- > Paul Hankin Yes, I did a test with a standard dict and that removed the bug, should have mentioned that. And, no, I'm not sure I need both. Currently I'm using the standard dict. I'm fairly sure I'll need to manually deregister sometimes, buttons and whatnot, but automatic deregistration sounds nice for later when I'll have hundreds of sprites flying around. From larry.bates at websafe.com Fri Oct 19 15:03:15 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 19 Oct 2007 14:03:15 -0500 Subject: Organizing Sequential Data (TimeStamps) Overthinking? In-Reply-To: <1192818402.479086.252360@e34g2000pro.googlegroups.com> References: <1192818402.479086.252360@e34g2000pro.googlegroups.com> Message-ID: <9IGdnZxjQcTzYoXanZ2dnUVZ_tfinZ2d@comcast.com> xkenneth wrote: > All, > > Just a quick question. I want to be able to have a data structure > that organizes data (timestamps I'm working with) sequentially, so > that i can easily retrieve the first x amount of timeStamps without > iterating over a list. My thought was to use a binary tree, am i > overthinking the problem to try and implement this structure inside of > python? I was also hoping this would already be done for me. > > Regards, > Ken > Sounds a little like premature optimization here. It depends on how many timestamps you are talking about. Certainly if you have a lot (millions), you should implement binary search, but I would write code first and if it is too slow, fix that part. -Larry From kw at codebykevin.com Fri Oct 5 08:10:57 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 05 Oct 2007 08:10:57 -0400 Subject: tkinter question In-Reply-To: References: <1191554174.490449.251400@50g2000hsm.googlegroups.com> Message-ID: <470629D1.2040404@codebykevin.com> Eric Brunel wrote: > > BTW, even for something that simple, using the grid geometry manager may > be easier... It is at least easier to explain: don't ask me what the > expand=1 option means, I never understood it... I just add or remove it > when the pack doesn't do what I want. The sticky option with grid is > easier to handle. > "expand = 1" == "expand=TRUE"--that means the widget resizes itself when the window is re-sized. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From jimmy.musselwhite at gmail.com Fri Oct 26 20:07:34 2007 From: jimmy.musselwhite at gmail.com (jimmy.musselwhite at gmail.com) Date: Fri, 26 Oct 2007 17:07:34 -0700 Subject: Going past the float size limits? In-Reply-To: References: <1193438154.931341.30450@50g2000hsm.googlegroups.com> <1193441374.061735.308710@o38g2000hse.googlegroups.com> Message-ID: <1193443654.528953.33610@y42g2000hsy.googlegroups.com> On Oct 26, 8:03 pm, St?phane Larouche wrote: > gmail.com> writes: > > > The calculation looks like this > > > A = 0.35 > > T = 0.30 > > C = 0.25 > > G = 0.10 > > > and then I basically continually multiply those numbers together. I > > need to do it like 200,000+ times but that's nuts. I can't even do it > > 1000 times or the number rounds off to 0.0. I tried taking the inverse > > of these numbers as I go but then it just shoots up to "inf". > > I suggest you add the logarithm of those numbers. > > St?phane Well I'd add the logarithms if it was me that made the algorithm. I don't think I understand it all that well. My professor wrote it out and I don't want to veer away and add the logs of the values because I don't know if that's the same thing or not. From orsenthil at gmail.com Mon Oct 22 04:10:34 2007 From: orsenthil at gmail.com (Phoe6) Date: Mon, 22 Oct 2007 01:10:34 -0700 Subject: package import question Message-ID: <1193040634.402343.127660@y27g2000pre.googlegroups.com> Hi all, I have the following directory structure: wallpaper/ -main.py -ng/ -- __init__.py -- setdesktop.py -yb/ -- __init__.py -- setdesktop.py >From main.py, I would like to do: import ng import yb ng.setdesktop.run() yb.setdesktop.run() But it is not working! when I import the package, the modules present inside the package are getting imported. However, following the python document if I do import ng.setdesktop import yb.setdesktop ng.setdesktop.run() yb.setdesktop.run() Works fine. I would like to use the notation. import and use the modules inside the package in the dotted module notation. What should I do the enable such a kind of imports. Please let me know. Thank you. Senthil From bignose+hates-spam at benfinney.id.au Tue Oct 16 05:14:57 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 16 Oct 2007 19:14:57 +1000 Subject: Python's coming... from unexpected angles. References: <5njcjpFil587U1@mid.uni-berlin.de> Message-ID: <87fy0b4e0e.fsf@benfinney.id.au> "Diez B. Roggisch" writes: > Just found this: The direct link to the article is . > I do believe that Python should be somewhat more upfront to brandish > it's merits - but then, sneaky ways are ok with me to... Well, it seems like she's an early adopter: she's eager to use PyPy all the time (though she has aliased it to 'pipi'). -- \ "Pinky, are you pondering what I'm pondering?" "I think so, | `\ Brain, but what kind of rides do they have in Fabioland?" -- | _o__) _Pinky and The Brain_ | Ben Finney From vasan999 at hotmail.com Mon Oct 15 13:58:00 2007 From: vasan999 at hotmail.com (vasan999 at hotmail.com) Date: Mon, 15 Oct 2007 17:58:00 -0000 Subject: Desperately need help for html to LaTeX conversion Message-ID: <1192471080.796928.230030@k35g2000prh.googlegroups.com> Because my previous thread had no reply that could help me, I start it again. I am very depressed now with the following problem. I have a set of html files, must be human readable (as some of the output tools produce human readable LaTeX) that I want to convert to human readable latex. The program by http://in.geocities.com/ad_rab/ produces human unreadable tex. and i could not see the compiled resulting dvi. The gnu program produces human readable latex, but does not handle all the tags. the C program by Faase ??? produces human readable latex but misses a few tags. The C program is unreadable by me so I cant modify it. On sourceforge there are two programs one in Perl and the other in Java. The perl one does not run due to path problems. The java one produces complicated latex, possibly human readable, but that does not compile so I could not see its quality. Does someone have a program? I prefer a well documented and fully commented program that one can modify or one that can do the job without the need for understanding its operation. Please help. The situation is very desperate. Vasantha Is there a html-merging tool that can merge a set of html files into a single html file and resolve the links and cross-references with minimal changes to the rest of the portions of the html, ie not scramble the rest of the file. I know some awk/perl/sed/python will do it. From jcb at iteris.com Fri Oct 19 16:15:56 2007 From: jcb at iteris.com (Metalone) Date: Fri, 19 Oct 2007 13:15:56 -0700 Subject: Is there a way to tell if a script has been run by Pythonw.exe instead of Python.exe? In-Reply-To: <1192788028.503824.52800@i13g2000prf.googlegroups.com> References: <1192744576.899687.93650@k35g2000prh.googlegroups.com> <1192788028.503824.52800@i13g2000prf.googlegroups.com> Message-ID: <1192824956.933289.23100@z24g2000prh.googlegroups.com> Thanks to all, I learned something in each post. When using py2exe to build an executable sys.executable does not provide the name of the python interpreter but the name of the executable generated by py2exe. From kf9150 at gmail.com Thu Oct 4 14:34:41 2007 From: kf9150 at gmail.com (Kelie) Date: Thu, 04 Oct 2007 11:34:41 -0700 Subject: using regular express to analyze lisp code In-Reply-To: <1191518939.509584.316690@19g2000hsx.googlegroups.com> References: <1191518039.676797.290620@22g2000hsm.googlegroups.com> <1191518939.509584.316690@19g2000hsx.googlegroups.com> Message-ID: <1191522881.700796.83420@k79g2000hse.googlegroups.com> On Oct 4, 7:28 am, Dan wrote: > So, paren matching is a canonical context-sensitive algorithm. Now, > many regex libraries have *some* not-purely-regular features, but I > doubt your going to find anything to match parens in a single regex. > If you want to go all out you can use a parser generator (for python > parser generators, seehttp://python.fyxm.net/topics/parsing.html). > Otherwise, you can go about it the quick-and-dirty way you describe: > scan for matching open and close parens, and ignore things in quotes > and comments. > > -Dan Dan, thanks for suggesting parser generators. From jcd at sdf.lonestar.org Tue Oct 16 21:47:29 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 16 Oct 2007 21:47:29 -0400 Subject: why doesn't have this list a "reply-to" ? In-Reply-To: <47156519.2090905@twcny.rr.com> References: <47156519.2090905@twcny.rr.com> Message-ID: <471569B1.7010504@sdf.lonestar.org> Dick Crepeau wrote: > It seems to me the original question was how can I reply to a posted > message. > > I'm new here and see that while there are replies to several messages, > many times, like with this note, the issue is brought up as if it is new. > > I don't know how to do a reply, can someone tell me how? This note was > sent to: python-list at python.org with the subject copied from an earlier > note. > > No need to discuss the politics of the choice. > > Dick C > > > > With thunderbird, I do "reply all," which has the ugly side effect that the poster of the message I'm responding to gets 2 copies, unless I remember to delete one of them. Same method with mutt, though I'm sure I could customize mutt to pay better attention to the headers, if I used it enough to bother. Cheers, Cliff From sjmachin at lexicon.net Mon Oct 1 20:50:34 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 01 Oct 2007 17:50:34 -0700 Subject: slice last 4 items from a list In-Reply-To: References: Message-ID: <1191286234.855980.118170@g4g2000hsf.googlegroups.com> On Oct 2, 6:27 am, brad wrote: > Is this the correct way to slice the last 4 items from a list? > > x = [1,2,3,4,5,6,7,8,9] > print x[-4:] > > It works, but is it Pythonic? It's Pythonic. It's also unambiguous, unlike your specification, which could be interpreted as 'chop off the last 4 items from a list' i.e. del x[-4:]. What you are actually doing is 'print the last 4 items of a list'. From steve at REMOVE-THIS-cybersource.com.au Tue Oct 9 18:53:46 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 09 Oct 2007 22:53:46 -0000 Subject: Static variable vs Class variable References: <1191946572.001076.271970@50g2000hsm.googlegroups.com> <5n1rosFftvtbU1@mid.uni-berlin.de> <13gngt29ovvcld1@corp.supernews.com> <5n26i7FfmohvU1@mid.uni-berlin.de> Message-ID: <13go1jqli5up5d1@corp.supernews.com> On Tue, 09 Oct 2007 22:27:47 +0200, Diez B. Roggisch wrote: > Steven D'Aprano schrieb: >> On Tue, 09 Oct 2007 19:23:37 +0200, Diez B. Roggisch wrote: >> >>> Your believes aside, this is simply wrong. The statement >>> >>> a += x >>> >>> always leads to a rebinding of a to the result of the operation +. >> >> Not true. > > > Yes, it is. I'm afraid not. As I admitted in my reply to Marc, I overstated my case by saying that L isn't rebound at all. Of course it is rebound, but to itself. However, it is not true that += "always leads to a rebinding of a to the result of the operation +". The + operator for lists creates a new list. += for lists does an in-place modification: >>> L = [] >>> M = L >>> L += [1] >>> M [1] Compare with: >>> L = [] >>> M = L >>> L = L + [1] >>> M [] You said: "I presume you got confused by the somewhat arbitrary difference between __add__ and __iadd__ that somehow suggest there is an in-place- modification going on in case of mutables but as the following snippet shows - that's not the case: ..." That's an explicit denial that in-place modification takes place, and that's *way* off the mark. I was concentrating so hard on showing in- place modification that I glossed over the "return self" part. -- Steven. From bignose+hates-spam at benfinney.id.au Tue Oct 16 07:19:26 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 16 Oct 2007 21:19:26 +1000 Subject: Python's coming... from unexpected angles. References: <5njcjpFil587U1@mid.uni-berlin.de> <87fy0b4e0e.fsf@benfinney.id.au> Message-ID: <877iln488x.fsf@benfinney.id.au> "Eric Brunel" writes: > Well, I'd definetely vote for a name change for PyPy, as in french, > it's pronounced "pee-pee", and yes, it means what you think it > means... ;-) Does that mean you pronounce the word for the serpent as "pee-thon"? Anyway, the pronunciation of "Python" (and hence the "Py" in "PyPy") is however you pronounce that word in the name of the comedy troupe, Monty Python. That's where the name originates, after all. -- \ "With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars." -- Raymond Hettinger | Ben Finney From seandavi at gmail.com Wed Oct 17 16:53:26 2007 From: seandavi at gmail.com (Sean Davis) Date: Wed, 17 Oct 2007 20:53:26 -0000 Subject: Async XMLRPC and job processing Message-ID: <1192654406.010168.205960@q3g2000prf.googlegroups.com> I would like to set up a server that takes XMLRPC requests and processes them asynchronously. The XMLRPC server part is trivial in python. The job processing part is the part that I am having trouble with. I have been looking at how to use threadpool, but I can't see how to get that working. I would like to have the XMLRPC part of things do something like: def method1(a,b,c): jobid=workRequest(long_method1,[a,b,c]) return(jobid) def method2(a,b,c): jobid=workRequest(long_method2,[a,b,c]) return(jobid) def long_method1(a,b,c) do lots of heavy computation, etc. store results in files in a given directory, etc return result .... for any number of methods Again, pretty straightforward. However, I run into problems with the threadpool and xmlrpc server both waiting. In particular, if I do something like: server = SimpleXMLRPCServer.SimpleXMLRPCServer(.....) server.serve_forever() Where can tell the threadpool that I have set up to wait indefinitely? Both are blocking. Thanks, Sean From bbxx789_05ss at yahoo.com Mon Oct 15 23:02:34 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 15 Oct 2007 20:02:34 -0700 Subject: groupby() seems slow Message-ID: <1192503754.490662.155610@v29g2000prd.googlegroups.com> I'm applying groupby() in a very simplistic way to split up some data, but when I timeit against another method, it takes twice as long. The following groupby() code groups the data between the "" strings: data = [ "1.5","","2.5","3.5","4.5","","","5.5","6.5","", "1.5","","2.5","3.5","4.5","","","5.5","6.5","", "1.5","","2.5","3.5","4.5","","","5.5","6.5","", ] import itertools def key(s): if s[0] == "<": return 'a' else: return 'b' def test3(): master_list = [] for group_key, group in itertools.groupby(data, key): if group_key == "b": master_list.append(list(group) ) def test1(): master_list = [] row = [] for elmt in data: if elmt[0] != "<": row.append(elmt) else: if row: master_list.append(" ".join(row) ) row = [] import timeit t = timeit.Timer("test3()", "from __main__ import test3, key, data") print t.timeit() t = timeit.Timer("test1()", "from __main__ import test1, data") print t.timeit() --output:--- 42.791079998 19.0128788948 I thought groupby() would be faster. Am I doing something wrong? From mulkiatsch at gmail.com Tue Oct 9 08:05:24 2007 From: mulkiatsch at gmail.com (Matthias Benkard) Date: Tue, 09 Oct 2007 05:05:24 -0700 Subject: The fundamental concept of continuations In-Reply-To: <1191906949.179197.217470@57g2000hsv.googlegroups.com> References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> Message-ID: <1191931524.047907.98040@v3g2000hsg.googlegroups.com> > (3) Is it present in python ...? I don't keep up to date with the recent developments in Python land, but the last time I used Python, it certainly didn't have first-class continuations. There used to be a project called Stackless Python that tried to add continuations to Python, but as far as I know, it has always been separate from the official Python interpreter. I don't know whether it's still alive. You may want to check http://stackless.com/ for details. > (6) any good readable references that explain it lucidly ? If you are familiar with Python syntax, there's http://www.ps.uni-sb.de/~duchier/python/continuations.html -- and even if you aren't, you may want to have a look at it, as simple Python code is ridiculously easy to read. ~ Matthias From george.sakkis at gmail.com Wed Oct 17 10:18:55 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 17 Oct 2007 14:18:55 -0000 Subject: Order by value in dictionary In-Reply-To: <5nmj7sFiouurU3@mid.uni-berlin.de> References: <1192628375.254492.183140@i38g2000prf.googlegroups.com> <5nmiplFiouurU2@mid.uni-berlin.de> <5nmj7sFiouurU3@mid.uni-berlin.de> Message-ID: <1192630735.734441.199820@q5g2000prf.googlegroups.com> On Oct 17, 10:06 am, "Diez B. Roggisch" wrote: > Diez B. Roggisch wrote: > > Abandoned wrote: > > >> Hi.. > >> I have a dictionary like these: > >> a={'a': '1000', 'b': '18000', 'c':'40', 'd': '600'} ...... 100.000 > >> element > >> I want to sort this by value and i want to first 100 element.. > >> Result must be: > >> [b, a, d, c .....] ( first 100 element) > > >> I done this using FOR and ITERATOR but it tooks 1 second and this is > >> very big time to my project. > >> I want to learn the fastest method.. > > > That is the fastest method, unless you write your own ordered dict > > implementation that sorts by value. But that will most probably lose the > > time when holding up the invariant when inserting key/values into the > > dictionary. > > Actually, I somehow read the FOR and ITERATOR above as something like this: > > entries = sorted(a.items(), key=lambda v: v[1])[:100] > > The gist of my statement above is nontheless the same: if you want sorted > results, you need to sort... > > Diez If you want the top 100 out of 100K, heapq.nlargest is more than an order of magnitude faster. George From besturk at gmail.com Mon Oct 1 13:13:48 2007 From: besturk at gmail.com (Abandoned) Date: Mon, 01 Oct 2007 10:13:48 -0700 Subject: Select as dictionary... In-Reply-To: <1191258548.820547.123560@k79g2000hse.googlegroups.com> References: <1191245527.228745.17100@r29g2000hsg.googlegroups.com> <4700fb42$0$18288$426a74cc@news.free.fr> <47010e97$0$7777$426a74cc@news.free.fr> <1191258548.820547.123560@k79g2000hse.googlegroups.com> Message-ID: <1191258828.206660.21570@22g2000hsm.googlegroups.com> Also if i need a list id what can i do ? aia.execute("SELECT id, w from list") links=aia.fetchall() I want to.. idlist=[1, 2, 3] ( I don't want to use FOR and APPEND because the query have 2 million result and i want to speed) From larry.bates at websafe.com Tue Oct 9 08:05:57 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 09 Oct 2007 07:05:57 -0500 Subject: Drop folder and race conditions Message-ID: I have a need to implement a drop folder upload mechanism for secure uploading of files to a server. At first glance this appears that it would be an easy application to write. Then I begin to think about the race conditions that exist between the process that will wake up to upload the files and the fact that the user can add additional files to the drop folder at any point in time. I would like to clear out files/folders after they have been processed but it is possible that while the background process was uploading files, the user added additional files/folders to the drop folder that make the deletion of folders impossible. This project has become significantly more complex than it appeared at first. Anyone out there have any "sage" advice on how to tackle this beast? Thanks in advance for any pointers. Regards, Larry Bates From timaranz at gmail.com Thu Oct 18 15:48:52 2007 From: timaranz at gmail.com (timaranz at gmail.com) Date: Thu, 18 Oct 2007 12:48:52 -0700 Subject: problem with Python class creating In-Reply-To: <1192735357.724298.55500@v29g2000prd.googlegroups.com> References: <1192735357.724298.55500@v29g2000prd.googlegroups.com> Message-ID: <1192736932.268928.9490@y27g2000pre.googlegroups.com> On Oct 19, 8:22 am, dmitrey wrote: > Hi all, > I have the code like this one: > > from myMisc import ooIter > class MyClass: > def __init__(self): pass > iterfcn = lambda *args: ooIter(self) # i.e pass the class instance > to other func named ooIter > field2 = val2 > field3 = val3 # etc > > So it yields "global name 'self' is not defined", that is true. How > could I handle the situation? > > Currently I do (and it works, but give me some troubles - I should > call MyClass.__init__ for each children class, and there are lots of > those ones) > > class MyClass: > def __init__(self): > iterfcn = lambda *args: ooIter(self) # i.e pass the class > instance to other func named ooIter > field2 = val2 > field3 = val3 # etc > > I suspect it has better solution, is it? > Thank you in advance, Dmitrey without having tested - I think this should work for you: from myMisc import ooIter class MyClass: def __init__(self): pass iterfcn = lambda self: ooIter(self) From deets at nospam.web.de Mon Oct 8 09:15:36 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Oct 2007 15:15:36 +0200 Subject: Don't use __slots__ (was Re: Problem of Readability of Python) References: <1191780456.833563.173080@57g2000hsv.googlegroups.com> <2tqdncU0D6K8v5TanZ2dnUVZ_hGdnZ2d@comcast.com> <13gk96sks58ad9f@corp.supernews.com> Message-ID: <5muoroFfdr86U2@mid.uni-berlin.de> Steven D'Aprano wrote: > On Sun, 07 Oct 2007 21:27:31 -0700, Aahz wrote: > >> In article <2tqdncU0D6K8v5TanZ2dnUVZ_hGdnZ2d at comcast.com>, Steven >> Bethard wrote: >>> >>>You can use __slots__ [...] >> >> Aaaugh! Don't use __slots__! >> >> Seriously, __slots__ are for wizards writing applications with huuuge >> numbers of object instances (like, millions of instances). For an >> extended thread about this, see >> >> http://groups.google.com/group/comp.lang.python/browse_thread/ > thread/8775c70565fb4a65/0e25f368e23ab058 > > Well, I've read the thread, and I've read the thread it links to, and for > the life of me I'm still no clearer as to why __slots__ shouldn't be used > except that: > > 1 Aahz and Guido say __slots__ are teh suxxor; > > 2 rumour (?) has it that __slots__ won't make it into Python 3.0; > > 3 inheritance from classes using __slots__ doesn't inherit the slot- > nature of the superclass. > > > Point 1 is never to be lightly dismissed, but on the other hand Guido > doesn't like reduce(), and I'm allergic to "Cos I Said So" arguments. > > History is full of things which were invented for one purpose being used > for something else. So, that being the case, suppose I accept that using > __slots__ is not the best way of solving the problem, and that people of > the skill and experience of Guido and Aahz will roll their eyes and > snicker at me. > > But is there actually anything *harmful* that can happen if I use > __slots__? Point 3 clearly is harmful. As is the fact that __slots__ gives you troubles if you e.g. pass objects to code that tries to set arbitrary attributes on an object. While this might be frowned upon, it can be useful in situations where you e.g. link GUI-code/objects with data-objects: instead of creating cumbersome, explicit mappings (as you have to in C/C++/Java) or wrappers, just set a well-named property. The question is: what does a slot buy you for this kind of problem? And while arguing with "then I can't set an attribute I didn't want to be set" is certainly possible, it ultimately leads to the darn static-vs-dynamic-discussion. Which we might spare us this time. Diez From martin at v.loewis.de Tue Oct 16 14:41:25 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 16 Oct 2007 20:41:25 +0200 Subject: Build Python 2.5 against Tk 8.5 In-Reply-To: <4714D4AB.3080103@codebykevin.com> References: <4714D34C.4050603@v.loewis.de> <4714D4AB.3080103@codebykevin.com> Message-ID: <471505D5.7010501@v.loewis.de> > It's been a while, but when I've tried to run my Tkinter app against Tk > 8.5 with a stock Python installation, I get an error message saying that > Tk 8.4.x is required. Can you please clarify what you mean by "stock Python installation"? I just built Python 2.5.1 with Tk 8.5 on Debian unstable, and it works fine. > It's probably tkinter.so that hard-codes the > Tcl/Tk version, not Python itself--I should have been clearer on that. It's still not clear. I'm the current maintainer of the _tkinter module, and I can assert that _tkinter.c does *not* hard-code Tk 8.4. As you refer to _tkinter.so, it appears you are talking about a precompiled version - did you try to build Python yourself? Regards, Martin From steve at REMOVE-THIS-cybersource.com.au Fri Oct 26 21:35:28 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 27 Oct 2007 01:35:28 -0000 Subject: Going past the float size limits? References: <1193438154.931341.30450@50g2000hsm.googlegroups.com> <1193441374.061735.308710@o38g2000hse.googlegroups.com> Message-ID: <13i55f0ib2m9gde@corp.supernews.com> On Fri, 26 Oct 2007 16:29:34 -0700, jimmy.musselwhite wrote: > On Oct 26, 6:56 pm, "Chris Mellon" wrote: >> On 10/26/07, jimmy.musselwh... at gmail.com >> wrote: >> >> > Hello all >> > It would be great if I could make a number that can go beyond current >> > size limitations. Is there any sort of external library that can have >> > infinitely huge numbers? Way way way way beyond say 5x10^350 or >> > whatever it is? >> >> > I'm hitting that "inf" boundary rather fast and I can't seem to work >> > around it. >> >> What in the world are you trying to count? > > The calculation looks like this > > A = 0.35 > T = 0.30 > C = 0.25 > G = 0.10 > > and then I basically continually multiply those numbers together. I need > to do it like 200,000+ times but that's nuts. Because this is homework, I'm not going to give you the answer. But I will give you *almost* the answer: (A*T*C*G)**200000 = ?.03?10875*10**-51?194 Some of the digits in the above have been deliberately changed to question marks, to keep you honest. > I can't even do it 1000 > times or the number rounds off to 0.0. I tried taking the inverse of > these numbers as I go but then it just shoots up to "inf". Hint: If we multiply A*T*C*G, we get 0.002625. That's the same as 0.2625 with a (negative) scale factor of 2. Another hint: for calculations of this nature, you can't rely on floating point because it isn't exact. You need to do everything in integer maths. A third hint: don't re-scale the product too often. Enough clues? -- Steven. From jadamson at partners.org Tue Oct 9 09:26:02 2007 From: jadamson at partners.org (Joel J. Adamson) Date: Tue, 09 Oct 2007 09:26:02 -0400 Subject: why did MIT drop scheme for python in intro to computing? References: <1191432204.361780.129850@d55g2000hsg.googlegroups.com> <1191863837.105036.45510@22g2000hsm.googlegroups.com> <1191900533.823209.252590@o3g2000hsb.googlegroups.com> Message-ID: <87fy0k1kt1.fsf@W0053328.mgh.harvard.edu> gnuist006 at hotmail.com writes: > On Oct 8, 1:23 pm, b... at cs.berkeley.edu (Brian Harvey) wrote: >> "Kjetil S. Matheussen" writes: [...] > > Does scheme have a gui library? Scheme is not a language, it's a standard for implementation. How much implementors choose to implement is entirely up to them. PLT Scheme, a particular implementation of Scheme, does have graphics and GUI libraries. Joel -- Joel J. Adamson Biostatistician Pediatric Psychopharmacology Research Unit Massachusetts General Hospital Boston, MA 02114 (617) 643-1432 (303) 880-3109 From emperorcezar at gmail.com Thu Oct 11 18:57:51 2007 From: emperorcezar at gmail.com (emperorcezar at gmail.com) Date: Thu, 11 Oct 2007 22:57:51 -0000 Subject: Django Contractual Position Message-ID: <1192143471.927098.319760@e9g2000prf.googlegroups.com> The Institute of Design of Chicago, IL is seeking an experienced Django developer to create an in-house contact and mailing web application. The application manages the contacts for the different conferences and events at the Institute of Design. The ideal candidate has experience with at least one completed Django application, the more the better. Good communication is required as the applicant will also be involved with design of the application. Pay is negotiable. This is a contractual position. Local applicants only. Applicant must be able to attend meetings at the Institute of Design 350 N. La Salle St. Chicago, IL 60610 please contact alon at id.iit.edu and cezar at id.iit.edu if interested. From robin at reportlab.com Tue Oct 9 13:21:02 2007 From: robin at reportlab.com (Robin Becker) Date: Tue, 09 Oct 2007 18:21:02 +0100 Subject: NUCULAR fielded text searchable indexing In-Reply-To: <1191935665.284553.110020@r29g2000hsg.googlegroups.com> References: <1191875335.134872.302660@d55g2000hsg.googlegroups.com> <1191929178.103375.308840@50g2000hsm.googlegroups.com> <1191933994.473730.73100@22g2000hsm.googlegroups.com> <1191935665.284553.110020@r29g2000hsg.googlegroups.com> Message-ID: <470BB87E.9010809@chamonix.reportlab.co.uk> aaron.watters at gmail.com wrote: > On Oct 9, 8:46 am, Istvan Albert wrote: >> ps. there is a python project named "The Devil Framework", I cringe >> every time I hear about it.Nucularis not as bad, but it is close. > > Aw shucks. I thought it was funny. Can't I make fun of > politicians in my open source projects? Besides there is > a great tradition of tounge-in-cheek package names, like > "Cold fusion", for example. >....... I think it's an excellent name :) -- Robin Becker From qam at quantal.com Thu Oct 25 17:41:38 2007 From: qam at quantal.com (QAM) Date: Thu, 25 Oct 2007 14:41:38 -0700 Subject: Read Matlab files with Python and Numeric? Message-ID: Hi Travis, Could you please send me the matlab reader you mentioned? Thanks, Frank -------------- next part -------------- An HTML attachment was scrubbed... URL: From wizzardx at gmail.com Fri Oct 5 04:25:05 2007 From: wizzardx at gmail.com (David) Date: Fri, 5 Oct 2007 10:25:05 +0200 Subject: Adding behaviour for managing "task" dependencies In-Reply-To: <1191335315.161387.238470@w3g2000hsg.googlegroups.com> References: <1191335315.161387.238470@w3g2000hsg.googlegroups.com> Message-ID: <18c1e6480710050125s7785616bk8b44a2f026d7035a@mail.gmail.com> > > Any thoughts would be most appreciated, though I would like to stress > that I don't think Python should support the syntax I'm proposing I'd > just like to know if I can extend a copy of it to do that. > You can use syntax like this: class MyJob1(Job): depends(MyJob2) depends(MyJob3) Or with quotes (if MyJob2 and MyJob3 could be declared later): class MyJob1(Job): depends('MyJob2') depends('MyJob3') (where 'depends' is a DSL-like construct. See Elixir (elixir.ematia.de) for an example of how to implement DSL statements like "depends". Check their implementation of the "belongs_to" statement. You could also extend your "depends" dsl statement to allow more than one dep at a time, eg: class MyJob1(Job): depends('MyJob2', 'MyJob3') Whatever approach you use, you should also look into implementing "topological sort" logic. This lets you resolve programatically which order the inter-dependent tasks should be handled in to satisfy their dependencies. You may find this module interesting in this regard: http://pypi.python.org/pypi/topsort David. From mbmessaoud at yahoo.com Fri Oct 26 04:30:18 2007 From: mbmessaoud at yahoo.com (mokhtar) Date: Fri, 26 Oct 2007 01:30:18 -0700 (PDT) Subject: renice Message-ID: <13422771.post@talk.nabble.com> Hi Is it possible to renice the python process executing the current python script ?:confused: -- View this message in context: http://www.nabble.com/renice-tf4695834.html#a13422771 Sent from the Python - python-list mailing list archive at Nabble.com. From gagsl-py2 at yahoo.com.ar Mon Oct 29 18:23:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Oct 2007 19:23:37 -0300 Subject: Using msvcrt (in Windows), how to catch Enter key? References: <1193657385.878620.35180@d55g2000hsg.googlegroups.com> <1193675164.790618.194190@57g2000hsv.googlegroups.com> <20071029165317.7009D1E4012@bag.python.org> <20071029174011.D22641E4029@bag.python.org> Message-ID: En Mon, 29 Oct 2007 14:39:49 -0300, Dick Moores escribi?: > But here's a case where it seems I do need the > > if msvcrt.kbhit() line At least add a small sleep() call inside the loop, to be nice to other running processes: > ========================= > #!/usr/bin/env python > #coding=utf-8 > import time > import msvcrt > timeNow = time.time() > oldTimeNow = timeNow > while True: > if msvcrt.kbhit(): > key = msvcrt.getch() > if key == 'h': > print 'Hello' > if key == 'b': > print 'Bye' > if key == '\r': # Enter key > break else: time.sleep(0.1) > timeNow = time.time() > if timeNow - oldTimeNow > 5: > print "5 seconds passed" > oldTimeNow = timeNow > ========================== -- Gabriel Genellina From http Thu Oct 25 01:20:14 2007 From: http (Paul Rubin) Date: 24 Oct 2007 22:20:14 -0700 Subject: Adding idle timeout capabilities to asyncore References: <1193081330.701282.149040@v29g2000prd.googlegroups.com> Message-ID: <7xlk9rvkhd.fsf@ruckus.brouhaha.com> Giampaolo Rodola' writes: > def readable(self): > if time.time() >= self.timeout: > self.send("Timeout") > self.close() > return 1 Don't do it this way. Put all the timeouts into a priority queue (see the heapq module) so you only need to check the one due to expire soonest. From ameyer2 at yahoo.com Tue Oct 23 14:24:18 2007 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 23 Oct 2007 11:24:18 -0700 Subject: Hiding tracebacks from end-users In-Reply-To: <13hs7247ncm67d@corp.supernews.com> References: <13hs7247ncm67d@corp.supernews.com> Message-ID: <1193163858.831863.182290@k35g2000prh.googlegroups.com> On Oct 23, 12:07 pm, Steven D'Aprano wrote: ... > if expert_mode: > # experts get the full traceback with no hand-holding. > raise > else: > # print a more friendly error message ... Another approach is to always print a friendly error message, but append the traceback to a log file (see the traceback module for how to do that.) The friendly error message can include a note that full information is available in the log file. The advantage of that is that you capture critical information that is otherwise lost when a non-expert user hits the exception. For intermittent bugs that are hard to reproduce, this can be a lifesaver - especially when your favorite non-expert user seems to have a knack for generating errors that you can't figure out how to create ;-) Alan From chlo.prog at gmail.com Tue Oct 2 11:12:09 2007 From: chlo.prog at gmail.com (rc) Date: Tue, 02 Oct 2007 15:12:09 -0000 Subject: win32com COMAdminCatalogObject Value method In-Reply-To: <1191274799_4541@sp12lax.superfeed.net> References: <1191247471.992094.203630@n39g2000hsh.googlegroups.com> <1191274799_4541@sp12lax.superfeed.net> Message-ID: <1191337929.043023.115290@r29g2000hsg.googlegroups.com> > Try objCOMAdminCatalogObject.SetValue("ID", AppID). > > Roger- Hide quoted text - > > - Show quoted text - When I try that I get exception: AttributeError: Add.SetValue I think the only valid methods are: Key(), Name(), Valid() and Value() The thing I'm most confused about is that it seems to be getting into the __getattr__ method, not the set, here's the whole error: Traceback (most recent call last): File "C:\programming\python\dev\src\FullInstallScripts \COMObjectFullInstall.py", line 74, in CreateApplication() File "C:\programming\python\dev\src\FullInstallScripts \COMObjectFullInstall.py", line 21, in CreateApplication objCOMAdminCatalogObject.SetValue("ID", AppID) File "C:\Python25\Lib\site-packages\win32com\client\dynamic.py", line 496, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: Add.SetValue From ptmcg at austin.rr.com Fri Oct 12 15:04:23 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 12 Oct 2007 12:04:23 -0700 Subject: matching a street address with regular expressions In-Reply-To: <1192195158.203063.143920@e9g2000prf.googlegroups.com> References: <1192195158.203063.143920@e9g2000prf.googlegroups.com> Message-ID: <1192206298.856282.124640@z24g2000prh.googlegroups.com> On Oct 12, 8:19 am, John Machin wrote: > "... most of the developed world" was the [very optimistic] request. > How does it go with "JAPAN 112-0001 TOKYO Bunkyo-Ku Hakusan 4-Chome 3- > 2" and will it give the same result for "4-3-2 HAKUSAN BUNKYO-KU TOKYO > 112-00001 JAPAN"? OK, a little exotic ... closer to "home", what about > addresses in Quebec? People often write addresses in formats that you > won't find on the postal service website, but the local postal workers > will still deliver. Rural addresses can be quaintly medieval e.g. "Lot > 123, Hundred of Foughbarre" [South Australia]. Etc etc ... John - As I'm sure you already know, the answer is "not too well". I've been to Japan and Europe too, and I can't even figure out how many digits a phone number is supposed to have! I once lived in a small town in Virginia, and received a Christmas card from a friend (who wanted to remind me just how small a town I was living in) addressed simply as "The McGuire's, , Virginia" - I happened to mention it the next time I was at the post office, and they said "yep, you're the only McGuires we got!" In the spectrum of tools from string.split, to re, to pyparsing and its ilk, to natural language toolkits, the broader the scope of your "address space", the further you find your self moving toward NLTK. I knew my pyparsing script wasn't in the "anywhere in the developed world" category, that's why I posted the test cases, too. If you've got an re that can handle everything from "123 Main" to "221B Baker Street" to "Hollywood and Vine" to "Lot 123, Hundred of Foughbarre", now THAT would be something. -- Paul From http Thu Oct 11 03:30:11 2007 From: http (Paul Rubin) Date: 11 Oct 2007 00:30:11 -0700 Subject: Fwd: NUCULAR fielded text searchable indexing References: Message-ID: <7xtzoynm64.fsf@ruckus.brouhaha.com> "Delaney, Timothy (Tim)" writes: > In the case of "nucular", it's a mispronunciation that has been widely > ridiculed all over the world. There are people (including myself) who so > associate it as an object of ridicule that it's an immediate turn-off. It gave me a chuckle, since it's an obvious play on the mispronunciation. As for the program itself, I've only had a chance to glance at the site, but it looks a little more akin to Solr than to Lucene. Solr is a Java application that wraps Lucene to present a more convenient interface, although it does this using XML over an HTTP socket. One thing about Solr and probably anything else like this: if you want to handle a high query load with big result sets, you absolutely must have enough ram to cache your entire index. Since ram is expensive and most of it will be sitting there doing nothing during the execution of any query, it follows that you want multiple CPU's sharing the ram. So we're back to the perennial topic of parallelism in Python... From paul at boddie.org.uk Tue Oct 2 05:29:12 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 02 Oct 2007 02:29:12 -0700 Subject: gui toolkits: the real story? (Tkinter, PyGTK, etc.) In-Reply-To: <1191293650.355504.312590@n39g2000hsh.googlegroups.com> References: <1191287053.541506.88530@d55g2000hsg.googlegroups.com> <7xr6kez5aa.fsf@ruckus.brouhaha.com> <1191293650.355504.312590@n39g2000hsh.googlegroups.com> Message-ID: <1191317352.082848.30060@g4g2000hsf.googlegroups.com> On 2 Okt, 04:54, bramble wrote: > > Maybe the key I'm missing is this: maybe GvR and company think that a > language absolutely should come off-the-shelf with GUI toolkit > bindings. So, given that, they feel they've gotta pick just one, and > they've already got Tkinter and it works, so that's that. Is that it? Yes. Also, Tk isn't a particularly fast-moving target compared to some of the other toolkits, so it's possible to not spend too much time maintaining the bindings for it, I imagine. Otherwise, Tkinter might have fallen out of the standard library by now. Paul From gneuner2/ at comcast.net Tue Oct 2 01:02:29 2007 From: gneuner2/ at comcast.net (George Neuner) Date: Tue, 02 Oct 2007 01:02:29 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> <13frd6vtarbee75@corp.supernews.com> Message-ID: <26k3g39enhpkqdamv6kopiopijotv6v7q6@4ax.com> On Tue, 02 Oct 2007 03:38:08 GMT, Roedy Green wrote: >On Fri, 28 Sep 2007 18:27:04 -0500, Damien Kick >wrote, quoted or indirectly quoted someone who said : > >>"free as in beer". > >but does not "free beer" nearly always come with a catch or implied >obligation? It means you have to bring the chips. George -- for email reply remove "/" from address From lew at lewscanon.com Sun Oct 21 11:52:03 2007 From: lew at lewscanon.com (Lew) Date: Sun, 21 Oct 2007 11:52:03 -0400 Subject: Distributed RVS, Darcs, tech love In-Reply-To: <1192981349.181197.308610@q5g2000prf.googlegroups.com> References: <1192850894.310464.89070@e9g2000prf.googlegroups.com> <1192914246.208743.94870@y27g2000pre.googlegroups.com> <471afd4c.179297746@news.readfreenews.net> <1192972158.250126.203980@v23g2000prn.googlegroups.com> <471b6714$0$90276$14726298@news.sunsite.dk> <1192981349.181197.308610@q5g2000prf.googlegroups.com> Message-ID: llothar wrote: > Well programming in the small like sort algorithms for sure. But not > for his great discoveries but for one of the first man who was paid > for this by this university employee. What a curious thesis. > But in the field of software enginering as i said before he > completely > failed. As you said, but for which you provided absolutely no evidence, and the counter evidence that Arne provided is that he has not "completely" failed for any useful value of "failed". Statements of absolute only need one counterexample. /The Art of Programming/ is arguably the most significant contribution to the field of software engineering. By any reasonable assessment, on the basis of that one work alone Knuth was a success. Your rhetorical tack of unfounded assertions and inflammatory characterizations, not to say complete disregard for the reality of the situation, do not make a cogent case, much less a convincing one. I am afraid that your conclusion is quite mistaken. Knuth is, if anything, a huge success in the field of software engineering, whether you rate it as making a contribution to the art, or as being paid to perform the art. -- Lew From hat at se-162.se.wtb.tue.nl Mon Oct 8 06:23:27 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 08 Oct 2007 12:23:27 +0200 Subject: Really basic problem References: Message-ID: On 2007-10-08, Andreas Tawn wrote: >> i know this example is stupid and useless, but that's not the answer >> to my question. >> here it goes: >> > You've just discovered the joys of floating point number comparisons. > > Consider this snippet: > > status = 0.0 > print (repr(status)) > > for i in range(10): > status += 0.1 > print (repr(status)) > > Output: > > 0.0 > 0.10000000000000001 > 0.20000000000000001 > 0.30000000000000004 > 0.40000000000000002 > 0.5 > 0.59999999999999998 > 0.69999999999999996 > 0.79999999999999993 > 0.89999999999999991 > 0.99999999999999989 > > The issue is that 0.1 etc don't have an exact representation as floating > point. > > Interestingly: > >>>> 0.10000000000000001 == 0.1 > True >>>> 0.30000000000000004 == 0.3 > False > > I guess this means that Python has some concept of "close enough", but > I'll have to defer to someone more knowledgeable to explain that. It's not Python, it is the computer, ie you have this problem with any program that uses floating point calculations. However, some programs hide it from you so you think there is no problem... Plz read the FAQ for an answer to this and many other questions: http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate Sincerely, Albert From bruno.42.desthuilliers at wtf.websiteburo.oops.com Sat Oct 6 08:16:01 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Sat, 06 Oct 2007 14:16:01 +0200 Subject: Segmentation fault.. In-Reply-To: References: <1191668481.171014.54840@57g2000hsv.googlegroups.com> Message-ID: <47077c62$0$18737$426a74cc@news.free.fr> Jorge Godoy a ?crit : > Abandoned wrote: > >> Hi.. >> I run a my script and 3-4 minutes later give me an error "segmentation >> fault". >> What is the reason of this error ? >> >> I use in my script: >> Threading >> Psycopg2 >> open & write to txt >> urlopen >> >> My platform is ubuntu linux. >> >> I'm sorry my bad english. >> King regards.. > > Without seeing any code, it is hard to say anything. But the answer to the > ultimate question is "42". Indeed. Err, what was the question, exactly ?-) > Show the group some code and I'm sure people will help. To be more precise: post the minimal working code reproducing the problem, and the full traceback. From p at ulmcnett.com Thu Oct 18 16:08:04 2007 From: p at ulmcnett.com (Paul McNett) Date: Thu, 18 Oct 2007 13:08:04 -0700 Subject: Problem with format string / MySQL cursor In-Reply-To: <1192736676.035569.188300@e9g2000prf.googlegroups.com> References: <1192732348.392303.151430@i38g2000prf.googlegroups.com> <1192736676.035569.188300@e9g2000prf.googlegroups.com> Message-ID: <4717BD24.5080607@ulmcnett.com> timaranz at gmail.com wrote: > On Oct 19, 7:32 am, Florian Lindner wrote: >> Hello, >> I have a string: >> >> INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`, >> `gid`, `password`) VALUES (%s, %s, %s, %s, %i, %i, %s) >> >> that is passed to a MySQL cursor from MySQLdb: >> >> ret = cursor.execute(sql, paras) >> >> paras is: >> >> ('flindner', 'te... at florian-lindner.de', '/home/flindner/', '/home/ >> flindner/Mail/test', 1001, 1001, '123') >> >> But that gives me an error: >> >> Traceback (most recent call last): >> File "account.py", line 188, in ? >> main() >> File "account.py", line 33, in main >> execute(action, account_type, options) >> File "account.py", line 129, in execute >> executeSQL(sql, options.username, options.login, options.home, >> options.directory, options.uid, options.gid, options.password) >> File "/home/flindner/common.py", line 29, in executeSQL >> ret = cursor.execute(sql, paras) >> File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line >> 148, in execute >> query = query % db.literal(args) >> TypeError: int argument required >> >> I don't see errors in the format string or some other problem.... >> >> What's wrong? > You should be using '?' for parameter bindings in your sql string not > python format specifiers (you are after all writing sql here not > python). > > INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`, > `gid`, `password`) VALUES (?, ?, ?, ?, ?, ?, ?) Sorry Tim, but that isn't correct: >>> import MySQLdb >>> MySQLdb.paramstyle 'format' Florian, what happens when you replace your %i with %s? -- pkm ~ http://paulmcnett.com From gagsl-py2 at yahoo.com.ar Mon Oct 22 11:50:12 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 22 Oct 2007 12:50:12 -0300 Subject: Check File Change Every 10 Seconds References: <27459.1491478079$1193048158@news.gmane.org> <40899.5410231457$1193064457@news.gmane.org> Message-ID: En Mon, 22 Oct 2007 11:45:49 -0300, Robert Rawlins - Think Blue escribi?: > Thanks for your time Gabriel, > > That certainly looks to be the type of thing that I'm looking to > achieve, however, I forgot to mention I'm running this on a Linux > platform and not a Win32 one :-( Sorry. Ouch! Should have asked... > I'm sure similar things are achievable, I've used os.stat before now to > get the time stamp for when a file was last changed, if I perhaps > combine this with the while 1: inside a thread I can achieve the same > end result? Sound like a good idea? Yes, that may work, but there are better ways I think. Check this recipe and the pyinotify module at sourceforge. -- Gabriel Genellina From alfonso66alfonso at yahoo.com Mon Oct 22 03:35:39 2007 From: alfonso66alfonso at yahoo.com (Alfonso) Date: Mon, 22 Oct 2007 00:35:39 -0700 Subject: Fat Loss 4 Idiots Message-ID: <1193038539.458781.273240@t8g2000prg.googlegroups.com> Learn the 10 Idiot proof rules of dieting and fat loss. Stop using low carb diets. Stop using low calorie diets. Stop using low fat diets. Be proud that you could finally loose those pounds. http://netsales77.4idiots.hop.clickbank.net From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Oct 25 13:29:23 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 25 Oct 2007 19:29:23 +0200 Subject: Python Windows Installation References: <1193195493.086681.40570@t8g2000prg.googlegroups.com> <5o8s2bFlhd8uU2@mid.individual.net> <13i09eohrt6il52@corp.supernews.com> Message-ID: <5oc23kFm4aqfU1@mid.individual.net> Dennis Lee Bieber wrote: > Besides preferring an install path that doesn't have spaces... Which I don't understand (works best for me, and is best practice in Windows). > On a proper XP (or later) system, one needs ADMIN privileges to > install/modify the contents of %PROGRAMFILES%. Any user can > probably install to a top-level "python25" directory. Really? That's a strange world. The normal place for user stuff is his Files directory. But it would be no problem to make a Python25 directory user-writable, no matter where it is. Regards, Bj?rn -- BOFH excuse #58: high pressure system failure From michele.simionato at gmail.com Sat Oct 6 08:02:13 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 06 Oct 2007 12:02:13 -0000 Subject: Yet another comparison of Python Web Frameworks In-Reply-To: <6b7kt4-v7q.ln1@strongwill.g2ctech> References: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> <6b7kt4-v7q.ln1@strongwill.g2ctech> Message-ID: <1191672133.323420.183340@g4g2000hsf.googlegroups.com> On Oct 6, 7:15 am, Jorge Godoy wrote: > Tim Chase wrote: > > Any respectable comparison of Python web frameworks should > > include evaluation of at least Django and TG. Or at least give > > good reason why the comparison excludes them. Mine is not a respectable comparison of Web frameworks, it is NOT intended to be so. It is just a set of notes I kept for myself and that may be or may be not of interest to others. > When he said that he didn't want anything complex neither anything that used > a templating system, I thought this had already excluded a lot of > frameworks, including TG and Django. This is clearly not true, since I could use these frameworks without using their templates if I wanted. It would be very stupid to dismiss an entire framework only because I dislike its templates. > > Zope is also missing, but I'm not sure Zope qualifies so much as > > a framework, but as an answer to the question "If Emacs were a > > Python web environment, what would it look like?" > > He already had dislikings with Plone that weren't clear, maybe a lot of > those are Zope related... > > I agree, though, that more time could be spent explaining "why" things were > discarded / ignored. Look, there are already tons of pages on the net ranting against Zope, my complaints are quite common and I have no interest in repeating what has been already said. For instance, if you Google a bit you should find the rants of the Quixote people against Zope. I share their position. I did not talk about TG because I see it as being very close to Pylons and everybody is saying they will be unified in the near future, so it would be a waste of effort to discuss TG per se. Michele Simionato From lennartb at xs4all.nl Fri Oct 26 04:54:01 2007 From: lennartb at xs4all.nl (Lennart Benschop) Date: Fri, 26 Oct 2007 10:54:01 +0200 Subject: Proposal: Decimal literals in Python. Message-ID: <4721ab28$0$1238$e4fe514c@dreader28.news.xs4all.nl> Python has had the Decimal data type for some time now. The Decimal data type is ideal for financial calculations. Using this data type would be more intuitive to computer novices than float as its rounding behaviour matches more closely what humans expect. More to the point: 0.1 and 0.01 are exact in Decimal and not exact in float. Unfortunately it is not very easy to access the Decimal data type. To obtain the decimal number 12.34 one has to do something like this: import decimal x=decimal.Decimal("12.34") Of course we can intruduce a single character function name as an alias for the Decimal type constructor, but even then we have to use both parentheses and quotes for each and every decimal constant. We cannot make it shorter than D("12.34") With Python 3000 major changes to the language are carried out anyway. My proposal would require relatively minor changes. My proposal: - Any decimal constant suffixed with the letter "D" or "d" will be interpreted as a literal of the Decimal type. This also goes for decimal constants with exponential notation. Examples of decimal literals: 1d 12.34d 1e-3d (equivalent to 0.001d) 1e3d (same value as 1000d, but without trailing zeros). 1.25e5d (same value as 125000d but without trailing zeros). When we print a decimal number or convert it to a string with str(), a trailing d should not be added. The repr function does yield strings with a trailing d. When decimal numbers are converted from strings, both numbers with and without a trailing d should be accepted. If we have decimal literals in the core language, we should probably have a type constructor in the core namespace, e.g. dec() along with int() and float(). We then need the decimal module only for the more advanced stuff like setcontext. Pros: - the Decimal data type will be more readily accessible, especially for novices. - Traling characters at the end of a literal are already used (the L for long). - It does not conflict with the syntax of other numeric constants or language constructs. - It does not change the meaning of existing valid literal constants. Constants that used to be float will continue to do so. Cons: - The lexical scanner of the Python interpreter will be slightly more complex. - The d suffix for constants with exponential notation is ugly. - Decimal numbers with exponentail notation like 2e5d could be mistaken for hex (by humans, not by the parser as hex requires the 0x prefix). - It requires the decimal module to be part of the core Python interpreter. -- Lennart From amdescombes at gmail.com Fri Oct 19 16:17:46 2007 From: amdescombes at gmail.com (AMD) Date: Fri, 19 Oct 2007 22:17:46 +0200 Subject: Memory Problems in Windows 2003 Server In-Reply-To: <5ngsgpFhiqfbU2@mid.uni-berlin.de> References: <470f7857$0$27795$426a74cc@news.free.fr> <4710a5ad$0$26731$426a74cc@news.free.fr> <6b63h3p842g6ggafqbc5d4f8n4o48ramdm@4ax.com> <4713338b$0$20269$426a74cc@news.free.fr> <5ngsgpFhiqfbU2@mid.uni-berlin.de> Message-ID: <471910e8$0$17463$426a34cc@news.free.fr> Thanks Marc, I just tried shelve but it is very slow :( I haven't tried the dbs yet. Andre Marc 'BlackJack' Rintsch a ?crit : > On Mon, 15 Oct 2007 11:31:59 +0200, amdescombes wrote: > >> Are there any classes that implement disk based dictionaries? > > Take a look at the `shelve` module from the standard library. > > Or object databases like ZODB or Durus. > > Ciao, > Marc 'BlackJack' Rintsch From cyberco at gmail.com Fri Oct 26 15:11:27 2007 From: cyberco at gmail.com (cyberco) Date: Fri, 26 Oct 2007 19:11:27 -0000 Subject: Eclipse Plugins In-Reply-To: References: <-5528451693797282245@unknownmsgid> Message-ID: <1193425887.446924.82800@50g2000hsm.googlegroups.com> > PyDev is open source, and the developer is pretty responsive, so if you > could describe what is missing there is a good chance it would get > implemented. I even fixed two bugs myself, my first ever real Java > contribution... > > -- > Heikki Toivonen I can second that. I'm a happy PyDev user myself for any Python module that is more than 100 lines long. The nice things is that it has a lot of the same keybindings as the Eclipse Java editor has (duplicating lines/blocks, organising imports, indent/dedent, etc). In cases where PyDev needs a patch the main developer is always there to help you out. 2B From mccredie at gmail.com Mon Oct 15 16:03:36 2007 From: mccredie at gmail.com (Matt McCredie) Date: Mon, 15 Oct 2007 13:03:36 -0700 Subject: Newbi Q: What is a rational for strings not being lists in Python? In-Reply-To: <53396d9e0710150805n6e2cfa53je05d24ec51190aa0@mail.gmail.com> References: <53396d9e0710150805n6e2cfa53je05d24ec51190aa0@mail.gmail.com> Message-ID: <9e95df10710151303s117658a5xde18c577d929f9ae@mail.gmail.com> On 10/15/07, Dmitri O.Kondratiev wrote: > To clarify my point: > reverse() is a lucky one - Python has variants of *this particular* > function both for lists and strings. Yet what about other list functions? > How in general, can I write a function that works both on list and string > types? Both are sequences, right? Why string is not a subtype of a list > then? > The advantage of string being a list of elements, where element is a char is > that all list functions will work *without any modifications* on strings as > well as on other types of lists. > So, I am trying to understand: what is a rational for strings not being > lists in Python? > > Thanks, > -- > Dmitri O. Kondratiev > dokondr at gmail.com > http://www.geocities.com/dkondr > > On 10/15/07, Dmitri O.Kondratiev wrote: > > Gary, thanks for lots of info! > > Python strings are not lists! I got it now. That's a pity, I need two > different functions: one to reverse a list and one to reverse a string: > > > > def reverseList(xs): > > if xs == []: > > return xs > > else: > > return (reverseList (xs[1:])) + [xs[0]] > > > > def reverseStr(str): > > if str == "": > > return str > > else: > > return (reverseStr (str[1:])) + str[0] > > > > Ok. Now regarding in-place reversal of a list: > > > > >>> l = [1,2,3] > > >>> l > > [1, 2, 3] > > >>> l.reverse() > > >>> l > > [3, 2, 1] > > > > That was, as I expected. Good. > > > > Then why this ? : > > > > >>> ls = [1,2,3].reverse() > > >>> ls > > >>> > > >>> print [1,2,3].reverse() > > None > > >>> > > I mean, why ls is empty after assignment? > > > > Also, I couldn't find in the Python docs what this form of slicing means: > > xs[::-1] ? > > > > It works for creating a reversed copy of either a string or a list, but > what does '::-1' syntax means? > > > > Thanks, > > > > Dmitri O. Kondratiev > > dokondr at gmail.com > > http://www.geocities.com/dkondr > > > > > > > > On 10/15/07, Gary Herron < gherron at islandtraining.com> wrote: > > > Dmitri O.Kondratiev wrote: > > > > > > > > The function I wrote (below) reverses lists all right: > > > > > > > > def reverse(xs): > > > > if xs == []: > > > > return [] > > > > else: > > > > return (reverse (xs[1:])) + [xs[0]] > > > > > > > > > > > > >>> reverse ([1,2,3]) > > > > [3, 2, 1] > > > > >>> > > > > > > > > > > > > Yet when I try to reverse a string I get: > > > > > > > > >>> reverse ("abc") > > > > > > > > ... > > > > ... > > > > ... > > > > > > > > File "C:\wks\python-wks\reverse.py", line 5, in reverse > > > > > > > > return (reverse (xs[1:])) + [xs[0]] > > > > > > > > File "C:\wks\python-wks\reverse.py", line 5, in reverse > > > > > > > > return (reverse (xs[1:])) + [xs[0]] > > > > > > > > File "C:\wks\python-wks\reverse.py", line 2, in reverse > > > > > > > > if xs == []: > > > > > > > > RuntimeError: maximum recursion depth exceeded in cmp > > > > > > > > >>> > > > > > > > > What's wrong? Why recursion never stops? > > > > > > > If you are doing this as an python-learning exercise, then read on. If > > > you are doing this reversal for real code, then try: > > > > > > xs.reverse() for in-place reversal of a list (but not a string), or > > > result = xs[::-1] for creating a reversed copy of either a string or a > > > list > > > > > > > > > Your recursion stops when xs == [], but when you're stripping characters > > > off a string, like 'abc', the remaining portion will be 'bc', then 'c', > > > than '', but never [] so you 'll never stop. > > > > > > Try: > > > > > > if xs == []: > > > return [] > > > elif xs == '': > > > return '' > > > else: > > > ... > > > > > > > > > Gary Herron > > > > > > > > > > > > > > Thanks, > > > > Dima The example you posted won't work with tuples either because they, like strings, are also immutable. So, the best way to get the posted code to work (which is a bad way to go about reversing a string, but I digress) is to cast the input parameter to a list first. The returned value will always be a list, but you will simply have to convert it back to the appropriate type when you are done. What is the purpose if immutability? It allows a value to be hashed. I don't want to get into a discussion about methods for hashing mutable types, if you are interested just do a search on the list archives. Hashing allows for quick comparisons of values, but more importantly it allows for values to be used as keys for the dict type. This is very important because, as you will soon find out if you keep learning the language, all namespaces in python are implemented as dicts. So... if you want a mutable string, just cast it to a list, do your operations and cast it back to a string. Incidentally, the proper method for converting a list of characters to a string is by using the join method on an empty string. >>> s = "I am a string" >>> x = list(s) >>> x ['I', ' ', 'a', 'm', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g'] >>> "".join(x) 'I am a string' Matt From dmcclouds at gmail.com Mon Oct 29 00:31:22 2007 From: dmcclouds at gmail.com (D) Date: Sun, 28 Oct 2007 21:31:22 -0700 Subject: iPod Library Message-ID: <1193632282.154132.277190@v3g2000hsg.googlegroups.com> Is there a Python library available that will allow you to read/write from the database of an iPod 3G and 5G? Basically, I'm sick of iTunes and would much rather write a simple program myself. Thanks. From kyosohma at gmail.com Mon Oct 22 09:43:23 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 22 Oct 2007 13:43:23 -0000 Subject: Problems in using wxPython in a multithreaded context In-Reply-To: <1193046805.616227.232330@k35g2000prh.googlegroups.com> References: <1193046805.616227.232330@k35g2000prh.googlegroups.com> Message-ID: <1193060603.808510.9450@t8g2000prg.googlegroups.com> On Oct 22, 4:53 am, mec2pa... at gmail.com wrote: > For my C application, I use many interpreters (withh the fonction > Py_NewInterpreter()). For my needs, I create many GUI with wxPython > and I have problems. Here is My C Code: > > { > PyEval_InitThreads(); > Py_Initialize(); > PyImport_ImportModule("myModule");//it creates a wxApp and a GUI > ...... > > Py_NewInterpreter(); > PyImport_ImportModule("anotherModule");//it should create a new > wxApp and a new GUI > > Unfortunately this code does not work. In fact, My C application which > use many interpreters is seen by wxPython as a single application, and > as wxPython is thread safe, it is not possible to create a second > App. > I have to use many interpreters to separate variables and to avoid > links between modules. > > What could I do to create many GUI in different interpreters (each GUI > have to be in a separate environment)??? > > Thanks. You should probably check out this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4ac31cd3a389a4d8/ And this might help as well: http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html And here's a wxPython specific article on threading: http://wiki.wxpython.org/LongRunningTasks You might consider posting to the wxPython mailing list too, as they can probably help you more. Mike From jasondrew72 at gmail.com Tue Oct 23 12:49:43 2007 From: jasondrew72 at gmail.com (Jason Drew) Date: Tue, 23 Oct 2007 09:49:43 -0700 Subject: greatest and least of these... In-Reply-To: References: Message-ID: <1193158183.092190.158210@q5g2000prf.googlegroups.com> What do you mean when you say the menu doesn't kick in? Do you get an exception, or does simply nothing happen? Before the if statements, you should put "print choice" so you can see what value is being returned by the input function. Also maybe "print type(choice)" for a bit more inspection. Speaking of which, you should probably be using something like "int(raw_input())" instead of just "input()" - if you read the help on the two functions you should see why. Hope this helps. Jason On Oct 23, 11:56 am, Shawn Minisall wrote: > I just wrote a program to let the user input a series of whole numbers > and tell them which is least and which is greatest based off of a menu. > However, the menu isn't kicking in after they pick a number. I included > a while statement for a loop just for the menu and compared it to my > other programs that have a similar setup and are working, but I'm > stumped. Here's the program... > > def main(): > > #define and initialize variables > #choice as int > choice = 0 > #number as int > number = 0 > > #intro > print "WELCOME TO THE GREATEST AND LEAST NUMBER PROGRAM!" > print > > #Menu loop > while choice != 2: > #display menu > print "Please choose from the following menu: " > print "1. Enter a number" > print "2. Exit" > print > > #prompt user for their menu choice > choice = input("Enter your choice here: ") > > #if statements to determine which choice > if choice == 1: > nums = [] > while number >=0: > nums.append(number) > number = input("Please enter a number.") > > elif choice == 2: > print "Have a great day!" > > if len(nums) > 0: > print "The smallest number that you entered was:",min(nums) > print "The largest number that you entered was:",max(nums) > > else: > #invalid > print "Invalid selection. Enter either one or two." > print > > Also, if they quit the program with choice #2 and entered numbers, it > should display the greatest and least of them. If they just started and > didn't enter anything and want to quit, I get an error message saying > UnboundLocalError: local variable 'nums' referenced before assignment. > Isn't the if statement supposed to keep python from going there since if > they didn't enter any input, the length of the list should just be zero. From hat at se-162.se.wtb.tue.nl Wed Oct 24 10:04:28 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 24 Oct 2007 16:04:28 +0200 Subject: Better writing in python References: <1193227780.481365.261900@q3g2000prf.googlegroups.com> Message-ID: > On 2007-10-24, Alexandre Badez wrote: > I'm just wondering, if I could write a in a "better" way this > code > > lMandatory = [] > lOptional = [] > for arg in cls.dArguments: > if arg is True: > lMandatory.append(arg) > else: > lOptional.append(arg) > return (lMandatory, lOptional) > > I think there is a better way, but I can't see how... You can do it shorter, not sure that it also qualifies as better.... d = { True : [] , False : [] } for arg in cls.arguments: d[arg == True].append(arg) return d[True], d[False] One potential problem here is that 'arg == True' may not be the same as 'if arg:'. I couldn't come up with a better equivalent expression, maybe one of the other readers knows more about this? Albert From thorsten at thorstenkampe.de Sat Oct 20 04:13:49 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 20 Oct 2007 16:13:49 +0800 Subject: Noob: Loops and the 'else' construct References: <1192761867.254928.115300@i38g2000prf.googlegroups.com> <1192793944.775832.295350@e9g2000prf.googlegroups.com> Message-ID: * Dustan (Fri, 19 Oct 2007 11:39:04 -0000) > On Oct 19, 3:12 am, Thorsten Kampe wrote: > > So a for/else loop is exactly the same thing as a for loop with the > > else clause outside the loop (except for "break")? > > Am I missing something here? It sounds to me like you just described > two identical constructs. # for i in range(10): print i else: print 'the end!' # is the same else # for i in range(10): print i print 'the end!' # From kw at codebykevin.com Fri Oct 5 09:17:24 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 05 Oct 2007 09:17:24 -0400 Subject: tkinter question In-Reply-To: References: <1191554174.490449.251400@50g2000hsm.googlegroups.com> <470629D1.2040404@codebykevin.com> Message-ID: <47063964.7000809@codebykevin.com> Eric Brunel wrote: > On Fri, 05 Oct 2007 14:10:57 +0200, Kevin Walzer > wrote: >> "expand = 1" == "expand=TRUE"--that means the widget resizes itself >> when the window is re-sized. > > That's the theory... But what does fill=BOTH means then? And why does > expand=1 (or TRUE, or True) is only needed in some cases and not others? > And I'm quite sure that sometimes, I use expand=1 and it does exactly > what I don't want, and removing it gives the behaviour I want. I've been > doing tk/Tkinter stuff for quite a few years now, and I still haven't > understood exactly when I should use this option... Quite > counter-intuitive, IMHO. > > But then, since I almost never use pack for this kind of layout, I guess > it's not really important... "Fill" refers to the dimension/space that is filled when you expand the widget (assuming "expand" is set to true). "fill=x" means the widget will expand horizontally (along the x axis). "fill=y" means that the widget will expand vertically (along the y axis). "fill=both" means the widget will expand in both direction. Frederick Lundh has a good introduction to the packer here: http://effbot.org/tkinterbook/pack.htm I find "pack" to be more flexible than "grid," so I prefer it for complex layouts. "grid" is better for simple layouts. HTH, Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From israelu at elbit.co.il Mon Oct 22 02:33:55 2007 From: israelu at elbit.co.il (iu2) Date: Sun, 21 Oct 2007 23:33:55 -0700 Subject: Failure to connect in SimpleXMLRPCServer/xmlrpclib Message-ID: <1193034835.803633.121600@z24g2000prh.googlegroups.com> Hi all, I've copied the example of RPC usage from the Python's doc. When the client and server were on the same PC ("localhost") (I use Windows) it worked ok. But putting the server on a different PC raised the error: gaierror: (11001, 'getaddrinfo failed') The error was raised upion accessing some function of the server, i.e., print s.add_nums(1, 2, 3) # server registered function PCs in our organization are accessed by "\\" so I used s = xmlrpclib.Server(r'http://\\pc_name:8000') I got the same error when I put some non-existing name. Trying to remove the double-backslash from the PC's name raised the error: error: (10061, 'Connection refused') I'll appreciate your help on this. Thanks iu2 From deets at nospam.web.de Mon Oct 29 12:31:25 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 29 Oct 2007 17:31:25 +0100 Subject: python2.5 and mysqldb References: <1193674960.082948.179940@22g2000hsm.googlegroups.com> Message-ID: <5omg6tFng8kqU1@mid.uni-berlin.de> writeson wrote: > Hi all, > > At work we're using python2.3 and I'd like to start getting us moved > up to python2.5. We run Centos4 which is the free, open source version > of RedHat Enterprise. I've got python2.5 installed on this machine, > but am stuck trying to get mysqldb installed and running on this > machine. I've tried with easy_install and by building from the tar > file and both return a long list of errors from a gcc compile. I'm not > sure what to do next to resolve this issue, so if anyone could give me > some guidance it would be greatly appreciated. Which we would love to do if you cared to post the long list of errors. Unless the PSU launches one of it's psychic members to work on your problem - but they are very usually very busy. Diez From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Oct 8 07:15:34 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 08 Oct 2007 13:15:34 +0200 Subject: Problem of Readability of Python In-Reply-To: References: <1191780456.833563.173080@57g2000hsv.googlegroups.com> <470924c8$0$15774$426a34cc@news.free.fr> Message-ID: <470a112b$0$28457$426a74cc@news.free.fr> Brian Elmegaard a ?crit : > Bruno Desthuilliers > writes: > >> Use dicts, not lists or tuples: >> >> a = dict(name='yadda', val=42) >> print a['name'] >> print a['val'] > > I guess you will then need a list or tuple to store the dicts? Should be a list then IMHO. But then it's the correct use of a list : an homegenous collection. From byte8bits at gmail.com Thu Oct 11 11:40:33 2007 From: byte8bits at gmail.com (brad) Date: Thu, 11 Oct 2007 11:40:33 -0400 Subject: Finding Peoples' Names in Files In-Reply-To: <1192116309.880026.83240@r29g2000hsg.googlegroups.com> References: <1192116309.880026.83240@r29g2000hsg.googlegroups.com> Message-ID: cokofreedom at gmail.com wrote: > On Oct 11, 5:22 pm, brad wrote: >> Crazy question, but has anyone attempted this or seen Python code that >> does? For example, if a text file contained 'Guido' and or 'Robert' and >> or 'Susan', then we should return True, otherwise return False. > > Can't you just use the string function .findall() ? > I mean *any* possible person's name... I don't *know* the names beforehand :) From kay.schluehr at gmx.net Tue Oct 9 11:18:13 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 09 Oct 2007 08:18:13 -0700 Subject: Mixing Python and C classes in a module In-Reply-To: <87wstwibfl.fsf@keizer.soze.com> References: <87wstwibfl.fsf@keizer.soze.com> Message-ID: <1191943093.138030.167960@57g2000hsv.googlegroups.com> On Oct 9, 4:56 pm, Stefan Arentz wrote: > Is it possible to mix classes defined in both Python and C in the same > module? Ideally I would like to be able to do: > > from some.module import MyPythonClass, MyCClass > > I guess that would mean that this would look like this on disk: > > some/ > __init__.py > module.py (contains MyPythonClass) > module.so (contains MyCClass) > > But would this work? > > S. Yes, but you need to write your own importer and customize it using ihooks.py. The builtin imp module also contains a function new_module that lets you allow creating a module without any file reference. This can be returned containg the names of both module.py and module.so. From phil at freehackers.org Fri Oct 12 06:57:18 2007 From: phil at freehackers.org (BlueBird) Date: Fri, 12 Oct 2007 03:57:18 -0700 Subject: Cross-platform GUI development In-Reply-To: References: <1192176809.756259.316980@v29g2000prd.googlegroups.com> <1192178193.734126.253610@z24g2000prh.googlegroups.com> Message-ID: <1192186638.902052.85880@i38g2000prf.googlegroups.com> On Oct 12, 12:30 pm, Nick Craig-Wood wrote: > > > My question is if Tix is old hat, what is the GUI toolkit I *should* > > > be using for quick-n-dirty cross platform GUI development? I guess > > > this is tangentially related to: > > > >http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > > Personnaly, I use PyQt simply because I prefere Qt to Gtk, witch is > > much more integrated with all desktop than Gtk. > > In fact, your application in Qt on Mac, Win or Linux look like a > > native app. >From my point of view, PyQt is very good. Qt is very actively developed and maintained, and the PyQt binding is of very good quality, and fully documented. I have used personally for several cross-platform projects and it worked like a charm. I like Qt's approach and extensive documentation. I've found that it works both for complex GUI as for quick'n dirty. There is usually a widget to do just what I need so that I can focus on my application logic instead of on the GUI code. In short, usage of Qt has driven me to love it. When looking at the other guis, I always find that the documentation is under my expectations, or that that things are quite complex to set- up to get what you need. On Oct 12, 12:30 pm, Nick Craig-Wood wrote: > I'd recommend wxPython over those becase > > 1) native look and feel on all platforms You get it with PyQt as well. > 2) doesn't require expensive licensing for non-commercial apps (QT) You mean "doesn't require expensive licensing for close source apps". Open source apps are free of charge. For professional developments, I bought the Qt license several times in the past because it was worth the time saved in my opinion. > 3) Isn't a pain to install on windows (GTK) You get it with Qt as well. I was able to use it even as a windows newbie. From panguohualove at sina.com Fri Oct 19 07:27:41 2007 From: panguohualove at sina.com (panguohua) Date: Fri, 19 Oct 2007 04:27:41 -0700 Subject: a good website for softwares,sports,movies and music ,sex etc. Message-ID: <1192793261.911816.161190@z24g2000prh.googlegroups.com> www.space666.com nice From carsten at uniqsys.com Thu Oct 18 14:17:29 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 18 Oct 2007 14:17:29 -0400 Subject: Convert string to command.. In-Reply-To: <87lka01f8k.fsf@mulj.homelinux.net> References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> <5npa5cFj5bvfU1@mid.uni-berlin.de> <1192720007.177063.194550@i13g2000prf.googlegroups.com> <5npbjbFio7g9U1@mid.uni-berlin.de> <1192720659.272611.320900@v29g2000prd.googlegroups.com> <873aw830lc.fsf@mulj.homelinux.net> <1192722090.740342.60950@i13g2000prf.googlegroups.com> <87y7e01kcv.fsf@mulj.homelinux.net> <1192724835.765738.141790@q5g2000prf.googlegroups.com> <87przc1im7.fsf@mulj.homelinux.net> <1192726872.921589.249670@i38g2000prf.googlegroups.com> <87lka01f8k.fsf@mulj.homelinux.net> Message-ID: <1192731449.3402.25.camel@dot.uniqsys.com> On Thu, 2007-10-18 at 19:53 +0200, Hrvoje Niksic wrote: > Don't > forget to also use a bind variable, something like: > > cursor.execute("INSERT INTO cache2 VALUES (?)", a) I second the advice, but that code won't work. The bind parameters must be a sequence, and psycopg2 (unfortunately) uses %s for parameter markers, instead of the SQL standard question mark. So the actual code would be cursor.execute("INSERT INTO cache2 VALUES (%s)", (a,) ) HTH, -- Carsten Haese http://informixdb.sourceforge.net From steven.bethard at gmail.com Mon Oct 22 14:17:04 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 22 Oct 2007 12:17:04 -0600 Subject: Python-URL! - weekly Python news and links (Oct 22) In-Reply-To: References: Message-ID: <471CE920.7080507@gmail.com> Gabriel Genellina wrote: > "I actually do a lot of unit testing. I find it both annoying and highly > necessary and useful." - Steven Bethard > http://groups.google.com/group/comp.lang.python/msg/4df60bdff72540cb That quote is actually due to Dan McLeran. A very good quote though. Steve From duncan.booth at invalid.invalid Tue Oct 2 03:54:52 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Oct 2007 07:54:52 GMT Subject: Select as dictionary... References: <1191245527.228745.17100@r29g2000hsg.googlegroups.com> <4700fb42$0$18288$426a74cc@news.free.fr> <47010e97$0$7777$426a74cc@news.free.fr> <1191258548.820547.123560@k79g2000hse.googlegroups.com> <1191258828.206660.21570@22g2000hsm.googlegroups.com> Message-ID: Abandoned wrote: > ( I don't want to use FOR and APPEND because the > query have 2 million result and i want to speed) > How many times do you plan on doing this? On my system I just timed adding 2 million elements to a dictionary: it took 0.35 seconds. Appending 2 million elements to a list took 0.43 seconds. Unless you really do need to repeat this operation many many many times then just write the obvious code instead of wasting your (and our) time trying to micro-optimise. From NikitaTheSpider at gmail.com Thu Oct 4 12:14:40 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Thu, 04 Oct 2007 12:14:40 -0400 Subject: Why doesn't Python's "robotparser" like Wikipedia's "robots.txt" file? References: Message-ID: In article , John Nagle wrote: > Filip Salomonsson wrote: > > On 02/10/2007, John Nagle wrote: > >> But there's something in there now that robotparser doesn't like. > >> Any ideas? > > > > Wikipedia denies _all_ access for the standard urllib user agent, and > > when the robotparser gets a 401 or 403 response when trying to fetch > > robots.txt, it is equivalent to "Disallow: *". > > > > http://infix.se/2006/05/17/robotparser > > That explains it. It's an undocumented feature of "robotparser", > as is the 'errcode' variable. The documentation of "robotparser" is > silent on error handling (can it raise an exception?) and should be > updated. Hi John, Robotparser is probably following the never-approved RFC for robots.txt which is the closest thing there is to a standard. It says, "On server response indicating access restrictions (HTTP Status Code 401 or 403) a robot should regard access to the site completely restricted." http://www.robotstxt.org/wc/norobots-rfc.html If you're interested, I have a replacement for the robotparser module that works a little better (IMHO) and which you might also find better documented. I'm using it in production code: http://nikitathespider.com/python/rerp/ Happy spidering -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From epost2 at gmail.com Mon Oct 8 10:11:53 2007 From: epost2 at gmail.com (Bruce) Date: Mon, 08 Oct 2007 07:11:53 -0700 Subject: changes on disk not visible to script ? In-Reply-To: References: <1191850024.006823.101610@r29g2000hsg.googlegroups.com> Message-ID: <1191852713.859771.109190@19g2000hsx.googlegroups.com> On 8 Okt, 15:56, Richie Hindle wrote: > [Bruce] > > > f.close() > > cmd = "echo %s | %s"%(argument_file,the_program) > > Either: you are a VB programmer and you've actually typed "f.close" rather > than "f.close()", > > Or: you meant "type" (or "cat") rather than "echo", > > Or: I need a new crystal ball. 8-) > > -- > Richie Hindle > ric... at entrian.com You are right, I forgot the () in f.close() ! thanks for pointing that out. VB programmer!? Thats really harsh.. From DustanGroups at gmail.com Tue Oct 30 07:11:39 2007 From: DustanGroups at gmail.com (Dustan) Date: Tue, 30 Oct 2007 11:11:39 -0000 Subject: A Python 3000 Question In-Reply-To: <472681dd$0$4375$9b4e6d93@newsspool4.arcor-online.net> References: <87abq1mxqc.fsf@merkury.smsnet.pl> <5on4b6Fnq6p5U2@mid.individual.net> <472681dd$0$4375$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <1193742699.561161.98780@19g2000hsx.googlegroups.com> On Oct 29, 7:59 pm, Wildemar Wildenburger wrote: > Bjoern Schliessmann wrote: > > The inconsistencies arise, IMHO, if an OO language introduces > > non-object types for performance reasons, after that gets wrapper > > classes to wrap those primitives, and even later gets the ability > > to automatically cast a primitive into a wrapper class instance. > > That's just ugly. > > If you mean Java, then just say Java. There was no need to; it was heavily implied. From nebulous99 at gmail.com Tue Oct 9 21:05:11 2007 From: nebulous99 at gmail.com (nebulous99 at gmail.com) Date: Wed, 10 Oct 2007 01:05:11 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> <13frd6vtarbee75@corp.supernews.com> <13gj0neh59oks91@corp.supernews.com> <1191819894.369786.130300@v3g2000hsg.googlegroups.com> Message-ID: <1191978311.987341.271000@r29g2000hsg.googlegroups.com> On Oct 8, 7:32 am, Joost Kremers wrote: > bbo... at gmail.com wrote: > > Don't both "man" and those words for measurement come ultimately from > > words for "hand" (similarly to words like "manual", as in labor)? > > no. Do not bluntly contradict me in public. > "manual" is derived from latin "manus" meaning "hand". the word "man" > is related to (though not directly derived from) "mind", and the latin word > "mens", which means "mind". So you assert, but "man" bears a much closer resemblance to "manus" than it does to "mens". Or are you proposing that the plural word "men" came first? That would be ... odd. From erik at myemma.com Fri Oct 12 14:31:43 2007 From: erik at myemma.com (Erik Jones) Date: Fri, 12 Oct 2007 13:31:43 -0500 Subject: PEP idea: Instrumented Python In-Reply-To: <20071012171013.8162.1037189775.divmod.quotient.22147@ohm> References: <20071012171013.8162.1037189775.divmod.quotient.22147@ohm> Message-ID: On Oct 12, 2007, at 12:10 PM, Jean-Paul Calderone wrote: > On Fri, 12 Oct 2007 11:33:11 -0500, Erik Jones > wrote: >> [snip] >> >> This got me thinking about building a module that could be included >> by projects that creates a socket and responds to messages on that >> socket in a separate thread from the main app so that you can connect >> to the app and explore its current state. Take a look at the >> evalexception module in Paste to see what he does. >> > > Or manhole in Twisted. Thanks for the tip! Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From exarkun at divmod.com Thu Oct 25 06:50:47 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 25 Oct 2007 06:50:47 -0400 Subject: Adding idle timeout capabilities to asyncore In-Reply-To: <1193287572.069324.91860@q3g2000prf.googlegroups.com> Message-ID: <20071025105047.8162.148263643.divmod.quotient.27568@ohm> On Thu, 25 Oct 2007 04:46:12 -0000, Josiah Carlson wrote: > [snip] >But really, since I already wrote code that handles *all* of >the timeout handling with a *single* time.time() call, and that also >generally minimizes all explicit function calls, I'm not sure that >your testing examples were ultimately germane to the conversation (how >would one handle timeouts in asyncore). Or maybe it's just late and >I've had a long day :/ . That's okay. I wasn't trying to be germane to the asyncore timeout handling conversation. Jean-Paul From smithsm at samuelsmith.org Mon Oct 29 17:48:32 2007 From: smithsm at samuelsmith.org (Samuel M. Smith) Date: Mon, 29 Oct 2007 15:48:32 -0600 Subject: Help ctypes on arm linux not compile Message-ID: I have built python 1.5.1 from source for an embedded ARM9 debian linux Sarge distribution but ctypes doesn't build. Anybody have any idea what the problem is? Do I have to have the libffi package installed. See my errors below. I looked and ffi.h exists in three places /usr/local/src/Python-2.5.1/Modules/_ctypes/libffi_arm_wince/ffi.h /usr/local/src/Python-2.5.1/Modules/_ctypes/libffi_msvc/ffi.h /usr/local/src/Python-2.5.1/build/temp.linux-armv4l-2.5/libffi/ include/ffi.h with two different definitions for ffi_closure typedef struct { char tramp[FFI_TRAMPOLINE_SIZE]; ffi_cif *cif; void (*fun)(ffi_cif*,void*,void**,void*); void *user_data; } ffi_closure __attribute__((aligned (8))); typedef struct { char tramp[FFI_TRAMPOLINE_SIZE]; ffi_cif *cif; void (*fun)(ffi_cif*,void*,void**,void*); void *user_data; } ffi_closure; is the __attribute__ syntax causing a problem building '_ctypes' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -fPIC -I. -I/usr/local/src/Python-2.5.1/./Include -Ibuild/ temp.linux-armv4l-2.5/libffi/include -Ibuild/temp.linux-armv4l-2.5/ libffi -I/usr/local/src/Python-2.5.1/Modules/_ctypes/libffi/src -I./ Include -I. -I/usr/local/include -I/usr/local/src/Python-2.5.1/ Include -I/usr/local/src/Python-2.5.1 -c /usr/local/src/Python-2.5.1/ Modules/_ctypes/_ctypes.c -o build/temp.linux-armv4l-2.5/usr/local/ src/Python-2.5.1/Modules/_ctypes/_ctypes.o In file included from /usr/local/src/Python-2.5.1/Modules/_ctypes/ _ctypes.c:126: /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:71: error: syntax error before "ffi_closure" /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:71: warning: no semicolon at end of struct or union /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:78: error: syntax error before '}' token /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:78: warning: type defaults to `int' in declaration of `ffi_info' /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:78: warning: data definition has no type or storage class /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:94: error: syntax error before "ffi_info" /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:94: warning: no semicolon at end of struct or union /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:101: error: conflicting types for `restype' /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:76: error: previous declaration of `restype' /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:109: error: syntax error before '}' token /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:109: warning: type defaults to `int' in declaration of `CFuncPtrObject' /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:109: warning: data definition has no type or storage class /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:165: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:168: warning: type defaults to `int' in declaration of `AllocFunctionCallback' /usr/local/src/Python-2.5.1/Modules/_ctypes/ctypes.h:168: warning: data definition has no type or storage class /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `c_void_p_from_param': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:1330: error: `func' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:1330: error: (Each undeclared identifier is reported only once /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:1330: error: for each function it appears in.) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:1331: error: syntax error before ')' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2470: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2471: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_set_errcheck': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2472: error: `ob' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2477: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2484: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2485: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_get_errcheck': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2486: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2495: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2496: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_set_restype': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2497: error: `ob' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2498: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2520: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2521: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_get_restype': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2523: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2539: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2540: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_set_argtypes': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2543: error: `ob' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2544: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2562: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2563: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_get_argtypes': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2565: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_FromDll': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2747: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2802: error: syntax error before ')' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_new': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2867: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2870: error: `thunk' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:2939: error: syntax error before ')' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3040: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3043: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `_build_callargs': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3044: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3054: error: `poutmask' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3055: error: `pinoutmask' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3056: error: `pnumretvals' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3064: error: `inargs' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3113: error: `kwds' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3268: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3269: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_call': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3274: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3329: error: `inargs' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3329: error: `kwds' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3398: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3399: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_traverse': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3400: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3400: warning: implicit declaration of function `visit' /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3400: error: `arg' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3407: error: `visit' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3411: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3412: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_clear': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3413: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3431: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3432: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_dealloc': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3433: error: `self' undeclared (first use in this function) /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: At top level: /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3438: error: syntax error before '*' token /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3439: warning: function declaration isn't a prototype /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_repr': /usr/local/src/Python-2.5.1/Modules/_ctypes/_ctypes.c:3448: error: `self' undeclared (first use in this function) ********************************************************************** Samuel M. Smith Ph.D. 2966 Fort Hill Road Eagle Mountain, Utah 84005-4108 801-768-2768 voice 801-768-2769 fax ********************************************************************** "The greatest source of failure and unhappiness in the world is giving up what we want most for what we want at the moment" ********************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From jhmsmits at gmail.com Tue Oct 2 09:26:07 2007 From: jhmsmits at gmail.com (SanPy) Date: Tue, 02 Oct 2007 06:26:07 -0700 Subject: access __doc__ from within function without reference to function name Message-ID: <1191331567.944636.263140@y42g2000hsy.googlegroups.com> The subject of this message might be a little cryptic, so here's an example of what I mean: def foo(): """doc string of foo""" print foo.__doc__ >>> foo() doc string of foo What I want to know is whether it is possible to call __doc__ against some builtin method, like __func__ or something like that. So calling __doc__ without the functions name, something like this: def foo(): """doc string of foo""" print __func__.__doc__ # pseudo code So basically, my question is: is there a way to access a function from within itself without using its name? Regards, Sander. From deets at nospam.web.de Mon Oct 29 07:44:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 29 Oct 2007 12:44:24 +0100 Subject: SQLite3; weird error References: <1193657924.375787.287740@o80g2000hse.googlegroups.com> Message-ID: <5olvcoFndjdvU1@mid.uni-berlin.de> TYR wrote: > Has anyone else experienced a weird SQLite3 problem? > > Going by the documentation at docs.python.org, the syntax is as > follows: > foo = sqlite3.connect(dbname) creates a connection object representing > the state of dbname and assigns it to variable foo. If dbname doesn't > exist, a file of that name is created. > > To do anything with it, you then need to create a cursor object by > calling foo's method cursor (bar = foo.cursor). is that really from the docs? If yes, they are buggy. The problem is pretty obvious: foo.cursor is NOT calling a method cursor on foo. It's a reference to that very method. So instead write bar = foo.cursor() and your done. > You can now pass an SQL query or command to the DB by calling the > cursor object's method execute() with the SQL query as a quoted > statement. > > (bar.execute("SELECT FROM squid WHERE squamous=True") > > And then do other stuff. > > Fine. When I call the cursor object, though, I get an AttributeError; > ('builtinfunction_or_method object has no attribute 'execute') Which is a pretty acute description of the error: you are trying to get an attribute (execute, which you ultimately expect to be a method) from a method. Diez From bignose+hates-spam at benfinney.id.au Tue Oct 16 21:36:48 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 Oct 2007 11:36:48 +1000 Subject: why doesn't have this list a "reply-to" ? References: Message-ID: <87odey1pzj.fsf@benfinney.id.au> Dick Crepeau writes: > It seems to me the original question was how can I reply to a posted > message. By choosing whether you want to "reply to the author", or "reply to the list". (Every message from the mailing list automatically provides the correct infromation to make both options work correctly.) Then invoking the appropriate function in your mail user program. If your mail program has only "reply", then that's likely "reply to the author". You need to find out how your mail program implements "reply to the list", or pressure your provider if it's not implemented at all. -- \ "One of the most important things you learn from the internet | `\ is that there is no 'them' out there. It's just an awful lot of | _o__) 'us'." ?Douglas Adams | Ben Finney From narutocanada at gmail.com Fri Oct 19 22:00:11 2007 From: narutocanada at gmail.com (narutocanada at gmail.com) Date: Fri, 19 Oct 2007 19:00:11 -0700 Subject: where do I need to "tab"? Message-ID: <1192845611.102983.310980@i38g2000prf.googlegroups.com> hi I'm following the python's translation of SICP: http://codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages:Python:Chapter_1 ... a = 3 b = a + 1 print a + b + (a * b) print (a == b) print b if ((b > a) and (b < (a * b))) else a everything was fine till this point, and I got: print b if ((b > a) and (b < (a * b))) else a ^ SyntaxError: invalid syntax Is there a good rule that I quickly memorize as to "when to tab"? Thanks. From duncan.booth at invalid.invalid Mon Oct 1 04:05:47 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Oct 2007 08:05:47 GMT Subject: Function return a dictionary References: Message-ID: Boris Mok wrote: > Hi all, > > I'm doing a function which needs return an arrary -- or more specially a > dictionary data type. > I have a sample like this > > def AFC(): > v["a"] = 1 > return v > > v = AFC() > print v["a"] > > with error > NameError: global name 'v' is not defined > > how do I go about it? > At some point you have to initialise v to a dictionary, Python isn't going to guess for you. e.g. def AFC(): v = {} v["a"] = 1 return v From nick.bastin at gmail.com Fri Oct 5 00:12:42 2007 From: nick.bastin at gmail.com (Nicholas Bastin) Date: Fri, 5 Oct 2007 00:12:42 -0400 Subject: Python 3.0 migration plans? In-Reply-To: References: Message-ID: <66d0a6e10710042112q22889b0fw9dcb75ddc4586e1f@mail.gmail.com> On 9/27/07, Steve Holden wrote: > I wondered if a straw poll could get some idea of readers' thoughts > about when they will be migrating to 3.0 on, so I used the new widget on > Blogger to add a poll for that. > > I'd appreciate if if you would go to > > http://holdenweb.blogspot.com/ > > and register your vote on your intended migration timescale. The options should have all been relative to the release date. Options one and two might very well be the same (yes, I know, but shit happens). Also, you're relying on people knowing the current timeframe for 3.0. -- Nick From thermostat at gmail.com Wed Oct 10 15:34:58 2007 From: thermostat at gmail.com (Dan) Date: Wed, 10 Oct 2007 19:34:58 -0000 Subject: How can Python print the value of an attribute but complain it does not exist? In-Reply-To: <1192043025.291748.198740@19g2000hsx.googlegroups.com> References: <1192043025.291748.198740@19g2000hsx.googlegroups.com> Message-ID: <1192044898.197028.262740@v3g2000hsg.googlegroups.com> On Oct 10, 3:03 pm, Emre Sevinc wrote: > Hello, > > I'm a Python newbie and I'm having a strange trouble with the > following code: > > generatefeedvector-debug.py > =============================================================== > import feedparser > import re > > def getwordcounts(url): > # Parse the feed > d = feedparser.parse(url) > wc = {} > > # Loop over all the entries > for e in d.entries: > if 'summary' in e: summary = e.summary > else: summary = e.description > > # Extract a list of words > words = getwords(e.title + ' ' + summary) > for word in words: > wc.setdefault(word, 0) > wc[word] += 1 > > print d.feed.title > return d.feed.title > > def getwords(html): > # Remove all the HTML tags > txt = re.compile(r'<[^>]+>').sub('', html) > > # Split words by all non-alpha characters > words = re.compile(r'[^A-Z^a-z]+').split(txt) > > # Convert to lowercase > return [word.lower() for word in words if word != ''] > > apcount = {} > wordcounts = {} > for feedurl in file('feedlist1-2.txt'): > title = getwordcounts(feedurl) > ================================================================== > > When I run it: > > $ python generatefeedvector-debug.py > Signal vs. Noise > Traceback (most recent call last): > File "generatefeedvector-debug.py", line 37, in ? > title = getwordcounts(feedurl) > File "generatefeedvector-debug.py", line 21, in getwordcounts > print d.feed.title > File "/var/lib/python-support/python2.4/feedparser.py", line 236, in > __getattr__ > raise AttributeError, "object has no attribute '%s'" % key > AttributeError: object has no attribute 'title' > > The strange thing is that it DOES print the value d.feed.title then > complains AttributeError: object has no attribute 'title'. What am I > doing wrong? > > The file feedlist1-2.txt includes just a single line: > > $ cat feedlist1-2.txthttp://feeds.feedburner.com/37signals/beMH > > I'm using Python 2.4 on Debian GNU/Linux. > > Any ideas about how to fix this error message? > > Regards, > > -- > Emre Sevinc This is a bit of a guess, but prehaps the file has a blank line, so the first url is fine, but the second (non-existant) url doesn't have a title. You can test this by doing: > for feedurl in file('feedlist1-2.txt'): > if feedurl.strip(): > title = getwordcounts(feedurl) -Dan From abarun22 at gmail.com Mon Oct 29 16:03:03 2007 From: abarun22 at gmail.com (abarun22 at gmail.com) Date: 29 Oct 2007 13:03:03 -0700 Subject: swig-python -> shared (vs) static libraries Message-ID: <1193672993.062544.68770@i38g2000prf.googlegroups.com> HI I am new to SWIG & Python and right now i am in the process of wrapping some "C" functionalities present in a static library for python. I do have my C file "name.c" which just contains some helper functions. I tried to link my object files (e.g name.o & name_wrap.o) with the static libraries (whose functionalities need to be wrapped) to form a shared library that can be imported from Python. While doing so i cannot be able to access the C data structure from Python and i got all values as zero. I work in Linux gcc version. I created my shared object like this: ld -G name.o name_wrap.o -o _name.so -Bstatic -lfoo1 -lfoo2 -lfoo3. On the other hand to dig more in to this i tried to simulate the static libraries with simple dummy code in my file "name.c" so that i can avoid linking the static libraries. This case i could be able to retrieve the vaues of the data structure. I wonder if the problem could be due to linking of the static libraries to create the shared object. Any body experienced the same problem or having related ideas pls help me. Best regards Arun From steve at REMOVE-THIS-cybersource.com.au Mon Oct 8 08:50:53 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 08 Oct 2007 12:50:53 -0000 Subject: Really basic problem References: Message-ID: <13gk9tdonh6gn90@corp.supernews.com> On Mon, 08 Oct 2007 12:09:28 +0200, Andreas Tawn wrote: > The issue is that 0.1 etc don't have an exact representation as floating > point. > > Interestingly: > >>>> 0.10000000000000001 == 0.1 > True >>>> 0.30000000000000004 == 0.3 > False > > I guess this means that Python has some concept of "close enough", but > I'll have to defer to someone more knowledgeable to explain that. No, not really, except in the sense that any floating point calculation will be necessarily imprecise in that sense. The first example: when you type 0.1 as a float, it can't be stored as exactly 1/10 in binary, so you actually get a tiny bit more than 1/10: >>> 0.1 0.10000000000000001 That means that whether you type 0.1 or 0.10000000000000001 makes no difference. Hence the following result: >>> 0.10000000000000001 == 0.1 True It isn't that Python looks at 0.10000000000000001 and 0.1 and says "well, the difference is only 0.00000000000000001 which is too tiny to worry about, so they're equal". Proof by example: >>> 0.10000000000000001 == 0.10000000000000002 False The second example: when you type 0.3, it too can't be represented precisely in binary as 3/10, and so you get this: >>> 0.3 0.29999999999999999 >>> 0.30000000000000001 0.29999999999999999 So typing 0.3 is the same as typing 0.29999999999999999 or 0.30000000000000001 as far as floating point binary values are concerned. (Although note that these results are platform dependent. Your mileage may vary.) -- Steven From bj_666 at gmx.net Sat Oct 27 15:59:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Oct 2007 19:59:07 GMT Subject: xmpfilter-a-like for python (code annotation) References: <1193505013.821461.149470@d55g2000hsg.googlegroups.com> <5ohaonFmgu6mU3@mid.uni-berlin.de> <1193507826.361771.151800@50g2000hsm.googlegroups.com> Message-ID: <5ohjkbFmgu6mU6@mid.uni-berlin.de> On Sat, 27 Oct 2007 17:57:06 +0000, thattommyhallll at gmail.com wrote: > On Oct 27, 6:27 pm, Marc 'BlackJack' Rintsch wrote: >> On Sat, 27 Oct 2007 17:10:13 +0000, thattommyhal... at gmail.com wrote: >> >http://eigenclass.org/hiki/xmpfilter >> > looks cool , anything like this for python? any reason that we culd >> > not do simmilar ? >> >> I just read that page and am a little confused. This program adds >> assertions based on the actual code, i.e. if the code is wrong it >> nonetheless adds assertions that don't fail. I always thought one writes >> assertions to test what the code should do and not what it actually does!? > > Its more the inline annotation lie here http://eigenclass.org/hiki.rb?xmpfilter#l4 > that I wanted Can you give *useful* examples? Ciao, Marc 'BlackJack' Rintsch From mensanator at aol.com Mon Oct 8 13:41:03 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 08 Oct 2007 10:41:03 -0700 Subject: pytz has so many timezones! In-Reply-To: <1191828739.635927.86590@57g2000hsv.googlegroups.com> References: <1191828739.635927.86590@57g2000hsv.googlegroups.com> Message-ID: <1191865263.572366.270820@y42g2000hsy.googlegroups.com> On Oct 8, 2:32 am, Sanjay wrote: > Hi All, > > I am using pytz.common_timezones to populate the timezone combo box of > some user registration form. But as it has so many timezones (around > 400), There are only 25 timezones: -12, -11, ... -1, 0 (GMT), +1, ... +11, +12. A handful of countries set their clocks offset by a half hour, but those aren't timezones. And there is one country whose clock setting is the product of a diseased mind (GMT+13), but that isn't a timezone either. The 400 you're seeing are duplications based on locality. Of the 86 shown in Windows, all but 33 are dulplicate references to the same timezones. For example, Windows has seperate listings for Central America Central Time (US & Canada) Guadalahara, Mexico City, Monterry - New Guadalahara, Mexico City, Monterry - Old Saskatchewan but they are all GMT-6 > it is a bit confusing to the users. Is there a smaller and more > practical set? Filter the list by location. > If not, some suggestions on how to handle the > registration form effectively would help me a lot. > > thanks > Sanjay From rcdailey at gmail.com Thu Oct 4 12:54:32 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 4 Oct 2007 11:54:32 -0500 Subject: RegEx question In-Reply-To: <1191515675.19400.39.camel@skinner.madoff.com> References: <496954360710040855t7fd68a32o75aed48a9fd91bf2@mail.gmail.com> <496954360710040858w6226424fi299f8a57ed29e72@mail.gmail.com> <1191515675.19400.39.camel@skinner.madoff.com> Message-ID: <496954360710040954j1f48a38du91895d55f1391f93@mail.gmail.com> On 10/4/07, Adam Lanier wrote: > > > try @param\[(in|out)\] \w+ > This didn't work either :( The tool using this regular expression (Comment Reflower for VS2005) May be broken... -------------- next part -------------- An HTML attachment was scrubbed... URL: From wizzardx at gmail.com Thu Oct 4 08:47:12 2007 From: wizzardx at gmail.com (David) Date: Thu, 4 Oct 2007 14:47:12 +0200 Subject: HELP me Am very new one To python In-Reply-To: <1191500432.872059.190840@d55g2000hsg.googlegroups.com> References: <1191500432.872059.190840@d55g2000hsg.googlegroups.com> Message-ID: <18c1e6480710040547j57fb4e99m5859abaa59b5cb4d@mail.gmail.com> > > how to configure apache where i want to configure . > if any files want to copy in to apache folder, wahts the procedure to > start the coding pls help me am very very beginner pls spend some time > to teach how to do that.please plaes > Unlike PHP, Python is not primarily a web programming language. What you installed was the standard interpreter which allows you to run scripts outside of a web server. It won't integrate into apache automatically. What you're probably looking for is an apache module that lets you run python scripts. This link may be useful: http://sourceforge.net/projects/spyce/ From bbxx789_05ss at yahoo.com Sat Oct 6 00:52:46 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 05 Oct 2007 21:52:46 -0700 Subject: Test doubles (stubs and mocks) for unit testing (was: unit testing) In-Reply-To: <877im1qio2.fsf_-_@benfinney.id.au> References: <1191604175.903042.228140@g4g2000hsf.googlegroups.com> <877im1qio2.fsf_-_@benfinney.id.au> Message-ID: <1191646366.288345.237800@o3g2000hsb.googlegroups.com> On Oct 5, 4:51 pm, Ben Finney wrote: > Thanks. From software at ginstrom.com Mon Oct 22 18:06:00 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Tue, 23 Oct 2007 07:06:00 +0900 Subject: ignoring chinese characters parsing xml file In-Reply-To: <851acc320710221224w55c9421cpf1973d0658ad84b4@mail.gmail.com> References: <851acc320710221224w55c9421cpf1973d0658ad84b4@mail.gmail.com> Message-ID: <098901c814f7$bc907300$0203a8c0@MOUSE> > On Behalf Of Fabian Lopez > like ^?u?u?????????w.?????L???????? or ????????????... The problem is that I get Just thought I'd point out here that the second string is Japanese, not Chinese. >From your second post, it appears that you've parsed the text without problems -- it's when you go to print them out that you get the error. This is no doubt because your default encoding can't handle Chinese/Japanese characters. I can imagine several ways to fix this, including encoding the text in utf-8 for printout. If you really want to strip out Asian characters, here's a way: def strip_asian(text): """"Returns the Unicode string text, minus any Asian characters""" return u''.join([x for x in text if ord(x) < 0x3000]) Regards, Ryan Ginstrom From gagsl-py2 at yahoo.com.ar Fri Oct 19 19:14:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Oct 2007 20:14:22 -0300 Subject: traceback over C API and PyObject_CallObject References: Message-ID: En Fri, 19 Oct 2007 13:53:03 -0300, Sami Vaisanen escribi?: > Hello group, > > I'm trying to get the Python exception information (message and > traceback) > stored into a string in my C++ code. However all i get back is the string > "None". This is what you get (actually "None\n") when there is no error set. > All the checks pass and all pointers get a value from the python > API calls. I've also tried with a different function such as > PyObject_CallFunctionObjArgs but the result is the same. Since you already know the three components (type, value, trace), I'd use traceback.format_exception instead (and remove the PyErr_Restore call - I'm unsure if it works the way you expect it). In this case you have to pass three arguments, so yes, use PyObject_CallFunctionObjArgs (remember the final NULL). Beware: format_exception returns a formatted list, not a string. You have to concatenate all the elements (either using ''.join or repeteadly calling PyString_Concat) > void get_python_exception(string& message, string& traceback) > { > GIL g; > PyObject* type = NULL; > PyObject* value = NULL; > PyObject* trace = NULL; > PyErr_Fetch(&type, &value, &trace); > py_ref ref_type(type); > py_ref ref_value(value); > py_ref ref_trace(trace); > py_ref name(PyString_FromString("traceback")); > py_ref module(PyImport_Import(name.get())); > if (module) > { > py_ref fun(PyObject_GetAttrString(module.get(), "format_exc")); > if (fun) > { > PyErr_Restore(type, value, trace); > ref_type.release(); > ref_value.release(); > ref_trace.release(); > py_ref ret(PyObject_CallObject(fun.get(), NULL)); > if (ret && PyString_Check(ret.get())) > { > char* str = PyString_AsString(ret.get()); > message = str; > traceback = "traceback not available"; > return; > } > } > } > message = "message not available"; > traceback = "traceback not available"; > } -- Gabriel Genellina From MDiPierro at cti.depaul.edu Tue Oct 16 14:17:36 2007 From: MDiPierro at cti.depaul.edu (DiPierro, Massimo) Date: Tue, 16 Oct 2007 13:17:36 -0500 Subject: re.sub In-Reply-To: <4715010B.7080203@tim.thechases.com> References: <1192503754.490662.155610@v29g2000prd.googlegroups.com> <1192516496.148265.103880@e9g2000prf.googlegroups.com> <11B0C495-19B5-4FFD-80EC-028078CB19CB@cti.depaul.edu> <34012412-98C7-47E1-98FF-061543A3A427@cti.depaul.edu>, <4715010B.7080203@tim.thechases.com> Message-ID: It is the fisrt line that is wrong, the second follows from the first, I agree. ________________________________________ From: Tim Chase [python.list at tim.thechases.com] Sent: Tuesday, October 16, 2007 1:20 PM To: DiPierro, Massimo Cc: python-list at python.org; Berthiaume, Andre Subject: Re: re.sub > Even stranger > > >>> re.sub('a', '\\n','bab') > 'b\nb' > >>> print re.sub('a', '\\n','bab') > b > b That's to be expected. When not using a print statement, the raw evaluation prints the representation of the object. In this case, the representation is 'b\nb'. When you use the print statement, it actually prints the characters rather than their representations. No need to mess with re.sub() to get the behavior: >>> s = 'a\nb' >>> s 'a\nb' >>> print s a b >>> print repr(s) 'a\nb' -tkc From rdm at rcblue.com Tue Oct 30 00:46:19 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 29 Oct 2007 21:46:19 -0700 Subject: Using msvcrt (in Windows), how to catch Enter key? In-Reply-To: References: <1193657385.878620.35180@d55g2000hsg.googlegroups.com> <1193675164.790618.194190@57g2000hsv.googlegroups.com> <20071029165317.7009D1E4012@bag.python.org> <20071029174011.D22641E4029@bag.python.org> <20071030002246.B9ED91E401F@bag.python.org> Message-ID: <20071030044632.B85231E4007@bag.python.org> At 06:34 PM 10/29/2007, Gabriel Genellina wrote: >En Mon, 29 Oct 2007 21:22:36 -0300, Dick Moores escribi?: > > > At 03:23 PM 10/29/2007, Gabriel Genellina wrote: > >> En Mon, 29 Oct 2007 14:39:49 -0300, Dick Moores > >> escribi?: > >> > >> > >> At least add a small sleep() call inside the loop, to be nice to other > >> running processes: > >> > > > > Yes, that makes a major difference in the CPU > > usage percentage on my computer. In fact I can't > > even tell that there is anything going on other > > than the usual behind-the-scenes XP stuff. CPU > > usage stays right around 0% or 6%, with an > > occasional 6% and a very occasional 15%. > > Interestingly, sleep(0.001) makes as big a > > difference as your sleep(0.1), but sleep(0.0001) bumps it up to a steady > > 100%! > >The underlying function in Windows is Sleep (or SleepEx) which takes an >argument in milliseconds. 0.0001s = 0.1ms and it's rounded to 0. Sleep(0) >has very specific semantics - for a single threaded program, it does >nothing, so your code is effectively a busy loop taking 100% CPU. Ah, useful information. Thank you. Where'd you learn that? Dick Moores From vasudevram at gmail.com Mon Oct 15 11:54:36 2007 From: vasudevram at gmail.com (vasudevram) Date: Mon, 15 Oct 2007 15:54:36 -0000 Subject: View XMLRPC Requests/Responses? In-Reply-To: <1192463390.951199.87670@z24g2000prh.googlegroups.com> References: <1192460878.597651.64680@k35g2000prh.googlegroups.com> <5nhe7fFi4prbU1@mid.uni-berlin.de> <1192463390.951199.87670@z24g2000prh.googlegroups.com> Message-ID: <1192463676.093742.115050@v29g2000prd.googlegroups.com> On Oct 15, 8:49 pm, vasudevram wrote: > On Oct 15, 8:10 pm, "Diez B. Roggisch" wrote: > > > xkenneth wrote: > > > Hi, > > > > I'm working on developing an XML-RPC interface from LabVIEW to > > > python and I would really like to see how python is forming it's XML- > > > RPC requests/responses. Is there any way I can force these to a log or > > > print them to the screen? Thanks. > > > I've utilized the apache axis tcpmon for that, as proxy. See > > >http://docs.pushtotest.com/axisdocs/user-guide.html#tcpmon > > > Diez > > I haven't used apache axis tcpmon - so don't know how easy or > difficult it is to use that approach - but if its non-trivial or > awkward, there's another easy way - since the xmlrpc lib source is > available - and it is, its part of the Python Standard library - just > root around in the source and modify it to log to a file or to the > screen. Will be pretty straightforward to do it. Its a hack, though, I > know - because your changes would need to be carried around everywhere > you want to use them (but then so does your code), and also because > they would get clobbered when you upgraded to the next Python > release. > > So a better way might be to inherit from an appropriate class of > xmlrpclib client or server, use that class in your code instead, and > modify the inherited class to log as needed, by getting hold of some > output stream of the parent class - if it is exposed. > > Vasudev Ram I sort of had a need for this myself recently when writing some Python XML-RPC code, but didn't do it because I could manage to debug my code without it - but I remember noticing that my XML-RPC server was logging the requests to stdout, by default (without any code by me to do it). So I think the approach I mention above should work - just look around in the server source code for where it does that, and modify it as per need. - Vasudev From mensanator at aol.com Thu Oct 25 14:44:53 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 25 Oct 2007 11:44:53 -0700 Subject: An efficient, pythonic way to calculate result sets In-Reply-To: <1193326263.917893.266620@e9g2000prf.googlegroups.com> References: <1193326263.917893.266620@e9g2000prf.googlegroups.com> Message-ID: <1193337893.635877.208050@v3g2000hsg.googlegroups.com> On Oct 25, 10:31 am, happyhon... at gmail.com wrote: > Hello everyone, > > I've got a little issue, both programming and performance-wise. I have > a set, containing objects that refer to other sets. For example, in a > simple notation: (, ) (or in a more object-like > display: set(obj1.choices=set(a, b, c) ). There may be obj1..objN > objects in the outer set, and the amount of items in the choices sets > could also reach a high number. The objects in the choices sets might > overlap. > > Now I want to have all possible combinations, like this: (a, d), (b, > d), (c, d), (a, e), (b, e), (c, e). > > However, I've got a few catches that make an already (icky) recursive > function worse to use. > > First of all, I want to be able to only choose things so that the > outer 'result sets' have the same length. For example, if you'd have > (, ), you might pick (a, a) with a simple algorythm, the > basic behaviour of sets reducing it to (a) and thus having an improper > length. I could add yet another loop after calculating everything to > throw out any result sets with the improper length, but that would be > highly inefficient. Does this do what you want? result_set = set([]) seta = set(['a','b','c','d','e']) setb = set(['a','c','f','g','h']) for i in seta: temp1 = setb.difference(set([i])) for j in temp1: result_set.add(tuple(set([i,j]))) for i in result_set: print i I figure there should be 4+5+3+5+5 results. No ('a'), no ('c'). Has ('a','c') but not ('c','a'). ## ('c', 'g') ## ('a', 'd') ## ('h', 'e') ## ('a', 'b') ## ('c', 'f') ## ('e', 'g') ## ('c', 'b') ## ('d', 'f') ## ('a', 'g') ## ('a', 'h') ## ('c', 'e') ## ('e', 'f') ## ('d', 'g') ## ('h', 'b') ## ('a', 'f') ## ('b', 'f') ## ('c', 'd') ## ('h', 'c') ## ('a', 'c') ## ('b', 'g') ## ('a', 'e') ## ('h', 'd') > > Second, I'd hope to be able to say that objX should be assumed to have > made the choice z. In the first example I mentioned, if I said that > 'obj1 == a', the only result sets that would come out would be (a, d) > and (a, e). Like this? result_set = set([]) seta = set(['a','b','c','d','e']) setb = set(['a','c','f','g','h']) target = 'a' for i in seta: temp1 = setb.difference(set([i])) for j in temp1: temp2 = set([i,j]) if target in temp2: result_set.add(tuple(temp2)) for i in result_set: print i ## ('a', 'f') ## ('a', 'g') ## ('a', 'd') ## ('a', 'e') ## ('a', 'h') ## ('a', 'b') ## ('a', 'c') > > I've been toying with this problem for a while, but I've found out it > quickly gets slow, so I hope some people here could find a way to > write code like this that is efficient (and hopefully not rely on > recursion and 'fix up' loops like I've got mockups with right now). > > Thank you for any suggestions you can offer. From duncan.booth at invalid.invalid Mon Oct 29 10:10:32 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Oct 2007 14:10:32 GMT Subject: Built-in functions and keyword arguments References: <1193665924.886459.20710@v3g2000hsg.googlegroups.com> Message-ID: Armando Serrano Lombillo wrote: > Why does Python give an error when I try to do this: > >>>> len(object=[1,2]) > Traceback (most recent call last): > File "", line 1, in > len(object=[1,2]) > TypeError: len() takes no keyword arguments > > but not when I use a "normal" function: > >>>> def my_len(object): > return len(object) > >>>> my_len(object=[1,2]) > 2 > At the C level there are several options for how you define a function callable from Python. The most general form is METH_VARARGS|METH_KEYWORDS which accepts both a tuple of arguments and a dictionary of keyword arguments. These then have to be parsed to find the actual arguments. Many of the builtin functions use only METH_VARARGS which means they don't support keyword arguments. "len" is even simpler and uses an option METH_O which means it gets a single object as an argument. This keeps the code very simple and may also make a slight difference to performance. I don't know if the reason that most builtin functions don't accept keywords is just historical (someone would have to go through a lot of code and add keyword argument names) or if there really is any measurable performance difference to not using the METH_KEYWORDS option. Being able to write less C code may be the main factor. From fredrik at pythonware.com Sat Oct 6 09:57:36 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 06 Oct 2007 15:57:36 +0200 Subject: slice with negative stride In-Reply-To: <1191672336.230508.50600@o3g2000hsb.googlegroups.com> References: <1191672336.230508.50600@o3g2000hsb.googlegroups.com> Message-ID: ajcppmod at gmail.com wrote: >>> mystr = 'my string' > > I would have then thought of the contents of mystr as: > > indices 0 1 2 3 4 5 6 7 8 > content m y s t r i n g > > with mystr[:3] = 'my ' > > Can someone explain to me how mystr[:3:-1] = 'gnirt'? A slice [i:j:k] includes the first index (i) but *not* the last index (j). Since you're stepping backwards, the slice will start at the end of the string (i=len(mystr)-1=8) and stop when it reaches j=3. >>> mystr[8] 'g' >>> mystr[7] 'n' >>> mystr[6] 'i' >>> mystr[5] 'r' >>> mystr[4] 't' From mail at timgolden.me.uk Tue Oct 2 03:20:47 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 02 Oct 2007 08:20:47 +0100 Subject: LastWriteTime in windows registry In-Reply-To: References: Message-ID: <4701F14F.6020501@timgolden.me.uk> Peters, Matthew J. ET3 wrote: > I'm looking for a way to read the lastwritetime property of > a windows registry key. ... I found the function in perl So what does the Perl source say? It presumably hooks some kind of Windows API. Take that and, if it isn't already exposed via pywin32, use ctypes to get hold of it. TJG From nick.bastin at gmail.com Tue Oct 9 22:32:59 2007 From: nick.bastin at gmail.com (Nicholas Bastin) Date: Tue, 9 Oct 2007 22:32:59 -0400 Subject: Mixing Python and C classes in a module In-Reply-To: <4866bea60710090802s1ac3fde4vb3a4d17693448383@mail.gmail.com> References: <87wstwibfl.fsf@keizer.soze.com> <4866bea60710090802s1ac3fde4vb3a4d17693448383@mail.gmail.com> Message-ID: <66d0a6e10710091932i1b141c99s46f8f813887959ea@mail.gmail.com> On 10/9/07, Chris Mellon wrote: > On 09 Oct 2007 16:56:30 +0200, Stefan Arentz wrote: > > > > Is it possible to mix classes defined in both Python and C in the same > > module? Ideally I would like to be able to do: > > > > from some.module import MyPythonClass, MyCClass > > > > I guess that would mean that this would look like this on disk: > > > > some/ > > __init__.py > > module.py (contains MyPythonClass) > > module.so (contains MyCClass) > > > > But would this work? > > > > No, you'll need to make module a package, and import from (differently > named) implementation packages. Nah, you can do it, just not in this way. You can either futz with ihooks, or name module.py something like _module.py, import it into C, and then re-export as 'module', after attaching all your C types. -- Nick From lew at lewscanon.com Wed Oct 3 17:14:53 2007 From: lew at lewscanon.com (Lew) Date: Wed, 03 Oct 2007 17:14:53 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <13frd6vtarbee75@corp.supernews.com> <85sl4sqckf.fsf@lola.goethe.zz> <85hcl8qaj7.fsf@lola.goethe.zz> Message-ID: rjack wrote: > Webster? WEBSTER. . . ? > > Whatever happened to the Oxford English Dictionary ? > Seems to me the English have always spoken the definitive > English. . . that's why they call it ENGLISH. What is in a name? A rose by any other name would still smell as sweet. -- Lew From happyhondje at gmail.com Thu Oct 25 11:31:03 2007 From: happyhondje at gmail.com (happyhondje at gmail.com) Date: Thu, 25 Oct 2007 15:31:03 -0000 Subject: An efficient, pythonic way to calculate result sets Message-ID: <1193326263.917893.266620@e9g2000prf.googlegroups.com> Hello everyone, I've got a little issue, both programming and performance-wise. I have a set, containing objects that refer to other sets. For example, in a simple notation: (, ) (or in a more object-like display: set(obj1.choices=set(a, b, c) ). There may be obj1..objN objects in the outer set, and the amount of items in the choices sets could also reach a high number. The objects in the choices sets might overlap. Now I want to have all possible combinations, like this: (a, d), (b, d), (c, d), (a, e), (b, e), (c, e). However, I've got a few catches that make an already (icky) recursive function worse to use. First of all, I want to be able to only choose things so that the outer 'result sets' have the same length. For example, if you'd have (, ), you might pick (a, a) with a simple algorythm, the basic behaviour of sets reducing it to (a) and thus having an improper length. I could add yet another loop after calculating everything to throw out any result sets with the improper length, but that would be highly inefficient. Second, I'd hope to be able to say that objX should be assumed to have made the choice z. In the first example I mentioned, if I said that 'obj1 == a', the only result sets that would come out would be (a, d) and (a, e). I've been toying with this problem for a while, but I've found out it quickly gets slow, so I hope some people here could find a way to write code like this that is efficient (and hopefully not rely on recursion and 'fix up' loops like I've got mockups with right now). Thank you for any suggestions you can offer. From Kevin.Smith at sixquickrun.com Thu Oct 25 23:53:33 2007 From: Kevin.Smith at sixquickrun.com (Kevin D. Smith) Date: Thu, 25 Oct 2007 22:53:33 -0500 Subject: How to create a PUG mailing list? Message-ID: I'm trying to get a Python User Group started in Norman, OK and I want to get one of those fancy mailing lists on mail.python.org. There is a link there to create a new list if you have the proper authority. How does someone get the proper authority? -- Kevin D. Smith From sbassi at clubdelarazon.org Thu Oct 18 13:05:34 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Thu, 18 Oct 2007 14:05:34 -0300 Subject: Convert string to command.. In-Reply-To: <1192718860.391481.139090@v29g2000prd.googlegroups.com> References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> <1192718860.391481.139090@v29g2000prd.googlegroups.com> Message-ID: <9e2f512b0710181005u1007e16ar26fbc64b6c7138a@mail.gmail.com> On 10/18/07, Adam Atlas wrote: > > Use the builtin function "eval". What is the difference with os.system()? -- Sebasti?n Bassi (???????). Diplomado en Ciencia y Tecnolog?a. Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6 GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D From duncan.booth at invalid.invalid Wed Oct 24 09:46:50 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Oct 2007 13:46:50 GMT Subject: Better writing in python References: <1193227780.481365.261900@q3g2000prf.googlegroups.com> <1193232109.743432.97240@i13g2000prf.googlegroups.com> Message-ID: Alexandre Badez wrote: > Thanks for your try Cliff, I was very confused :P > More over I made some mistake when I post (to make it easiest). > > Here is my real code: > > with > dArguments = { > 'argName' : { > 'mandatory' : bool, # True or False > [...], # other field we do not care here > } > } > > lMandatory = [] > lOptional = [] > for arg in cls.dArguments: > if cls.dArguments[arg]['mandatory']: > lMandatory.append(arg) > else: > lOptional.append(arg) > return (lMandatory, lOptional) > > So, as you see, we agree each other about "if bool" or "if bool is > True" ;) > > So, my question was how to give it a better 'python like' look ? > Any idea ? > > For a 'python like' look lose the Hungarian notation (even Microsoft have largely stopped using it), increase the indentation to 4 spaces, and also get rid of the spurious parentheses around the result. Otherwise it is fine: clear and to the point. If you really wanted you could write something like: m, o = [], [] for arg in cls.dArguments: (m if cls.dArguments[arg]['mandatory'] else o).append(arg) return m, o Or even: m, o = [], [] action = [o.append, m.append] for arg in cls.dArguments: action[bool(cls.dArguments[arg]['mandatory'])](arg) return m, o but it just makes the code less clear, so why bother? From ldo at geek-central.gen.new_zealand Mon Oct 1 23:21:30 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 02 Oct 2007 16:21:30 +1300 Subject: Question about quoting style. References: Message-ID: In message , Steven W. Orr wrote: > foo=bar # No quotes needed > echo $foo # Also none needed Actually, it's not clear to me that quotes will never be needed on the second line. Unless foo is always going to have the value "bar". From theller at ctypes.org Tue Oct 30 04:55:48 2007 From: theller at ctypes.org (Thomas Heller) Date: Tue, 30 Oct 2007 09:55:48 +0100 Subject: Help ctypes on arm linux not compile In-Reply-To: References: Message-ID: Samuel M. Smith schrieb: > I have built python 1.5.1 from source for an embedded ARM9 debian > linux Sarge distribution but > ctypes doesn't build. Anybody have any idea what the problem is? Do > I have to have the libffi package > installed. > See my errors below. ctypes won't work with Python 1.5 because it uses new style classes, introduced in Python 2.2. It uses other, newer features additionally, so it requires Python 2.3 at least. Then, the included libffi package doesn't support ARM, you need a newer libffi version. I think that the current Python 2.5 sources, from SVN, should work. Thomas From kar1107 at gmail.com Tue Oct 16 19:15:37 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 16 Oct 2007 23:15:37 -0000 Subject: negative base raised to fractional exponent In-Reply-To: <1192571332.470809.279160@v23g2000prn.googlegroups.com> References: <1192571332.470809.279160@v23g2000prn.googlegroups.com> Message-ID: <1192576537.866907.87400@i38g2000prf.googlegroups.com> On Oct 16, 2:48 pm, schaefer... at gmail.com wrote: > Does anyone know of an approximation to raising a negative base to a > fractional exponent? For example, (-3)^-4.11111 since this cannot be > computed without using imaginary numbers. Any help is appreciated. Use complex numbers. They are part of python (no special modules needed). Just write your real number r, as r+0j e.g. square-root of -4 is 2j >>> (-4+0j)**(0.5) (1.2246063538223773e-16+2j) # real part is almost zero >>> >>> (-4.234324+0j)**(0.5) (1.2599652164116278e-16+2.0577473119894969j) >>> 2.0577473119894969j ** 2 (-4.234324+0j) >>> Karthik From timr at probo.com Thu Oct 25 02:28:05 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Oct 2007 06:28:05 GMT Subject: win32com.client documentation? References: <1193236546.344635.54080@e9g2000prf.googlegroups.com> Message-ID: Mark Morss wrote: > >I want to be able to script the creation of Excel spreadsheets and >Word documents, interract with Access data bases, and so forth. Empirically, the best way to do this (for me, at least) is to Google for examples. There are a few simple rules to learn on how to map the Visual Basic and C++ COM examples you typically find into Python equivalents. Once you've seen them once, it becomes pretty natural. There are a few more esoteric topics (like indexed properties) that require more exploration, and the pywin32 mailing list is absolutely invaluable for those occasions. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mathieu.malaterre at gmail.com Fri Oct 19 03:42:43 2007 From: mathieu.malaterre at gmail.com (mathieu) Date: Fri, 19 Oct 2007 07:42:43 -0000 Subject: strptime and microseconds In-Reply-To: <1192740849.207061.251690@q3g2000prf.googlegroups.com> References: <1192723239.854957.257280@v29g2000prd.googlegroups.com> <1192725397.632337.73420@k35g2000prh.googlegroups.com> <1192725976.909230.265280@q3g2000prf.googlegroups.com> <1192740849.207061.251690@q3g2000prf.googlegroups.com> Message-ID: <1192779763.429703.237990@q3g2000prf.googlegroups.com> On Oct 18, 10:54 pm, Gabriel Genellina wrote: > On 18 oct, 13:46, mathieu wrote: > > > > > On Oct 18, 6:36 pm, mathieu wrote: > > > > I am trying to use strptime to parse my microseconds but I was not > > > > able the documentation for it. The only list I found was: > > Ok final version is simply: > > > s1 = "20070619" > > s2 = "115344.51" > > s3 = "115446.123456" > > > ms2 = eval(s2) % 1 > > mms2 = int(ms2 * 1000000 + 0.5) > > ms3 = eval(s3) % 1 > > mms3 = int(ms3 * 1000000 + 0.5) > > > s = s1 + s2 > > d1 = datetime(*strptime(s[:14], "%Y%m%d%H%M%S")[0:6]) > > d1 = d1.replace(microsecond = mms2) > > What about this: > > py> import datetime > py> s1 = "20070619 115344.025" > py> p1, p2 = s1.split(".", 1) > py> d1 = datetime.datetime.strptime(p1, "%Y%m%d %H%M%S") python2.3: from time import strptime > py> ms = int(p2.ljust(6,'0')[:6]) ljust padds with space only in python 2.3. But thanks anyway your solution is much cleaner ! -Mathieu From zyzhu2000 at gmail.com Tue Oct 23 16:38:29 2007 From: zyzhu2000 at gmail.com (beginner) Date: Tue, 23 Oct 2007 20:38:29 -0000 Subject: Life-time of temporary variables in list comprehensions In-Reply-To: <1193158968.578330.204710@t8g2000prg.googlegroups.com> References: <1193158968.578330.204710@t8g2000prg.googlegroups.com> Message-ID: <1193171909.291405.263860@i13g2000prf.googlegroups.com> On Oct 23, 12:02 pm, beginner wrote: > Hi All, > > If I have a list comprehension: > > ab=["A","B"] > c = "ABC" > [1.0 if c=='A' else c='B' for c in ab] > print c > > >>"B" > > My test shows that if c is not defined before the list comprehension, > it will be created in the list comprehension; if it is defined before > the list comprehension, the value will be overwritten. In other words, > temp variables are not local to list comprehensions. > > My question is why is this and is there any way to make c local to > list comp? > > Thanks, > Geoffrey I see. Thanks for everyone's help! From gnuist006 at gmail.com Tue Oct 9 15:24:23 2007 From: gnuist006 at gmail.com (gnuist006 at gmail.com) Date: Tue, 09 Oct 2007 19:24:23 -0000 Subject: The fundamental concept of continuations In-Reply-To: References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> Message-ID: <1191957863.093505.293800@v3g2000hsg.googlegroups.com> Special thanks to many of you for your very decent replies. On Oct 9, 11:18 am, George Neuner wrote: > On Tue, 09 Oct 2007 05:15:49 -0000, gnuist... at gmail.com wrote: > >Again I am depressed to encounter a fundamentally new concept that I > >was all along unheard of. Its not even in paul graham's book where i > >learnt part of Lisp. Its in Marc Feeley's video. > > >Can anyone explain: > > >(1) its origin > > Lambda calculus. Continuation is just a formal term for "what the > code does next". It manifests, literally, as the next instruction(s) > to be executed. > > >(2) its syntax and semantics in emacs lisp, common lisp, scheme > > Lisp does not have explicit continuations so there is no syntax for > them. Continuations in Lisp mainly take the form of function calls, > function returns, exceptions, conditions, etc. Sometimes code is > written in "continuation passing style" (CPS) in which each function > has one or more additional function parameters (the continuations) - > the function terminates by passing its result as an argument to one of > those continuation functions. > > Scheme has explicit continuations based on closures. Closure > continuations are created using CALL-WITH-CURRENT-CONTINUATION > (usually abbreviated as CALL/CC). Some Schemes also recognize a > LET/CC form used mainly for escape continuations (exceptions). > Scheme's closure continuations can be stored in data structures and > used for complex control forms such as multitasking. Like Lisp, > Scheme code also is sometimes written using CPS. > > >(3) Is it present in python and java ? > > It is present in all languages. It generally takes the form of > procedure or function calls, returns, exceptions, etc. > > >(4) Its implementation in assembly. for example in the manner that > >pointer fundamentally arises from indirect addressing and nothing new. > >So how do you juggle PC to do it. > > As I stated above, every function call or return _is_ a continuation > ... their implementation is obvious. > > For the closure form used in Scheme, the implementation is to create a > closure, a data structure containing the function address and some > method of accessing the function's free variables, and to call the > function. How you do this depends greatly on the instruction set. > > >(5) how does it compare to and superior to a function or subroutine > >call. how does it differ. > > Calling closure continuations is a little more complicated and a bit > slower than calling a normal function. Creating the closure in the > first place may be simple or complicated depending on the complexity > of the source code and the processor's instruction set. > > >Thanks a lot. > > >(6) any good readable references that explain it lucidly ? > > Get yourself a good textbook on compilers. Most of the techniques are > applicable to all languages - even for seemingly very different > languages, the differences in their compilers are simply in how the > basic compilation techniques are combined. > > My favorite intermediate-level books are > > Aho, Sethi & Ullman. "Compilers: Principles, Techniques and Tools". > 2nd Ed. 2006. ISBN 0-321-48681-1. > The first edition from 1986, ISBN 0-201-10088-6, is also worth having > if you can still find it. The 1st edition is mainly about procedural > languages, the 2nd gives more time to functional languages and modern > runtime issues like GC and virtual machines. > > Cooper & Torczon, "Engineering a Compiler", 2004. > ISBN 1-55860-698-X (hardcover), 1-55860-699-8 (paperback). > Also available as a restricted 90-day ebook fromhttp://rapidshare.com/files/24382311/155860698X.Morgan_20Kaufmann.Eng... > > There are also some decent intro books available online. They don't > go into excruciating detail but they do cover the basics of code > shaping which is what you are interested in. > > Torben Mogensen. "Basics of Compiler Design"http://www.diku.dk/~torbenm/Basics/ > > "Engineering a Compiler". I don't have this author's name, nor can > Google find it at the moment. I have a copy though (~2MB) - if you > are interested, contact me by email and I'll send it to you. > > Also Google for free CS books. Many older books (including some > classics) that have gone out of print have been released > electronically for free download. > > George > -- > for email reply remove "/" from address From bozonm at vscht.cz Sun Oct 7 13:17:32 2007 From: bozonm at vscht.cz (Michal Bozon) Date: Sun, 07 Oct 2007 19:17:32 +0200 Subject: Pil image module, "mode" bug.. References: <1191762186.617411.309700@g4g2000hsf.googlegroups.com> <1191772929.299902.87760@g4g2000hsf.googlegroups.com> Message-ID: On Sun, 07 Oct 2007 09:02:09 -0700, Abandoned wrote: > On Oct 7, 4:47 pm, Michal Bozon wrote: >> On Sun, 07 Oct 2007 06:03:06 -0700, Abandoned wrote: >> > Hi.. >> > I find the picture color with: >> > im=Image.open("/%s" %name) >> > color=im.mode #p=black & beyaz rgb=color L=grey >> >> > This usually work true but in these pictures: >> >http://malatya.meb.gov.tr/images/alt/ilsis_logo.gif >> >http://malatya.meb.gov.tr/images/meb.gif >> >> > Say me P (black&white) but these pictures are color.. >> >> > What is the reason of this ? >> >> > I'm sorry my bad english >> >> P does mean palette, black&white is a special case of palette, with two >> colors. > > How can i understand the picture color ? (black &white or color or > grey) If you know how to work with RGB images, you can convert the image from the palette mode easily: img2 = img.convert(mode='RGB') Anyway, always is helpful to read the tutorial or basic documentation.. ;) MB From martin at v.loewis.de Wed Oct 31 10:16:45 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 31 Oct 2007 15:16:45 +0100 Subject: _tkinter installation in python 2.5 on mandriva with a default 2.4 In-Reply-To: <1193813238.978699.154830@57g2000hsv.googlegroups.com> References: <1193775761.764547.148730@i38g2000prf.googlegroups.com> <4727b1e6$0$13390$9b622d9e@news.freenet.de> <1193813238.978699.154830@57g2000hsv.googlegroups.com> Message-ID: <47288E4D.6010301@v.loewis.de> > however make still complains of the non existance of the the Tcl/Tk > libs and/or headers So where it tk.h located? Regards, Martin From sndive at gmail.com Tue Oct 30 20:04:45 2007 From: sndive at gmail.com (sndive at gmail.com) Date: Wed, 31 Oct 2007 00:04:45 -0000 Subject: simple? embedding question In-Reply-To: <4727854D.3050201@spam.com> References: <1193769063.364226.208300@o38g2000hse.googlegroups.com> <4727854D.3050201@spam.com> Message-ID: <1193789085.081049.152410@22g2000hsm.googlegroups.com> On Oct 30, 1:26 pm, Farshid Lashkari wrote: > snd... at gmail.com wrote: > > suppose i have imported two modules foo and bar with > > foo=PyImport_ImportModule("foo") and bar=PyImport_ImportModule("bar") > > respectively. > > > Now suppose I have an artitrary python expression to evaluate. > > Do I need to parse that thring and check for foo. and bar. before > > jumping the usual > > PyModule_GetDict,PyDict_GetItemString,PyObject_CallObject hoop hoop on > > the PyObject for > > the prefix or there is a better way? > > > btw PyRun_SimpleString("foo.baz()"); does not work: > > Traceback (most recent call last): > > File "", line 1, in ? > > NameError: name 'foo' is not defined > > > and i potentially need a PyObject* back with the result of the > > expression anyway. > > I believe the problem is that you are not importing the "foo" and "bar" > modules into the __main__ scope. Try using PyImport_ImportModuleEx, > which will allow you to specify the global scope to import the module > into. For example, to import the modules into the __main__ scope you > could do the following: > > PyObject* mainmod = PyImport_AddModule("__main__"); > PyObject* maindict = PyModule_GetDict(mainmod); > > foo = PyImport_ImportModuleEx("foo", maindict , maindict , NULL); > bar = PyImport_ImportModuleEx("bar", maindict , maindict , NULL); > > Once the modules are imported into the __main__ scope, you should be > able to use PyRun_SimpleString() to evaluate expressions. > > -Farshid i switched to PyImport_ImportModuleEx per your suggestion but i still get Traceback (most recent call last): File "", line 1, in ? NameError: name '__main__' is not defined i tried PyRun_SimpleString("__main__.foo.baz()"); : Traceback (most recent call last): File "", line 1, in ? NameError: name '__main__' is not defined i do not have if __name__ == '__main__': statement anywhere in the module i'm importing, but nevertheless i checked that PyImport_AddModule("__main__"); and subsequent getdict return non null pointers. does non null dictionary indicate that PyImport_AddModule succeeded as opposed to creating an empty module object? From iansan at gmail.com Wed Oct 17 12:58:53 2007 From: iansan at gmail.com (IamIan) Date: Wed, 17 Oct 2007 16:58:53 -0000 Subject: CGI and external JavaScript nightmare In-Reply-To: <1192529804.759199.76350@i13g2000prf.googlegroups.com> References: <1192083786.137629.24550@r29g2000hsg.googlegroups.com> <1192529804.759199.76350@i13g2000prf.googlegroups.com> Message-ID: <1192640333.986171.67720@v29g2000prd.googlegroups.com> Thank you for the replies. After a lot of research I tracked down the issue. I was using the CGI to build all of the pages for the site, then filling in content with .innerHTML= as users clicked on tabs. Since I wanted to place the Google Ads in different parts of each page, the Google Ads JavaScript was in each page chunk being dynamically placed with .innerHTML. It turns out that JavaScript isn't executed when it is placed in a page via .innerHTML. I tried some tricks to execute it after it was added to the page (eval, appendChild) but it still didn't work. The Google Ads JavaScript is very touchy and their agreement is very strict; it wasn't even clear that what I was doing was in line with it, so I broke the site up into multiple CGI pages and now it works fine. One CGI question - since all of my CGIs are spitting out HTML is their source code safe? wget and linking to the source deliver the output HTML. Are there any other methods of trying to steal the source CGI I need to protect against? Thank you. From chris.monsanto at gmail.com Fri Oct 5 11:42:57 2007 From: chris.monsanto at gmail.com (chris.monsanto at gmail.com) Date: Fri, 05 Oct 2007 15:42:57 -0000 Subject: novice list In-Reply-To: <87ir5lfxph.fsf@rudin.co.uk> References: <87ir5lfxph.fsf@rudin.co.uk> Message-ID: <1191598977.515953.288720@50g2000hsm.googlegroups.com> On Oct 5, 10:22 am, Paul Rudin wrote: > Istv?n writes: > > Could somebody suggest me a novice Python list, please? > > Here you go: > > ['novice'] > > (Sorry, couldn't resist.) No no... I think he meant a "simple" list. Like, you know, a list novices can handle. I suggest the empty list []! From akraemer at sbcglobal.net Fri Oct 19 18:30:21 2007 From: akraemer at sbcglobal.net (Andreas Kraemer) Date: Fri, 19 Oct 2007 22:30:21 -0000 Subject: Strange behaviour with reversed() In-Reply-To: References: <13hdochic30oo43@corp.supernews.com> <13he60e4vc6i753@corp.supernews.com> <1192726016.847208.35040@v23g2000prn.googlegroups.com> Message-ID: <1192833021.006585.192250@t8g2000prg.googlegroups.com> On Oct 19, 1:49 pm, Duncan Booth wrote: > Andreas Kraemer wrote: > >> The only other behaviours I would regard as intuitive for iteration over > >> a mutating sequence would be to throw an exception either for mutating > >> the sequence while the iterator exists or for using the iterator after a > >> mutation. > > > Maybe it would have been slightly more intuitive if reversed() had > > been implemented like this, > > > def Reversed(seq): > > for i in xrange(len(seq)-1,-1,-1): > > yield seq[i] > > > so that the length of the sequence is determined when the iteration > > starts, not when the iterator is created? > > Perhaps, but either way it comes down to "don't modify the sequence while > iterating". Definitely agreed. From stef.mientki at gmail.com Tue Oct 16 16:43:26 2007 From: stef.mientki at gmail.com (stef mientki) Date: Tue, 16 Oct 2007 22:43:26 +0200 Subject: how to get my own namespace ? Message-ID: <4715226E.2020904@gmail.com> I want to view my own namespace, i.e. to see the modules namespace in the module itself, is that possible ? I can use dir() but I read dir is just a convenience function, and besides I want key/value pairs. thanks, Stef Mientki From siona at chiark.greenend.org.uk Wed Oct 31 09:16:38 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 31 Oct 2007 13:16:38 +0000 (GMT) Subject: Creating a temporary file in Python References: <1193832119.872710.108920@k79g2000hse.googlegroups.com> Message-ID: <6ux*naIYr@news.chiark.greenend.org.uk> looping wrote: >I want to create a temporary file, read it in an external command and >finally delete it (in Windows XP). > >I try to use tempfile module but it doesn't work, the file couldn't be >open by my other process (error like: SP2-0310: unable to open file "c: >\docume~1\looping\locals~1\temp\tmpau81-s.sql") You're using NamedTemporaryFile. The tempfile documentation (http://docs.python.org/lib/module-tempfile.html) says: " [ ... ] Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later)." You probably want to use tempfile.mkstemp and explicitly close (before running the external command) and delete it. -- \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 chowroc.z+l at gmail.com Thu Oct 18 03:51:03 2007 From: chowroc.z+l at gmail.com (Roc Zhou) Date: Thu, 18 Oct 2007 15:51:03 +0800 Subject: A near realtime file system mirror application written in Python In-Reply-To: <7847e5160710161952t7a22881ei1ba0d70b69dec883@mail.gmail.com> References: <7847e5160710161952t7a22881ei1ba0d70b69dec883@mail.gmail.com> Message-ID: <7847e5160710180051je64f2b6j9af3c9bbe6c7d50@mail.gmail.com> mirrord/fs_mirror makes use of inotify, which is a functionality afforded by the recent Linux (from 2.6.12). It is a counterpart of FAM, since Linux FAM has stopped so long. On 10/17/07, Roc Zhou wrote: > > Hello: > > Recently I started an open source project "cutils" on the > sourceforge: > https://sourceforge.net/projects/crablfs/ > > The document can be found at: > http://crablfs.sourceforge.net/#ru_data_man > > This project's mirrord/fs_mirror is a near realtime file system > mirroring application across 2 or more hosts, now it can work > for me. > > I hope this tool can be useful to you. > > Thank you. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas.weholt at gmail.com Wed Oct 10 04:39:55 2007 From: thomas.weholt at gmail.com (Thomas W) Date: Wed, 10 Oct 2007 01:39:55 -0700 Subject: pyxml package not working? No xml.dom.ext.reader module available after install. Message-ID: <1192005595.981054.150530@22g2000hsm.googlegroups.com> I've tried to install the pyxml-package, available at http://pyxml.sourceforge.net/, both from source and using some hack on the win32-binary package available for python2.4, but without luck. After install the module xml.dom.ext.reader is not available, eventhough the folder, __init__py and everything is in place. Why? And could someone please make a win32-binary package of pyxml for python2.5? Thanks! From gandalf at shopzeus.com Wed Oct 3 09:37:15 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 03 Oct 2007 15:37:15 +0200 Subject: gdbm objects not iterable? Message-ID: <47039B0B.7080301@shopzeus.com> Hi All, gdbm objects have a "firstkey" and a "nextkey" method. So if I want iterate through the keys (which I often do) then I have to do this: def itergdbmkeys(gdbm_obj): key = gdbm_obj.firstkey() if key is None: raise StopIteration yield key while True: key = gdbm_obj.nextkey(key) if key is None: raise StopIteration yield key Then I can do this: for key in itergdbmkeys(gdbm_obj): process(key,gdbm_obj) I wonder why we do not have a "next()" method, which could return an iterator instantly. I don't think that it would be harmful, but definitely it would be useful. Then we could do this: for key in gdbm_obj: process(key,obj) I know that this is a very small change, but it can make gdbm objects look more like dictionaries. Please make comments. :-) Laszlo From hancock.robert at gmail.com Thu Oct 18 18:21:15 2007 From: hancock.robert at gmail.com (milan_sanremo) Date: Thu, 18 Oct 2007 22:21:15 -0000 Subject: What Data is Available With a Pickled Object Over a Socket? Message-ID: <1192746075.952684.152760@z24g2000prh.googlegroups.com> I've read the library entry for pickle a couple of times, and I'm still not sure what data is maintained when an item is pickled and sent over a socket. Two importable modules: class envelope(): def __init__(self, rec, d): self.recipient = rec self.listData = d class mailbag(): def __init__(self): self.dicEnvelope = [] def addEnvelope(self, uuid, envelope): self.dicEnvelope[uuid] = envelope Client --------- import envelope, mailbag, cPickle, socket remoteHost = "999.666.888.777 mb = mailbag() env1 = envelope('John', ('a', 'b', 'c')) env2 = envelope('Mary', ('d', 'e', f')) mb.addEnvelope(1, env1) mb.addEvenlop(2, env2) pickledMailbag = cPickle.dump(mb, HIGHEST_PROTOCOL) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(remoteHost) sock.send(pickledMailbag) Server --------- import envelope, mailbag, cPickle, socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(host, port) sock.listen(5) conn, addr = sock.accept() while 1: pickledData = conn.recv(1024) if not pickledData break mb = cPickle.load(pickledData) At this point, does mb contain a dictionary with the two envelopes with their data? From mdipierro at cti.depaul.edu Fri Oct 12 23:55:17 2007 From: mdipierro at cti.depaul.edu (Massimo Di Pierro) Date: Fri, 12 Oct 2007 22:55:17 -0500 Subject: Yet another comparison of Python Web Frameworks In-Reply-To: References: <1733A730-1B02-4057-82DF-C5FA9E2CD9C8@cti.depaul.edu> Message-ID: <2CEA8691-12EC-4E63-B13E-B923E6CDD54F@cti.depaul.edu> happy to hear that. you may want take a loot at http://mdp.cti.depaul.edu/vqcd It is mostly python stuff and will post the code soon. Massimo On Oct 12, 2007, at 10:47 PM, Fernando Perez wrote: > Massimo Di Pierro wrote: > >> P.S. Michele Simionato. I have heard your name before? Is it possible >> we have met in Pisa in 1990-1996? I am also a Quantum Field Theorist >> and there is not many of us. > > More than you think, it seems. Some of us were even using python > to process > Lattice QCD computations years ago ;-) > > Cheers, > > f > > -- > http://mail.python.org/mailman/listinfo/python-list From iansan at gmail.com Wed Oct 17 17:05:43 2007 From: iansan at gmail.com (IamIan) Date: 17 Oct 2007 14:05:43 -0700 Subject: CGI and external JavaScript nightmare In-Reply-To: <1192529804.759199.76350@i13g2000prf.googlegroups.com> References: <1192083786.137629.24550@r29g2000hsg.googlegroups.com> <1192529804.759199.76350@i13g2000prf.googlegroups.com> Message-ID: <1192639690.306271.298190@z24g2000prh.googlegroups.com> Thank you for the replies. After a lot of research I tracked down the issue. I was using the CGI to build all of the pages for the site, then filling in content with .innerHTML= as users clicked on tabs. Since I wanted to place the Google Ads in different parts of each page, the Google Ads JavaScript was in each page chunk being dynamically placed with .innerHTML. It turns out that JavaScript isn't executed when it is placed in a page via .innerHTML. I tried some tricks to execute it after it was added to the page (eval, appendChild) but it still didn't work. The Google Ads JavaScript is very touchy and their agreement is very strict; it wasn't even clear that what I was doing was in line with it, so I broke the site up into multiple CGI pages and now it works fine. One CGI question - since all of my CGIs are spitting out HTML is their source code safe? wget and linking to the source deliver the output HTML. Are there any other methods of trying to steal the source CGI I need to protect against? Thank you. From bdesth.quelquechose at free.quelquepart.fr Wed Oct 3 23:06:27 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Oct 2007 05:06:27 +0200 Subject: Boolean parser.. In-Reply-To: <1191598074.893657.233250@57g2000hsv.googlegroups.com> References: <1191526196.866591.322950@r29g2000hsg.googlegroups.com> <1191583772.041261.71790@19g2000hsx.googlegroups.com> <1191585605.393165.72100@k79g2000hse.googlegroups.com> <1191598074.893657.233250@57g2000hsv.googlegroups.com> Message-ID: <4706ab00$0$8918$426a34cc@news.free.fr> Paul McGuire a ?crit : (snip) May I suggest a couple cleanifications for our newbie friends around ? > from searchparser import SearchQueryParser > > products = [ "grape juice", "grape jelly", "orange juice", "orange > jujubees", > "strawberry jam", "prune juice", "prune butter", "orange > marmalade", > "grapefruit juice" ] # round 1 : extracting constants from iterations > class FruitSearchParser(SearchQueryParser): > def GetWord(self, word): > return set( p for p in products if p.startswith(word + " ") ) def GetWord(self, word): target = word + " " return set(p for p in products if p.startswith(target) ) > def GetWordWildcard(self, word): > return set( p for p in products if p.startswith(word[:-1]) ) def GetWordWildcard(self, word): target = word[:-1] return set( p for p in products if p.startswith(target) ) # round 2 : factoring out common code class FruitSearchParser(SearchQueryParser): def _find_products_starting_with(self, target): return set(p for p in products if p.startswith(target)) def GetWord(self, word): return self._find_products_starting_with(word + " ") def GetWordWildcard(self, word): return self._find_products_starting_with(word[:-1]) # round 3: doing proper encapsulation: class FruitSearchParser(SearchQueryParser): def __init__(self, products): self._products = products def _find_products_starting_with(self, target): return set(p for p in self._products if p.startswith(target)) def GetWord(self, word): return self._find_products_starting_with(word + " ") def GetWordWildcard(self, word): return self._find_products_starting_with(word[:-1]) # round 4 : respecting pep08 (naming conventions): # heck ! I guess that this would need a rewrite of SearchQueryParser From stef.mientki at gmail.com Tue Oct 16 17:39:44 2007 From: stef.mientki at gmail.com (stef mientki) Date: Tue, 16 Oct 2007 23:39:44 +0200 Subject: how to get my own namespace ? In-Reply-To: References: <4715226E.2020904@gmail.com> Message-ID: <47152FA0.5070703@gmail.com> Robert Kern wrote: > stef mientki wrote: > >> I want to view my own namespace, >> i.e. to see the modules namespace in the module itself, >> is that possible ? >> >> I can use >> dir() >> but I read dir is just a convenience function, >> and besides I want key/value pairs. >> > > vars() will give you a dictionary copy of the local namespace, but modifying it > won't modify the namespace. > > globals() will give you the module's namespace as a dictionary which you can modify. > > locals() will give you the local namespace (wherever you happen to be), but you > may be restricted from modifying that dictionary in some circumstances. > > thanks Robert, funny, that this is much more complicated than __dict__ of an external module: - you have to make a copy before iterating - iterating more than once increases the list I think I just write a module on top. cheers, Stef Mientki From none at try.invalid Thu Oct 25 11:56:11 2007 From: none at try.invalid (Pete Bartonly) Date: Thu, 25 Oct 2007 16:56:11 +0100 Subject: local variable referenced before assignment In-Reply-To: References: <47205ba1$0$515$5a6aecb4@news.aaisp.net.uk> Message-ID: <4720bc9b$0$511$5a6aecb4@news.aaisp.net.uk> A.T.Hofkamp wrote: > On 2007-10-25, Pete Bartonly wrote: >> Quick question, probably quite a simple matter. Take the follow start of >> a method: >> >> >> def review(filesNeedingReview): >> >> for item in filesNeedingReview: >> (tightestOwner, logMsg) = item >> >> if (logMsg != None): >> for logInfo in logMsg.changed_paths: >> >> >> This generates the error: >> >> UnboundLocalError: local variable 'logMsg' referenced before assignment > > This should work, are you sure you didn't make a typo in one of the names? Nope, the above is verbatim. This is why I'm so confused. It should work! I'm editing in emacs, and the indents are tab chars. I've re-indented the indents using 'tab' key - same result. The entire error output is this: Traceback (most recent call last): File "checkCode.py", line 602, in ? analyseFiles(tempDir) File "checkCode.py", line 448, in analyseFiles analyseFilesInARepos(startDir, f) File "checkCode.py", line 590, in analyseFilesInARepos makeReport(projName, filesNeedingReview, filesFailedReview) File "checkCode.py", line 422, in makeReport for logInfo in logMsg.changed_paths: UnboundLocalError: local variable 'logMsg' referenced before assignment I'm rather stuck at what to try next! thanks. Pete > > Another way to make this fail would be when the if-condition is outside > the loop (is the indentation correct in your code?). > > A short demontration: >>>> def r(fnr): > ... for item in fnr: > ... w,m = item > ... if m == 2: > ... print w > ... >>>> fnr = [(1,2), (3,4)] >>>> r(fnr) > 1 > > With respect to compactness and style, you can move your multi-assignment > statement in the for loop, as in > > for tightestOwner, logMsg in filesNeedingReview: > > Also, brackets around conditions (in the if) are not needed, and comparing > against None is usually done with 'is' or 'is not' instead of '==' or '!='. > The result is then > > if logMsg is not None: > > >> I thought I'd assigned it in the "(tightestOwner, logMsg) = item" line - >> so in the python interpreter complaining about the fact this assignment >> might not go well? > > No, you'd get an error at that point in that case. > > > Sincerely, > Albert From torerik81 at gmail.com Mon Oct 8 15:19:50 2007 From: torerik81 at gmail.com (=?ISO-8859-1?Q?Tor_Erik_S=F8nvisen?=) Date: Mon, 8 Oct 2007 21:19:50 +0200 Subject: Convert obejct string repr to actual object Message-ID: <96f089100710081219t5b48be86u89d266ff4bd74dbf@mail.gmail.com> Hi, I've tried locating some code that can recreate an object from it's string representation... The object in question is really a dictionary containing other dictionaries, lists, unicode strings, floats, ints, None, and booleans. I don't want to use eval, since I can't trust the source sending the object.... I'm sure someone must have had the same need and created code for it... Maybe Pypy has what I need??? Haven't looked though... Regards, Tor Erik PS: The string repr is created by a server outside of my control... From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Oct 10 17:00:08 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 10 Oct 2007 23:00:08 +0200 Subject: I'm starting to think like a Pythonista References: Message-ID: <5n4sqoFg4bs3U1@mid.individual.net> brad wrote: > low_odds = [1,3,5,7,9] > # make a list containing 10 - 98 evens only > big_evens = big_evens = [x for x in list(xrange(99)) if x % 2 == > 0 and x >8] Why use xrange if you convert it to a full list in place? No advantage there. Regards, Bj?rn -- BOFH excuse #300: Digital Manipulator exceeding velocity parameters From carsten at uniqsys.com Fri Oct 12 13:14:11 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 12 Oct 2007 13:14:11 -0400 Subject: Convert obejct string repr to actual object In-Reply-To: References: Message-ID: <1192209251.3406.38.camel@dot.uniqsys.com> On Fri, 2007-10-12 at 17:41 +0100, English, Mark wrote: > > From: Tor Erik S?nvisen > > Date: October 8th 2007 > > I've tried locating some code that can recreate an object from > > it's string representation... > On a related note I've wondered about this: > >>> class Foo(object): pass > >>> f = Foo() > >>> s = repr(f) > >>> s > '<__main__.Foo object at 0x007CBAB0>' > > So how do I get f back from s ? > Obviously this is open to abuse. I just wondered if a mechanism existed short of writing > a C-extension which parses that string, casts the hex number to a PyObject *, INCREFs it, > and gives it back... I can't help but wonder, do you often find yourself having to locate an object from its hexadecimal address? -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Tue Oct 30 03:54:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Oct 2007 04:54:51 -0300 Subject: A class question References: <87ejfe457k.fsf@mulj.homelinux.net> <4725c510$0$4627$426a74cc@news.free.fr> <874pga3zo7.fsf@mulj.homelinux.net> <4725ea41$0$8018$426a74cc@news.free.fr> <87hcka2d76.fsf@mulj.homelinux.net> <47260805$0$5155$426a34cc@news.free.fr> <87d4uxk08l.fsf@mulj.homelinux.net> Message-ID: En Tue, 30 Oct 2007 02:51:39 -0300, Donn Ingle escribi?: >> While Java's variable declarations bear a superficial (syntactical) >> similarity to C, their semantics is in fact equivalent to the >> object-reference semantics we know in Python. > > I come from Z80A/GWBASIC/VB and a little C, I would describe a Python > variable as a pointer - in that it contains the address of something. > What that "something" is, is a little fuzzy. Right now I imagine it's to > a > kind of structure which has meta info about the object as well as it's > actual address. > > How far off would that be? Almost true. A Python variable is a name inside a namespace, pointing to a Python object. Many names may point to the same object, of course. An object (in CPython) is a structure containing a reference count, followed by a pointer to the object's type, followed by the object contents itself. The object contents may as simple as a single value (e.g. int or float objects) or rather complex (like the frame object which contains about 18 other values, including many pointers to other structures and arrays). The object's type would be what you call the meta info, and contains the type name, many pointers to functions (implementing the type methods) and some flags describing the type behavior. -- Gabriel Genellina From mensanator at aol.com Tue Oct 9 14:21:41 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Tue, 09 Oct 2007 11:21:41 -0700 Subject: pytz has so many timezones! In-Reply-To: <5n1ebbFfok0sU1@mid.uni-berlin.de> References: <1191828739.635927.86590@57g2000hsv.googlegroups.com> <1191865263.572366.270820@y42g2000hsy.googlegroups.com> <1191874404.292250.87130@y42g2000hsy.googlegroups.com> <5n1ebbFfok0sU1@mid.uni-berlin.de> Message-ID: <1191954101.289278.216770@g4g2000hsf.googlegroups.com> On Oct 9, 8:34 am, "Diez B. Roggisch" wrote: > mensana... at aol.com wrote: > > On Oct 8, 1:03 pm, Carsten Haese wrote: > >> On Mon, 2007-10-08 at 10:41 -0700, mensana... at aol.com wrote: > >> > For example, Windows has seperate listings for > > >> > Central America > >> > Central Time (US & Canada) > >> > Guadalahara, Mexico City, Monterry - New > >> > Guadalahara, Mexico City, Monterry - Old > >> > Saskatchewan > > >> > but they are all GMT-6 > > >> But they could have different rules for Daylight Saving Time. > > > Which only matters if you're setting your clock. > > That's BS. If I'm supposed to be attending a video-conference that spans a > few continents which is scheduled using a web-app, it's VITAL that I get > the invitation and reminder rendered in MY local timezone, DST included. > > And for the matter of > > """ > There are only 25 timezones: -12, -11, ... -1, 0 (GMT), +1, ... +11, > +12. > """ > > who says that timezones have to be separated by one hour each? The Earth says. It takes 24 hours to revolve. > Why aren't they separated by 30minutes, or 20, or 10? Or 2 hours? Why isn't an hour defined to be 30 minutes? > Or why don't we have a global time? Like UTC? > > Your 25 timezones are an abstraction the same way Not the same way at all. The 25 timezones I speak of are not merely an abstraction, but related to longitude. > as are the 400 apparently in use by people all over the world Where the correlation to longitude is much looser. Granted, it doesn't need to be for non-navigational purposes. And although governments can legislate things like DST, they can't legislate longitude. > - and last time I checked, there was no > fundamental law in physics or such that limited the allowed or sensible > number of timezones... Isn't there some law somewhere that says the circumference of a sphere is 360deg? Doesn't that same law mean that no two points on a sphere can be seperated by more than 180deg longitude? Doesn't that make GMT+13 non-sensible? > > Diez From steven at REMOVE.THIS.cybersource.com.au Fri Oct 19 04:58:36 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 19 Oct 2007 08:58:36 -0000 Subject: how to iterate over sequence and non-sequence ? References: Message-ID: On Fri, 19 Oct 2007 01:24:09 +0200, stef mientki wrote: > hello, > > I generate dynamically a sequence of values, but this "sequence" could > also have length 1 or even length 0. > > So I get some line in the form of: > line = '(2,3,4)' > line = '' > line = '(2)' > (in fact these are not constant numbers, but all kind of integer > variables, coming from all over the program, selected from a tree, that > shows all "reachable" variables) > > So in fact I get the value from an exec statement, like this > exec 'signals = ' + line And then, one day, somebody who doesn't like you will add the following to your input data: "0; import os; os.system('rm # -rf /')" [ Kids: don't try this at home! Seriously, running that command will be bad for your computer's health. Or at least it would, if I hadn't put a spike in it. ] Don't use exec in production code unless you know what you're doing. In fact, don't use exec in production code. > Now I want to iterate over "signals", which works perfect if there are 2 > or more signals, > but it fails when I have none or just 1 signal. > for value in signals : > do something No, I would say it already failed before it even got there. >>> line = '' >>> exec 'signals = ' + line Traceback (most recent call last): File "", line 1, in ? File "", line 1 signals = ^ SyntaxError: unexpected EOF while parsing This is the right way to deal with your data: input_data = """ (2, 3 , 4) (2) (3,4,5) ( 1, 2,3) """ for line in input_data.split('\n'): line = line.strip().strip('()') values = line.split(',') for value in values: value = value.strip() if value: print(value) > As this meant for real-time signals, I want it fast, so (I think) I > can't afford extensive testing. Don't guess, test it and see if it is fast enough. Some speed ups: If you're reading from a file, you can just say: "for line in file:" instead of slurping the whole lot into one enormous string, then splitting over newlines. If you can guarantee that there is no extra whitespace in the file, you can change the line line = line.strip().strip('()') to the following: line = line.strip('\n()') and save a smidgen of time per loop. Likewise, drop the "value = value.strip()" in the inner loop. -- Steven. From simon at brunningonline.net Mon Oct 15 11:12:22 2007 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 15 Oct 2007 16:12:22 +0100 Subject: Newbi Q: What is a rational for strings not being lists in Python? In-Reply-To: <53396d9e0710150805n6e2cfa53je05d24ec51190aa0@mail.gmail.com> References: <53396d9e0710150805n6e2cfa53je05d24ec51190aa0@mail.gmail.com> Message-ID: <8c7f10c60710150812g30a2181cw7aa067343cd32e22@mail.gmail.com> On 10/15/07, Dmitri O.Kondratiev wrote: > To clarify my point: > reverse() is a lucky one - Python has variants of *this particular* > function both for lists and strings. Yet what about other list functions? > How in general, can I write a function that works both on list and string > types? Both are sequences, right? Why string is not a subtype of a list > then? Lists are mutable, strings are not, so so strings can't support all a list's methods. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Oct 22 08:00:02 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 22 Oct 2007 14:00:02 +0200 Subject: calling a function from string In-Reply-To: <1193043242.235837.86590@e34g2000pro.googlegroups.com> References: <1193043242.235837.86590@e34g2000pro.googlegroups.com> Message-ID: <471c90ba$0$27724$426a34cc@news.free.fr> james_027 a ?crit : > hi, > > i have a function that I could like to call, but to make it more > dynamic I am constructing a string first that could equivalent to the > name of the function I wish to call. how could I do that? the string > could might include name of the module. > > for example > > a_string = 'datetime.' + 'today()' > > how could I call a_string as function? The obvious answer is to use eval or exec, but it's 99.99 times out of 100 the wrong solution. Better solutions usually rely on Python's introspection features - mostly globals(), locals(), sys.modules, and of course getattr(). From tim at timgolden.me.uk Sun Oct 7 13:30:57 2007 From: tim at timgolden.me.uk (Tim Golden) Date: Sun, 07 Oct 2007 18:30:57 +0100 Subject: How to create a file on users XP desktop In-Reply-To: <47090D86.5080805@tim.thechases.com> References: <1191727914.018474.172950@g4g2000hsf.googlegroups.com> <1191735169.441525.106060@o80g2000hse.googlegroups.com> <4708CAF4.7020206@bigfoot.com> <47090D86.5080805@tim.thechases.com> Message-ID: <470917D1.10900@timgolden.me.uk> Tim Chase wrote: >> You are assuming the system is not localized, that won't work if you >> distribute your applications internationally. In my system it is not >> "Desktop", it is "Escritorio", and I guess it will vary with every >> locale. Does someone know a way to find out what name does the desktop >> have? > > I believe you need to read the Desktop value from > > """ > HKEY_CURRENT_USER\software\microsoft\windows\currentversion\explorer\shell > folders > """ > > which should (in my understanding) hold the full path of the > particular folder(s) of interest at that location, including > across localizations. > > -tkc Ideally, use the shell API exposed by pywin32: from win32com.shell import shell, shellcon desktop = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0) For slight convenience: http://timgolden.me.uk/python/winshell.html TJG From lasses_weil at klapptsowieso.net Wed Oct 3 18:47:02 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 04 Oct 2007 00:47:02 +0200 Subject: racism kontrol In-Reply-To: References: <1191430790.537383.115880@r29g2000hsg.googlegroups.com> <1191435296.523842.160230@g4g2000hsf.googlegroups.com> <4703f631$0$7692$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <47041be6$0$30382$9b4e6d93@newsspool4.arcor-online.net> Steve Holden wrote: > Wildemar Wildenburger wrote: >> (I aplogize for that last remark. I have nothing against turkish >> people, I just couldn't let the opportunity for a mean joke slip.) > > Does this mean you are an equal-opportunity racist? > Yeah! Well observed. :) Although "equal-opportunity misantropist" might be a more fitting term. Whatever suits me to express my hatred towards humans. Race, gender, text editor ... you name it. /W (By the way: Accusing a German of racism is almost too easy an insult. Not that I had taken any, just saying.) From Florian.Lindner at xgm.de Fri Oct 12 17:04:58 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Fri, 12 Oct 2007 23:04:58 +0200 Subject: test if email References: <1192220077.109848.74740@e9g2000prf.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Oct 12, 2:55 pm, Florian Lindner wrote: >> Hello, >> is there a function in the Python stdlib to test if a string is a valid >> email address? >> >> Thanks, >> >> florian > > What do you mean? If you're just testing the construction of the email > address string, then it's pretty easy. If you want to know if the > email address is live and works, the only way to reliably find that > out is to send a test email there to see if it goes through or > bounces. > > Here's an interesting article on the topic, which is completely non- > Python related: > > http://www.oreillynet.com/onlamp/blog/2002/12/how_to_validate_an_email_addre.html Answer to everybody: I was just asking for the correct syntax of the mail address. I know about the various problems actually impossibility to test for a live and valid address. Regards, Florian From daniel_nolan at msn.com Mon Oct 29 22:17:19 2007 From: daniel_nolan at msn.com (daniel) Date: Mon, 29 Oct 2007 19:17:19 -0700 Subject: trouble with PAMIE Message-ID: <1193710639.580564.319360@y42g2000hsy.googlegroups.com> I'm trying to use PAMIE to automate some web browsing. My problem is with the buttonClick() method; it doesn't seem to work when the button is supposed to open a new window. For example, I can use it to submit a username and password and advance to the next page but it fails on a button that opens a PDF Preview in a new window. There is no error message. Any ideas? From raims at dot.com Sat Oct 6 10:04:38 2007 From: raims at dot.com (Lawrence Oluyede) Date: Sat, 6 Oct 2007 16:04:38 +0200 Subject: Yet another comparison of Python Web Frameworks References: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> Message-ID: <1i5kk8d.qm6uoao9zyz4N%raims@dot.com> Tim Chase wrote: > Any respectable comparison of Python web frameworks should > include evaluation of at least Django and TG. Or at least give > good reason why the comparison excludes them. I think you didn't read the foreword of the comparison. That is by no means a comprehensive comparison and is not meant to be one. Is a series of thoughts about the frameworks we already tried (we don't have to decide today) and the ones we experimented with. Django is not completely off the radar because I used it extensively this year but the company has certain requirements and the full stackness of Django is not really one of our needs. > Zope is also missing, but I'm not sure Zope qualifies so much as > a framework, but as an answer to the question "If Emacs were a > Python web environment, what would it look like?" Zope2/Plone2 is the one framework they are running away from :-) More KISS less over engineering, that's the mantra. > Django's built-in templating system is one of those things you > either love or you hate. Fortunately, if you're a hater, you can > mindlessly swap it out for your template system of choice with > minimal fuss. I really, really like Django (and its community and the competence of the developers) and I think it deserves what it has gained and more but we are not here to decide who's the best (there's always no best). -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From allen.fowler at yahoo.com Thu Oct 11 02:53:50 2007 From: allen.fowler at yahoo.com (allen.fowler) Date: Wed, 10 Oct 2007 23:53:50 -0700 Subject: Exceptions: Logging TB and local variables? In-Reply-To: <470CC4D9.3010401@websafe.com> References: <1191989030.598822.283420@50g2000hsm.googlegroups.com> <470CC4D9.3010401@websafe.com> Message-ID: <1192085630.373939.121600@d55g2000hsg.googlegroups.com> > Two possibilieies: > > You will need to determine ALL the exceptions that the 3rd party party modules > can raise. If they are custom exceptions you will need to import them into your > application from their modules. > > example: > > say that 3rd party modules raise TransientError, IOError, and ValueError > exceptions. TransientError is a custom exception from module foo > > from foo import TransientError > > for item in bigset: > try: > self.__sub1(item) > self.__sub2(item) > self.__sub3(item) > except (TransientError, IOError, ValueError): > # Log error and continue to next item in set. > log_error_to_file() > > 2) Hook exception traceback handler > > def myTraceBackHandler(type, value,tb): > global > # > # This function allows the user to redefine what happens if the program > # aborts due to an uncaught exception. > # This provides a way to get a "partial" session log if the program > # aborts"as well as some information about what caused the program to > # abort. > # > import traceback > # > # Get traceback lines > # > tblines=traceback.format_exception(type, value,tb) > # > # Write some lines to log > # > log_error_to_file() > # > # Always write the exceptions to screen > # > sys.exit('\n'.join(tblines)) > > Hope this helps. > > -Larry This looks interesting... What is myTraceBackHandler? Is it some sort of event handler? Can you clarify? Thanks, Allen From harlinseritt at yahoo.com Wed Oct 17 16:54:02 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 17 Oct 2007 13:54:02 -0700 Subject: Pull Last 3 Months Message-ID: <1192638583.237609.170000@q5g2000prf.googlegroups.com> Is there a module that can pull str values for say the last 3 months? Something like: print lastMonths(3) ['Sep', 'Aug', 'Jul'] Thanks From a.harrowell at gmail.com Mon Oct 29 09:13:01 2007 From: a.harrowell at gmail.com (TYR) Date: Mon, 29 Oct 2007 13:13:01 -0000 Subject: SQLite3; weird error In-Reply-To: References: <1193657924.375787.287740@o80g2000hse.googlegroups.com> Message-ID: <1193663581.028879.185480@v3g2000hsg.googlegroups.com> On Oct 29, 11:51 am, Duncan Booth wrote: > TYR wrote: > > To do anything with it, you then need to create a cursor object by > > calling foo's method cursor (bar = foo.cursor). > > Perhaps this would work better if you actually try calling foo's method? > > bar = foo.cursor() > > Without the parentheses all you are doing is assigning the method to a > variable, not calling it. Ah. Apologies for a silly question. From Caseyweb at gmail.com Thu Oct 4 11:11:09 2007 From: Caseyweb at gmail.com (Casey) Date: Thu, 04 Oct 2007 08:11:09 -0700 Subject: What does the syntax [::-1] really mean? Message-ID: <1191510669.307178.257500@57g2000hsv.googlegroups.com> I've used [::-1] as a shorthand for reverse on several occasions, but it occurred to me yesterday I never really thought about why it works. First, I checked out the documentation. >From section 3.6 of the Python Library Reference: "The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become ``end'' values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1." >From Section 5.3.3 of the Python Language Reference (x[::-1] is a "proper slice" in the BNF, hence the excerpt): "The conversion of a proper slice is a slice object (see section 3.2) whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions." Following the reference to section 3.2 provides a (non-rigorous) description of what a slice object is, in terms of the extended slicing semantics. But it doesn't shed any additional light on the meaning of [::-1]. >From this, I would expect that x[::-1] would be identical to x[n:0:-1] (n and 0 being the "end" values, with the order switched due to the negative step value). But the clause that "(but never including j)" means that x[n:0:-1] excludes the 1st element of x, x[0]. A quick test in ipython confirms that "abc"[3:0:-1] => "cb", not "cba". Changing the "end" value to x[n:-1:-1] results in an empty string. So my question is: "what exactly is [::-1] shorthand for"? Or is it a special case, in which case why isn't it defined as such in the library? From steve at holdenweb.com Wed Oct 3 16:27:07 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 03 Oct 2007 16:27:07 -0400 Subject: spam kontrol In-Reply-To: <4703f631$0$7692$9b4e6d93@newsspool2.arcor-online.net> References: <1191430790.537383.115880@r29g2000hsg.googlegroups.com> <1191435296.523842.160230@g4g2000hsf.googlegroups.com> <4703f631$0$7692$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Wildemar Wildenburger wrote: > George Sakkis wrote: >> On Oct 3, 12:59 pm, "oruc... at gmail.com" wrote: >>> hii >>> ? think you know spam page is the most pest for net user. >> ...closely followed in the second position by incoherent misspelled >> posts in silly IM-speak. >> >> > You know, there are such people as non-native English speakers. Maybe > you should consider that before possibly insulting people who do not > derserve to be insulted (altough he does appear to be turkish). > > /W > (I aplogize for that last remark. I have nothing against turkish people, > I just couldn't let the opportunity for a mean joke slip.) Does this mean you are an equal-opportunity racist? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From bj_666 at gmx.net Mon Oct 29 05:08:42 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Oct 2007 09:08:42 GMT Subject: sharing vars with different functions References: <1193648594.380143.153450@o38g2000hse.googlegroups.com> Message-ID: <5olm8qFneqbaU1@mid.uni-berlin.de> On Mon, 29 Oct 2007 09:03:14 +0000, scripteaze at gmail.com wrote: > Im tryin to call a var thats sitting in a function, example: > > class someclass(object): > somevar = open(blah, 'r').readlines() Thats a class variable. Is that really what you want!? > def something(): > > for line in somevar: > print line > ----------------------------------------------------------------------- > > i guess im not graspng the whole global or local var topic.. There is no real global here. One is (somewhat) local to the class the other local to the function. > Any examples?? def something(lines): for line in lines: print lines And the call it with the object. Ciao, Marc 'BlackJack' Rintsch From stefan.behnel-n05pAM at web.de Sat Oct 6 16:29:29 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 06 Oct 2007 22:29:29 +0200 Subject: Create a string array of all comments in a html file... In-Reply-To: <1191166775.660477.97840@o80g2000hse.googlegroups.com> References: <1191166775.660477.97840@o80g2000hse.googlegroups.com> Message-ID: <4707F029.1090805@web.de> sophie_newbie wrote: > Hi, I'm wondering how i'd go about extracting a string array of all > comments in a HTML file, HTML comments obviously taking the format > "". > > I'm fairly stumped on how to do this? Maybe using regular expressions? from lxml import etree parser = etree.HTMLParser() tree = etree.parse("somefile.html", parser) print tree.xpath("//comment()") http://codespeak.net/lxml Stefan From steve at holdenweb.com Sun Oct 7 11:57:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 07 Oct 2007 11:57:42 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <13frd6vtarbee75@corp.supernews.com> <47016899$0$4524$9b4e6d93@newsspool3.arcor-online.net> Message-ID: lhb at nowhere.com wrote: > Wildemar Wildenburger wrote in > news:47016899$0$4524$9b4e6d93 at newsspool3.arcor-online.net: > >> While I agree that the word "free" implies "free of monetary cost" to >> many people societies, that is by no means set in stone (talk to native >> americans, blacks, jews, palestinians, etc. about the word free, see >> what they have to say). > > Words are defined by popular usage. In popular usage, the meaning of free > as an adjective depends on the context. If the adjective is applied to > people, it means the opposite of slavery or imprisonment. If it's applied > to something other than people, it means free as in beer. > > For example, a dog with no owner, wandering freely (adverb), would not be > called a free dog (adjective), to mean possessing freedom. Free dog means > free as in beer. Likewise, in popular usage, free software means free as > in beer. People who use it with a different meaning are vainly trying to > change its meaning. But the meanings of words can't be arbitrarily > changed, just by dictating different meanings. The meaning has to be > adopted by popular usage, which free-as-in-GPL software has not been. > > Therefore, I propose, using dog freedom as our logic, we call it stray > software. But that sounds like software that may once have had a good home, but then one day a pack of stray software came into town and called to its wild side, so it left the PC of its birth ... you get the idea. Interestingly, this issue does ultimately hinge on ideas of "property" and "ownership". Amazon (or their lawyers and marketing department together) would like you to believe that "the idea of being able to order a product with a single click" is protectable intellectual property, but ultimately it will be agreed, I predict, that such claims will fail on the grounds of obviousness of invention. though in a country where they regularly show fifth graders to be smarter than adults on network TV one can never be sure. A tide is turning in the world of IP, but only just, and so the ebb is hardly yet underway. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it From steve at REMOVE-THIS-cybersource.com.au Thu Oct 4 19:11:25 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 04 Oct 2007 23:11:25 -0000 Subject: module confusion References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> <874ph8sdhx.fsf@benfinney.id.au> <13g9ch1fi5c7se5@corp.supernews.com> Message-ID: <13gasot6r5bnu1a@corp.supernews.com> On Thu, 04 Oct 2007 23:01:06 +1300, Lawrence D'Oliveiro wrote: > In message <13g9ch1fi5c7se5 at corp.supernews.com>, Steven D'Aprano wrote: > >> ... pedants ... > > When people use that word against me, it's generally a sign they're > trying not to admit I'm right. Yeah, you keep telling yourself that. What does type(os.path) return when you try it? -- Steven. From exarkun at divmod.com Wed Oct 24 16:01:13 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 24 Oct 2007 16:01:13 -0400 Subject: Socket communication problem In-Reply-To: <471FA039.2080206@gmail.com> Message-ID: <20071024200113.8162.602763053.divmod.quotient.27328@ohm> On Wed, 24 Oct 2007 20:42:49 +0100, Sandy Dunlop wrote: >Hi, >I'm new here, and fairly new to Python. I have been playing around with >Python and started having a look at socket IO. I have written a script >that communicates over a network to a server which is written in C. >While trying to get this working, I have been running into a problem >where the Python client appears to hang when it should be receiving data >back from the server. > >After a few successful exchanges of data, the server sends 3605 bytes to >the client, which the client receives. The server then sends 2 bytes to >the client, and the client doesn't get them. A client program written in >C# does not have this problem. Neither the server nor client Python programs you linked to uses the socket API correctly. The most obvious mistake is that the code does not check the return value of socket.send(), which you must do. Twisted is a third-party library which abstracts many of the low-level details of the BSD socket API away from you. You might want to take a look at it. Jean-Paul From mogmios at mlug.missouri.edu Fri Oct 5 05:20:00 2007 From: mogmios at mlug.missouri.edu (Michael) Date: Fri, 5 Oct 2007 03:20:00 -0600 Subject: Duplicate content filter.. In-Reply-To: <1191428555.278268.253700@g4g2000hsf.googlegroups.com> References: <1191428555.278268.253700@g4g2000hsf.googlegroups.com> Message-ID: <58d0a7010710050220l577d48a3i1e28660ef6c9889f@mail.gmail.com> Markov chains maybe? You could probably create a pretty fast db of sorts for checking on word to page relationships and word to word relationships. Or else a normal db could probably do it pretty fast. Break the page into words and remove common words (*prepositions, etc)* and keep a database of word:page pairs. Simply go through the words on the new page and check for other pages with the same words. If any other page scores to high then there you go. I'd probably go with the simple chains as it's a lot lighter solution and could probably be made to be pretty quick. On 10/3/07, Abandoned wrote: > > Hi.. > I'm working a search engine project now. And i have a problem. My > problem is Duplicate Contents.. > I can find the percentage of similarity between two pages but i have a > 5 millions index and i search 5 million page contents to find one > duplicate :( > > I want to a idea for how can i find duplicate pages quickly and fast ? > > Please help me, i'm sorry my bad english. > King regards.. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.bates at websafe.com Wed Oct 31 18:02:49 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 31 Oct 2007 17:02:49 -0500 Subject: Dictionary help In-Reply-To: References: Message-ID: Steve wrote: > I'm currently working on a little database type program is which I'm > using a dictionary to store the information. The key is a component a and > the definition is a list of parts that make up the component. My problem > is I need to list out several components, but not all, and there > associated parts to a printer. Not having any luck. I can list them to > the screen but not the printer. Any help/ideas would be appreciated. > > Steve Windows or Linux or Mac. Printers are handled differently on different platforms. On Windows you can simply open LPT1, LPT2 or LPT3 as a file and write to it (for simple printing). For more complex "Windows" printing you must use Win32 extensions or something like wxWindows. -Larry From tedpottel at gmail.com Thu Oct 18 19:39:46 2007 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Thu, 18 Oct 2007 23:39:46 -0000 Subject: Need scrip to reed rss feeds Message-ID: <1192750786.466914.109080@v23g2000prn.googlegroups.com> Hi, Does any one know whare I can find some code to phrase a rss feeds? Thank you, Ted From george.sakkis at gmail.com Thu Oct 25 06:24:57 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 25 Oct 2007 10:24:57 -0000 Subject: python project ideas In-Reply-To: <47206BF0.1060604@web.de> References: <1193285340.816550.188040@v29g2000prd.googlegroups.com> <47205C66.6090906@web.de> <1193303762.909548.199230@50g2000hsm.googlegroups.com> <47206BF0.1060604@web.de> Message-ID: <1193307897.755168.33370@22g2000hsm.googlegroups.com> On Oct 25, 6:12 am, Stefan Behnel wrote: > Template engines are amongst the things that seem easy enough to look at the > available software and say "bah, I'll write my own in a day", but are complex > enough to keep them growing over years until they become as huge and > inaccessible as all the other implementations. Then it's time for someone else > to look at it and say "bah, I'll write my own in a day". QOTW :) From jim.hefferon at gmail.com Wed Oct 3 08:03:05 2007 From: jim.hefferon at gmail.com (Jim) Date: Wed, 03 Oct 2007 05:03:05 -0700 Subject: toprettyxml messes up with whitespaces In-Reply-To: References: <1191358854.210832.70630@n39g2000hsh.googlegroups.com> <1191405464.131347.18420@r29g2000hsg.googlegroups.com> Message-ID: <1191412985.267747.151360@50g2000hsm.googlegroups.com> On Oct 3, 6:18 am, "Jorgen Bodde" wrote: > Should I file this as a bug to be solved? I have my workaround now, > but I read online that more people seem to have ran into this. Perhaps it is not a bug in that it does not violate the standard. But I know that I have been annoyed by it any number of times. I think it is fair to say that it violates the principle of least surprise. IMHO "

Then a shot rang out.\nHe shouted.

" should be pretty-printed as

Then a shot rang out. He shouted.

That is, I perceive that the "right" behavior is to not add white space to the textual data. No doubt this is a matter of taste and of intended audience (and maybe there are complications that I don't see). But let me urge you to send the mataintainers something. Jim Hefferon From zentraders at gmail.com Wed Oct 17 00:33:57 2007 From: zentraders at gmail.com (Zentrader) Date: Tue, 16 Oct 2007 21:33:57 -0700 Subject: while statements In-Reply-To: <47150b83$0$11925$9a622dc7@news.kpnplanet.nl> References: <47150b83$0$11925$9a622dc7@news.kpnplanet.nl> Message-ID: <1192595637.706075.76830@q3g2000prf.googlegroups.com> O> > while cal <=0: > > #Prompt for calories > > cal = input("Please enter the number of calories in your food: ") > > if cal <=0: > > print "Error. The number of calories must be positive." > > > #Prompt for fat > > fat = input("Please enter the number of fat grams in your food: ") > > if fat <=0: > > print "Error. The number of fat grams must be positive." You can also use a function def get_value( lit ): ret_val = 0 while ret_val <= 0: ret_val = input("Please enter the number of %s in your food: " % (lit)) if ret_val <=0: print "Error. The number of %s must be positive." % (lit) return ret_val # cal = get_value( "calories" ) fat = get_value( "fat grams" ) ## ## Calculate values, etc. From __peter__ at web.de Sat Oct 27 13:31:52 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 27 Oct 2007 19:31:52 +0200 Subject: os.walk and recursive deletion References: Message-ID: Martin Marcher wrote: > Hello, > > I'm playing around with os.walk and I made up del_tree(path) which I > think is correct (in terms of the algorithm, but not as python wants > it :)). > > As soon as some directory is deleted the iterator of os.walk chokes. > OK that is somehow clear to me as it can't be valid anymore since it > can't go to the just deleted directory but it is in the iterator. > > I generated the test data with (bash, don't know of other shell > expansion features) > > # root="test" > # mkdir $root > # mkdir -p > # $root/{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}/{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} > # touch $root/{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}/{0,1,2,3,4,5,6,7,8,9} > # touch $root/{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}/{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}/{0,1,2,3,4,5,6,7,8,9} > > Here goes the script, as far as I tested it it runs fine in test mode. > Now that is just use the print statements like attached below. as soon > as os.rmdir and os.unlink are involved the iterator chokes. How do I > get around that, or what should I use to be able to recursively delete > everything under a certain subdir? > > #--snip > import sys > import os > import unittest > > def del_tree(path): > walker = os.walk(path) > for entry in walker: > cwd = entry[0] > subdirs = entry[1] > files = entry[2] > print "Checking directory: %s" %(cwd, ) > if files: > for file in files: > file = os.path.join(cwd, file) > print "The file is now: %s" % (file, ) > #os.unlink(file) > print "OK directory %s has no more files, checking for > subdirs..." % (cwd, ) > else: > print "OK directory %s NEVER HAD FILES, checking for > subdirs..." % (cwd, ) > if not subdirs: > print "We can delete: %s" % (cwd, ) > #os.rmdir(cwd) > else: > for subdir in subdirs: > subdir = os.path.join(cwd, subdir) > print "We need to recurse into: %s" % (subdir, ) > del_tree(subdir) > #os.rmdir(path) > print "Removing: %s" % (path, ) > #--snap While it is possible to mix recursion and os.walk()... def del_tree(path): for cwd, subdirs, files in os.walk(path): print "Checking directory: %s" %(cwd, ) if files: for file in files: file = os.path.join(cwd, file) print "The file is now: %s" % (file, ) os.unlink(file) print "OK directory %s has no more files, checking for subdirs..." % (cwd, ) else: print "OK directory %s NEVER HAD FILES, checking for subdirs..." % (cwd, ) for subdir in subdirs: subdir = os.path.join(cwd, subdir) print "We need to recurse into: %s" % (subdir, ) del_tree(subdir) break # ugly but necessary print "Removing: %s" % (path, ) os.rmdir(path) ...the idea behind it is that you use it instead of recursion: def del_tree(root): for path, dirs, files in os.walk(root, False): for fn in files: os.unlink(os.path.join(path, fn)) for dn in dirs: os.rmdir(os.path.join(path, dn)) os.rmdir(root) The second parameter to os.walk() ensures that the tree is walked depth-first, i. e. the contents of a directory are seen before the directory itself. Personally, I would prefer a recursive implementation based on os.listdir(), def del_tree(root): for name in os.listdir(root): path = os.path.join(root, name) if os.path.isdir(path): del_tree(path) else: os.unlink(path) os.rmdir(root) an approach that is also taken by shutils.rmtree(). Peter From george.sakkis at gmail.com Thu Oct 18 01:33:48 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 18 Oct 2007 05:33:48 -0000 Subject: Noob questions about Python In-Reply-To: <1192659838.773066.160060@i38g2000prf.googlegroups.com> References: <1192649863.496557.230730@v29g2000prd.googlegroups.com> <1192658316.048082.212190@v23g2000prn.googlegroups.com> <1192659838.773066.160060@i38g2000prf.googlegroups.com> Message-ID: <1192685628.782748.30760@v29g2000prd.googlegroups.com> On Oct 17, 6:23 pm, Paul Hankin wrote: > On Oct 17, 10:58 pm, Ixiaus wrote: > > > > > Thank you for the quick responses. > > > I did not know that about integer literals beginning with a '0', so > > thank you for the explanation. I never really use PHP except for > > handling basic forms and silly web stuff, this is why I picked up > > Python because I want to teach myself a more powerful and broad > > programming language. > > > With regard to why I asked: I wanted to learn about Binary math in > > conjunction with Python, so I wrote a small function that would return > > a base 10 number from a binary number. It is nice to know about the > > int() function now. > > > Just for the sake of it, this was the function I came up with: > > > def bin2dec(val): > > li = list(val) > > li.reverse() > > res = [int(li[x])*2**x for x in range(len(li))] > > res.reverse() > > print sum(res) > > > Now that I look at it, I probably don't need that last reverse() > > because addition is commutative... > > > def bin2dec(val): > > li = list(val) > > li.reverse() > > res = [int(li[x])*2**x for x in range(len(li))] > > print sum(res) > > Right idea: now to remove all those intermediate lists you construct. > 1. reversed(val) creates an iterator that runs over the elements (here > of a string) in reverse order. > 2. enumerate() is usually better than using an explicit list index. > 3. You can use a generator in your sum to avoid constructing the final > list. > > Applying these to your function, and noting that n << k is nicer than > n * 2 ** k, we get a one-liner: > > def bin2dec(val): > return sum(int(i) << k for k, i in enumerate(reversed(val))) > > Or a slightly nicer alternative is to filter the generator using 'if': > > def bin2dec(val): > return sum(1 << k for k, i in enumerate(reversed(val)) if int(i)) Changing the condition to if i=='1' makes it than twice faster. There's also a small improvement by looping forward rather than reversed: def bin2dec_2(val): n = len(val)-1 return sum(1<>= 1 if bit == '1': s += p return s And here's the benchmark: if __name__ == '__main__': # uncomment for Psyco # import psyco; psyco.full() import timeit setup = 'import __main__; bin="101001010001001010"' for func in bin2dec, bin2dec_2, bin2dec_3: name = func.__name__ timer = timeit.Timer('__main__.%s(bin)' % name, setup) print '%s: %s' % (name, timer.timeit()) ### Without Psyco #### bin2dec: 17.6126108206 bin2dec_2: 7.57195732977 bin2dec_3: 5.46163297291 ### With Psyco #### bin2dec: 17.6995679618 bin2dec_2: 8.60846224869 bin2dec_3: 0.16031255369 George From timaranz at gmail.com Thu Oct 4 16:00:39 2007 From: timaranz at gmail.com (timaranz at gmail.com) Date: Thu, 04 Oct 2007 13:00:39 -0700 Subject: Boolean parser.. In-Reply-To: <1191526196.866591.322950@r29g2000hsg.googlegroups.com> References: <1191526196.866591.322950@r29g2000hsg.googlegroups.com> Message-ID: <1191528039.339381.47220@d55g2000hsg.googlegroups.com> On Oct 5, 7:29 am, Abandoned wrote: > Hi.. > I try a boolean parser in python since 1 weak.. But i can't do this > because this is very complicated :( > Do you know any blooean parser script in python or how do i write a > boolean parser ? > example query: ((google or yahoo) or (live msn)) not web > I'm sorry my bad english. > King Regards.. Try the pyparsing module (google it) They have several examples. From lasses_weil at klapptsowieso.net Sun Oct 28 10:47:55 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 28 Oct 2007 15:47:55 +0100 Subject: Return value from os.system() call In-Reply-To: References: Message-ID: <4724a11f$0$16662$9b4e6d93@newsspool3.arcor-online.net> Calder Coalson wrote: > I was searching for ways to get the return value from os.system() calls, > when I came across this from 6 years ago. I tried what was suggested in > this thread, but > output = os.popen("/tmp/other").read() > returns > sh: line 1: /tmp/other: Permission denied > I would assume that this is an OS problem more than a python problem. Do you have write access to /tmp/other? I'm fairly sure its a permission thing. /W From nagle at animats.com Sat Oct 20 11:42:15 2007 From: nagle at animats.com (John Nagle) Date: Sat, 20 Oct 2007 08:42:15 -0700 Subject: Dealing with "funny" characters In-Reply-To: References: <1192886024.889377.118300@e34g2000pro.googlegroups.com> Message-ID: Gert-Jan wrote: > sophie_newbie schreef: >> Hi, I want to store python text strings that characters like "?" "?" >> in a mysql varchar text field. Now my problem is that mysql does not >> seem to accept these characters. I'm wondering if there is any way I >> can somehow "encode" these characters to appear as normal characters >> and then "decode" them when I want to get them out of the database >> again? > > > It seems you'll have to use Unicode in your program rather than 'plain' > strings. > > Before storing an unicode textstring in a database or a file, you must > encode it using an appropriate encoding/codepage, for example: > > outputstring = unicodeobject.encode('utf-8') No, no, that's wrong. MySQL and the Python interface to it understand Unicode. You don't want to convert data to UTF-8 before putting it in a database; the database indexing won't work. Here's how to do it right. First, tell MySQL, before you create your MySQL tables, that the tables are to be stored in Unicode: ALTER database yourdatabasename DEFAULT CHARACTER SET utf8; You can also do this on a table by table basis, or even for single fields, but you'll probably get confused if you do. Then, when you connect to the database in Python, use something like this: db = MySQLdb.connect(host="localhost", use_unicode = True, charset = "utf8", user=username, passwd=password, db=database) That tells MySQLdb to talk to the database in Unicode, and it tells the database (via "charset") that you're talking Unicode. Within Python, you can use Unicode as well. If you have a Unicode text editor, you can create Python source files in Unicode and have Unicode text constants in quotes. If you do this, you should put # -*- coding: UTF-8 -*- as the first line of Python files. Quoted constants should be written as s = u'Test' rather than s = 'Test' Instead of "str()", use "unicode()". Once everything is set up like this, you can pass Unicode in and out of MySQL databases freely, and all the SQL commands will work properly on Unicode data. John Nagle From thermostat at gmail.com Wed Oct 24 11:47:15 2007 From: thermostat at gmail.com (Dan) Date: Wed, 24 Oct 2007 15:47:15 -0000 Subject: optparse help output Message-ID: <1193240835.563154.113810@e9g2000prf.googlegroups.com> I've been using optparse for a while, and I have an option with a number of sub-actions I want to describe in the help section: parser.add_option("-a", "--action", help=\ """Current supported actions: create, build, import, exp_cmd and interact. create -- Vaguely depreciated, should create a new project, but it is not currently suppored. First create a project in SVN, then use import. build -- Build the project (invoking make usually). import -- Put the project under metaman control. Assumes that the current working directory is a SVN-controlled sandbox. Metaman checks out its own copy, does analysis to determine dependencies and the metadata to be collected. interact -- Creates a MetaMan object and starts the python interactive interpreter. Designed for debugging or advanced usage. The MetaMan object is bound to the identifier 'mm'. Only use this option if you know what you're doing. exp_cmd -- add an experiment for strataman. """) Unfortunately, when I run the script with --help, this is what I get for the -a option: -aACTION, --action=ACTION Current supported actions: create, build, import, exp_cmd and interact. create -- Vaguely depreciated, should create a new project, but it is not currently suppored. First create a project in SVN, then use import. build -- Build the project (invoking make usually). import -- Put the project under metaman control. Assumes that the current working directory is a SVN-controlled sandbox. Metaman checks out its own copy, does analysis to determine dependencies and the metadata to be collected. interact -- Creates a MetaMan object and starts the python interactive interpreter. Designed for debugging or advanced usage. The MetaMan object is bound to the identifier 'mm'. Only use this option if you know what you're doing. exp_cmd -- add an experiment for strataman. Is there any way to get the formatting I want? -Dan From gagsl-py2 at yahoo.com.ar Tue Oct 2 23:27:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Oct 2007 00:27:48 -0300 Subject: LastWriteTime in windows registry References: <4701F14F.6020501@timgolden.me.uk> Message-ID: En Tue, 02 Oct 2007 04:20:47 -0300, Tim Golden escribi?: > Peters, Matthew J. ET3 wrote: >> I'm looking for a way to read the lastwritetime property of >> a windows registry key. ... I found the function in perl > > So what does the Perl source say? It presumably hooks some kind > of Windows API. Take that and, if it isn't already exposed via > pywin32, use ctypes to get hold of it. It's already present: see win32api.RegQueryInfoKey -- Gabriel Genellina From ptmcg at austin.rr.com Wed Oct 17 16:37:25 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 17 Oct 2007 13:37:25 -0700 Subject: pyparsing batch file In-Reply-To: References: Message-ID: <1192653445.765147.204870@y27g2000pre.googlegroups.com> On Oct 17, 4:47 pm, Fabian Braennstroem wrote: > Unfortunately, it does not parse the whole file names with > the underscore and I do not know yet, how I can access the > line with 'define/boundary-conditions'. Every 'argument' of > that command should become a separate python variable!? > Does anyone have an idea, how I can achieve this!? > Regards! > Fabian You are trying to match "keps1500_500.dat" with the expression "Word(alphanums)". Since the filename contains characters other than alphas and numbers, you must add the remaining characters ("." and "_") to the expression. Try changing: write= Word(alphanums) to: write= Word(alphanums+"._") To help you to parse "/define/boundary-conditions in velocity-inlet 10 0.1 0.1 no 1", we would need to know just what these arguments are, and what values they can take. I'll take a wild guess, and propose this: real = Combine(integer + "." + integer) defineBoundaryConditions = "/define/boundary-conditions" + \ oneOf("in out inout")("direction") + \ Word(alphanums+"-")("conditionName") + \ integer("magnitude") + \ real("initialX") + \ real("initialY") + \ oneOf("yes no")("optional") + \ integer("normal") (Note I am using the new notation for setting results names, introduced in 1.4.7 - simply follow the expression with ("name"), instead of having to call .setResultsName.) And here is a slight modification to your printout routine, using the dump() method of the ParseResults class: for tokens in defineBoundaryConditions.searchString(data): print print "Boundary Conditions = "+ tokens.conditionName print tokens.dump() print print 50*"-" prints: Boundary Conditions = velocity-inlet ['/define/boundary-conditions', 'in', 'velocity-inlet', '10', '0.1', '0.1', 'no', '1'] - conditionName: velocity-inlet - direction: in - initialX: 0.1 - initialY: 0.1 - magnitude: 10 - normal: 1 - optional: no From adurdin at gmail.com Mon Oct 15 10:27:20 2007 From: adurdin at gmail.com (Andrew Durdin) Date: Mon, 15 Oct 2007 15:27:20 +0100 Subject: EasyMock for python ? In-Reply-To: <87ve9d9icx.fsf@benfinney.id.au> References: <1192034695.321302.26580@o3g2000hsb.googlegroups.com> <87ve9d9icx.fsf@benfinney.id.au> Message-ID: <59e9fd3a0710150727v5dc56210vf63ac000a094d190@mail.gmail.com> On 10/12/07, Ben Finney wrote: > > I've had good results with Ian Bicking's 'minimock.py' > . It uses the existing > 'doctest' functionality for its output, and a minimock.Mock will mock > *everything* (using further Mock instances for attributes and methods) > unless explicitly told otherwise. One problem I can see with the current implementation of using minimock + doctest is that if you have more than one mock object needed for a particular function call in a test, the output from each mock will be interleaved; there should really be some way to use minimock so that you can output a call log from each mock individually after calling the function to test. Of course, that might need to be a feature in still_small_but_slightly_large_than_minimock.py ;-) Andrew From tdwdotnet at gmail.com Tue Oct 9 07:38:02 2007 From: tdwdotnet at gmail.com (Tim Williams) Date: Tue, 9 Oct 2007 12:38:02 +0100 Subject: Editing particular lines of a text file. In-Reply-To: <1191928770.776311.226710@r29g2000hsg.googlegroups.com> References: <1191928770.776311.226710@r29g2000hsg.googlegroups.com> Message-ID: <9afea2ac0710090438t1c4c1635ub86c77f948cbf054@mail.gmail.com> On 09/10/2007, Shriphani wrote: > Hello all, > > I am trying to create a script that looks at specific strings in a > file like: > > msgid "I am a disco dancer." > > and compares the part in quotes to the keys in a dictionary, finds the > value and creates a new line right after this string in the file. I > have planned to write this as follows: > > 1. Open the file in read mode > 2. parse each line to figure out which line contains "msgid" and use > the shlex module's split method to go and split this line and pick the > 2nd element list[1]. > 3. find the value from the dictionary corresponding to the above > element. > 4. Insert the line. This part is where I face a problem. How do I > plainly edit just one line. I would also like to look at some sample > code that does this. > 5. open a new file and write the new file with the inserted strings to > it. > 6. close both files opened. infile = open('infile.txt') outfile = open('outfile.txt','w') for line in infile: if 'msgid' in line: # transform line # make sure the line ending is intact outfile.write(line) infile.close() outfile.close() or maybe infile = open('infile.txt') outfile = open('outfile.txt','w') new_file = [] for line in infile: if 'msgid' in line: # transform line # make sure the line ending is intact new_file.append(line) outfile.write(''.join(new_file) infile.close() outfile.close() -- Tim Williams From ed at leafe.com Fri Oct 26 11:35:08 2007 From: ed at leafe.com (Ed Leafe) Date: Fri, 26 Oct 2007 11:35:08 -0400 Subject: [ANN] Dabo 0.8.2 Released Message-ID: <71A2365A-7028-4121-856B-B86E6FCAFFB4@leafe.com> We are pleased to announce the release of Dabo 0.8.2, the latest version of our desktop application framework. It is available on our download page: http://dabodev.com/download If you're not familiar with Dabo, it is the leading framework for building desktop applications in Python. You can get more information about Dabo on our website: http://dabodev.com Probably the biggest change is in the way we will be handling updates and releases. We will no longer maintain separate 'stable' and 'development' versions, as the 'stable' got out-of-date so quickly that the name became ironic. Instead, we will only have a single development branch. What's made this possible is the incorporation of Web Update into the framework. This will check our servers regularly for updates, and notify you if any are available. If you want to grab those updates, you simply need to click the 'OK' button, and your framework is updated for you. Of course, nothing is ever updated without you knowing about it, and you can turn the whole thing off if you so desire. We are also including DaboDemo and the visual tools in the download, instead of making you grab those separately. We plan on integrating Web Update-like features into these in the near future. As usual, there have been a bunch of minor changes and bugfixes; instead of including them here, you can see them at: http:// svn.dabodev.com/dabo/tags/dabo-0.8.2/ChangeLog -- Ed Leafe -- http://leafe.com -- http://dabodev.com From python.comp.lang.id982 at vbgunz.com Fri Oct 5 12:27:53 2007 From: python.comp.lang.id982 at vbgunz.com (Victor B. Gonzalez) Date: Fri, 5 Oct 2007 12:27:53 -0400 Subject: "SyntaxError: Non-ASCII character '\xc2'...", was Re: Is there a nicer way to do this? In-Reply-To: References: <87ejgawpug.fsf@keizer.soze.com> Message-ID: <200710051227.53254.python.comp.lang.id982@vbgunz.com> On Friday 05 October 2007 3:33:43 am Peter Otten wrote: > Victor B. Gonzalez wrote: > > anyhow, I keep getting "SyntaxError: Non-ASCII character '\xc2'..." on > > line 5. anyone know what this is? > > I too had that problem with KNode. Leading space consists of NO-BREAK SPACE > (unichr(160)) which translates to '\xc2\xa0' in UTF-8. As I don't see this > problem here (using pan) I suspect it may be specific to KMail/KNode. > > Peter You're right, thank you for pointing that out. I am bad with almost anything like \this but stripping off the leading whitespace solved the issue. thank you for the heads up! -- Best Regards Victor B. Gonzalez From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Oct 18 09:29:59 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 18 Oct 2007 15:29:59 +0200 Subject: Noob questions about Python In-Reply-To: <471758e0$0$8995$9b622d9e@news.freenet.de> References: <1192649863.496557.230730@v29g2000prd.googlegroups.com> <47166b47$0$5248$426a74cc@news.free.fr> <471758e0$0$8995$9b622d9e@news.freenet.de> Message-ID: <47175fd6$0$12504$426a74cc@news.free.fr> Stargaming a ?crit : > On Wed, 17 Oct 2007 22:05:36 +0200, Bruno Desthuilliers wrote: > [snip] >> Note that there's also the reverse() function that returns a reverse >> iterator over any sequence, so you could also do: >> >> li = list('allo') >> print ''.join(reverse(li)) >> > > Note this certainly should've been `reversed()`, with a trailing 'd'. 2-0 for Stargaming. I'll have to either change glasses, buy a new keyboard (this one is obviously broken), or learn to both use a keyboard and re-read what I post. From python.list at tim.thechases.com Thu Oct 11 19:23:59 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 11 Oct 2007 18:23:59 -0500 Subject: remove header line when reading/writing files In-Reply-To: <470EAFA2.2060409@tim.thechases.com> References: <1192143175.137620.319470@q5g2000prf.googlegroups.com> <470EAFA2.2060409@tim.thechases.com> Message-ID: <470EB08F.6000607@tim.thechases.com> Forgot the enumerate call of all things > for zipfile in filelist: > for i, line in enumerate(gzip.Gzipfile(zipfile,'r')): > if i: outfile.write(line) Some days, I'm braindead. -tkc From duncan.booth at invalid.invalid Wed Oct 3 17:06:18 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Oct 2007 21:06:18 GMT Subject: Convert on uppercase unaccentent unicode character References: Message-ID: Steve Holden wrote: >> No, that will uppercase the string, but it doesn't (and shouldn't) >> strip the accents: >> > I can agree that is doesn't (though I am taking your word for it), but > a French person will definitely feel it's doing the wrong thing. Upper > case letters aren't accented in written French. > I didn't know that, and I'm not sure I believe it: but then the French tend to have conventions honoured more in the breach than the observance. I just hit a few French websites, and the first one that I found which had any capital letters that might be accented had four accented capital letters on its front page (two capitalized words and two words in block capitals). From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Oct 29 13:30:28 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 29 Oct 2007 18:30:28 +0100 Subject: Built-in functions and keyword arguments In-Reply-To: <1193672801.382944.42180@57g2000hsv.googlegroups.com> References: <1193665924.886459.20710@v3g2000hsg.googlegroups.com> <4725ec3a$0$6623$426a74cc@news.free.fr> <1193672801.382944.42180@57g2000hsv.googlegroups.com> Message-ID: <472618b2$0$11442$426a74cc@news.free.fr> Armando Serrano Lombillo a ?crit : > On Oct 29, 3:20 pm, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Armando Serrano Lombillo a ?crit : >> >>> Why does Python give an error when I try to do this: >>>>>> len(object=[1,2]) >>> Traceback (most recent call last): >>> File "", line 1, in >>> len(object=[1,2]) >>> TypeError: len() takes no keyword arguments >>> but not when I use a "normal" function: >>>>>> def my_len(object): >>> return len(object) >>>>>> my_len(object=[1,2]) >>> 2 >> In the second case, the name of the argument *is* 'object'. Which is not >> the case for the builtin len (which, fwiw, has type >> 'builtin_function_or_method', not 'function', so inspect.getargspec >> couldn't tell me more). > > so that's the point, built-in functions don't behave as normal > functions. >> >> While we're at it, you should avoid using builtin's names for >> identifiers - here, using 'object' as the arg name shadows the builtin >> 'object' class). >> > > As Duncan points out, I was using the name object because it's what > you get when you type help(len) That what I thought. But anyway, you're not the only person reading this newsgroup, and there are a couple gotchas that are worth pointing out for those who don't know yet. >(or in the calltips, or in). Anyway, I > don't think there's any harm in overriding a builtin name in such a > small scope In this specific case, possibly - because there are few chances you need to get at the builtin object type here. Still, it's better to avoid shadowing builtin names IMHO - if only for readability. From bscrivener42 at gmail.com Sat Oct 27 13:45:47 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Sat, 27 Oct 2007 17:45:47 -0000 Subject: how to creating html files with python In-Reply-To: <1193504578.745710.166190@k35g2000prh.googlegroups.com> References: <1193504578.745710.166190@k35g2000prh.googlegroups.com> Message-ID: <1193507147.745397.148340@57g2000hsv.googlegroups.com> On Oct 27, 12:02 pm, George Sakkis wrote: > The only strange thing here is that you think this is a strange > requirement :) This is quite typical, and practically required for web > development. I was wondering about this myself the other day. Suppose you wanted to get by on the cheap without setting up a whole new Joomla or WordPress installation for another smallish blog or website where you are the only poster, and all you need is simple CMS. How hard would it be to create, say, a calendar of events, or news postings using MySQL and Python and HTML. Create the page on your local machine using Python templating, and then just post the HTML code daily? I'm a rank amateur, but was wondering if this is silly and making work, or if one of those templating systems you all are mentioning would work for simple CMS and calendaring? Thanks, rd From mogmios at mlug.missouri.edu Mon Oct 8 06:03:37 2007 From: mogmios at mlug.missouri.edu (Michael) Date: Mon, 8 Oct 2007 04:03:37 -0600 Subject: Top Programming Languages of 2013 In-Reply-To: <20071007060510.5DC811E4006@bag.python.org> References: <20071007060510.5DC811E4006@bag.python.org> Message-ID: <58d0a7010710080303y4e247282jaef5bef3c7253181@mail.gmail.com> I'd guess that by 2013 we'll be using a slightly more graceful, but still horribly wrong (and unsupported by IE 7.666), redo of HTML, CSS, Javascript, Flash, and Java with a poorly conceived back-end marriage of PHP + MySQL or some horrible Microsoft technology for most apps. I'll also venture that as great as Python is it won't have settled on a really good web development framework by then because half it's fans want to copy bloat like Ruby on Rails or .NET and the other half want to be able to develop every line of code themselves and none of them can agree on a single stable easy-to-use Pythonic platform. We still won't have a Python-based Javascript replacement either because nobody can get motivated to replace the crappy client-side scripting language web developers have come to know and hate. 2013 isn't that far away. A few buzzwords will become boring by then and we'll mostly be doing what we're doing now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Sun Oct 7 13:25:48 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 07 Oct 2007 11:25:48 -0600 Subject: weakrefs and bound methods In-Reply-To: <47090ee0$0$11610$3b214f66@tunews.univie.ac.at> References: <4708f276$0$11868$3b214f66@tunews.univie.ac.at> <5msflnFepbdqU1@mid.uni-berlin.de> <47090ee0$0$11610$3b214f66@tunews.univie.ac.at> Message-ID: Mathias Panzenboeck wrote: > Marc 'BlackJack' Rintsch wrote: >> ``del b`` just deletes the name `b`. It does not delete the object. >> There's still the name `_` bound to it in the interactive interpreter. >> `_` stays bound to the last non-`None` result in the interpreter. > > Actually I have the opposite problem. The reference (to the bound method) > gets lost but it shouldn't! Ahh, so you expected that ``Wrapper(self._foo)`` would not immediately lose the reference? It will, because every time you write ``self._foo``, a new bound method is created:: >>> class C(object): ... def foo(self): ... pass ... >>> f = C.foo >>> g = C.foo >>> id(f), id(g) (14931448, 14891008) Thus, there is only the one reference to the bound method, and by wrapping it in a weakref, you are allowing it to disappear immediately:: >>> x = weakref.ref(C.foo) >>> print x() None What behavior do you want here? That is, when were you hoping that the bound method would disappear? STeVe From bj_666 at gmx.net Sat Oct 6 02:28:51 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Oct 2007 06:28:51 GMT Subject: module confusion References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> <874ph8sdhx.fsf@benfinney.id.au> <13g9ch1fi5c7se5@corp.supernews.com> <13gasot6r5bnu1a@corp.supernews.com> <5mm85kFe9gesU1@mid.uni-berlin.de> Message-ID: <5moo92Fehnl3U1@mid.uni-berlin.de> On Sat, 06 Oct 2007 19:16:47 +1300, Lawrence D'Oliveiro wrote: > In message <5mm85kFe9gesU1 at mid.uni-berlin.de>, Marc 'BlackJack' Rintsch > wrote: > >> To me a `variable` is made of a name, a memory address, a data type, and >> a value. In languages like C the address and type are attached to the >> name while in Python both are attached to the value. > > How does C++ with RTTI fit into your picture, then? I'm no C++ expert but I'd say the type is attached to the value too there. Same is true for Java. Ciao, Marc 'BlackJack' Rintsch From stef.mientki at gmail.com Thu Oct 4 18:06:29 2007 From: stef.mientki at gmail.com (stef mientki) Date: Fri, 05 Oct 2007 00:06:29 +0200 Subject: Howto Launch a windows application ? In-Reply-To: <1191451269.731350.134600@g4g2000hsf.googlegroups.com> References: <1191451269.731350.134600@g4g2000hsf.googlegroups.com> Message-ID: <470563E5.30609@gmail.com> Matimus wrote: > stef mientki wrote: > >> hello, >> >> I'm trying to launch a windows application, >> but as many others on this list, I've some trouble. >> I read some other threads about this topic, >> but sorry, I still don't understand all this (never heard of pipes). >> >> When I use a batch file, I can launch the bat-file from python, >> and the windows application launched from the batchfile is run perfectly. >> >> Now when I try to run the same windows application from Popen or call, >> nothing happens (or at least it's very fast and produces not the >> expected output). >> >> Please enlighten me, preferable in "windows-terminology" ;-) >> >> thanks, >> Stef Mientki >> >> from subprocess import * >> >> cmd =[] >> cmd.append ( 'D:\\PIC-tools\\JALxxx\\jalv2_3.exe' ) >> cmd.append ( '-long-start' ) >> cmd.append ( '-d') >> cmd.append ( '-clear' ) >> cmd.append ( '-sD:\\PIC-tools\\JAL\\libs2' ) >> cmd.append ( 'd:\\pic-tools\\jal\\programs\\test_rs232\\test_rs232_hw.jal' ) >> cmd.append ( '>d:\\data_actueel\\d7_test_browser\\temp.log' ) >> >> # DOESN'T WORK >> result = call ( cmd ) >> >> # Both Popen and call work >> cmd = [ 'd:\\data_actueel\\d7_test_browser\\JALcc.bat' ] >> #output = Popen ( cmd ) >> result = call ( cmd ) >> print result >> > > My guess is that with the redirect you simple need to set the 'shell' > option to true. > > call(cmd, shell=True) > > I haven't tested it, but it is worth a try. > > thanks, I tried, but it didn't work. cheers, Stef > Matt > > From bj_666 at gmx.net Sat Oct 27 16:01:23 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Oct 2007 20:01:23 GMT Subject: Proposal: Decimal literals in Python. References: <4721ab28$0$1238$e4fe514c@dreader28.news.xs4all.nl> <1193438763.190428.134710@q5g2000prf.googlegroups.com> <87tzodii6i.fsf@benfinney.id.au> <1193494184.618613.81090@50g2000hsm.googlegroups.com> <1193498867.815682.69050@v3g2000hsg.googlegroups.com> <1193501811.620522.261570@o80g2000hse.googlegroups.com> Message-ID: <5ohjojFmgu6mU7@mid.uni-berlin.de> On Sat, 27 Oct 2007 13:28:02 -0500, Tim Chase wrote: >>> Even clearer is not to allow octal literals :) Is there *any* use for >>> them? >> >> The mode argument to os.chmod. > > You mean instead of > > import this > os.chmod(filename, os.R_OK | os.W_OK | os.X_OK) > > which explicitly (rather than implicitly) spells it out? And the equivalent of ``os.chmod(filename, 0777)`` looks like what!? Ciao, Marc 'BlackJack' Rintsch From chris.lyon at spritenote.co.uk Wed Oct 31 23:09:24 2007 From: chris.lyon at spritenote.co.uk (wyleu) Date: Wed, 31 Oct 2007 20:09:24 -0700 Subject: _tkinter installation in python 2.5 on mandriva with a default 2.4 In-Reply-To: <4728cda0$0$4583$9b622d9e@news.freenet.de> References: <1193775761.764547.148730@i38g2000prf.googlegroups.com> <4727b1e6$0$13390$9b622d9e@news.freenet.de> <1193813238.978699.154830@57g2000hsv.googlegroups.com> <47288E4D.6010301@v.loewis.de> <1193847896.441329.315560@o80g2000hse.googlegroups.com> <4728afce$0$7845$9b622d9e@news.freenet.de> <1193853812.998544.113780@y27g2000pre.googlegroups.com> <4728cda0$0$4583$9b622d9e@news.freenet.de> Message-ID: <1193886564.331628.93620@22g2000hsm.googlegroups.com> On 31 Oct, 18:46, "Martin v. L?wis" wrote: > > Those TK libraries tcllib=None tklib=None tcl_includes=None > > tk_includes=None > > This also contradicts your earlier statement that you have libtk8.4.so > on your machine. [chris at localhost Python-2.5.1]$ ls -las /usr/lib/libtk*.* 0 lrwxrwxrwx 1 root root 13 Oct 31 07:43 /usr/lib/libtk8.4.so -> libtk8.4.so.0* 969 -rwxr-xr-x 1 root root 986216 Apr 21 2006 /usr/lib/libtk8.4.so.0* 1 -rwxr-xr-x 1 root root 119 Apr 21 2006 /usr/lib/libtk.so* 183 -rw-r--r-- 1 root root 186092 Apr 21 2006 /usr/lib/libtkstub8.4.a lib_dir:['/usr/local/lib', '/lib64', '/usr/lib64', '/lib', '/usr/lib'] Inc_dir:['./Include', '.', '/usr/local/include', '/home/chris/ Python-2.5.1/Include', '/home/chris/Python-2.5.1', '/usr/include'] so if libtk is being looked for it should have found it. and indeed it did!! from the print in distutils in unixccompiler.py shared=/usr/lib/libtk8.4.so dylib=/usr/lib/libtk8.4.dylib static=/usr/lib/libtk8.4.a FOUND!:-/usr/lib/libtk8.4.so tklib:-/usr/lib/libtk8.4.so but no tcllib !!! perhaps that's the problem? Did I assume that it was installed by the tk mandriva module ? Perhaps theres a libtcl module to load... Indeed there is ! 787 -rwxr-xr-x 1 root root 800132 Apr 21 2006 /usr/lib/libtcl8.4.so. 0* 1 -rwxr-xr-x 1 root root 122 Apr 21 2006 /usr/lib/libtcl.so* 75 -rw-r--r-- 1 root root 75232 Apr 21 2006 /usr/lib/ libtclstub8.4.a It would seems so ! Thus after make,su, make install... [root at localhost Python-2.5.1]# python2.5 Python 2.5.1 (r251:54863, Oct 30 2007, 19:01:24) [GCC 4.1.1 20060724 (prerelease) (4.1.1-3mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import _tkinter >>> Thank you very much for your help Martin. much learned. From eu_my123 at hotmail.com Fri Oct 12 12:28:01 2007 From: eu_my123 at hotmail.com (TidyTrax@2) Date: Fri, 12 Oct 2007 09:28:01 -0700 Subject: Melhor Site de Downloads [ BIG SITE AND LINKS FASTED] Message-ID: <1192206481.294443.137940@q3g2000prf.googlegroups.com> www.forumgratiz.com.br www.forumgratiz.com.br www.forumgratiz.com.br Download de : Filmes Games XXX Programas Isso e muito ++ totalmente gratis http://www.forumgratiz.com.br/forumb/index.php?act=reg http://www.forumgratiz.com.br/forumb/index.php?act=reg http://www.forumgratiz.com.br/forumb/index.php?act=reg Somente Registrados Podem Ver os T?picos Por Favor Votem Tamb?m http://www.topinho.com/index.php?a=in&u=jeanmartins http://www.topinho.com/index.php?a=in&u=jeanmartins http://www.topinho.com/index.php?a=in&u=jeanmartins Pois o Site Sobrevive disso. .. From khemkaamit at gmail.com Tue Oct 16 06:46:58 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Tue, 16 Oct 2007 16:16:58 +0530 Subject: easy but difficult In-Reply-To: References: Message-ID: <1360b7230710160346y4601047es90858291a0d9ebdb@mail.gmail.com> On 10/16/07, Beema shafreen wrote: > hi everybody, > I have a file separated by hash: > as shown below, > file: > A#1 > B#2 > A#2 > A#3 > B#3 > > I need the result like this: > A 1#2#3 > B 2#3 > > how will generate the result like this from the above file > can somebody tell me what i have to do...... > My code: > fh =open('abc_file','r') > for line in fh.readlines(): > data = line.strip().split('#') > for data[0] in line > print line > > I tried but i donot know how to create 1#2#3 in a single line > regards > shafreen While looping over the file you may store alphabets as key in a dictionary and numbers as values. for example: d = {} for line in open('abc_file'): data = line.strip().split('#') # add the numbers to the 'alphabet' key as a list d[data[0]] = d.get(data[0], []) + [data[1]] Now you can just iterate over the dictionary and write it into a file Cheers, -- -- Amit Khemka From grante at visi.com Tue Oct 2 22:18:25 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 03 Oct 2007 02:18:25 -0000 Subject: gui toolkits: the real story? (Tkinter, PyGTK, etc.) References: <1191287053.541506.88530@d55g2000hsg.googlegroups.com> Message-ID: <13g5uvh698l9h1c@corp.supernews.com> On 2007-10-02, Chris Mellon wrote: > PyGtk has poor cross platform support, a very large footprint (the > largest of all these libraries) It's larger than wxWidgets on top of Gtk? > as well as a complicated runtime environment. It's probably > the closest to suitable for standard library inclusion, but it > doesn't have the binary linking exemption that wxPython does > (theres some question as to how needed that is for Python > code, though) and it's got no compelling API advantage over > Tk. I like the fact that it doesn't include a whole extra scripting language interpreter along with it the way tkinter sucks in Tcl. -- Grant Edwards grante Yow! I'm encased in the at lining of a pure pork visi.com sausage!! From gagsl-py2 at yahoo.com.ar Sun Oct 21 12:43:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Oct 2007 13:43:54 -0300 Subject: Visibility of symbols between extension modules References: <1192965710.4525.16.camel@sup3rkiddo.einstein> Message-ID: En Sun, 21 Oct 2007 08:21:50 -0300, Sudharshan S escribi?: > I have been learning to write extension modules using the C API that > python provides, and have hit a minor roadblock that is turning out to > be major headache. > My project essentially is organized as follows, > > foo > | > --------------------------------- > | | | > bar _foo baz What is foo? a directory? And bar/_foo/baz, source files in C? Each one defining a module object, or is there a single module - foo perhaps? > _foo basically does some init stuff, nothing much. Thats where the > problem starts. The "handler" variable which is initialized in _foo > isn't visible to others. One solution that worked was calling the > initializing function in each of the module's PyMODINIT_FUNC. Debugging > through the interpreter I found out the it loads all the .so's and > executes PyMODINIT_FUNCs. But by doing so, the routine to initialize the > handle gets executed three times, something which i find to be sort of > unclean. Ah, ok, after rereading it I see you have three modules. > The definition of the variable is included in a header and the sources > of the other modules include this master header, So I do have that > variable in scope, but its not initialized. _foo does the job of > declaring that variable. Is it a global C variable, or a module attribute? If you want it to be available to other Python code, it should be a module attribute. In this case, you retrieve the value using PyObject_GetAttrString as with any other object. If it's a global C variable, once it's assigned it should be visible to all (but decades of warning against using global variables can't be wrong...) The single most common error using the Python API is getting wrong the reference counts. If you lose a reference, your object may be garbage collected. If you leak a reference, it will never be freed. Maybe this is what happens here. > I did my share of RTFM and found CObjects as a potential alternative. > But I feel its use rather complicated for a single variable that goes > out of scope. Is there any other way to solve this, or is my approach > itself borked =(?, What am I missing? Perhaps if you explain a bit more what you want to do someone can give some advice. -- Gabriel Genellina From aleax at mac.com Sun Oct 7 16:05:35 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 7 Oct 2007 13:05:35 -0700 Subject: Newbie packages Q References: <1191755440.850529.288860@o3g2000hsb.googlegroups.com> <1191763497.852128.130710@k79g2000hse.googlegroups.com> <4708ebfc$0$21561$426a74cc@news.free.fr> <1191768074.585609.251570@22g2000hsm.googlegroups.com> <4708f9b7$0$4527$9b4e6d93@newsspool3.arcor-online.net> <1191771348.165051.36790@50g2000hsm.googlegroups.com> <47090370$0$32758$426a74cc@news.free.fr> <1191773880.322472.100070@57g2000hsv.googlegroups.com> <47091e82$0$15807$426a74cc@news.free.fr> <1191786525.264853.107630@k79g2000hse.googlegroups.com> Message-ID: <1i5m6we.1wwjdby573v11N%aleax@mac.com> MarkyMarc wrote: ... > > > And sys.path is /python/Test/bpack sys.path must be a LIST. Are you saying you set yours to NOT be a list, but, e.g., a STRING?! (It's hard to tell, as you show no quotes there). > > The 'Test' package is *not* in your sys.path. > > I can say yes to the first: > The atest.py is in the right dir/package. > And the third. If it is not good enough that this /python/Test/bpack > is in the path. > Then I can not understand the package thing. > > I also tried to put /python/ and /python/Test in the sys.path same > result. If the only ITEM in the list that is sys.path is the string '/python', then any Python code you execute will be able to import Test.apack (as well as Test.bpack, or just Test). Alex From Frank.Aune at broadpark.no Fri Oct 19 07:04:43 2007 From: Frank.Aune at broadpark.no (Frank Aune) Date: Fri, 19 Oct 2007 13:04:43 +0200 Subject: python logging module and custom handler specified in config file In-Reply-To: <1192728419.133020.133590@q5g2000prf.googlegroups.com> References: <1192728419.133020.133590@q5g2000prf.googlegroups.com> Message-ID: <200710191304.43944.Frank.Aune@broadpark.no> On Thursday 18 October 2007 19:26:59 Vinay Sajip wrote: > The values in the config file are interpreted in the context of the > logging module's namespace. Hence, one way of achieving what you want > is putting any custom handlers in > a module of your own, and providing a binding in the logging module's > namespace. What if you want to datestamp filenames for filehandlers, say with todays date for example? [handler_file] class=FileHandler level=NOTSET formatter=normal args=('filename.log', 'w') Say you want filenames to be on format filename-YYYYMMDD.log Thanks, Frank From peterbe at gmail.com Mon Oct 15 12:33:26 2007 From: peterbe at gmail.com (Peter Bengtsson) Date: Mon, 15 Oct 2007 16:33:26 -0000 Subject: Normalize a polish L Message-ID: <1192466006.735303.20470@i38g2000prf.googlegroups.com> In UTF8, \u0141 is a capital L with a little dash through it as can be seen in this image: http://static.peterbe.com/lukasz.png I tried this: >>> import unicodedata >>> unicodedata.normalize('NFKD', u'\u0141').encode('ascii','ignore') '' I was hoping it would convert it it 'L' because that's what it visually looks like. And I've seen it becoming a normal ascii L before in other programs such as Thunderbird. I also tried the other forms: 'NFC', 'NFKC', 'NFD', and 'NFKD' but none of them helped. What am I doing wrong? From see.signature at no.spam Tue Oct 16 05:42:57 2007 From: see.signature at no.spam (Eric Brunel) Date: Tue, 16 Oct 2007 11:42:57 +0200 Subject: Python's coming... from unexpected angles. References: <5njcjpFil587U1@mid.uni-berlin.de> <87fy0b4e0e.fsf@benfinney.id.au> Message-ID: On Tue, 16 Oct 2007 11:14:57 +0200, Ben Finney wrote: > "Diez B. Roggisch" writes: > >> Just found this: > > The direct link to the article is > . > >> I do believe that Python should be somewhat more upfront to brandish >> it's merits - but then, sneaky ways are ok with me to... > > Well, it seems like she's an early adopter: she's eager to use PyPy > all the time (though she has aliased it to 'pipi'). Well, I'd definetely vote for a name change for PyPy, as in french, it's pronounced "pee-pee", and yes, it means what you think it means... ;-) -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From mensanator at aol.com Tue Oct 23 18:10:16 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Tue, 23 Oct 2007 15:10:16 -0700 Subject: Anagrams In-Reply-To: <1193173950.629761.182090@t8g2000prg.googlegroups.com> References: <1193127665.868582.257380@z24g2000prh.googlegroups.com> <1193173950.629761.182090@t8g2000prg.googlegroups.com> Message-ID: <1193177416.305472.240010@q3g2000prf.googlegroups.com> On Oct 23, 4:12 pm, "mensana... at aol.com" wrote: > On Oct 23, 3:21 am, cokofree... at gmail.com wrote: > > > > > > > This was from a random website I found on practising good programming > > techniques and I thought I'd see what ways people could find to write > > out this example. Below are my two examples (which should work...). > > > I am merely interested in other techniques people have (without > > resorting to overusage of C modules and such like), just python and > > good computer science techniques. > > > For the wordlist go to this link Kata Anagrams > > Anyway here are my two examples. > > > This one uses a dictionary to store prime values of each letter in the > > alphabet and for each line multiple the results of the characters > > (which is unique for each anagram) and add them to a dictionary for > > printing latter. > >
> > def anagram_finder():
> >     primeAlpha = {'a':2, 'b':3, 'c':5, 'd':7,'e' : 11, 'f':13, 'g':17,
> > 'h':19,        \
> >                   'i':23, 'j':29, 'k':31, 'l':37, 'm':41, 'n':43, 'o':
> > 47, 'p':53,    \
> >                   'q':59, 'r':61, 's':67, 't':71, 'u':73, 'v':79, 'w':
> > 83, 'x':89,    \
> >                   'y':97, 'z':101}
> >     dictAna =  {}
> >     file = open ("wordlist.txt", "r")
> >     for line in file:
> >         value = 1
> >         for s in line:
> >             if s.lower() in primeAlpha:
> >                    value *= primeAlpha[s.lower()]
> >         dictAna.setdefault(value, []).append(line.strip())
> >     file.close()
> >     print "\n".join(['Anagrams are: %s' % (v) for k, v in
> > dictAna.items() if len(dictAna[k]) > 1])
> > 
> > > My second is a little bit simpler. Each dictionary key is an > > alphabetical ordering of the line in question, so that anagrams will > > appear the same. It will add to the dictionary the new word either in > > an existing key, or create a new one for it. > > >
> > def anagram_finder():
> >     dict = {}
> >     file = ('wordlist.txt', 'r')
> >     for line in file:
> >                 strip_line = line.strip().lower()
> >                 sort_line = str(sorted(strip_line))
> >                 dict.setdefault(sort_line, []).append(strip_line)
> >     file.close()
> >     print '\n'.join(['Anagrams are: %s' % (v) for k, v in dict.items()
> > if len(dict[k]) > 1])
> > 
> > > Comparing them with timeit, they both took around 1 second or so, with > > the first being slightly faster. > > > What other ways do people think will work (and do mine actually work > > for other people!) > > ## I took a somewhat different approach. Instead of in a file, > ## I've got my word list (562456 words) in an MS-Access database. > ## And instead of calculating the signature on the fly, I did it > ## once and added the signature as a second field: > ## > ## TABLE CONS_alpha_only_signature_unique > ## -------------------------------------- > ## CONS text 75 > ## signature text 26 > ## > ## The signature is a 26 character string where each character is > ## the count of occurences of the matching letter. Luckily, in > ## only a single case was there more than 9 occurences of any > ## given letter, which turned not to be a word but a series of > ## words concatenated so I just deleted it from the database > ## (lots of crap in the original word list I used). > ## > ## Example: > ## > ## CONS signature > ## aah 20000001000000000000000000 # 'a' occurs twice & 'h' once > ## aahed 20011001000000000000000000 > ## aahing 20000011100001000000000000 > ## aahs 20000001000000000010000000 > ## aaii 20000000200000000000000000 > ## aaker 20001000001000000100000000 > ## aal 20000000000100000000000000 > ## aalborg 21000010000100100100000000 > ## aalesund > 20011000000101000010100000 > ## > ## Any words with identical signatures must be anagrams. > ## > ## Once this was been set up, I wrote a whole bunch of queries > ## to use this table. I use the normal Access drag and drop > ## design, but the SQL can be extracted from each, so I can > ## simply open the query from Python or I can grab the SQL > ## and build it inside the program. The query > ## > ## signatures_anagrams_select_signature > ## > ## is hard coded for criteria 9 & 10 and should be cast inside > ## Python so the criteria can be changed dynamically. > ## > ## > ## QUERY signatures_anagrams_longest > ## --------------------------------- > ## SELECT Len([CONS]) AS Expr1, > ## Count(Cons_alpha_only_signature_unique.CONS) AS > CountOfCONS, > ## Cons_alpha_only_signature_unique.signature > ## FROM Cons_alpha_only_signature_unique > ## GROUP BY Len([CONS]), > ## Cons_alpha_only_signature_unique.signature > ## HAVING (((Count(Cons_alpha_only_signature_unique.CONS))>1)) > ## ORDER BY Len([CONS]) DESC , > ## Count(Cons_alpha_only_signature_unique.CONS) DESC; > ## > ## This is why I don't use SQLite3, must have crosstab queries. > ## > ## QUERY signatures_anagram_summary > ## -------------------------------- > ## TRANSFORM Count(signatures_anagrams_longest.signature) AS > CountOfsignature > ## SELECT signatures_anagrams_longest.Expr1 AS [length of word] > ## FROM signatures_anagrams_longest > ## GROUP BY signatures_anagrams_longest.Expr1 > ## PIVOT signatures_anagrams_longest.CountOfCONS; > ## > ## > ## QUERY signatures_anagrams_select_signature > ## ------------------------------------------ > ## SELECT Len([CONS]) AS Expr1, > ## Count(Cons_alpha_only_signature_unique.CONS) AS > CountOfCONS, > ## Cons_alpha_only_signature_unique.signature > ## FROM Cons_alpha_only_signature_unique > ## GROUP BY Len([CONS]), > ## Cons_alpha_only_signature_unique.signature > ## HAVING (((Len([CONS]))=9) AND > ## ((Count(Cons_alpha_only_signature_unique.CONS))=10)) > ## ORDER BY Len([CONS]) DESC , > ## Count(Cons_alpha_only_signature_unique.CONS) DESC; > ## > ## QUERY signatures_lookup_by_anagram_select_signature > ## --------------------------------------------------- > ## SELECT signatures_anagrams_select_signature.Expr1, > ## signatures_anagrams_select_signature.CountOfCONS, > ## Cons_alpha_only_signature_unique.CONS, > ## Cons_alpha_only_signature_unique.signature > ## FROM signatures_anagrams_select_signature > ## INNER JOIN Cons_alpha_only_signature_unique > ## ON signatures_anagrams_select_signature.signature > ## = Cons_alpha_only_signature_unique.signature; > ## > ## > ## Now it's a simple matter to use the ODBC from Win32 to extract > ## the query output into Python. > > import dbi > import odbc > > con = odbc.odbc("words") > cursor = con.cursor() > > ## This first section grabs the anagram summary. Note that > ## queries act just like tables (as long as they don't have > ## internal dependencies). I read somewhere you can get the > ## field names, but here I put them in by hand. > > ##cursor.execute("SELECT * FROM signature_anagram_summary") > ## > ##results = cursor.fetchall() > ## > ##for i in results: > ## for j in i: > ## print '%4s' % (str(j)), > ## print > > ## (if this wraps, each line is 116 characters) Sorry, s/b 96 characters, I was looking at the line number. Anyway, each line starts with a double hash, so it's easy to fix. > ## 2 3 4 5 6 7 8 9 10 11 12 13 > 14 15 16 17 18 23 > ## 2 259 None None None None None None None None None None None > None None None None None None > ## 3 487 348 218 150 102 None None None None None None None > None None None None None None > ## 4 1343 718 398 236 142 101 51 26 25 9 8 3 > 2 None None None None None > ## 5 3182 1424 777 419 274 163 106 83 53 23 20 10 > 6 4 5 1 3 1 > ## 6 5887 2314 1051 545 302 170 114 54 43 21 15 6 > 5 4 4 2 None None > ## 7 7321 2251 886 390 151 76 49 37 14 7 5 1 > 1 1 None None None None > ## 8 6993 1505 452 166 47 23 8 6 4 2 2 None > None None None None None None > ## 9 5127 830 197 47 17 6 None None 1 None None None > None None None None None None > ## 10 2975 328 66 8 2 None None None None None None None > None None None None None None > ## 11 1579 100 5 4 2 None None None None None None None > None None None None None None > ## 12 781 39 2 1 None None None None None None None None > None None None None None None > ## 13 326 11 2 None None None None None None None None None > None None None None None None > ## 14 166 2 None None None None None None None None None None > None None None None None None > ## 15 91 None 1 None None None None None None None None None > None None None None None None > ## 16 60 None None None None None None None None None None None > None None None None None None > ## 17 35 None None None None None None None None None None None > None None None None None None > ## 18 24 None None None None None None None None None None None > None None None None None None > ## 19 11 None None None None None None None None None None None > None None None None None None > ## 20 6 None None None None None None None None None None None > None None None None None None > ## 21 6 None None None None None None None None None None None > None None None None None None > ## 22 4 None None None None None None None None None None None > None None None None None None > > ## From the query we have the word size as row header and size of > ## anagram set as column header. The data value is the count of > ## how many different anagram sets match the row/column header. > ## > ## For example, there are 7321 different 7-letter signatures that > ## have 2 anagram sets. There is 1 5-letter signature having a > ## 23 member anagram set. > ## > ## We can then pick any of these, say the single 10 member anagram > ## set of 9-letter words, and query out out the anagrams: > > cursor.execute("SELECT * FROM > signatures_lookup_by_anagram_select_signature") > results = cursor.fetchall() > for i in results: > for j in i: > print j, > print > > ## 9 10 anoretics 10101000100001100111000000 > ## 9 10 atroscine 10101000100001100111000000 > ## 9 10 certosina 10101000100001100111000000 > ## 9 10 creations 10101000100001100111000000 > ## 9 10 narcotise 10101000100001100111000000 > ## 9 10 ostracine > > read more ?- Hide quoted text - > > - Show quoted text -... From f.braennstroem at gmx.de Sat Oct 20 07:52:52 2007 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Sat, 20 Oct 2007 11:52:52 +0000 Subject: open remote terminal References: Message-ID: Fabian Braennstroem wrote: > Hi Steve, > > Steve Holden wrote: > >> Fabian Braennstroem wrote: >>> Hi, >>> >>> I would like to use python to start an terminal, e.g. xterm, and login >>> on a remote machine using rsh or ssh. This could be done using 'xterm -e >>> ssh machine', but after the login I would like to jump to a given >>> directory. Does anyone have an idea how to do this with python? >>> >>> Regards! >>> Fabian >>> >> pexpect would be the usual solution, I believe, if you could get it to >> interact correctly with your virtual terminal. >> >> http://pexpect.sourceforge.net/ I actually gave it a first very simple try: import pexpect child=pexpect.spawn('xterm') child.sendline('ls') Unfortunately nothing happens expect the start of xterm!? Does anyone have an idea, what I am doing wrong? Fabian From patrick.waldo at gmail.com Mon Oct 22 12:57:39 2007 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Mon, 22 Oct 2007 16:57:39 -0000 Subject: Problem Converting Word to UTF8 Text File In-Reply-To: References: <1192984543.240902.3790@t8g2000prg.googlegroups.com> <1192991577.355854.264410@v29g2000prd.googlegroups.com> Message-ID: <1193072259.710700.207320@q5g2000prf.googlegroups.com> That KB document was really helpful, but the problem still isn't solved. What's wierd now is that the unicode characters like become ? in some odd conversion. However, I noticed when I try to open the word documents after I run the first for statement that Word gives me a window that says File Conversion and asks me how i want to encode it. None of the unicode options retain the characters. Then I looked some more and found it has a central european option both ISO and Windows which works perfectly since the documents I am looking at are in Czech. Then I try to save the document in word and it says if I try to save it as a text file I will lose the formating! So I guess I'm back at the start. Judging from some internet searches, I'm not the only one having this problem. For some reason Word can only save as .doc even though .txt can support the utf8 format with all these characters. Any ideas? On Oct 22, 5:39 am, "Gabriel Genellina" wrote: > En Sun, 21 Oct 2007 15:32:57 -0300, escribi?: > > > However, I still cannot read the unicode from the Word file. If take > > out the first for-statement, I get a bunch of garbled text, which > > isn't helpful. I would save them all manually, but I want to figure > > out how to do it in Python, since I'm just beginning. > > > My intuition says the problem is with > > > FileFormat=win32com.client.constants.wdFormatText > > > because it converts fine to a text file, just not a utf-8 text file. > > How can I modify this or is there another way to code this type of > > file conversion from *.doc to *.txt with unicode characters? > > Ah! I thought you were getting the right file format. > I can't test it now, but this KB documenthttp://support.microsoft.com/kb/209186/en-us > suggests you should use wdFormatUnicodeText when saving the document. > What the MS docs call "unicode" when dealing with files, is in general > utf16. > In this case, if you want to convert to utf8, the sequence would be: > > f = open(original_filename, "rb") > udata = f.read().decode("utf16") > f.close() > f = open(new_filename, "wb") > f.write(udata.encode("utf8")) > f.close() > > -- > Gabriel Genellina From paul.hankin at gmail.com Thu Oct 11 04:12:32 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 11 Oct 2007 08:12:32 -0000 Subject: for loop question In-Reply-To: <13gr6p3apqjik3c@corp.supernews.com> References: <496954360710101256w2502c99dh5341ade1c0aaa88d@mail.gmail.com> <1192047900.124690.284890@19g2000hsx.googlegroups.com> <13gr6p3apqjik3c@corp.supernews.com> Message-ID: <1192090352.659722.231270@v3g2000hsg.googlegroups.com> On Oct 11, 4:40 am, Steven D'Aprano wrote: > On Wed, 10 Oct 2007 20:25:00 +0000, Paul Hankin wrote: > >> A "works-for-me": > > >> >>> pairs = (test[i:i+2] for i in xrange(len(test)-1)) > >> >>> for a,b in pairs: > >> ... print a,b > > > for a, b in zip(test, test[1:]): > > print a, b > > May be unfortunately slow if test is half a gigabyte of data, what with > essentially making three copies of it. Lazy procedures like the generator > expression above are often much better. > > Just for completion, here's another way: > > prev = test[0] > for i in xrange(1, len(test)): > print prev, test[i] > prev = test[i] Why not just: for i in xrange(len(test) - 1): print test[i], test[i + 1] -- Paul Hankin From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Oct 5 03:28:09 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 05 Oct 2007 09:28:09 +0200 Subject: Mysql class works like php In-Reply-To: References: Message-ID: <4705e772$0$19642$426a74cc@news.free.fr> Andrey a ?crit : > Hi > > just a quick question about using MySQL module... are there any api / class > available to give a higher level in working with Mysql in python? > such as > db.fetch_array(), > db.fetch_rows(), > db.query(), > for eachrow in db.fetch_array(): > xxxx You really find this "higher level" than Python's db-api ??? > just as easy as PHP? D'oh :( // PHP: // suppose we have a valid $connection $q = mysql_query("select * from yaddayadda", $connection) if (is_resource($q)) { while($row = mysql_fetc_row($q)) { do_something_with($row); } mysql_free($q); } else { // handle the error here } # python: # suppose we have a valid connection cursor = connection.cursor() # can specify the kind of cursor here try: cursor.execute("select * from yaddayadda") except MysqlError, e: # handle error here else: for row in cursor: do_something_with(row) # not strictly necessary, you can reuse the same # cursor for another query cursor.close() As far as I'm concerned, I fail to see how PHP is "higher level" or "easier" here. From gagsl-py2 at yahoo.com.ar Sun Oct 28 23:52:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Oct 2007 00:52:30 -0300 Subject: caluclating median distance References: Message-ID: En Sun, 28 Oct 2007 11:13:39 -0300, Beema shafreen escribi?: > 10000175 10000234 43 A_16_P03652190 > 10000277 10000336 387 A_16_P41582022 > 10000723 10000782 98 A_16_P03652191 > > how to calculate the median spacing of an data in the file basically > focusing on the third column of an file. say for example the median > spacing > is to be 635. how do we programtically calculate the median spacing and > sort > the file according to the third column's median spacing. > hope median we calculate using (N+1)/2 I don't understand exactly what you want. To compute the median, the easiest and obvious way is to sort the data first and choose the middle element. For large sets, there are more efficient ways; see this recipe in the Python Cookbook: -- Gabriel Genellina From ggpolo at gmail.com Wed Oct 10 06:15:25 2007 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 10 Oct 2007 07:15:25 -0300 Subject: struct.unpack less than 1 byte In-Reply-To: <1192010223.490715.205380@57g2000hsv.googlegroups.com> References: <1192010223.490715.205380@57g2000hsv.googlegroups.com> Message-ID: 2007/10/10, cprogrammer : > hello all, > > i need to read from a file a struct like this [1byte, 12bits, 12bits] > reading 1 byte or more is not a problem ... but the 12 bits values > are ... > > thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > 12bits, 12bits == 3 byes -- -- Guilherme H. Polo Goncalves From nick.bastin at gmail.com Sun Oct 7 20:43:40 2007 From: nick.bastin at gmail.com (Nicholas Bastin) Date: Sun, 7 Oct 2007 20:43:40 -0400 Subject: Problem using subprocess.Popen on windows In-Reply-To: References: Message-ID: <66d0a6e10710071743m20b5dca8t8678c8ed22406c6a@mail.gmail.com> On 10/7/07, jorma kala wrote: > from subprocess import * > > p1 = Popen(["dir"], stdout=PIPE) > output = p1.communicate()[0] > > > But I get a WindowsError : [Error 2] File Not Found Tim answered your actual question, but why are you doing this in the first place? The Python standard library provides all the functionality that dir will provide and you don't have to parse the output... Look into , and specifically, os.listdir(path). -- Nick From f.guerrieri at gmail.com Tue Oct 16 06:42:10 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Tue, 16 Oct 2007 12:42:10 +0200 Subject: easy but difficult In-Reply-To: References: Message-ID: <79b79e730710160342m519b33c5t19b5277495386536@mail.gmail.com> On 10/16/07, Beema shafreen wrote: > hi everybody, > I have a file separated by hash: > as shown below, > file: > A#1 > B#2 > A#2 > A#3 > B#3 > > I need the result like this: > A 1#2#3 > B 2#3 > > how will generate the result like this from the above file > can somebody tell me what i have to do...... > My code: > fh =open('abc_file','r') > for line in fh.readlines(): > data = line.strip().split('#') > for data[0] in line > print line > > I tried but i donot know how to create 1#2#3 in a single line > regards This certainly seems to be a homework assignment :) You could try if dictionaries or their variants. There is an example very similar example to the task you are trying to solve in the documentation available online on the site docs.python.org francesco From fw3 at hotmail.co.jp Thu Oct 25 12:56:09 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Thu, 25 Oct 2007 16:56:09 +0000 Subject: Need to help to parse the matlab log file. In-Reply-To: <4720c5c3$0$20084$426a74cc@news.free.fr> References: <1193324851.162883.59500@y42g2000hsy.googlegroups.com> <4720c5c3$0$20084$426a74cc@news.free.fr> Message-ID: I have a big log file generated by matlab. Here is a copy of part of it. I want to write a function to parse some results. For example, if I want to get the results of BandWidth and freq_offset_in_KHz, the function will print all lines with contain them as : BandWidth = 10 freq_offset_in_KHz=50 I have submited a similar question to this forum and have not got any answer. May be my first one is too simple. So I decided to send part of the log file. I could not attach the whole file since it is big and restricted by company. This is not a student homework. Thanks Frank Matlab log: ans = 24-Oct-2007 09:53:11 BandWidth = 10 freq_offset_in_KHz = 50 maxPreambMissCount = 1 maxlIterations = 300 testCasesToBeRun = 11 Bandwidth 10.000000 Using config file: config_1024_V1_Acq_2 case_snr = -1 case_backoff = 20 case_refPid = 1 case_refRuns = 300 case_refTOmin = -12.9196 case_refTOmax = 20.8386 case_refTOmean = 3.8924 case_refTOstd = 3.6888 case_refFOEmin = -0.4730 case_refFOEmax = 0.3788 case_refFOEmean = 6.3300e-004 case_refFOEstd = 0.148 _________________________________________________________________ ?????????????????IE7?MSN??????????????? http://promotion.msn.co.jp/ie7/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From kaaveland at gmail.com Wed Oct 10 14:30:12 2007 From: kaaveland at gmail.com (=?iso-8859-1?q?Robin_K=E5veland?=) Date: Wed, 10 Oct 2007 18:30:12 -0000 Subject: Plugins / Modularity Message-ID: <1192041012.099313.282600@d55g2000hsg.googlegroups.com> Hi there. I'm basically in the process of writing my first substantial application in Python, and I've made a couple of (I'd like to say) design decisions so it won't just be a jumble. So, I've divided my program into three sub-packages, core, plugins and utilities. The core will be needed for the program to be run, but I've put it in a package by itself to make things more tidy. The utilities will be things that are handy to have (I'm thinking packages written by others that will make my work easier), but aren't necessary for the program to run. I'm not sure if this is needed yet, but I want to have the option in case it turns out to be useful. The plugins will basically be a package with modules adding functionality to the program, so to make it more extensible, and let others have a very simple way of extending the functionality without having to read a lot of source code and documentation. Adding a plugin should be really simple, preferrably you shouldn't have to modify any existing source, just put a .py file into the directory. This is where I'm sort of stuck. Does anyone know a way I can achieve this? This poses a couple of challenges for me, given the structure of my project and that I have no clue about how to do it. I'm thinking here that every plugin will have a main callable, which will recieve a Request object which can be queried for information, and an Action object which can be used to affect the state of the program to some degree. These will ideally be very simple (And for the moment, they obviously are). What I want, is a moment to 'contact' every module in the plugins package, and send these two objects to it's main callable. I also want to add a way for the program to load and reload plugin modules on the fly, so I can modify them without having to shut it down. Does anyone have some links for me? Alternatively any ideas? Thanks in advance. From robin at NOSPAMreportlab.com Sat Oct 20 10:31:14 2007 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sat, 20 Oct 2007 15:31:14 +0100 Subject: vote for Python - PLEASE In-Reply-To: References: Message-ID: <471A1132.8040604@jessikat.plus.net> Monty Taylor wrote: > Hey everybody, > > MySQL has put up a poll on http://dev.mysql.com asking what your primary > programming language is. Even if you don't use MySQL - please go stick > in a vote for Python. I'm constantly telling folks that Python needs > more love, but PHP and Java are kicking our butts... > > (I know the world would be a better place if the poll were honest, but > I'd rather that people got the message that they should do more python > development work!) > > Thanks! > Monty well I did vote as we use python+mysql; I dispute the value of "kicking our butts" though. When I voted python was running at 39.8% about equal to java+php (41.4%). -- Robin Becker From adam at atlas.st Thu Oct 18 10:47:40 2007 From: adam at atlas.st (Adam Atlas) Date: Thu, 18 Oct 2007 07:47:40 -0700 Subject: Convert string to command.. In-Reply-To: <1192717399.296654.270350@k35g2000prh.googlegroups.com> References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> Message-ID: <1192718860.391481.139090@v29g2000prd.googlegroups.com> On Oct 18, 10:23 am, Abandoned wrote: > I want to convert a string to command.. > For example i have a string: > a="['1']" > I want to do this list.. > How can i do ? Use the builtin function "eval". From python at hope.cz Mon Oct 1 03:42:06 2007 From: python at hope.cz (Johny) Date: Mon, 01 Oct 2007 00:42:06 -0700 Subject: Python and SSL In-Reply-To: <6cydncA2Jpv082DbnZ2dnUVZ_q6dnZ2d@comcast.com> References: <1190959345.041723.108130@k79g2000hse.googlegroups.com> <6cydncA2Jpv082DbnZ2dnUVZ_q6dnZ2d@comcast.com> Message-ID: <1191224526.856466.305980@57g2000hsv.googlegroups.com> On Sep 28, 11:13 pm, Heikki Toivonen wrote: > Johny wrote: > > I need to use Python with SSL comunication betweeen servers. > > (I use hhtplib but I think urllib2 can also be used ) > > I think I need to use SSL root certificate and tell a program to > > trust this certificate. > > You can't do secure SSL with the builtin SSL support, you need to use a > third party module. There are a few available, including M2Crypto, TLS > Lite, pyOpenSSL and pyOpenSSL-extended. Since I am the maintainer Thank you all for help I probably put my question in a wrong way. So again: For the purpose of the application debugging I would like to know how to add a new certification authority to Python( so that my Python program will accept that certificate). By using my Python program I am attempting to trust a certificate signed by a certification authority that Python doesn't trust and that causes the error. Thanks for help. L. From byte8bits at gmail.com Tue Oct 2 11:00:14 2007 From: byte8bits at gmail.com (brad) Date: Tue, 02 Oct 2007 11:00:14 -0400 Subject: Dictionary invalid token error In-Reply-To: References: Message-ID: Tim Chase wrote: > Numbers with leading zeros are parsed as octal. 8 and 9 are invalid > digits in octal. Thus, it falls over. 00 through 07 will work fine, > but 08 and 09 will go kaput. > > http://docs.python.org/ref/integers.html > > -tkc Thanks... that makes sense. I'll store them as strings. From bj_666 at gmx.net Sat Oct 27 01:52:04 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Oct 2007 05:52:04 GMT Subject: Proposal: Decimal literals in Python. References: <4721ab28$0$1238$e4fe514c@dreader28.news.xs4all.nl> <1193438763.190428.134710@q5g2000prf.googlegroups.com> <87tzodii6i.fsf@benfinney.id.au> Message-ID: <5og204Fmh2htU2@mid.uni-berlin.de> On Fri, 26 Oct 2007 19:29:47 -0400, J. Cliff Dyer wrote: > Ben Finney wrote: >> So, the original poster might get further by proposing an '0dNNN.NNN' >> syntax for 'decimal.Decimal' literals. > It would rather be remarkably inconsistent and confusing. > > Python 3.0a1 (py3k:57844, Aug 31 2007, 16:54:27) [MSC v.1310 32 bit > (Intel)] on win32 > >>>> type(0b1) > >>>> type(0o1) > >>>> type(0x1) > >>>> assert 0b1 is 0x1 >>>> That this doesn't raise `AssertionError` is an implementation detail. It's not guaranteed the two objects are really the same. Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Wed Oct 17 11:31:54 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Oct 2007 15:31:54 GMT Subject: Order by value in dictionary References: <1192628375.254492.183140@i38g2000prf.googlegroups.com> <5nmiplFiouurU2@mid.uni-berlin.de> <5nmj7sFiouurU3@mid.uni-berlin.de> <1192630735.734441.199820@q5g2000prf.googlegroups.com> <5nmk3kFiv0krU2@mid.uni-berlin.de> <1192633790.090464.306800@t8g2000prg.googlegroups.com> Message-ID: <5nmo79Fiva37U4@mid.uni-berlin.de> On Wed, 17 Oct 2007 08:09:50 -0700, Abandoned wrote: > Very very thanks everbody.. > > These are some method.. > Now the fastest method is second.. Maybe because the second seems to be the only one that's not processing the whole dictionary but just 500 items less!? You are building way too much intermediate lists in your functions. > ==== 1 === > def sortt(d): > items=d.items() Builds a list of all items. > backitems=[ [v[1],v[0]] for v in items] Builds another list from all items. > backitems.sort() > a=[ backitems[i][1] for i in range(0,len(backitems))] And again a new list *plus* a list of len(backitems) integers that is built just to iterate over it. Instead of iterating directly over `backitems` without the index. > a.reverse() > return a This whole function can be written as (untested): def sortt(d): sorted_items = sorted((item[1], item[0]) for item in d.iteritems(), reverse=True) return map(operator.itemgetter(1), sorted_items) > ==== 2 ===== > import operator > def sortt(d): > backitems=d.items() > boyut=len(backitems) > backitems=backitems[boyut-500:] > backitems=sorted(backitems, key=operator.itemgetter(1)) > a=[ backitems[i][0] for i in range(0,len(backitems))] > a.reverse() > return a Without throwing away 500 items: def sortt(d): sorted_items = sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True) return map(operator.itemgetter(0), sorted_items) Ciao, Marc 'BlackJack' Rintsch From amdescombes at gmail.com Sat Oct 13 07:02:11 2007 From: amdescombes at gmail.com (AMD) Date: Sat, 13 Oct 2007 13:02:11 +0200 Subject: Memory Problems in Windows 2003 Server In-Reply-To: References: <470f7857$0$27795$426a74cc@news.free.fr> Message-ID: <4710a5ad$0$26731$426a74cc@news.free.fr> Hi Brad, I do the reading one line at a time, the problem seems to be with the dictionary I am creating. Andre > amdescombes wrote: >> Hi, >> >> I am using Python 2.5.1 >> I have an application that reads a file and generates a key in a >> dictionary for each line it reads. I have managed to read a 1GB file >> and generate more than 8 million keys on an Windows XP machine with >> only 1GB of memory and all works as expected. When I use the same >> program on a Windows 2003 Server with 2GB of RAM I start getting >> MemoryError exceptions! >> I have tried setting the IMAGE_FILE_LARGE_ADDRESS_AWARE on both >> Python.exe and Python25.dll and setting the /3GB flag on the boot.ini >> file to no avail. I still get the MemoryError exceptions. >> >> Has anybody encountered this problem before? >> >> Thanks in advance for any ideas/suggestions. >> >> Best Regards, >> >> Andr? M. Descombes > > I forgot to mention that the OS itself or other processes may be using a > lot of memory. So, just because you have 2GB, that does not mean you can > access all of that at once. I would guess that 25% of memory is in > constant use by the OS. So, do your IO/reads in smaller chunks similar > to the example I gave earlier. > > Brad From bdesth.quelquechose at free.quelquepart.fr Wed Oct 3 22:23:37 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Oct 2007 04:23:37 +0200 Subject: migrating to packages In-Reply-To: References: <4703C661.50009@fmed.uba.ar> <27E2B61D-3D3E-466D-9650-69E0DA27E952@myemma.com> <47045b29$0$11005$4c368faf@roadrunner.com> <47060d9a$0$30531$426a74cc@news.free.fr> Message-ID: <4706a0f5$0$31740$426a74cc@news.free.fr> Gerardo Herzig a ?crit : > Bruno Desthuilliers wrote: > >> Gerardo Herzig a ?crit : >> >> >>> Carl Bank a ?crit : >>> >>> >>>> Add these lines in __init__.py: >>>> >>>> from MYCLASSES.A import A >>>> from MYCLASSES.B import B >>>> >>>> >>>> >>> >>> Ummm, that works indeed, but forces me to import all (more than A and >>> B) classes, rigth? >>> >> >> >> Why so ? >> >> >> > If the original MYCLASSES.py has 5 different classes ,say A,B,C,D,E , > each one has to be imported where ? In the __init__.py or in the client code ? > (as A and B) in order to be used for the > client code. From the client code POV, it doesn't change anything. > The thing is, there are more than 5 classes, Here again : where ? You know, it's pretty common in Python to have more than one single symbol publicly available from a given module, and you don't *have* to do the java one-class-per-file dance. The main reason for splitting an existing module into multiple submodules of a package is to keep module's size manageable. If each of your classes is so big it need a whole module, then you possibly have another problem... > and looks like > a lot of unnecesary work to me, since a particular program can use 1,2, > or 3 classes at the time.... Then either it import the package and use fqn, or it only imports the needed classes. > Thats why im watching the way to override > the `import statement'....... IMHO, chances are you're going for the wrong solution. From rcdailey at gmail.com Fri Oct 19 18:37:29 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 19 Oct 2007 17:37:29 -0500 Subject: C++ version of the C Python API? Message-ID: <496954360710191537r62ab6f28p3f61ca459fdc2116@mail.gmail.com> Hi, Is there a C++ version of the C Python API packaged with python 2.5? It would be nice to have a OOP approach to embedding python in C++. It would also be a bonus if this C++ Python API cleaned up a lot of the messy code involved in embedding python. Thanks. From zaz600 at gmail.com Thu Oct 25 08:18:42 2007 From: zaz600 at gmail.com (NoName) Date: Thu, 25 Oct 2007 12:18:42 -0000 Subject: about functions question In-Reply-To: <1193305621.987689.24060@o80g2000hse.googlegroups.com> References: <1193293696.450188.108330@q3g2000prf.googlegroups.com> <1193304629.429307.50980@v3g2000hsg.googlegroups.com> <1193305621.987689.24060@o80g2000hse.googlegroups.com> Message-ID: <1193314722.985517.252220@d55g2000hsg.googlegroups.com> sorry! Yes it's work. What about 2 question? Can i put function after main block? print qq() def qq(): return 'hello' Traceback (most recent call last): File "C:\Python25\projects\indexer\test.py", line 1, in print qq() NameError: name 'qq' is not defined Or onli possible: def main(): print qq() def qq(): return 'hello' main() From bdesth.quelquechose at free.quelquepart.fr Tue Oct 23 18:07:03 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 Oct 2007 00:07:03 +0200 Subject: Automatic Generation of Python Class Files In-Reply-To: References: <1193073156.493809.184110@z24g2000prh.googlegroups.com> <1193076352.576143.123260@z24g2000prh.googlegroups.com> <1193078577.129883.317680@k35g2000prh.googlegroups.com> <471d06e2$0$12275$426a74cc@news.free.fr> <471da4b7$0$22586$426a34cc@news.free.fr> <471e431f$0$21451$426a34cc@news.free.fr> Message-ID: <471e713f$0$5252$426a34cc@news.free.fr> Steven Bethard a ?crit : > Bruno Desthuilliers wrote: > >>> I guess as long as your documentation is clear about which attributes >>> require computation and which don't... >> >> >> Why should it ? FWIW, I mentionned that I would obviously not use >> properties for values requiring heavy, non cachable computation. This >> set aside, the fact that the attribute is computed (or not) is none of >> the concerns of client code. I think you know that concept, it's >> called 'encapsulation' !-) > > > Encapsulation doesn't mean having no understanding of the object you're > using. Nope (or not exactly !-) but it means that interface should be decoupled from implemantation, and that, as a user, you shouldn't have have to worry that much about implementation details. > We all use Python lists, knowing that adding to the end is > cheap, and adding to the front is expensive. If you're using someone's > data type, but you have no idea where the performance costs are, you're > just asking for trouble. Indeed. But 1/ this is true weither you use properties only for refactoring plain attributes or you use them righ from the start 2/ I'm sorry to have to repeat it, but I never advised using computed attributes for heavy computations. > That's true even if you're not prematurely > optimizing -- in the case of lists, doing the wrong sort of insert can > make an O(N) algorithm an O(N**2) algorithm. So I don't think this has > anything to do with encapsulation. I can only agree on this. But is this really what we're talking about ? I thought you said - well, let me quote it, it will be simpler (nb: emphasis is yours): """ if you're creating a class for the first time, it should *never* use property() """ Now you're talking about not _abusing_ this feature - a point on which, FWIW, I wholefully agree from the start. Are you saying that using properties is an abuse in itself ? If then, one should only use explicit accessors ? But then, what would prevent anyone to put heavy computations into accessors ? And else - ie, if you think using computed attributes is legitimate for simple things - why not using them right from the start when it makes sens instead of having a strange mix of attribute syntax and explicit accessors syntax (for an implementation that may finally end up using properties under the hood and have explicit accessors just, well, accessing a plain attribute) ? > This really only has to do with what you and I think are natural > programming intuitions. I agree that Python is not Java, or C, or > whatever, but there are a wide variety of precedents in a wide variety > of languages (the Python stdlib included) that lead many programmers to > expect only minimal computation to be performed when accessing > attributes. Should I mention *once again* that I never advertized using properties for heavy computations ?-) > I believe we simply disagree on whether or not Python > programmers need to be trained out of these expectations. I believe we simply disagree on weither properties should be used when it makes sens (from a semantic POV, which doesn't prevent common sens, thanks) or if they should be restricted to refactoring-life-saver. Now since the second use implies that some attributes-looking properties of an object may not be what they looks like - and even worth, may suddenly become (a little bit) more costly without client code being warned - I don't see what's your problem with the first one. Ok, I think we all understood your (quite sensible) concerns about not calling super-heavy-computations without knowing, but (did I say it ?) that's certainly not what I'm talking about, nor how anyone in it's own mind would use this feature. No, don't tell me, I know there are a couple ho-so-very-smart peoples out there that actually will. But what ? There's no cure for stupidity. So far, it seems that most Python users don't suffer from such major brain disorders - I'd even find them suprisingly reasonnable when it comes to black magic -, so I don't think there's a need for such a rule as the one you were suggesting. Ho, and wrt/ training and expectations, I'm afraid you have to live with the fact that computed attributes (either properties and custom descriptors) are alreay widely used. FWIW, may I remind you that a method is actually a callable returned by a computed attribute ?-) From Anthon.van.der.Neut at googlemail.com Thu Oct 11 05:24:12 2007 From: Anthon.van.der.Neut at googlemail.com (Anthon) Date: Thu, 11 Oct 2007 02:24:12 -0700 Subject: Python SVN down? Message-ID: <1192094652.913626.171650@v3g2000hsg.googlegroups.com> I am trying to get at the python source code, but it seems svn.python.org is down, at least on port 80 (http) and 3690 (svn). This happened earlier this week and then it came back (at least yesterday). Are all the real ( ;-) ) developers using ssh+svn and not noticing this? Anthon From stef.mientki at gmail.com Tue Oct 16 17:45:07 2007 From: stef.mientki at gmail.com (stef mientki) Date: Tue, 16 Oct 2007 23:45:07 +0200 Subject: why doesn't have this list a "reply-to" ? Message-ID: <471530E3.9090602@gmail.com> hello, I'm always have great difficulties, replying to this beautiful and helpful list. When I hit the reply button, the message is sent personally to the sender and not to the list. I've subscribed to dozen's of lists, and all have an "reply-to" address, that points to list and not to the individual. cheers, Stef Mientki From wink at saville.com Wed Oct 10 14:41:19 2007 From: wink at saville.com (wink) Date: Wed, 10 Oct 2007 18:41:19 -0000 Subject: Pythonic way for handling file errors Message-ID: <1192041679.657266.320210@o80g2000hse.googlegroups.com> Hello, I would like to know what would be considered the most Pythonic way of handling errors when dealing with files, solutions that seem reasonable using 2.5: ------- try: f = open('afile', 'r') content = f.read() error = 200 except Exception: error = 404 finally: if locals().has_key('f'): f.close() ------ try: f = open('afile', 'r') content = f.read() except Exception: error = 404 else: error = 200 finally: if locals().has_key('f'): f.close() ------- try: f = open('afile', 'r') content = f.read() error = 200 except Exception: error = 404 finally: try: f.close() except Exception: pass ------- try: f = None f = open('afile', 'r') content = f.read() error = 200 except Exception: error = 404 finally: if f: f.close() ---- try: with open('afile', 'r') as f: content = f.read() error = 200 except Exception: error = 404 ---- Of the above I think I like the last one best, but I think I'd really like to have: with open('afile', 'r') as f with exceptions: content = f.read() error = 200 except Exception: error = 404 Another words from looking at PEP343 it is the author of the object returned by the with expression that gets to decide if exceptions are re-raised. But it would seem to me it should be the programmer using it that should decide. Of course as a newbie, I may be way off base. Thanks, Wink Saville From mensanator at aol.com Mon Oct 22 18:37:10 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 22 Oct 2007 15:37:10 -0700 Subject: for loop In-Reply-To: <5o4m5kFktnthU6@mid.uni-berlin.de> References: <5o4m5kFktnthU6@mid.uni-berlin.de> Message-ID: <1193092630.751179.198560@q5g2000prf.googlegroups.com> On Oct 22, 5:22 pm, Marc 'BlackJack' Rintsch wrote: > On Mon, 22 Oct 2007 18:17:56 -0400, Shawn Minisall wrote: > > #Intro > > print "*********************************************" > > print "WELCOME TO THE POPULATION GROWTH CALCULATOR" > > print "*********************************************" > > > print "This program will predict the size of a population of organisms." > > print > > print > > organisms=input("Please enter the starting number of organisms: ") > > > increase=input("Please enter the average daily population increase > > as a percentage (20% = .20): ") > > > days=input("Please enter the number of days that they will multiply: ") > > > print " Day Population" > > print "----------------------------------------------------------" > > > for p in range (days): > > > population = organisms * population * increase > > > print days, > > > print "\t\t\t\t",population > > > I'm having problems with my for loop here to calculate estimated > > population output to a table. Instead of knowing how much I want to > > loop it, the loop index is going to be whatever number of days the user > > enters. When I run my program, it asks the 3 questions above but then > > just dead stops at a prompt which leads me to believe there's something > > wrong with my loop. > > It should not run at all as it is indented inconsistently. If that > problem is corrected it will stop with a `NameError` because you try to > read `population` before anything was assigned to it. > > Ciao, > Marc 'BlackJack' Rintsch Also, I would guess that you want to print p, not days. From aleax at mac.com Wed Oct 17 11:13:31 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 17 Oct 2007 08:13:31 -0700 Subject: Inheriting automatic attributes initializer considered harmful? References: Message-ID: <1i64bxc.7f41mi1tsdr45N%aleax@mac.com> Andrew Durdin wrote: > On 10/17/07, Thomas Wittek wrote: > > > > Writing such constructors for all classes is very tedious. > > So I subclass them from this base class to avoid writing these constructors: > > > > class AutoInitAttributes(object): > > def __init__(self, **kwargs): > > for k, v in kwargs.items(): > > getattr(self, k) # assure that the attribute exits > > setattr(self, k, v) > > > > Is there already a standard lib class doing (something like) this? > > Or is it even harmful to do this? > > It depends on your kwargs and where they're coming from. You could do > something like this, for example: > > def fake_str(self): > return "not a User" > > u = User(__str__=fake_str) > str(u) ...and, if you did, that would be totally harmless (in a new-style class as shown by the OP): >>> class AutoInitAttributes(object): ... def __init__(self, **kwargs): ... for k, v in kwargs.items(): ... getattr(self, k) # assure that the attribute exits ... setattr(self, k, v) ... >>> class User(AutoInitAttributes): pass ... >>> def fake_str(self): ... return "not a User" ... >>> u = User(__str__=fake_str) >>> str(u) '<__main__.User object at 0x635f0>' >>> fake_str is not called, because special-method lookup occurs on the TYPE, *NOT* on the instance. The OP's idea is handy for some "generic containers" (I published it as the "Bunch" class back in 2001 in , and I doubt it was original even then); it's not particularly recommended for classes that need to have some specific *NON*-special methods, because then the "overwriting" issue MIGHT possibly be a (minor) annoyance. Alex From israelu at elbit.co.il Mon Oct 22 08:33:35 2007 From: israelu at elbit.co.il (iu2) Date: Mon, 22 Oct 2007 05:33:35 -0700 Subject: Failure to connect in SimpleXMLRPCServer/xmlrpclib In-Reply-To: References: <1193034835.803633.121600@z24g2000prh.googlegroups.com> Message-ID: <1193056415.104998.16270@q3g2000prf.googlegroups.com> On Oct 22, 12:47 pm, "J. Cliff Dyer" wrote: > iu2 wrote: > > Hi all, > > > I've copied the example of RPC usage from the Python's doc. > > When the client and server were on the same PC ("localhost") (I use > > Windows) > > it worked ok. But putting the server on a different PC raised the > > error: > > > gaierror: (11001, 'getaddrinfo failed') > > The error was raised upion accessing some function of the server, > > i.e., > > print s.add_nums(1, 2, 3) # server registered function > > > PCs in our organization are accessed by "\\" so I used > > > s = xmlrpclib.Server(r'http://\\pc_name:8000') > > I got the same error when I put some non-existing name. > > Trying to remove the double-backslash from the PC's name raised the > > error: > > error: (10061, 'Connection refused') > > > I'll appreciate your help on this. > > > Thanks > > iu2 > > Don't use the \\. That's a windows networking convention, and it does > not apply if you are using http. Your error messages tell you this. > The first one (r'http://\\pc_name:8000') could not resolve the address. > The second one reached the server just fine, but the server rejected the > client's request. So now the issue is why is the request being > rejected? Did you check your firewall to see if it is blocking access > to port 8000 on the ethernet adapter? > > Cheers, > Cliff- Hide quoted text - > > - Show quoted text - Cliff and Diez, thanks. That helped. The server indeed was listening on 127.0.0.1. I changed the hostname from "localhost" to socket.gethostname() and it worked! From cokofreedom at gmail.com Thu Oct 11 11:25:09 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 11 Oct 2007 15:25:09 -0000 Subject: Finding Peoples' Names in Files In-Reply-To: References: Message-ID: <1192116309.880026.83240@r29g2000hsg.googlegroups.com> On Oct 11, 5:22 pm, brad wrote: > Crazy question, but has anyone attempted this or seen Python code that > does? For example, if a text file contained 'Guido' and or 'Robert' and > or 'Susan', then we should return True, otherwise return False. Can't you just use the string function .findall() ? From trekker182 at comcast.net Wed Oct 24 18:30:39 2007 From: trekker182 at comcast.net (Shawn Minisall) Date: Wed, 24 Oct 2007 18:30:39 -0400 Subject: for loop In-Reply-To: <1193114335.616347.146300@e34g2000pro.googlegroups.com> References: <5o4m5kFktnthU6@mid.uni-berlin.de> <1193092630.751179.198560@q5g2000prf.googlegroups.com> <1193094348.431443.237740@q3g2000prf.googlegroups.com> <1193114335.616347.146300@e34g2000pro.googlegroups.com> Message-ID: <471FC78F.80106@comcast.net> I agree, but if I want to get a A on the program, thats how my professor wants the output. :) mensanator at aol.com wrote: > On Oct 22, 9:12?pm, Shawn Minisall wrote: > >> Thanks, everyone! Using everyone's suggestions and points, the program >> is working great now. >> > > Actually, it's not. I assume not printing the population > was a copy error. > > But, by adding the "if (p>1):", you have now made > day 1 the initial population, so if you ask for > 8 days of multiplication, you actually only get 7. > > Although your code is working, it's not giving you > the correct answer. Most of the time in these kinds > of problems, days means elapsed days. That means for > 100 organisms @ 25% growth/day, there will be 125 > after 1 elapsed day. But that "if (p>1):" means you > show 100 at day 1, which is wrong. You have 100 after > 0 elapsed days (or day 0). > > > >> Here's the updated code. >> >> :) >> >> import math >> >> def main(): >> #Declare and initialize variables >> #starting number of organisms >> organisms = 0 >> #average daily population increase as % >> increase = 0.0 >> #number of days they will multiply >> days = 0 >> #population prediction >> population = 0.0 >> >> #Intro >> print "*********************************************" >> print "WELCOME TO THE POPULATION GROWTH CALCULATOR" >> print "*********************************************" >> >> print "This program will predict the size of a population of organisms." >> print >> print >> while organisms <=1: >> organisms=input("Please enter the starting number of organisms: ") >> if organisms <=1: >> print "Error. Population must be at least two." >> >> while increase <=0: >> increase=input("Please enter the average daily population >> increase as a percentage (20% = .20): ") >> if increase <=0: >> print "The percent of increase must be positive." >> >> while days <=0: >> days=input("Please enter the number of days that they will >> multiply: ") >> if days <=0: >> print "The number of days must be positive." >> >> print " Day Population" >> print "----------------------------------------------------------" >> population = organisms >> >> for p in range (1,days+1): >> if( p > 1 ): >> population = population + ( population * increase ) >> >> print "\t",p, >> >> >> >> mensana... at aol.com wrote: >> >>> On Oct 22, 5:37 pm, "mensana... at aol.com" wrote: >>> >>>> On Oct 22, 5:22 pm, Marc 'BlackJack' Rintsch wrote: >>>> >>>>> On Mon, 22 Oct 2007 18:17:56 -0400, Shawn Minisall wrote: >>>>> >>>>>> #Intro >>>>>> print "*********************************************" >>>>>> print "WELCOME TO THE POPULATION GROWTH CALCULATOR" >>>>>> print "*********************************************" >>>>>> >>>>>> print "This program will predict the size of a population of organisms." >>>>>> print >>>>>> print >>>>>> organisms=input("Please enter the starting number of organisms: ") >>>>>> >>>>>> increase=input("Please enter the average daily population increase >>>>>> as a percentage (20% = .20): ") >>>>>> >>>>>> days=input("Please enter the number of days that they will multiply: ") >>>>>> >>>>>> print " Day Population" >>>>>> print "----------------------------------------------------------" >>>>>> >>>>>> for p in range (days): >>>>>> >>>>>> population = organisms * population * increase >>>>>> >>>>>> print days, >>>>>> >>>>>> print "\t\t\t\t",population >>>>>> >>>>>> I'm having problems with my for loop here to calculate estimated >>>>>> population output to a table. Instead of knowing how much I want to >>>>>> loop it, the loop index is going to be whatever number of days the user >>>>>> enters. When I run my program, it asks the 3 questions above but then >>>>>> just dead stops at a prompt which leads me to believe there's something >>>>>> wrong with my loop. >>>>>> >>>>> It should not run at all as it is indented inconsistently. If that >>>>> problem is corrected it will stop with a `NameError` because you try to >>>>> read `population` before anything was assigned to it. >>>>> >>>>> Ciao, >>>>> Marc 'BlackJack' Rintsch >>>>> >>>> Also, I would guess that you want to print p, not days >>>> >>> Oh, and your calculation is incorrect. You don't multiply by >>> organisms in every loop iteration, organisms is the initial >>> value of population, so you can solve the "Name" error by doing >>> population = organisms before the for..loop. >>> >>> And since you're asking for an increase, you don't multiply by the >>> percent (as that would decrease the population), but instead by >>> 1+increase. >>> >>> Also, does day==0 represent the first day of increase or the >>> initial value? One would normally expect day==0 to be the initial >>> value, but as written, day==0 is the first day of increase. I >>> would use xrange(1,days+1) instead. >>> >>> Lastly, you can't have a fraction of an organism, right? You might >>> want to print your floating point population rounded to an integer. >>> >>> population = organisms >>> for p in xrange(1,days+1): >>> population = population * (1 + increase) >>> print p, >>> print "\t\t\t\t%0.0f" % (population) >>> >>> ## ********************************************* >>> ## WELCOME TO THE POPULATION GROWTH CALCULATOR >>> ## ********************************************* >>> ## This program will predict the size of a population of organisms. >>> ## >>> ## >>> ## Please enter the starting number of organisms: 100 >>> ## Please enter the average daily population increase as a percentage >>> (20% = .20): 0.25 >>> ## Please enter the number of days that they will multiply: 8 >>> ## Day Population >>> ## ---------------------------------------------------------- >>> ## 1 125 >>> ## 2 156 >>> ## 3 195 >>> ## 4 244 >>> ## 5 305 >>> ## 6 381 >>> ## 7 477 >>> ## 8 596- Hide quoted text - >>> >> - Show quoted text - >> > > > From prabavaguru.kcas at gmail.com Mon Oct 15 09:49:17 2007 From: prabavaguru.kcas at gmail.com (praba) Date: Mon, 15 Oct 2007 06:49:17 -0700 Subject: Online Jobs.Earn Rs.50000 every month. Message-ID: <1192456157.272467.62020@v23g2000prn.googlegroups.com> Online Jobs.Earn Rs.50000 every month. http://readymademoney.blogspot.com/ From gmguyx at gmail.com Sat Oct 27 03:29:39 2007 From: gmguyx at gmail.com (gmguyx) Date: Sat, 27 Oct 2007 00:29:39 -0700 Subject: cannot open webpage which requires authentication Message-ID: <1193470179.922850.90410@v23g2000prn.googlegroups.com> I tried using urllib.urlopen to open a personalized webpage (my.yahoo.com) but it doesn't work: print urllib.urlopen(http://my.yahoo.com).read() Instead of returning my.yahoo.com, it returns a page asking me to log in. So then I tried urllib.urlencode: data = urllib.urlencode({'action': 'https://login.yahoo.com/config/ login?', 'login': , 'passwd': }) print urllib.urlopen(http://my.yahoo.com, data).read() However, this doesn't work either. Is there a way to do this? Thanks in advance. From rbonvall at gmail.com Tue Oct 16 12:51:47 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Tue, 16 Oct 2007 16:51:47 -0000 Subject: Normalize a polish L In-Reply-To: <1192485438.934146.139740@q5g2000prf.googlegroups.com> References: <1192466006.735303.20470@i38g2000prf.googlegroups.com> <1192485438.934146.139740@q5g2000prf.googlegroups.com> Message-ID: <1192553507.049705.17200@z24g2000prh.googlegroups.com> On Oct 15, 6:57 pm, John Machin wrote: > To "asciify" such text, you need to build a look-up table that suits > your purpose. unicodedata.decomposition() is (accidentally) useful in > providing *some* of the entries for such a table. This is the only approach that can actually work, because every language has different conventions on how to represent text without diacritics. For example, in Spanish, "?" (u with umlaut) should be represented as "u", but in German, it should be represented as "ue". ping?ino -> pinguino Fr?hst?ck -> Fruehstueck I'd like that web applications (e.g. blogs) took into account these conventions when creating URLs from the title of an article. -- Roberto Bonvallet From korovev76 at gmail.com Tue Oct 23 14:29:17 2007 From: korovev76 at gmail.com (korovev76 at gmail.com) Date: Tue, 23 Oct 2007 11:29:17 -0700 Subject: Root element name not declared Message-ID: <1193164157.943495.226850@z24g2000prh.googlegroups.com> Hi guys, i'm using pyrxp to parse some xml like this one: abc def ..... where the dtd is defined like this: ,,,,, While parsing, I receive an error like this one: Root element name MyMessage not declared.... Being both the file and the dtd provided by the supplier, I believe they're correct so I don't understand what's wrong. MyMessage IS declared... isn't it sufficient? Thanx korovev From horpner at yahoo.com Tue Oct 30 11:25:54 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 30 Oct 2007 15:25:54 GMT Subject: setting variables in outer functions References: <87myu1k4rm.fsf@mulj.homelinux.net> Message-ID: On 2007-10-29, Steven Bethard wrote: > Hrvoje Niksic wrote: >> Tommy Nordgren writes: >> >>> Given the following: >>> def outer(arg) >>> avar = '' >>> def inner1(arg2) >>> # How can I set 'avar' here ? >> >> I don't think you can, until Python 3: >> http://www.python.org/dev/peps/pep-3104/ > > But it definitely does work in Python 3 if you use 'nonlocal':: > > Python 3.0a1+ (py3k:58681, Oct 26 2007, 19:44:30) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more > information. > >>> def f(): > ... x = 1 > ... def g(): > ... nonlocal x > ... x = 2 > ... print(x) > ... g() > ... print(x) > ... > >>> f() > 1 > 2 > > That said, I'd like to see the reason you think you want to do > this. It's allows a standard programming idiom which provides a primitive form of object oriented programming using closures to represent state. def account(opening_balance): balance = opening_balance def get_balance(): nonlocal balance return balance def post_transaction(x): nonlocal balance balance += x return balance, post_transaction fred_balance, fred_post = account(1500) joe_balance, joe_post = account(12) fred_post(20) joe_post(-10) fred_balance() 1520 joe_balance() 2 Python classes will of course nearly always win, though the idiom looks like it might be faster (I don't have Python 3000 to try it out). -- Neil Cerutti It isn't pollution that is hurting the environment; it's the impurities in our air and water that are doing it. --Dan Quayle From ptmcg at austin.rr.com Tue Oct 2 18:23:37 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 02 Oct 2007 15:23:37 -0700 Subject: List Question In-Reply-To: References: <1191360038.845477.170160@22g2000hsm.googlegroups.com> Message-ID: <1191363817.022851.308170@y42g2000hsy.googlegroups.com> On Oct 2, 4:58 pm, Pablo Ziliani wrote: > Paul Hankin wrote: > > On Oct 2, 10:06 pm, brad wrote: > > >> How is this expressed in Python? > > >> If x is in y more than three times: > >> print x > > >> y is a Python list. > > > Simple and readable: > > if len([a for a in y if x == a]) > 3: > > print x > > > Or the slightly-too-flashy version: > > if sum(1 for a in y if x == a) > 3: > > print x > > > > I always use this full-featured, all-inclusive, rock-solid version (see > the try/except block): > > count = i = 0 > x = 1 > y = [1,2,3,4,5,1,2,3,4,1,2,1] > try: > while count < 3: > if y[i] == x: > count += 1 > i += 1 > except RuntimeError: > pass > except IndexError: > pass > else: > print x > > > > Sorry, couldn't resist...- Hide quoted text - > > - Show quoted text - Well, there is an advantage to your method/madness, in that it does short-circuiting once the magic count of 3 is found. If the list contained *many* entries, or if the predicate were expensive to evaluate, or if the count were likely to be satisfied within the first few list elements, your approach beats the other count or sum suggestions (since they evaluate all list entries). Here's a version of your code using itertools.takewhile: count = 0 for a in itertools.takewhile(lambda _:count<3,y): count += (x==a) if count==3: print x -- Paul From mail at microcorp.co.za Sun Oct 28 03:55:15 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 28 Oct 2007 09:55:15 +0200 Subject: Proposal: Decimal literals in Python. References: <4721ab28$0$1238$e4fe514c@dreader28.news.xs4all.nl><1193438763.190428.134710@q5g2000prf.googlegroups.com><87tzodii6i.fsf@benfinney.id.au><1193494184.618613.81090@50g2000hsm.googlegroups.com> <1193498867.815682.69050@v3g2000hsg.googlegroups.com> Message-ID: <006801c81937$e0f04ec0$03000080@hendrik> "Paul Hankin" wrote: > Even clearer is not to allow octal literals :) Is there *any* use for > them? I tend to agree with this point of view - but I fear it will set up a howl of protest amongst the Brits who cut their teeth on 24 bit ICT/ICL equipment... - Hendrik From steve at holdenweb.com Fri Oct 5 07:44:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 05 Oct 2007 07:44:46 -0400 Subject: Python Magazine: Issue 1 Free! Message-ID: I've just been told by the editors at Python Magazine that the first issue is out. It's all-electronic so anyone can download and read it. Let them know what you think: http://www.pythonmagazine.com/c/issue/2007/10 regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it From alan.isaac at gmail.com Mon Oct 29 12:10:24 2007 From: alan.isaac at gmail.com (Alan Isaac) Date: Mon, 29 Oct 2007 12:10:24 -0400 Subject: simple try/except question In-Reply-To: References: Message-ID: <472605F0.5070909@american.edu> Tim Chase wrote: > It works for me(tm)... > Python 2.4.3 Sorry to have left out that detail. Yes, it works for me in Python 2.4, but not in 2.5.1. The code I posted was copyied from the interpreter. Alan Isaac From goldtech at worldpost.com Sat Oct 6 23:18:02 2007 From: goldtech at worldpost.com (goldtech) Date: Sat, 06 Oct 2007 20:18:02 -0700 Subject: Tkinter text widget Message-ID: <1191727082.655903.15590@w3g2000hsg.googlegroups.com> I thought the "DISABLED" made it so I could not edit it. But it also makes it so I can not scroll down. If you make the window smaller than the content then try to put a cursor in there to use up/down arrow you can't. What I want is not to be able to change text content, but no other action is disabled. Is this complicated to do? Thanks. from Tkinter import * root = Tk() text = Text(root, font=("Courier")) text.pack() i='123456789abcdefghijklmnopqrstuvwxyz\n' for x in range(30): text.insert(END, i) text.config(state=DISABLED) mainloop() From paul.hankin at gmail.com Sat Oct 27 11:27:47 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 27 Oct 2007 15:27:47 -0000 Subject: Proposal: Decimal literals in Python. In-Reply-To: <1193494184.618613.81090@50g2000hsm.googlegroups.com> References: <4721ab28$0$1238$e4fe514c@dreader28.news.xs4all.nl> <1193438763.190428.134710@q5g2000prf.googlegroups.com> <87tzodii6i.fsf@benfinney.id.au> <1193494184.618613.81090@50g2000hsm.googlegroups.com> Message-ID: <1193498867.815682.69050@v3g2000hsg.googlegroups.com> On Oct 27, 3:09 pm, MRAB wrote: > On Oct 27, 12:12 am, Ben Finney > wrote:> Matimus writes: > > > The trailing L [for 'long' literals] is going away in Python 3.0. > > > Yes. On the other hand, we are gaining '0bNNNN' for binary literals, > > to go along with '0oNNNN' for octal and '0xNNNN' for hexadecimal. > > > So, the original poster might get further by proposing an '0dNNN.NNN' > > syntax for 'decimal.Decimal' literals. At least the syntax would be > > consistent and wouldn't add a new punctuation character to the > > language... > > [snip] > Some languages have or permit 0qNNNN or 0QNNNN for octal to reduce the > chance of confusion of 'O' (oh) with '0' (zero) in uppercase, eg. > 0Q123 is clearer than 0O123 (0 oh 123), although lowercase is better, > eg. 0q123 or 0o123. Even clearer is not to allow octal literals :) Is there *any* use for them? -- Paul Hankin From beema.shafreen at gmail.com Tue Oct 30 01:28:18 2007 From: beema.shafreen at gmail.com (Beema shafreen) Date: Tue, 30 Oct 2007 10:58:18 +0530 Subject: appending into a list Message-ID: hi everybody, I have a file : A B C D E 2717353 2717412 A_16_P03641964 214 -59 2717626 2717685 A_16_P41563655 25 -59 2717710 2717754 A_16_P03641965 1250 -44 2719004 2719063 A_16_P03641966 -36 -59 2719027 2719086 A_16_P21360229 289 -59 2719375 2719428 A_16_P03641967 60 -53 2719488 2719542 A_16_P21360231 418 -54 2719960 2720014 A_16_P03641968 727 -54 2720741 2720786 A_16_P03641969 494 -45 2721280 2721339 A_16_P03641970 -28 -59 2721311 2721370 A_16_P21360234 150 -59 2721520 2721569 A_16_P21360235 199 -49 2721768 2721821 A_16_P03641971 139 -53 2721960 2722004 A_16_P21360237 312 -44 I need to append the column D and E into a list: in such a way that the list should have [D,E,D,E,D,E........] How do i do it. regards shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From besturk at gmail.com Wed Oct 31 17:39:05 2007 From: besturk at gmail.com (Abandoned) Date: Wed, 31 Oct 2007 21:39:05 -0000 Subject: 3 number and dot.. In-Reply-To: <1193863848.080615.191090@v3g2000hsg.googlegroups.com> References: <1193860737.687984.13400@k79g2000hse.googlegroups.com> <1193863848.080615.191090@v3g2000hsg.googlegroups.com> Message-ID: <1193866745.406360.62830@z9g2000hsf.googlegroups.com> On Oct 31, 10:50 pm, Roberto Bonvallet wrote: > On 31 oct, 16:58, Abandoned wrote: > > > > > Hi.. > > I want to do this: > > for examle: > > 12332321 ==> 12.332.321 > > > How can i do? > >>> x = 12332321 > >>> '.'.join(''.join(i for n, i in g) for k, g in groupby(enumerate(reversed(str(x))), lambda (n, i): n//3))[::-1] > '12.332.321' > > -- > Roberto Bonvallet I'm sorry but it give me error "no module named groupby" My python version is 2.51 From bcd at pvv.ntnu.no Wed Oct 3 14:20:38 2007 From: bcd at pvv.ntnu.no (Bent C Dalager) Date: Wed, 3 Oct 2007 18:20:38 +0000 (UTC) Subject: The Modernization of Emacs: terminology buffer and keybinding References: <13frd6vtarbee75@corp.supernews.com> <85ve9ov971.fsf@lola.goethe.zz> Message-ID: In article , George Neuner wrote: >On Wed, 3 Oct 2007 09:36:40 +0000 (UTC), bcd at pvv.ntnu.no (Bent C >Dalager) wrote: > >> >>Only if you're being exceedingly pedantic and probably not even >>then. Webster 1913 lists, among other meanings, >> >>Free >>(...) >>"Liberated, by arriving at a certain age, from the control >>of parents, guardian, or master." >> >>The point presumably being that having been "liberated", you are now >>"free". > > (...) > >The English language has degenerated significantly in the last 30 >years. > (...) > >Dictionaries used to be the arbiters of the language - any word or >meaning of a word not found in the dictionary was considered a >colloquial (slang) use. Since the 1980's, an entry in the dictionary >has become little more than evidence of popularity as the major >dictionaries (OED, Webster, Cambridge, etc.) will now consider any >word they can find used in print. Apparantly, you missed the part where I referred to the 1913 edition of Webster. I have kept it in the quoted text above for your convenience. I can assure you that 1913 is both more than 30 years ago /and/ it is before 1980, in case that was in doubt. Cheers Bent D -- Bent Dalager - bcd at pvv.org - http://www.pvv.org/~bcd powered by emacs From deets at nospam.web.de Thu Oct 18 11:35:28 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Oct 2007 17:35:28 +0200 Subject: Convert string to command.. References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> <5npa5cFj5bvfU1@mid.uni-berlin.de> <1192720007.177063.194550@i13g2000prf.googlegroups.com> <5npbjbFio7g9U1@mid.uni-berlin.de> <1192720659.272611.320900@v29g2000prd.googlegroups.com> Message-ID: <5npcq3Fjgi5nU1@mid.uni-berlin.de> Abandoned wrote: > On Oct 18, 6:14 pm, "Diez B. Roggisch" wrote: >> Abandoned wrote: >> > Thanks you all answer.. >> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19....} >> > (100.000 elements) >> > Is there any easy alternative ? >> >> How big? How slow? For me, a 10000-element list takes 0.04 seconds to be >> parsed. Which I find fast. >> >> Diez > > 173.000 dict elements and it tooks 2.2 seconds this very big time for > my project Where does the data come from? Diez From duncan.booth at invalid.invalid Wed Oct 31 09:49:50 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Oct 2007 13:49:50 GMT Subject: A Python 3000 Question References: Message-ID: Neil Cerutti wrote: > But if I'm wrong about the performance benefits then I guess I'm > still in the dark about why len is a builtin. The only compelling > thing in the linked explation was the signatures of the guys who > wrote the artible. (Guido does admit he would, "hate to lose it > as a builtin," but doesn't explain why that should be a bad > thing). With most of the builtin functions there is an advantage since they wrap a bit of extra logic round the implementation: e.g. getattr hooks to __getattr__ or __getattribute__. With len that doesn't really apply, as the only extra logic seems fairly pointless: sequences and mappings implement length differently so you could have a type which acts as both and returns different lengths for each. Also the result returned from __len__ is cast from a Python object to a C value and back again so you can't return a length which is too large to convert. The main benefit that I can think of is that it avoids namespace pollution: most Python special methods (the ones you aren't supposed to call directly) have the double-underscores flagging them as separate from user methods. This is a good thing: you can create a class which acts like a builtin sequence, but which has any attributes you fancy: the obvious example being the classic "it's a tuple but all the elements are also accessible as attributes" returned from time.localtime(), os.stat(). Try this in a language like Javascript and nasty things happen when your attribute names clash with internal attribute names. So that's my conclusion: it is a builtin function rather than a method in order to avoid polluting the user attribute space of user-defined classes. Obviously it isn't an absolute thing: lists and dictionaries do have other methods in the user namespace, so the decision to keep len out of that namespace is partly a judgement call, and partly historical (I think tuples didn't used to have any methods at all). From Caseyweb at gmail.com Thu Oct 4 16:58:05 2007 From: Caseyweb at gmail.com (Casey) Date: Thu, 04 Oct 2007 13:58:05 -0700 Subject: What does the syntax [::-1] really mean? In-Reply-To: References: <1191510669.307178.257500@57g2000hsv.googlegroups.com> Message-ID: <1191531485.929483.146370@k79g2000hse.googlegroups.com> On Oct 4, 4:32 pm, Duncan Booth wrote: > Duncan Booth wrote: > > the invariant that you are looking for is that for all non-negative a, b: > > x[a:b:1] reversed is x[-len(x)+b-1:-len(x)+a-1:-1] > > I should of course have said "all a, b in the range 0 <= a <= len(x) and 0 > <= b <= len(x)". Thanks, again! I figured it out from Fred's and your initial posts. IM(ns)HO, this is non-intuitive. I would expect that the reverse of x[i,j,k] would be x[j,i,-k]; eg; x[0:len(x):1] would be x[len(x):0:-1]. This representation is little more than syntactic sugar for x[y for y in range(i,j,k)], with a -1 adjustment to i and j if k is < 0 (due to the way range operates) and with appropriate boundary checking on i and j. The default values for i and j would become (0,len(x)), flopped for k < 0. There may be a good (or not-so-good) reason this representation wouldn't have worked or would have caused problems. Or maybe it is just personal preference. From coolman_suk at yahoo.com Tue Oct 16 01:21:28 2007 From: coolman_suk at yahoo.com (coolman_suk at yahoo.com) Date: Mon, 15 Oct 2007 22:21:28 -0700 Subject: i need to get orkut (google) data without gdata, pls help!!!! Message-ID: <1192512088.494244.290490@q3g2000prf.googlegroups.com> hi,i am making a plugin for my app ( insert.clappings() ) and right now i am in some serious problem. i need a way to authenticate myself into orkut.com, get a session cookie , open a bunch of files, and make rss out of them! i can handle the make rss part. some of u might know about gdata for python (it exists , found out today on python.org) but it doesnt support the orkut service moreover i just need to get data not send it. i had been trying to getinto orkut for a while, (actually i was writing a urllib http handler) but i could not handle the cookie dance that google was playing with me. my eyes are paining right now AND I NEED SOME HELP FROM U GUYES (not how to rest my eyes lol but how to login to orkut!) anyone who has ever done this or could explain how google plays the cookie dance! SKI (giving my eyes some rest) From rowing.golfer at no_spam.virgin.net Fri Oct 26 11:37:06 2007 From: rowing.golfer at no_spam.virgin.net (Neil Wallace) Date: Fri, 26 Oct 2007 10:37:06 -0500 Subject: Dual Python Installed Environments.. References: Message-ID: On Thu, 25 Oct 2007 14:45:51 -0700, sam wrote: > Hi.. > > I'm looking to install dual versions of python 2.3, 2.4 on the same box. > I'm trying to figure out if there's something I'm missing, some kind of > gotchas that I haven't seen. > > I'm also trying to figure out how to allow my script to determine which > version to use??? > > Thanks Here's one that tripped me up... I altered the symlink at /usr/bin/python to point to Python 2.2 which I installed in my home folder (see below for the reason.. in case you are wondering) this broke some packages in my distribution (Ubuntu). I could see the broken packages, and didn't need them anymore, but I was unable to remove them as the removal scripts were (presumably) python 2.4+ Much head scratching at the time. Neil. Reason - I had written some CGI scripts and tested them thoroughly on my localhost version of the site. However I uploaded the files, and some of them didn't work, my sites server (not under my full control) runs Python 2.2, so I downloaded 2.2, and made it default so that localhost used this version so I could retest and ammend etc.. From ldo at geek-central.gen.new_zealand Thu Oct 4 04:05:06 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Oct 2007 21:05:06 +1300 Subject: A question about subprocess References: <1191429980.784610.39020@22g2000hsm.googlegroups.com> Message-ID: In message , Lawrence D'Oliveiro wrote: > ... each one waiting for a remote process > on some master machine to terminate. Of course, "master" there should be "slave". :) From beema.shafreen at gmail.com Tue Oct 30 08:14:08 2007 From: beema.shafreen at gmail.com (Beema shafreen) Date: Tue, 30 Oct 2007 17:44:08 +0530 Subject: redundancy_check Message-ID: hi everbody, I have a file, a b c 1454 VALTGLTVAEYFR 8.9954e-07 1454 VALTGLTVAEYFR 0.00404626 1498 STLTDSLVSK 0.00404626 1505 TIAMDGTEGLVR 1.50931e-05 1528 GAEISAILEER 0.00055542 1528 GAEISAILEER 0.00055542 1538 YPIEHGIITNWDDMEK 0.0180397 1540 YPIEHGIITNWDDMEK 3.69329e-05 1552 AQIVGGFPIDISEAPYQISLR 0.015136 The file has redundancy in lines , I have to print the line without redundancy on consideration to the column c of the two lines which are redundant and those that are having column c lesser value than the other. how do i do it. regards shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From massung at gmail.com Tue Oct 9 15:27:10 2007 From: massung at gmail.com (Jeff M.) Date: Tue, 09 Oct 2007 19:27:10 -0000 Subject: The fundamental concept of continuations In-Reply-To: <1191906949.179197.217470@57g2000hsv.googlegroups.com> References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> Message-ID: <1191958030.300166.209950@57g2000hsv.googlegroups.com> > (6) any good readable references that explain it lucidly ? This was something that has been very interesting to me for a while now, and I'm actually still having a difficult time wrapping my head around it completely. The best written explanation that I've come across was in "The Scheme Programming Language" (http://mitpress.mit.edu/catalog/item/ default.asp?ttype=2&tid=9946). But perhaps others have better references. I'll attempt my own little explanation of call/cc. I'll butcher some of it, I'm sure, but hopefully those more knowledgeable will politely correct me. I will start with a loose analogy and point out a couple examples I came across that did make a lot of sense. First, the bad analogy I have (if you are coming from C programming like me) is setjmp and longjmp. This is a bad analogy in that you're talking about hardware and stack states as opposed to functions, but a good analogy in that it saves the current state of execution, and returns to that same state at a later time with a piece of data attached to it. My first example of using this would be to create a return function in Scheme. I hope I don't get this wrong, but the example would be something like this: (define (my-test x) (call/cc (lambda (return) (return x)))) Now, here's my understanding of what is happening under-the-hood: 1. call/cc stores the current execution state and creates a function to restore to that state. 2. call/cc then calls its own argument with the function it created. The key here is that "return" is a function (created by call/cc) taking 1 argument, and it restores execution at the same state it was when the call/cc began (or immediately after it?). This line: (return x) is really just calling the function created by call/cc, which will restore the execution state to what it was just prior to the call/cc, along with a parameter (in this case, the value of x). My next example I don't follow 100%, and I won't attempt to reproduce it here, but it generates a continuation that modifies itself (bad?) to define a list iterator. http://blog.plt-scheme.org/2007/07/callcc-and-self-modifying-code.html I recommend putting that code into a Scheme interpreter and running it. You'll get it. Hope this helps, and I look forward to better explanations than mine that will help me along as well. :) Jeff M. From Scott.Daniels at Acm.Org Thu Oct 25 22:46:59 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 25 Oct 2007 19:46:59 -0700 Subject: Parallel insert to postgresql with thread In-Reply-To: References: <1193310044.750654.157320@22g2000hsm.googlegroups.com> <5obctcFm7sogU1@mid.uni-berlin.de> <13i12q276igp0df@corp.supernews.com> Message-ID: <13i2l4k42hvaccd@corp.supernews.com> Erik Jones wrote: > > On Oct 25, 2007, at 7:28 AM, Scott David Daniels wrote: >> Diez B. Roggisch wrote: >>> Abandoned wrote: >>>> Hi.. >>>> I use the threading module for the fast operation. But .... >> [in each thread] >>>> def save(a,b,c): >>>> cursor.execute("INSERT INTO ... >>>> conn.commit() >>>> cursor.execute(...) >>>> How can i insert data to postgresql the same moment ?... >>> >>> DB modules aren't necessarily thread-safe. Most of the times, a >>> connection (and ... cursor) can't be shared between threads. >>> So open a connection for each thread. >> >> Note that your DB server will have to "serialize" your inserts, so >> ... a single thread through a single connection to the DB is the way >> to go. Of course it (the DB server) may be clever enough to behave >> "as if" they are serialized, but most of your work parallelizing at >> your end simply creates new work at the DB server end. > > Fortunately, in his case, that's not necessarily true.... If he > goes the recommended route with a separate connection for each thread, > then Postgres will not serialize multiple inserts coming from separate > connections unless there is something like and ALTER TABLE or REINDEX > concurrently happening on the table. > The whole serialized inserts thing is strictly something popularized > by MySQL and is by no means necessary or standard (as with a lot of > MySQL). But he commits after every insert, which _does_ force serialization (if only to provide safe transaction boundaries). I understand you can get clever at how to do it, _but_ preserving ACID properties is exactly what I mean by "serialize," and while I like to bash MySQL as well as the next person, I most certainly am not under the evil sway of the vile MySQL cabal. The server will have to be able to abort each transaction _independently_ of the others, and so must serialize any index updates that share a page by, for example, landing in the same node of a B-Tree. -Scott David Daniels Scott.Daniels at Acm.Org From tim at timgolden.me.uk Sat Oct 13 05:03:45 2007 From: tim at timgolden.me.uk (Tim Golden) Date: Sat, 13 Oct 2007 10:03:45 +0100 Subject: Pyro: ActiveState (wind32) to Unix In-Reply-To: <470F311C.2000201@timgolden.me.uk> References: <0A53725C4A497848A7B3A0874B2598313D38EB@acesxch01.ADVENTISTCORP.NET> <470F311C.2000201@timgolden.me.uk> Message-ID: <471089F1.4040801@timgolden.me.uk> Tim Golden wrote: > Sells, Fred wrote: >> I'm using ActiveState python on a windows box to talk to ACtive >> Directory. > > I'm running a Pyro Server on the same box. >> >> The client is Linux running std Python 2.4. >> >> It works just fine until the server codes calls some > > win32com.client api; then I get >> >> ImportError: No module named pywintypes [followed by private email from Fred containing the client/server files] Well it works ok for me running from an XP box to a Ubuntu VMWare image on the same machine. Since I don't have AD running on this laptop I made as few changes as possible to substitute WMI instead which uses the same Python & Windows tech. infrastructure -- ie you pass a moniker to win32com.client.GetObject. Obviously there could be something specific to the AD LDAP: interface here but I seriously doubt it. One thing you will have to be aware of -- although I honestly doubt it's behind the issue here -- is that running a Pyro server means implictly running in threads. And *that* means that, since the LDAP: interface is a (D)COM-based interface, you'll need to call pythoncom.CoInitialize to kick COM into threading mode. Failing to do that using WMI causes the mildly bizarre "Syntax error" when you try to do .GetObject ("wimgmts:..."). It's just possible that the error you're seeing is the LDAP equivalent. And that Pyro is trying to pull the error message across the link to tell you what it is. (Maybe). In short, then, try adding the line: pythoncom.CoInitialize () within the proxy's .getProperties method (having imported pythoncom up to, of course) and then: pythoncom.CoUninitialize () just before the return in that method. I've only just realised that this is a thread on the main python-list. If this goes nowhere here, try copying it over to the Pyro mailing list; I'm not sure if Irmen (Mr Pyro) follows this list. TJG From shriphanip at gmail.com Wed Oct 10 07:42:00 2007 From: shriphanip at gmail.com (Shriphani) Date: Wed, 10 Oct 2007 11:42:00 -0000 Subject: Last value of yield statement In-Reply-To: <470cb1fd@news.eftel.com.au> References: <1192011545.384425.189530@o80g2000hse.googlegroups.com> <470cb1fd@news.eftel.com.au> Message-ID: <1192016520.355582.317090@57g2000hsv.googlegroups.com> On Oct 10, 4:05 pm, John Machin wrote: > On 10/10/2007 8:19 PM, Shriphani wrote: > > > > > Hello all, > > > Let us say I have a function like this: > > > def efficientFiller(file): > > worthless_list = [] > > pot_file = open(file,'r') > > pot_file_text = pot_file.readlines() > > for line in pot_file_text: > > if line.find("msgid") != -1: > > message_id = shlex.split(line)[1] > > if message_id in dictionary: > > number = pot_file_text.index(line) > > corresponding_crap = > > dictionary.get(message_id) > > final_string = 'msgstr' + " " + '"' + > > corresponding_crap + '"' + '\n' > > pot_file_text[number+1] = final_string > > yield pot_file_text > > > efficient_filler = efficientFiller("libexo-0.3.pot") > > new_list = list(efficient_filler) > > print new_list > > > I want to plainly get the last value the yield statement generates. > > How can I go about doing this please? > > I don't think that 'efficient' and 'plainly' mean what you think they > mean. However to answer your question: > > new_list[-1] if new_list else None > > BTW I get the impression that the yield statement yields the whole > pot_file_text list each time, so that new_list will be a list of lists; > is that intentional? Hello again, I am sorry for having made that extra post and should have seen that the solution I wanted was posted here. Anyway thanks a lot Regards, Shriphani Palakodety From fabian at syameses.com Mon Oct 22 17:29:35 2007 From: fabian at syameses.com (=?ISO-8859-1?Q?Fabian_L=F3pez?=) Date: Mon, 22 Oct 2007 23:29:35 +0200 Subject: ignoring chinese characters parsing xml file In-Reply-To: <5o4evvFktnthU5@mid.uni-berlin.de> References: <5o4evvFktnthU5@mid.uni-berlin.de> Message-ID: <851acc320710221429ob9034c4ofa10066ebcb8bf00@mail.gmail.com> Thanks Mark, the code is like this. The attrib name is the problem: from lxml import etree context = etree.iterparse("file.xml") for action, elem in context: if elem.tag == "weblog": print action, elem.tag , elem.attrib["name"],elem.attrib["url"], elem.attrib["rssUrl"] And the xml file like: 22 Oct 2007 20:20:16 GMT, Marc 'BlackJack' Rintsch : > > On Mon, 22 Oct 2007 21:24:40 +0200, Fabian L?pez wrote: > > > I am parsing an XML file that includes chineses characters, like ^ > > uu????w.?L??? or ??????... The problem is that I get an error like: > > UnicodeEncodeerror:'charmap' codec can't encode characters in > > position.. > > You say you are *parsing* the file but this is an *encode* error. Parsing > means *decoding*. > > You have to show some code and the actual traceback to get help. Crystal > balls are not that reliable. ;-) > > Ciao, > Marc 'BlackJack' Rintsch > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From nytrokiss at gmail.com Mon Oct 15 00:08:50 2007 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 14 Oct 2007 21:08:50 -0700 Subject: Entering username & password automatically using urllib.urlopen In-Reply-To: <5ne85rFhraaeU1@mid.uni-berlin.de> References: <1192333275.927370.83790@i13g2000prf.googlegroups.com> <5ne85rFhraaeU1@mid.uni-berlin.de> Message-ID: <8a6b8e350710142108y443b2652r6cfab9e039b65d98@mail.gmail.com> if you want to hardcode the password in the url. What you need to do is http:username:password at www.passwordprotectedsite.com On 10/14/07, Diez B. Roggisch wrote: > > rodrigo schrieb: > > I am trying to retrieve a password protected page using: > > > > get = urllib.urlopen('http://password.protected.url"').read() > > > > While doing this interactively, I'm asked for the username, then the > > password at the terminal. > > Is there any way to do this non-interactively? To hardcode the user/ > > pass into the script so I can get the page automatically? > > > > (This is not a cracking attempt, I am trying to retrieve a page I have > > legitimate access to, just doing it automatically when certain > > conditions are met.) > > Is that HTTP-auth? Then this might help: > > http://www.voidspace.org.uk/python/articles/authentication.shtml > > BTW, use urllib2. > > Diez > -- > 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 travis.brady at gmail.com Thu Oct 25 10:21:43 2007 From: travis.brady at gmail.com (Travis Brady) Date: Thu, 25 Oct 2007 10:21:43 -0400 Subject: delineating by comma where commas inside quotation marks don't count In-Reply-To: <1193278225.923337.217160@k35g2000prh.googlegroups.com> References: <1193278225.923337.217160@k35g2000prh.googlegroups.com> Message-ID: On 10/24/07, Dan Bishop wrote: > > On Oct 24, 8:56 pm, "Junior" wrote: > > I want to open a text file for reading and delineate it by comma. I > also > > want any data > > surrounded by quotation marks that has a comma in it, not to count the > > commas inside the > > quotation marks > > Use the csv module. > > -- > The csv module is definitely the way to go here as it knows how to handle commas within text qualifiers (double quotes). Do something like this: import csv reader = csv.reader(open('testfile.txt')) for ct,row in enumerate(reader): print "var2=", row[2] if ct>2: break The comma separated list parser in pyparsing is also great for this, particularly when the input gets dirtier: http://pyparsing.wikispaces.com/space/showimage/commasep.py -- Travis Brady http://travisbrady.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From willshak at 00hvc.rr.com Thu Oct 11 22:32:16 2007 From: willshak at 00hvc.rr.com (willshak) Date: Thu, 11 Oct 2007 22:32:16 -0400 Subject: Top 10 Caribbean island destinations In-Reply-To: <470ed8b0$0$24257$4c368faf@roadrunner.com> References: <1192137188.121863.212020@19g2000hsx.googlegroups.com> <470ed8b0$0$24257$4c368faf@roadrunner.com> Message-ID: <13gtn5go9k25p56@news.supernews.com> on 10/11/2007 10:14 PM Audio expert said the following: > Now I know where NOT to go. > TOO crowded for me. > No one goes there anymore. It's too crowded. Lawrence "Yogi" Berra > > wrote in message > news:1192137188.121863.212020 at 19g2000hsx.googlegroups.com... > >> See the most popular Caribbean island destinations >> >> http://tropical-destinations.blogspot.com/ >> >> > > > -- Bill In Hamptonburgh, NY To email, remove the double zeroes after @ From jcd at sdf.lonestar.org Mon Oct 29 11:40:43 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Mon, 29 Oct 2007 11:40:43 -0400 Subject: two file into a single file In-Reply-To: References: Message-ID: <20071029154043.GA3648@sdf.lonestar.org> You will need to use the open() builtin for each input file, and again for the output file. Documentation is available in the python tutorial here: http://docs.python.org/tut/node9.html#SECTION009200000000000000000 You should read also the whole tutorial, and work with it until you understand it, but for now, that section should get you going. Cheers, Cliff On Mon, Oct 29, 2007 at 09:02:30PM +0530, Beema shafreen wrote regarding two file into a single file: > Delivered-To: python-list at bag.python.org > Date: Mon, 29 Oct 2007 21:02:30 +0530 > From: "Beema shafreen" > To: python-list at python.org > Subject: two file into a single file > Precedence: list > List-Id: General discussion list for the Python programming language > > List-Unsubscribe: , > > List-Archive: > List-Post: > List-Help: > List-Subscribe: , > > Errors-To: python-list-bounces+jcd=sdf.lonestar.org at python.org > > hi everybody, > I have a two file, > file 1: > 100007097 > 100007186 > 10000723 > 100007895 > 100007906 > 100008295 > 100008311 > 10000880 > 100009160 > 100009629 > file 2: > 100007097 > 100007186 > 10000723 > 100007895 > 100007906 > 100008295 > 100008311 > 10000880 > 100009160 > 100009629 > how do i make into a single file......like this > file 1 file 2 > 100007097 100007097 > 100007186 100007097 > 100007186 10000880 > 10000723 100007895 > 100007895 100007895 > 100007906 100007895 > 100008295 00008311 > 100008311 1000088 > -- > http://mail.python.org/mailman/listinfo/python-list From goldtech at worldpost.com Sat Oct 6 23:31:54 2007 From: goldtech at worldpost.com (goldtech) Date: Sat, 06 Oct 2007 20:31:54 -0700 Subject: How to create a file on users XP desktop Message-ID: <1191727914.018474.172950@g4g2000hsf.googlegroups.com> Can anyone link me or explain the following: I open a file in a python script. I want the new file's location to be on the user's desktop in a Windows XP environment. fileHandle = open (....., 'w' ) what I guess I'm looking for is an environmental variable that will usually be correct on most XP desktops and will work in the open statement. Or is there another way? Thanks From kyosohma at gmail.com Mon Oct 29 11:28:50 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 29 Oct 2007 15:28:50 -0000 Subject: while within while In-Reply-To: <13ibrd9m39oua4e@corp.supernews.com> References: <13i88bo9djpu279@corp.supernews.com> <13ibrd9m39oua4e@corp.supernews.com> Message-ID: <1193671730.506934.81610@v3g2000hsg.googlegroups.com> On Oct 29, 9:26 am, Steven D'Aprano wrote: > On Sun, 28 Oct 2007 21:02:02 -0400, Shawn Minisall wrote: > > Thanks a lot for your suggestions. Unfortunately, a lot of the issues > > brought up were simply the way I was taught by my professor and the way > > she wants things done,having to use a numbered menu as opposed to > > entering r, p or s, being taught just to use one main function for the > > entire program, having to init all variables in the program b4 the > > actual program starts or else points off for each program, while > > statements surrounding every input statement for input validation > > purposes... > > > Going beyond those things, would look like someone else wrote my program > > since we didn't talk about or ever cover them in class. > > Haven't you heard of "I've been reading ahead from the text book" or > "I've been reading discussion groups where they talk about good > programming techniques"? > > Besides, you'll probably find your prof will forgive nearly anything if > you acknowledge it first: plagiarism is considered a worse sin than > failing to learn anything. Look up this thread on Google Groups, and > include the URL in your assignment (you might want to give a TinyURL as > well), and your prof can see for herself that we're not doing your > homework for you. > > (Hey, chances are that she's googling for your name already...) > > Unless the assignment explicitly says "DO NOT SPLIT YOUR CODE INTO > FUNCTIONS", you shouldn't be marked down for writing better code than you > were asked for. > > On the other hand, if the assignment specifies "YOU MUST DO THIS" then > naturally you must follow the instructions. > > * shakes head sadly * > > Kids today, more concerned about following instructions than learning... > > * half wink * > > -- > Steven I had a professor who insisted that we not use loops and what-not before they were taught in class as well. It seems to be a standard thing in Computer Science classes. Kind of like learning mathematical proofs or doing standard deviation the long way first. In some ways, it's very helpful. In others, it's extremely lame. Typical of the college education system though. Mike From sandip.more at gmail.com Mon Oct 29 23:39:29 2007 From: sandip.more at gmail.com (sandipm) Date: Mon, 29 Oct 2007 20:39:29 -0700 Subject: python in academics? Message-ID: <1193715569.261522.219520@i13g2000prf.googlegroups.com> seeing posts from students on group. I am curious to know, Do they teach python in academic courses in universities? in undergrad comp science courses, We had scheme language as scheme is neat and beautiful language to learn programming. We learnt other languages ourselve with basics set right by scheme.. sandip From lukasz.f24 at gmail.com Thu Oct 18 04:06:06 2007 From: lukasz.f24 at gmail.com (lukasz.f24 at gmail.com) Date: Thu, 18 Oct 2007 01:06:06 -0700 Subject: MOD_PYTHON + packages reloading Message-ID: <1192694766.953529.25270@k35g2000prh.googlegroups.com> Hello, I came across annoying problem during my fun with mod_python. I turned out that mod_python load package only onca and don't care about any changes to it. Obviously it makes sense on production server but during development is more then annoying. I find a way to reload my module: m = apache.import_module(name) reload(m) But this solution doesn't satisfy my. Is there any way to use old good import x.x.x or from x.x.x import y and somehow set mod_python to autoreload packages? apache.import_module(name,autoreload=1) didn't work. What is more interesting if a file is in the same directory (no in the package) i don't need to wory about reloading, python doesn't cache it. Please help me :) From george.sakkis at gmail.com Wed Oct 3 14:14:56 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 03 Oct 2007 18:14:56 -0000 Subject: spam kontrol In-Reply-To: <1191430790.537383.115880@r29g2000hsg.googlegroups.com> References: <1191430790.537383.115880@r29g2000hsg.googlegroups.com> Message-ID: <1191435296.523842.160230@g4g2000hsf.googlegroups.com> On Oct 3, 12:59 pm, "oruc... at gmail.com" wrote: > hii > ? think you know spam page is the most pest for net user. ...closely followed in the second position by incoherent misspelled posts in silly IM-speak. From bh at izb.knu.ac.kr Tue Oct 16 22:13:49 2007 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Wed, 17 Oct 2007 11:13:49 +0900 Subject: why doesn't have this list a "reply-to" ? In-Reply-To: <471530E3.9090602@gmail.com> References: <471530E3.9090602@gmail.com> Message-ID: <1192587229.888.13.camel@viola.izb.knu.ac.kr> On Tue, 2007-10-16 at 23:45 +0200, stef mientki wrote: > hello, > > I'm always have great difficulties, replying to this beautiful and > helpful list. > > When I hit the reply button, > the message is sent personally to the sender and not to the list. > I've subscribed to dozen's of lists, > and all have an "reply-to" address, that points to list and not to the > individual. Just click "Ctrl-L", then you can reply to lists directly if you use good mailer like mutt or thunderbird or evolution ;; -- Byung-Hee HWANG "I need a guy I can trust." "Yeah, OK, let me think about it." -- Johnny Fontane and Nino Valenti, "Chapter 12", page 177 From samwyse at gmail.com Wed Oct 10 10:03:29 2007 From: samwyse at gmail.com (samwyse) Date: Wed, 10 Oct 2007 07:03:29 -0700 Subject: Symbolic Link In-Reply-To: References: <1187475296.173269.263080@k79g2000hse.googlegroups.com> <1187555373.202634.163160@57g2000hsv.googlegroups.com> <1187646982.760523.195750@i38g2000prf.googlegroups.com> <1187879000.370831.118780@j4g2000prf.googlegroups.com> <1o1Fi.33230$RX.26068@newssvr11.news.prodigy.net> Message-ID: <1192025009.157745.268010@d55g2000hsg.googlegroups.com> On Sep 9, 10:05 pm, Lawrence D'Oliveiro wrote: > In message <1o1Fi.33230$RX.26... at newssvr11.news.prodigy.net>,samwysewrote: > > > A hard-link, OTOH, allows > > direct access to the contents of a file, as long as it is on the same > > filesystem. No extra steps are required, so the process runs a few > > microseconds faster, and directory-level permissions can't get in the way. > > Hard links are best avoided, because of the confusion they can cause. There are reasons to use hard links, there are reasons to use symbolic links. Depending on the circumstances, either could "cause confusion" simply because either could do something other than what's needed. Here's a handy chart to help decide which is appropriate: http://publib.boulder.ibm.com/iseries/v5r1/ic2924/index.htm?info/ifs/rzaaxmstlinkcmp.htm From raims at dot.com Sat Oct 6 10:04:37 2007 From: raims at dot.com (Lawrence Oluyede) Date: Sat, 6 Oct 2007 16:04:37 +0200 Subject: Cross platform way of finding number of processors on a machine? References: <1191554907.422787.197740@y42g2000hsy.googlegroups.com> <1i5k9kn.kxih581ipiy0sN%raims@dot.com> <1191677166.962158.50350@k79g2000hse.googlegroups.com> Message-ID: <1i5kjv2.1r2h2vgbi0m6kN%raims@dot.com> Paul Boddie wrote: > From the experiments I've done with pprocess [1], pretending that a > hyperthreading "virtual CPU" is as good as a real CPU (or CPU core) > tends to be counter-productive: the performance benefits in moving > from the utilisation of one to two "virtual CPUs" are virtually non- > existent. We came the same conclusion at work. One of my colleagues has a machine with HyperThreading and he noticed no real performance increase with the processing library altough on my machine (which is a dual Core 2 Duo) the performance boost was definitely there :-) The good side of this is hyperthreading with parallel processes is like using a mono-CPU machine so we don't have to take into account it like if it was an entirely different kind of architecture. -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From hniksic at xemacs.org Thu Oct 4 08:52:50 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 04 Oct 2007 14:52:50 +0200 Subject: migrating to packages References: <4703C661.50009@fmed.uba.ar> <27E2B61D-3D3E-466D-9650-69E0DA27E952@myemma.com> <87hcl7jsn0.fsf@mulj.homelinux.net> <4704a3a5$0$5110$426a34cc@news.free.fr> <874ph79sw7.fsf@mulj.homelinux.net> <4704cfc8$0$15826$426a74cc@news.free.fr> Message-ID: <87r6kb82jh.fsf@mulj.homelinux.net> Bruno Desthuilliers writes: >> We agree on that. It is the OP who *wants* to access his modules >> directly without ever naming the package. > > To be exact, he wants to reorganize it's source code (splitting a > file that's getting too big AFAICT) You're right, I misread his original problem statement (as you also correctly pointed out later in the post). So yes, a package will do what he wants, simply by arranging the necessary imports in __init__.py. Sorry about the misunderstanding. >> That is why I think he is missing the point of having a package in >> the first place. > > MHO opinion is that *you* are missing *one* of the point*s* of having > packages. :-) From jelleferinga at gmail.com Wed Oct 31 11:32:49 2007 From: jelleferinga at gmail.com (jelle feringa) Date: Wed, 31 Oct 2007 16:32:49 +0100 Subject: shouldn't 'string'.find('ugh') return 0, not -1 ? In-Reply-To: <37fac3b90710310831xbabb2ddl7d12b87675edc6d9@mail.gmail.com> References: <47289BA8.5000109@tim.thechases.com> <37fac3b90710310831xbabb2ddl7d12b87675edc6d9@mail.gmail.com> Message-ID: <37fac3b90710310832r778776dfi486880fae849a400@mail.gmail.com> Hi Tim, Well, I this is another idiom in itself, right? Your checking if something is part of an iterable. I'm checking truth before entering a conditional expression. The latter is considered to be pythonic, right? -jelle On 10/31/07, Tim Chase wrote: > > > if I check a string for for a substring, and this substring isn't found, > > should't the .find method return 0 rather than -1? > > this breaks the > > > > if check.find('something'): > > do(somethingElse) > > > > idiom, which is a bit of a pity I think. > > That idiom is spelled: > > if 'something' in check: > do(somethingElse) > > Unless you really do need to start at a particular offset where > you use the additional parameters of find(), such as > find('something', 3, 42). In that case, you can slice your target: > > if 'something' in check[3:42]: > do(somethingElse) > > The above is untested, so check for fencepost errors, but the > theory holds. > > So pretty much, I'd never consider using find() :) > > -tkc > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ihatespam at hotmail.com Mon Oct 22 05:18:54 2007 From: ihatespam at hotmail.com (Just Another Victim of the Ambient Morality) Date: Mon, 22 Oct 2007 09:18:54 GMT Subject: Need help parsing with pyparsing... Message-ID: <2WZSi.151640$nh4.105853@fe09.news.easynews.com> I'm trying to parse with pyparsing but the grammar I'm using is somewhat unorthodox. I need to be able to parse something like the following: UPPER CASE WORDS And Title Like Words ...into two sentences: UPPER CASE WORDS And Title Like Words I'm finding this surprisingly hard to do. The problem is that pyparsing implicitly assumes whitespace are ignorable characters and is (perhaps necessarily) greedy with its term matching. All attempts to do the described parsing either fails to parse or incorrectly parses so: UPPER CASE WORDS A nd Title Like Words Frankly, I'm stuck. I don't know how to parse this grammar with pyparsing. Does anyone know how to accomplish what I'm trying to do? Thank you... From duncan.booth at invalid.invalid Sat Oct 20 09:19:02 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Oct 2007 13:19:02 GMT Subject: __main__ : What is this? References: <1192839982.488484.102860@e34g2000pro.googlegroups.com> Message-ID: "Matt McCredie" wrote: > or, as I prefer: > > a = 'c' == b > > It is just habit from writing so much C code that way. In C the > reasoning is that if you have mistyped it, you will catch the issue at > compile time instead of runtime (which is potentially much more > difficult to debug). I'm used to seeing that pattern. In terms of > natural language I do agree with you. It really is just my _humble_ > opinion. I can't make a huge argument for it in Python. To be honest, > I didn't give it much thought before I wrote it. I am simply used to > doing it that way, and being irked whenever I see it written the other > way in C or C++ (and perhaps unjustifiably Python). Alternatively you could just tell your C compiler to regard dodgy looking assignments as an error and stop worrying about it. Much less hassle all round. e.g. For gcc -Werror -Wparentheses, for Microsoft compiler -W4 -WX, or an appropriate #pragma in a header file for each. From sethia.vishal at gmail.com Thu Oct 4 15:27:42 2007 From: sethia.vishal at gmail.com (Vishal Sethia) Date: Thu, 4 Oct 2007 12:27:42 -0700 Subject: Owner of spawned process in threads Message-ID: <2ee048b40710041227o2ff1c73xdc11910f3591aaad@mail.gmail.com> Just trying to understand the behaviour of spawn. Consider I have a function which creates two threads. And in one of the threads I make a call to pexpect.spawn. spawn would fork and create a new new child In this case who becomes the owner of this child process. Is it the thread that spawned becomes the owner or is the main program becomes the owner of that child process. Thanks, -V From sean at buildingonline.com Tue Oct 30 20:00:59 2007 From: sean at buildingonline.com (sberry) Date: Tue, 30 Oct 2007 17:00:59 -0700 Subject: SOAPpy / WSDL help... please In-Reply-To: <1193785839.266287.37470@k35g2000prh.googlegroups.com> References: <1193785839.266287.37470@k35g2000prh.googlegroups.com> Message-ID: <1193788859.594847.184150@t8g2000prg.googlegroups.com> On Oct 30, 4:10 pm, sberry wrote: > I have an Adobe InDesign server running that includes a built-in SOAP > server. The wsdl is located here:http://www.seanberry.com/IDSP.wsdl. > > I have a PHP example that looks like this for calling the SOAP > function runScriptParameters > Sorry, I meant that I was trying to run the SOAP function RunScript... not runScriptParameters like I posted previously. Thanks for any help. From robert.kern at gmail.com Tue Oct 16 18:17:42 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 16 Oct 2007 17:17:42 -0500 Subject: why doesn't have this list a "reply-to" ? In-Reply-To: <471530E3.9090602@gmail.com> References: <471530E3.9090602@gmail.com> Message-ID: stef mientki wrote: > hello, > > I'm always have great difficulties, replying to this beautiful and > helpful list. > > When I hit the reply button, > the message is sent personally to the sender and not to the list. > I've subscribed to dozen's of lists, > and all have an "reply-to" address, that points to list and not to the > individual. It's not universal. Many people consider it harmful. Google "reply-to considered harmful" for a variety of opinions, for and against. I use GMane to read and post to this list because I like my lists to act like USENET. http://gmane.org -- 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 daniel_nolan at msn.com Mon Oct 29 01:58:55 2007 From: daniel_nolan at msn.com (daniel_nolan at msn.com) Date: Sun, 28 Oct 2007 22:58:55 -0700 Subject: IEC - cannot find button Message-ID: <1193637535.413630.252960@22g2000hsm.googlegroups.com> I'm brand new to Python--and programming in general. I'm trying to use IEC to control Internet Explorer. I've navigated to a page, and now I'm trying to click a button. The button appears to be called 'PDF Preview' but I honestly do not know whether that's the name or the caption. Here is my code: from win32com.client import Dispatch import IEC . . . ie = IEC.IEController(window_num = 1) ie.Navigate(URL_part_1 + x + URL_part_2) ie.ClickButton(name='PDF Preview') (I've also tried replacing name w/ caption but I get a similar error message.) I get this error message: Traceback (most recent call last): File "C:\Program Files\Python25\experiment", line 14, in ie.ClickButton(name='PDF Preview') File "C:\Program Files\Python25\lib\IEC.py", line 126, in ClickButton elem = elemcoll.item(i) File ">", line 3, in item com_error: (-2147024891, 'Access is denied.', None, None) I really have no idea how to interpret this. I'm pasting the button tag below:
From Michael.J.Fromberger at Clothing.Dartmouth.EDU Fri Oct 19 18:12:49 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Fri, 19 Oct 2007 18:12:49 -0400 Subject: Last iteration? References: <5n94u3Fh5e4gU1@mid.uni-berlin.de> <5nebmhFhp48uU1@mid.uni-berlin.de> <1192603763.894935.39680@e34g2000pro.googlegroups.com> Message-ID: In article <1192603763.894935.39680 at e34g2000pro.googlegroups.com>, Raymond Hettinger wrote: > [Diez B. Roggisch] > > > out:) But I wanted a general purpose based solution to be available that > > > doesn't count on len() working on an arbitrary iterable. > > [Peter Otten] > > You show signs of a severe case of morbus itertools. > > I, too, am affected and have not yet fully recovered... > > Maybe you guys were secretly yearning for a magical last element > detector used like this: [...] Although there have already been some nice solutions to this problem, but I'd like to propose another, which mildly abuses some of the newer features of Python It is perhaps not as concise as the previous solutions, nor do I claim it's better; but I thought I'd share it as an alternative approach. Before I affront you with implementation details, here's an example: | from __future__ import with_statement | with last_of(enumerate(file('/etc/passwd', 'rU'))) as fp: | for pos, line in fp: | if fp.marked(): | print "Last line, #%d = %s" % (pos + 1, line.strip()) In short, last_of comprises a trivial context manager that knows how to iterate over its input, and can also indicate that certain elements are "marked". In this case, only the last element is marked. We could also make the truth value of the context manager indicate the marking, as illustrated here: | with last_of("alphabet soup") as final: | for c in final: | if final: | print "Last character: %s" % c This is bit artificial, perhaps, but effective enough. Of course, there is really no reason you have to use "with," since we don't really care what happens when the object goes out of scope: You could just as easily write: | end = last_of(xrange(25)) | for x in end: | if end: | print "Last element: %s" % x But you could also handle nested context, using "with". Happily, the machinery to do all this is both simple and easily generalized to other sorts of "marking" tasks. For example, we could just as well do something special with all the elements that are accepted by a predicate function, e.g., | def isinteger(obj): | return isinstance(obj, (int, long)) | with matching(["a", 1, "b", 2, "c"], isinteger) as m: | for elt in m: | if m.marked(): | print '#%s' % elt, | else: | print '(%s)' % elt, | | print Now that you've seen the examples, here is an implementation. The "marker" class is an abstract base that does most of the work, with the "last_of" and "matching" examples implemented as subclasses: | class marker (object): | """Generate a trivial context manager that flags certain elements | in a sequence or iterable. | | Usage sample: | with marker(ITERABLE) as foo: | for elt in foo: | if foo.marked(): | print 'this is a marked element' | else: | print 'this is an unmarked element' | | Subclass overrides: | .next() -- return the next unconsumed element from the input. | .marked() -- return True iff the last element returned is marked. | | By default, no elements are marked. | """ | def __init__(self, seq): | self._seq = iter(seq) | try: | self._fst = self._seq.next() | except StopIteration: | self.next = self._empty | | def _empty(self): | raise StopIteration | | def _iter(self): | while True: | yield self.next() | | def next(self): | out = self._fst | try: | self._fst = self._seq.next() | except StopIteration: | self.next = self._empty | | return out | | def marked(self): | return False | | def __iter__(self): | return iter(self._iter()) | | def __nonzero__(self): | return self.marked() | | def __enter__(self): | return self | | def __exit__(self, *args): | pass A bit verbose, but uncomplicated apart from the subtlety in handling the end case. Here's last_of, implemented as a subclass: | class last_of (marker): | def __init__(self, seq): | super(last_of, self).__init__(seq) | self._end = False | | def next(self): | out = super(last_of, self).next() | if self.next == self._empty: | self._end = True | | return out | | def marked(self): | return self._end And finally, matching: | class matching (marker): | def __init__(self, seq, func): | super(matching, self).__init__(seq) | self._func = func | self._mark = False | | def next(self): | out = super(matching, self).next() | self._mark = self._func(out) | return out | | def marked(self): | return self._mark Generally speaking, you should only have to override .next() and .marked() to make a useful subclass of marker -- and possibly also __init__ if you need some additional setup. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From mhearne808 at gmail.com Thu Oct 4 14:32:38 2007 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Thu, 04 Oct 2007 11:32:38 -0700 Subject: Don't understand module search path... Message-ID: <1191522758.012794.141860@n39g2000hsh.googlegroups.com> I think I don't understand how the module search path works... Let's say I have a folders called 'test'. Underneath it, I create two more folders called 'foo' and 'bar'. In 'foo', I create an empty '__init__.py' file, indicating that this folder is a package 'foo'. I then create a simple python script 'foo.py' consisting of the following code: ---------------------------- #!/usr/bin/python def printhello(): print 'Hello world!' ---------------------------- Then in test/bar, I create 'bar.py' consisting of the following code: ---------------------------- #!/usr/bin/python import sys import os (curpath,thisdir) = os.path.split(os.getcwd()) foopath = os.path.join(curpath,'foo') sys.path.append(foopath) print sys.path os.chdir(os.path.join(os.getcwd(),'..')) print os.getcwd() from foo.foo import printhello ---------------------------- When I try to run bar.py, I get the following: ---------------------------- [sys.path search path, including full path to 'foo' folder] path/to/test Traceback (most recent call last): File "/path/to/test/bar/testfoo.py", line 16, in from foo.foo import printhello ImportError: No module named foo ---------------------------- Why? If 'foo' is in sys.path, shouldn't it appear when I try to import the foo module from it? Incidentally, when I move the script up to 'test' and modify it so that it just says: ---------------------------- #!/usr/bin/python from foo.foo import printhello ---------------------------- I get no errors. I don't understand the difference... Incidentally, my platform info: Python 2.5.1 Darwin Kernel Version 8.10.1 (Mac OS X) Help! --Mike From mensanator at aol.com Tue Oct 23 17:12:30 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Tue, 23 Oct 2007 14:12:30 -0700 Subject: Anagrams In-Reply-To: <1193127665.868582.257380@z24g2000prh.googlegroups.com> References: <1193127665.868582.257380@z24g2000prh.googlegroups.com> Message-ID: <1193173950.629761.182090@t8g2000prg.googlegroups.com> On Oct 23, 3:21 am, cokofree... at gmail.com wrote: > This was from a random website I found on practising good programming > techniques and I thought I'd see what ways people could find to write > out this example. Below are my two examples (which should work...). > > I am merely interested in other techniques people have (without > resorting to overusage of C modules and such like), just python and > good computer science techniques. > > For the wordlist go to this link Kata Anagrams > Anyway here are my two examples. > > This one uses a dictionary to store prime values of each letter in the > alphabet and for each line multiple the results of the characters > (which is unique for each anagram) and add them to a dictionary for > printing latter. >
> def anagram_finder():
>     primeAlpha = {'a':2, 'b':3, 'c':5, 'd':7,'e' : 11, 'f':13, 'g':17,
> 'h':19,        \
>                   'i':23, 'j':29, 'k':31, 'l':37, 'm':41, 'n':43, 'o':
> 47, 'p':53,    \
>                   'q':59, 'r':61, 's':67, 't':71, 'u':73, 'v':79, 'w':
> 83, 'x':89,    \
>                   'y':97, 'z':101}
>     dictAna =  {}
>     file = open ("wordlist.txt", "r")
>     for line in file:
>         value = 1
>         for s in line:
>             if s.lower() in primeAlpha:
>                    value *= primeAlpha[s.lower()]
>         dictAna.setdefault(value, []).append(line.strip())
>     file.close()
>     print "\n".join(['Anagrams are: %s' % (v) for k, v in
> dictAna.items() if len(dictAna[k]) > 1])
> 
> > My second is a little bit simpler. Each dictionary key is an > alphabetical ordering of the line in question, so that anagrams will > appear the same. It will add to the dictionary the new word either in > an existing key, or create a new one for it. > >
> def anagram_finder():
>     dict = {}
>     file = ('wordlist.txt', 'r')
>     for line in file:
>                 strip_line = line.strip().lower()
>                 sort_line = str(sorted(strip_line))
>                 dict.setdefault(sort_line, []).append(strip_line)
>     file.close()
>     print '\n'.join(['Anagrams are: %s' % (v) for k, v in dict.items()
> if len(dict[k]) > 1])
> 
> > Comparing them with timeit, they both took around 1 second or so, with > the first being slightly faster. > > What other ways do people think will work (and do mine actually work > for other people!) ## I took a somewhat different approach. Instead of in a file, ## I've got my word list (562456 words) in an MS-Access database. ## And instead of calculating the signature on the fly, I did it ## once and added the signature as a second field: ## ## TABLE CONS_alpha_only_signature_unique ## -------------------------------------- ## CONS text 75 ## signature text 26 ## ## The signature is a 26 character string where each character is ## the count of occurences of the matching letter. Luckily, in ## only a single case was there more than 9 occurences of any ## given letter, which turned not to be a word but a series of ## words concatenated so I just deleted it from the database ## (lots of crap in the original word list I used). ## ## Example: ## ## CONS signature ## aah 20000001000000000000000000 # 'a' occurs twice & 'h' once ## aahed 20011001000000000000000000 ## aahing 20000011100001000000000000 ## aahs 20000001000000000010000000 ## aaii 20000000200000000000000000 ## aaker 20001000001000000100000000 ## aal 20000000000100000000000000 ## aalborg 21000010000100100100000000 ## aalesund 20011000000101000010100000 ## ## Any words with identical signatures must be anagrams. ## ## Once this was been set up, I wrote a whole bunch of queries ## to use this table. I use the normal Access drag and drop ## design, but the SQL can be extracted from each, so I can ## simply open the query from Python or I can grab the SQL ## and build it inside the program. The query ## ## signatures_anagrams_select_signature ## ## is hard coded for criteria 9 & 10 and should be cast inside ## Python so the criteria can be changed dynamically. ## ## ## QUERY signatures_anagrams_longest ## --------------------------------- ## SELECT Len([CONS]) AS Expr1, ## Count(Cons_alpha_only_signature_unique.CONS) AS CountOfCONS, ## Cons_alpha_only_signature_unique.signature ## FROM Cons_alpha_only_signature_unique ## GROUP BY Len([CONS]), ## Cons_alpha_only_signature_unique.signature ## HAVING (((Count(Cons_alpha_only_signature_unique.CONS))>1)) ## ORDER BY Len([CONS]) DESC , ## Count(Cons_alpha_only_signature_unique.CONS) DESC; ## ## This is why I don't use SQLite3, must have crosstab queries. ## ## QUERY signatures_anagram_summary ## -------------------------------- ## TRANSFORM Count(signatures_anagrams_longest.signature) AS CountOfsignature ## SELECT signatures_anagrams_longest.Expr1 AS [length of word] ## FROM signatures_anagrams_longest ## GROUP BY signatures_anagrams_longest.Expr1 ## PIVOT signatures_anagrams_longest.CountOfCONS; ## ## ## QUERY signatures_anagrams_select_signature ## ------------------------------------------ ## SELECT Len([CONS]) AS Expr1, ## Count(Cons_alpha_only_signature_unique.CONS) AS CountOfCONS, ## Cons_alpha_only_signature_unique.signature ## FROM Cons_alpha_only_signature_unique ## GROUP BY Len([CONS]), ## Cons_alpha_only_signature_unique.signature ## HAVING (((Len([CONS]))=9) AND ## ((Count(Cons_alpha_only_signature_unique.CONS))=10)) ## ORDER BY Len([CONS]) DESC , ## Count(Cons_alpha_only_signature_unique.CONS) DESC; ## ## QUERY signatures_lookup_by_anagram_select_signature ## --------------------------------------------------- ## SELECT signatures_anagrams_select_signature.Expr1, ## signatures_anagrams_select_signature.CountOfCONS, ## Cons_alpha_only_signature_unique.CONS, ## Cons_alpha_only_signature_unique.signature ## FROM signatures_anagrams_select_signature ## INNER JOIN Cons_alpha_only_signature_unique ## ON signatures_anagrams_select_signature.signature ## = Cons_alpha_only_signature_unique.signature; ## ## ## Now it's a simple matter to use the ODBC from Win32 to extract ## the query output into Python. import dbi import odbc con = odbc.odbc("words") cursor = con.cursor() ## This first section grabs the anagram summary. Note that ## queries act just like tables (as long as they don't have ## internal dependencies). I read somewhere you can get the ## field names, but here I put them in by hand. ##cursor.execute("SELECT * FROM signature_anagram_summary") ## ##results = cursor.fetchall() ## ##for i in results: ## for j in i: ## print '%4s' % (str(j)), ## print ## (if this wraps, each line is 116 characters) ## 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 23 ## 2 259 None None None None None None None None None None None None None None None None None ## 3 487 348 218 150 102 None None None None None None None None None None None None None ## 4 1343 718 398 236 142 101 51 26 25 9 8 3 2 None None None None None ## 5 3182 1424 777 419 274 163 106 83 53 23 20 10 6 4 5 1 3 1 ## 6 5887 2314 1051 545 302 170 114 54 43 21 15 6 5 4 4 2 None None ## 7 7321 2251 886 390 151 76 49 37 14 7 5 1 1 1 None None None None ## 8 6993 1505 452 166 47 23 8 6 4 2 2 None None None None None None None ## 9 5127 830 197 47 17 6 None None 1 None None None None None None None None None ## 10 2975 328 66 8 2 None None None None None None None None None None None None None ## 11 1579 100 5 4 2 None None None None None None None None None None None None None ## 12 781 39 2 1 None None None None None None None None None None None None None None ## 13 326 11 2 None None None None None None None None None None None None None None None ## 14 166 2 None None None None None None None None None None None None None None None None ## 15 91 None 1 None None None None None None None None None None None None None None None ## 16 60 None None None None None None None None None None None None None None None None None ## 17 35 None None None None None None None None None None None None None None None None None ## 18 24 None None None None None None None None None None None None None None None None None ## 19 11 None None None None None None None None None None None None None None None None None ## 20 6 None None None None None None None None None None None None None None None None None ## 21 6 None None None None None None None None None None None None None None None None None ## 22 4 None None None None None None None None None None None None None None None None None ## From the query we have the word size as row header and size of ## anagram set as column header. The data value is the count of ## how many different anagram sets match the row/column header. ## ## For example, there are 7321 different 7-letter signatures that ## have 2 anagram sets. There is 1 5-letter signature having a ## 23 member anagram set. ## ## We can then pick any of these, say the single 10 member anagram ## set of 9-letter words, and query out out the anagrams: cursor.execute("SELECT * FROM signatures_lookup_by_anagram_select_signature") results = cursor.fetchall() for i in results: for j in i: print j, print ## 9 10 anoretics 10101000100001100111000000 ## 9 10 atroscine 10101000100001100111000000 ## 9 10 certosina 10101000100001100111000000 ## 9 10 creations 10101000100001100111000000 ## 9 10 narcotise 10101000100001100111000000 ## 9 10 ostracine 10101000100001100111000000 ## 9 10 reactions 10101000100001100111000000 ## 9 10 secration 10101000100001100111000000 ## 9 10 tinoceras 10101000100001100111000000 ## 9 10 tricosane 10101000100001100111000000 ## Nifty, eh? From rjack at com Wed Oct 3 16:53:46 2007 From: rjack at com (rjack) Date: Wed, 03 Oct 2007 16:53:46 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <13frd6vtarbee75@corp.supernews.com> <85sl4sqckf.fsf@lola.goethe.zz> <85hcl8qaj7.fsf@lola.goethe.zz> Message-ID: Webster? WEBSTER. . . ? Whatever happened to the Oxford English Dictionary ? Seems to me the English have always spoken the definitive English. . . that's why they call it ENGLISH. From rosros-3 at email.it Thu Oct 25 09:10:24 2007 From: rosros-3 at email.it (news.interbusiness.it) Date: Thu, 25 Oct 2007 15:10:24 +0200 Subject: Help wanted for opensource project Message-ID: I'm looking for Python programmers for an open source project: http://sourceforge.net/projects/spectrag/ SpectraG is a program to generate, edit and convert gradients. Formats: ggr, svg, ... Gradients are used in Inkscape, The Gimp, and are an essential tool for graphics. Current Gradient Editors do not support generation of gradients by means of formulas. From Jean-Bernard.jacquet-at-tele-deux-point-fr at invalid.org Thu Oct 4 04:29:43 2007 From: Jean-Bernard.jacquet-at-tele-deux-point-fr at invalid.org (JBJ) Date: Thu, 04 Oct 2007 10:29:43 +0200 Subject: Convert on uppercase unaccentent unicode character References: <4703dfff$0$30966$426a74cc@news.free.fr> <1191439792.666146.217150@d55g2000hsg.googlegroups.com> Message-ID: <4704a38c$0$2769$426a74cc@news.free.fr> Steve Holden wrote: > Duncan Booth wrote: >> timaranz at gmail.com wrote: >> >>> On Oct 4, 7:35 am, JBJ >> point... at invalid.org> wrote: >>>> Hi, >>>> I'am very newbie in Python. >>>> For the moment I'am trying to convert an unicode character to his >>>> uppercase unaccented character. >>>> By example with locale fr_FR: >>>> a,A,?,? should return A >>>> o,O,?,? should return O >>>> ?,? should return ? >>>> i,I,?,? should return I >>>> >>>> Have you some suggestions ? >>>> >>>> Thank. >>> Unicode strings have an upper() method - try that. I'm think it >>> should work properly with your locale - it doesn't give the expected >>> result for me with an english locale. >>> >> No, that will uppercase the string, but it doesn't (and shouldn't) strip >> the accents: >> > I can agree that is doesn't (though I am taking your word for it), but a > French person will definitely feel it's doing the wrong thing. Upper > case letters aren't accented in written French. > > regards > Steve http://www.academie-francaise.fr/langue/questions.html#accentuation Regards From DustanGroups at gmail.com Fri Oct 19 07:39:04 2007 From: DustanGroups at gmail.com (Dustan) Date: Fri, 19 Oct 2007 11:39:04 -0000 Subject: Noob: Loops and the 'else' construct In-Reply-To: References: <1192761867.254928.115300@i38g2000prf.googlegroups.com> Message-ID: <1192793944.775832.295350@e9g2000prf.googlegroups.com> On Oct 19, 3:12 am, Thorsten Kampe wrote: > So a for/else loop is exactly the same thing as a for loop with the > else clause outside the loop (except for "break")? Am I missing something here? It sounds to me like you just described two identical constructs. > Guess that's why I > never used that... > > Thorsten From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Oct 30 05:22:58 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 30 Oct 2007 10:22:58 +0100 Subject: A Python 3000 Question In-Reply-To: References: <87abq1mxqc.fsf@merkury.smsnet.pl> Message-ID: <4726f7ec$0$14478$426a74cc@news.free.fr> brad a ?crit : > Rob Wolfe wrote: > >> I wonder why people always complain about `len` function but never >> about `iter` or `pprint.pprint`? :) > > Not complaining. len is simple and understandable and IMO fits nicely > with split(), strip(), etc... that's why I used it as an example, but > list(), etc. could be used as examples as well: > > a_string.list() instead of list(a_string) Oh, fine. And a_string.tuple(), a_string.int(), a_string.this(), a_string.that() etc ? In case you don't know, list is a type, not a function !-) >> And to answer the question. In OO programming generic functions >> are no less important than classes and objects. > > Do they not take away from the OOness of the overall language Why so ? > and > introduce inconsistencies? The monotonic approach to callables in Python (I mean: functions are callable objects, classes are callable objects, so instanciation and function call have the exact same syntax - which let you decouple interface from implementation) is another way to be consistent. because you can switch from type to factory function (or from closure to callable object, etc) back and forth without breaking client code. From craig.howard at earthlink.net Fri Oct 5 05:38:05 2007 From: craig.howard at earthlink.net (Craig Howard) Date: Fri, 5 Oct 2007 05:38:05 -0400 Subject: unit testing In-Reply-To: References: Message-ID: <0E2EFA65-B6A6-4CF4-AB31-05AAD66C1666@earthlink.net> On Oct 4, 2007, at 3:02 PM, brad wrote: > Does anyone else feel that unittesting is too much work? Not in > general, > just the official unittest module for small to medium sized projects? > > It seems easier to write some quick methods that are used when needed > rather than building a program with integrated unittesting. I see the > value of it (the official unittest that is)... especially when > there's a > lot of source code. But this... > > if len(x) != y: > sys.exit('...') > > is a hell of a lot easier and quicker that subclassing > unittest.TestCase > on small projects :) > > Do others do their own "informal" unit testing? > > Just curious, > > Brad > -- > http://mail.python.org/mailman/listinfo/python-list Brad: If the program is more than 100 lines or is a critical system, I write a unit test. I hate asking myself, "Did I break something?" every time I decide to refactor a small section of code. For instance, I wrote an alarm system in Python for a water treatment plant. If the chlorine, pH, or turbidity are out of spec, an email message is sent to the plant operator's pager. Because of the nature of the alarm system, extensive field testing was out of the question. Unit testing was the only way to ensure it worked without disrupting the plant operation. Craig From seungchan.oh at gmail.com Fri Oct 12 11:32:39 2007 From: seungchan.oh at gmail.com (seungchan.oh at gmail.com) Date: Fri, 12 Oct 2007 08:32:39 -0700 Subject: Simple question about python logic. Message-ID: <1192203159.292973.204470@v23g2000prn.googlegroups.com> I have a file containing following data. But the dimension can be different. A B C D E F G 3 4 1 5 6 2 4 7 2 4 1 6 9 3 3 4 1 5 6 2 4 7 2 4 1 6 9 3 . . . . What is the best approach to make a column vector with the name such as A B, etc? From foo at bar.biz Tue Oct 9 16:32:33 2007 From: foo at bar.biz (.) Date: 09 Oct 2007 20:32:33 GMT Subject: The fundamental concept of continuations References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> <470b1b30$0$11022$4c368faf@roadrunner.com> <1191957606.187050.272820@v3g2000hsg.googlegroups.com> Message-ID: <470be561$0$24270$4c368faf@roadrunner.com> On Tue, 09 Oct 2007 19:20:06 +0000, gnuist006 wrote: > On Oct 8, 11:09 pm, "." wrote: >> On Tue, 09 Oct 2007 05:15:49 +0000, gnuist006 wrote: > >> >> > Can anyone explain: >> >> > (1) its origin >> >> One of the lambda papers, I think. I don't remember which. > > Hey no-name "dot" you are the only one who says its origin is in > one of the old lambda papers. Give me a reference or someone > give me a reference. I dont have access to any ACM journals or > other conferences. So I said "I think." Matthias corrected me. They're all on readscheme.org ( http://library.readscheme.org/page1.html ) though, and well worth reading. I note that I'm being mocked for not using my real name by someone not using his/her real name. Thank you, no-name gnuist006, you make me laugh. From paul at boddie.org.uk Wed Oct 24 08:25:50 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 24 Oct 2007 05:25:50 -0700 Subject: building a linux executable In-Reply-To: <5o8rl3Flhd8uU1@mid.individual.net> References: <1193223316.020001.77940@i13g2000prf.googlegroups.com> <5o8rl3Flhd8uU1@mid.individual.net> Message-ID: <1193228750.497591.202330@y27g2000pre.googlegroups.com> On 24 Okt, 14:20, Bjoern Schliessmann wrote: > > I'm sorry I cannot help, but how many linux distros have no python > installed or no packages of it? It's not usually the absence of Python that's the problem. What if your application uses various extension modules which in turn rely on various libraries (of the .so or .a kind)? It may be more convenient to bundle all these libraries instead of working out the package dependencies for all the target distributions, even if you know them all. Paul From michele.simionato at gmail.com Mon Oct 8 00:58:36 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 08 Oct 2007 04:58:36 -0000 Subject: Yet another comparison of Python Web Frameworks In-Reply-To: <1191795246.297622.88170@y42g2000hsy.googlegroups.com> References: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> <1191771096.541915.247650@k79g2000hse.googlegroups.com> <1191774244.572607.259510@o3g2000hsb.googlegroups.com> <1191795246.297622.88170@y42g2000hsy.googlegroups.com> Message-ID: <1191819516.274556.157500@d55g2000hsg.googlegroups.com> On Oct 7, 6:14 pm, Istvan Albert wrote: > On Oct 7, 12:24 pm, Michele Simionato > wrote: > > > Here we disagree: I think that a programmer should know what he > > is using. > > My point was that they should not *need* to know. Too much information > can be detrimental. Actually, in principle I *do* agree with you. For instance, when I type 1+1, I have no idea of what exactly Python is doing, but I don't need to know, because adding two integers is a problem which is well understood and has been solved by others years ago, I don't need to care about it. I wait with impatience the time when Web programming will become a solved problem with a standard built-in solution that works. Unfortunately, that time is not near in the future and for the moment I am forced to know how all the pieces work if I want to build a reliable application. I don't like it, since I am not particularly interested in the low levels and in the plumbings myself, but this is the way it is. > ... truth to > be told I was just curious of how they would go about integrating a > database and still keep it "pluggable". > > Because it would either need to know about the way the server handles > the database connections (which makes it application specific) or it > has to create new database connections in which case it would be > duplicating the functionality leading to all kinds of headaches. > > So there, even a simple requirement exposes the fallacy of building > anything complex out of "pluggable" components. I suppose Beaker rely on SQLAlchemy since it comes from the same mind, but I don't see the issue: a component may well depend from another one, partially or totally, but this does not detract at all from the usefulness of the component approach. If I don't need persistent on a database, for instance, I like to have the choice between a full-fledged component and a poor man component that satisfies my basic requirements and nothing more. I don't want to be forced to use a monolithic-good-for-everybody solution. Michele Simionato From deets at nospam.web.de Mon Oct 22 06:47:18 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 Oct 2007 12:47:18 +0200 Subject: Failure to connect in SimpleXMLRPCServer/xmlrpclib References: <1193034835.803633.121600@z24g2000prh.googlegroups.com> <5o34stFkiv5sU1@mid.uni-berlin.de> <1193045401.857790.307960@v29g2000prd.googlegroups.com> Message-ID: <5o3ddmFkh9a6U3@mid.uni-berlin.de> >> Maybe using the IP-address helps? >> >> Diez- Hide quoted text - >> >> - Show quoted text - > > No, that doesn't help either. > May be I don't use it right. > I tried "http://1.2.3.4:8000" > and > r"http://\\1.2.3.4:8000" > > with no success. The former should work. The latter is Windows-name-style and has nothing to do here. I'm not a windows-user, but there should be ways to determine which program listens to which port on a machine. And a common problem is that servers listen on 127.0.0.1 instead of the ethernet interface. Try putting the server's IP as argument to the listening XMLRPC-server, and check with the windows-netstat-equivalent if it works out. Diez From trekker182 at comcast.net Sat Oct 27 15:20:39 2007 From: trekker182 at comcast.net (Shawn Minisall) Date: Sat, 27 Oct 2007 15:20:39 -0400 Subject: while within while Message-ID: <47238F87.2010808@comcast.net> K I've since fixed the UnboundLocalError: local variable 'ai' referenced before assignment error, I forgot to include decision = (1, 2, 3) inside " " for each number. Now when I run it, I get this.. >>> main() READY TO PLAY ROCK, PAPER, SCISSORS??? Please choose from the following menu: 1. See the rules 2. Play against the computer 3. Play a two player game 4. Exit Please enter your choice here: 2 ===================== you choose scissors I choose YOU LOSE! Rounds Won: 0 Rounds Lost: 1 Rounds Tied: 0 Would you like to play again? y Please choose from the following menu: 1. See the rules 2. Play against the computer 3. Play a two player game 4. Exit Please enter your choice here: 2 Please choose a weapon from the following menu: 1. Rock 2. Paper 3. Scissors Please choose a weapon: 1 and then the weapon submenu repeats over and over. It's also like the program is ignoring if ai == "1": ai = "rock" if ai == "2": ai = "paper" if ai == "3": ai = "scissors" since it says I choose ________ From steve at holdenweb.com Fri Oct 5 07:37:34 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 05 Oct 2007 07:37:34 -0400 Subject: module confusion In-Reply-To: <13gc6alr30la682@corp.supernews.com> References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> <874ph8sdhx.fsf@benfinney.id.au> <13g9ch1fi5c7se5@corp.supernews.com> <13gasot6r5bnu1a@corp.supernews.com> <13gc6alr30la682@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Fri, 05 Oct 2007 00:12:33 -0500, Robert Kern wrote: > >> This is somewhat odd, because most modules aren't exposed that way. They >> are either in their own file and accessed by importing them directly, or >> they are inside a package. > > Any time you say: > > import parrot > > > in one of your modules, you export parrot to anything that subsequently > imports your > module. (Unless you take specific steps to prevent it, for instance with > del parrot.) or the creation of an __all__ containing an exclusive list of names for export. > > > Just to pick some random examples: > >>>> import ConfigParser, base64, fileinput >>>> ConfigParser.re > >>>> base64.struct > >>>> base64.binascii > >>>> fileinput.sys > >>>> fileinput.os > > > > It's quite common. > > OK, I am sort of getting used to the idea that you guys are going to beat this one to death with a stick, and will still be tossing emails back and forth to each other while the rest of us are admiring the heat death of the universe. So please try and avoid writing anything that will be misconstrued by newless cloobs unfortunate enough to reach this thread as a result of a search for meaningful information on Python imports. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it From __peter__ at web.de Mon Oct 8 13:03:13 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 8 Oct 2007 19:03:13 +0200 Subject: [OT] Re: Variable scoping rules in Python? References: <1191853056.970304.209350@k79g2000hse.googlegroups.com> Message-ID: joshua.davies wrote: > Ok, I'm relatively new to Python (coming from C, C++ and Java). I'm > working on a program that outputs text that may be arbitrarily long, > but should still line up, so I want to split the output on a specific > column boundary. Since I might want to change the length of a column, > I tried defining the column as a constant (what I would have made a > "#define" in C, or a "static final" in Java). I defined this at the > top level (not within a def), and I reference it inside a function. > Like this: > > COLUMNS = 80 > > def doSomethindAndOutputIt( ): > ... > for i in range( 0, ( len( output[0] ) / COLUMNS ) ): > print output[0][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ] > print output[1][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ] > .. > > etc. etc. It works fine, and splits the output on the 80-column > boundary just like I want. Just in case it's not intentional: You'll lose every 80th character as python intervals do not include the upper bound. The same problem affects the for loop -- e. g. when output[0] has less than COLUMNS columns nothing is printed: >>> range(0, 79/80) [] Peter From paul at boddie.org.uk Fri Oct 26 14:42:06 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 26 Oct 2007 11:42:06 -0700 Subject: "Standard" Full Text Search Engine In-Reply-To: <7xy7dp233g.fsf@ruckus.brouhaha.com> References: <7xy7dp233g.fsf@ruckus.brouhaha.com> Message-ID: <1193424126.688154.144670@19g2000hsx.googlegroups.com> On 26 Okt, 19:33, Paul Rubin wrote: > > Ferret is basically a Lucene clone, originally written in Ruby but > with the intensive parts later rewritten in C for speed since the Ruby > version was too slow. There was something similar done in Python > (PyLucene, I think) that was also pretty slow. You're thinking of Lupy, whose authors/supporters then seemed to switch to Xapian: http://www.divmod.org/projects/lupy Meanwhile, PyLucene doesn't seem particularly slow to me. Provided you can build the software (it requires gcj), it seems to work rapidly and reliably - the only problem I've ever had was related to a threading bug in Python 2.3 which was subsequently fixed by the Python core developers. Paul From george.sakkis at gmail.com Sun Oct 7 14:44:56 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 07 Oct 2007 18:44:56 -0000 Subject: Problem of Readability of Python In-Reply-To: <2tqdncU0D6K8v5TanZ2dnUVZ_hGdnZ2d@comcast.com> References: <1191780456.833563.173080@57g2000hsv.googlegroups.com> <2tqdncU0D6K8v5TanZ2dnUVZ_hGdnZ2d@comcast.com> Message-ID: <1191782696.538929.289770@22g2000hsm.googlegroups.com> On Oct 7, 2:14 pm, Steven Bethard wrote: > Licheng Fang wrote: > > Python is supposed to be readable, but after programming in Python for > > a while I find my Python programs can be more obfuscated than their C/C > > ++ counterparts sometimes. Part of the reason is that with > > heterogeneous lists/tuples at hand, I tend to stuff many things into > > the list and *assume* a structure of the list or tuple, instead of > > declaring them explicitly as one will do with C structs. So, what used > > to be > > > struct nameval { > > char * name; > > int val; > > } a; > > > a.name = ... > > a.val = ... > > > becomes cryptic > > > a[0] = ... > > a[1] = ... > > > Python Tutorial says an empty class can be used to do this. But if > > namespaces are implemented as dicts, wouldn't it incur much overhead > > if one defines empty classes as such for some very frequently used > > data structures of the program? > > > Any elegant solutions? > > You can use __slots__ to make objects consume less memory and have > slightly better attribute-access performance. Classes for objects that > need such performance tweaks should start like:: > > class A(object): > __slots__ = 'name', 'val' > > The recipe below fills in the obvious __init__ method for such classes > so that the above is pretty much all you need to write: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 > > STeVe For immutable records, you may also want to check out the named tuples recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261 George From lew at lewscanon.com Mon Oct 22 12:19:05 2007 From: lew at lewscanon.com (Lew) Date: Mon, 22 Oct 2007 12:19:05 -0400 Subject: TeX pestilence (was Distributed RVS, Darcs, tech love) In-Reply-To: <1pfph3dqfvhka2b6t5isv39po183ppp5ha@4ax.com> References: <1192914246.208743.94870@y27g2000pre.googlegroups.com> <471afd4c.179297746@news.readfreenews.net> <1192972158.250126.203980@v23g2000prn.googlegroups.com> <471b6714$0$90276$14726298@news.sunsite.dk> <1192981349.181197.308610@q5g2000prf.googlegroups.com> <1193037849.011136.282480@y27g2000pre.googlegroups.com> <1193057430.359962.68820@v29g2000prd.googlegroups.com> <1pfph3dqfvhka2b6t5isv39po183ppp5ha@4ax.com> Message-ID: Xah Lee wrote: >> 4. Inargurated a massive collection of documents that are invalid >> HTML. (due to the programing moron's ingorance and need to idolize a >> leader, and TeX's inherent problem of being a typesetting system that >> is unsuitable of representing any structure or semantics) There's something a little fey about someone calling out a "programing [sic] moron's ingorance [sic]" and then devolving right into blue speech. I think Xah Lee should look into: -- Lew From steve at holdenweb.com Thu Oct 4 08:56:04 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 04 Oct 2007 08:56:04 -0400 Subject: Program with wx in Linux and Windows In-Reply-To: References: Message-ID: marcpp wrote: > Hi I've developed a program (WXpython GUI). In Linux the GUI is correct > (various distributions), but in Windows all appears disordered. > Any recomendations? A slightly unhelpful one might be "learn to use sizers", as they are the key to ordered layouts. Unfortunately the learning materials available aren't for everyone (to the extent that I am considering producing some more). But with sizers you can certainly ease cross-platform issues considerably. If you have an existing interface layout you might want to try just dropping all the components into a GridSizer to start with, then add more layout sophistication as you get into it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it From jjl at pobox.com Thu Oct 11 15:25:16 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 11 Oct 2007 19:25:16 GMT Subject: Finding Peoples' Names in Files References: Message-ID: <87wstt78tf.fsf@pobox.com> brad writes: > Crazy question, but has anyone attempted this or seen Python code that > does? For example, if a text file contained 'Guido' and or 'Robert' > and or 'Susan', then we should return True, otherwise return False. A few ideas: 1. If you don't have a list of names, find a list of words that doesn't contain proper nouns (there are a few word lists out there, not sure if any exclude people's names, though). Look for short runs of two or three "words" (punctuation-separated tokens) in the email that aren't in the dictionary. Some of them will be people's names. 2. Send the text through Google translate and look for runs of words that are unchanged. Some of them will be people's names. 3. Search the literature and look for fancy algorithms. Here are some papers (the last mentions some commercial software to do this): http://citeseer.ist.psu.edu/bikel99algorithm.html http://citeseer.ist.psu.edu/618945.html http://arxiv.org/html/cmp-lg/9706017 John From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Oct 11 12:18:59 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 11 Oct 2007 18:18:59 +0200 Subject: Problem of Readability of Python References: <1191780456.833563.173080@57g2000hsv.googlegroups.com> <5n4t2vFgajr3U1@mid.individual.net> Message-ID: <5n70njFgjdo3U2@mid.individual.net> Steven Bethard wrote: > Actually, your posting just used dicts normally. > > Kevin is creating a prototype dict with a certain set of keys, and > then copying that dict and filling in the keys each time he > creates a new instance. It's basically a poor man's OOP. And operatively, IMHO, there is no difference. Regards, Bj?rn -- BOFH excuse #176: vapors from evaporating sticky-note adhesives From paul.hankin at gmail.com Fri Oct 5 05:34:53 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Fri, 05 Oct 2007 09:34:53 -0000 Subject: Strange generator problem In-Reply-To: References: Message-ID: <1191576893.725144.185090@y42g2000hsy.googlegroups.com> On Oct 5, 10:23 am, Joost Cassee wrote: > Hello all, > > I bumped into an unexpected problem using generators. Consider this code: > > def test(s): > return _test([], [], s) > def _test(s1, s2, s): > if s: > s1.append(s.pop()) > for x in _test(s1, s2, s): > yield x > s2.append(s1.pop()) > for x in _test(s1, s2, s): > yield x > s.append(s2.pop()) > else: > yield s1, s2 Lists aren't copied when they're yielded, so you're returning the same lists (with different elements) each time. Your final list looks like [(s1, s2), (s1, s2), ...] and as it happens, s1 and s2 are both [] by the end. You can fix it by copying the lists manually before yielding them, or using a better sub-list algorithm :) -- Paul Hankin From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Oct 15 18:27:16 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 16 Oct 2007 00:27:16 +0200 Subject: Normalize a polish L References: <1192466006.735303.20470@i38g2000prf.googlegroups.com> Message-ID: <5ni7q4Fi0k1tU2@mid.individual.net> Thorsten Kampe wrote: > The 'L' is actually pronounced like the English "w"... '?' originally comes from "L" () and is AFAIK transcribed so. Also, a friend of mine writes himself "Lukas" (pronounced L-) even though in Polish his name is ?ukas (short Wh-). Regards, Bj?rn -- BOFH excuse #126: it has Intel Inside From marco at sferacarta.com Tue Oct 23 14:04:25 2007 From: marco at sferacarta.com (Marco Mariani) Date: Tue, 23 Oct 2007 20:04:25 +0200 Subject: Iteration for Factorials In-Reply-To: <1193160794.433684.245150@v29g2000prd.googlegroups.com> References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <1193075845.148527.80820@k35g2000prh.googlegroups.com> <87bqarov3n.fsf@rudin.co.uk> <1193080349.610343.95430@v23g2000prn.googlegroups.com> <250fcec00710221238g76f24cb8n158e8854c45d7a61@mail.gmail.com> <1193089836.219692.117420@q5g2000prf.googlegroups.com> <1193160794.433684.245150@v29g2000prd.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Needs work. Uh... ok.. this one gives an exception ;-) def fact(n): try: return eval('*'.join(str(x) for x in range(1,n+1))) except: return n>=0 or ValueError print fact(-1) From zzbbaadd at aol.com Tue Oct 23 23:11:33 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Tue, 23 Oct 2007 20:11:33 -0700 Subject: Python Windows Installation Message-ID: <1193195493.086681.40570@t8g2000prg.googlegroups.com> I am trying to install Python 2.5 on Windows XP. It installs into the root directory on C:\ instead of C:\Python25 which it shows by default as what it plans to install to. Selecting D:\Python25 on a previous iteration put the exe in D:\ and did not create a Python25 directory. On the most recent iteration, when requesting an install to D: \Python25 it appears to have put files on C:\. I am installing on Windows XP Professional. When it asks me for whether I want to install for all users or just me, I select just me. I do not have admin rights on the machine. From ells.david at gmail.com Tue Oct 2 11:16:41 2007 From: ells.david at gmail.com (David Ells) Date: Tue, 02 Oct 2007 15:16:41 -0000 Subject: Question on overriding implicit lookups Message-ID: <1191338201.762723.72750@22g2000hsm.googlegroups.com> In Python we have a wonderful facility for customizing attribute access by defining __getattr__ or __getattribute__ in our classes. Unfortunately (or perhaps fortunately, for reasons I don't know), this facility only works for explicit attribute access, i.e. accessing foo.bar. What I am in need of, for reasons I'll keep out of the discussion for now, is a similar facility for implicit attribute access, such as the call to foo.__len__ when something like len(foo) is executed. I would like some way to customize access during these implicit lookups without having to define each one in the class myself. Essentially what I am looking for is a mechanism like __getattribute__, only one that will work for these implicit lookups to functions like __len__, __str__, __getitem__, and so on. Hopefully my question makes sense. From jcd at sdf.lonestar.org Sat Oct 27 16:36:52 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Sat, 27 Oct 2007 16:36:52 -0400 Subject: Proposal: Decimal literals in Python. In-Reply-To: <5ohjojFmgu6mU7@mid.uni-berlin.de> References: <4721ab28$0$1238$e4fe514c@dreader28.news.xs4all.nl> <1193438763.190428.134710@q5g2000prf.googlegroups.com> <87tzodii6i.fsf@benfinney.id.au> <1193494184.618613.81090@50g2000hsm.googlegroups.com> <1193498867.815682.69050@v3g2000hsg.googlegroups.com> <1193501811.620522.261570@o80g2000hse.googlegroups.com> <5ohjojFmgu6mU7@mid.uni-berlin.de> Message-ID: <4723A164.60908@sdf.lonestar.org> Marc 'BlackJack' Rintsch wrote: > On Sat, 27 Oct 2007 13:28:02 -0500, Tim Chase wrote: > > >>>> Even clearer is not to allow octal literals :) Is there *any* use for >>>> them? >>>> >>> The mode argument to os.chmod. >>> >> You mean instead of >> >> import this >> os.chmod(filename, os.R_OK | os.W_OK | os.X_OK) >> >> which explicitly (rather than implicitly) spells it out? >> > > And the equivalent of ``os.chmod(filename, 0777)`` looks like what!? > > Ciao, > Marc 'BlackJack' Rintsch > Ugly. But is one function in one library, which doesn't even exist in one of the major operating systems really worth its own syntactic construct in the language? It seems that it would be fairly simple for python to treat the octal argument as a string, rather than an int: os.chmod(filename, "777") If somebody had a good *general* use for octal, it might be worth having in the language. Otherwise, it seems like an unused which is only kept around because it used to get played with. (back in the days of six bit hardware?) Cheers, Cliff -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Oct 30 22:07:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Oct 2007 23:07:10 -0300 Subject: Built-in functions and keyword arguments References: <1193665924.886459.20710@v3g2000hsg.googlegroups.com> <4725ec3a$0$6623$426a74cc@news.free.fr> Message-ID: En Tue, 30 Oct 2007 14:43:48 -0300, Duncan Booth escribi?: > "J. Clifford Dyer" wrote: > >>> >>> help(int) >>> Help on class int in module __builtin__: >>> >>> class int(object) >>> | int(x[, base]) -> integer >>> ... >>> >> OK, good point. Perhaps it's not so specific as the type, but >> certainly the use of name and x in the docstrings listed above only >> imply something about the character of the argument, not the name of >> the argument itself, which is what I was trying to get at. Help >> documentation for keyword arguments usually shows the argument being >> used as a keyword, like the example from __import__ above. > > Usually, but not in the second example I gave: > >>>> int(base=12, x='42') > 50 So one can conclude that, unfortunately, there is no way to tell from the docs alone whether a certain function will accept keyword arguments or not. Too bad :( -- Gabriel Genellina From deets at nospam.web.de Thu Oct 18 11:14:51 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Oct 2007 17:14:51 +0200 Subject: Convert string to command.. References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> <5npa5cFj5bvfU1@mid.uni-berlin.de> <1192720007.177063.194550@i13g2000prf.googlegroups.com> Message-ID: <5npbjbFio7g9U1@mid.uni-berlin.de> Abandoned wrote: > Thanks you all answer.. > But "eval" is very slow at very big dictionary {2:3,4:5,6:19....} > (100.000 elements) > Is there any easy alternative ? How big? How slow? For me, a 10000-element list takes 0.04 seconds to be parsed. Which I find fast. Diez From carsten at uniqsys.com Mon Oct 1 19:40:25 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 01 Oct 2007 19:40:25 -0400 Subject: Question about quoting style. In-Reply-To: References: <470153d9$0$27239$426a74cc@news.free.fr> Message-ID: <1191282025.3412.4.camel@localhost.localdomain> On Mon, 2007-10-01 at 15:10 -0700, James Stroud wrote: > Bruno Desthuilliers wrote: > > First point is that Python has no "variable interpolation". > > If you squint, it kind of does*: > > >>> print '%(language)s has %(#)03d quote types.' % \ > {'language': "Python", "#": 2} > Python has 002 quote types. > > You might think if the dict as a name space and the formatting operation > as performing interpolation--but this take on formatting might be a stretch. It looks even more like interpolation if you do it like this: >>> language = "Python" >>> num = 2 >>> print '%(language)s has %(num)03d quote types.' % locals() Python has 002 quote types. -- Carsten Haese http://informixdb.sourceforge.net From jstroud at mbi.ucla.edu Sun Oct 21 15:15:20 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 21 Oct 2007 12:15:20 -0700 Subject: what is the difference between the two kinds of brackets? In-Reply-To: References: <1192875315.887877.210550@y27g2000pre.googlegroups.com> <1192898800.059965.272700@q3g2000prf.googlegroups.com> Message-ID: Hendrik van Rooyen wrote: > "Paul Hankin" wrote: > >> If everything else is equal, use tuples. > > Interesting point of view - mine is just the opposite. > > I wonder if its the philosophical difference between: > > "Anything not expressly allowed is forbidden" > > and > > "Anything not expressly forbidden is allowed" ? > > - Hendrik > The latter is how I interpret any religious moral code--life is a lot more fun that way. Maybe that percolates to how I use python? James -- James Stroud UCLA-DOE Institute of Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From trekker182 at gmail.com Wed Oct 10 16:29:21 2007 From: trekker182 at gmail.com (Shawn Minisall) Date: Wed, 10 Oct 2007 16:29:21 -0400 Subject: if then elif Message-ID: <470D3621.4070900@gmail.com> I just learned about if, then elif statements and wrote this program. The problem is, it's displaying all of the possibilities even after you enter a 0, or if the fat grams are more then the total number of calories , that is supposed to stop the program instead of continuing on with the print statements that don't apply. Any idea's? thanks #Prompt for calories cal = input("Please enter the number of calories in your food: ") #Prompt for fat fat = input("Please enter the number of fat grams in your food: ") #Input validation if cal or fat <= 0: #Display message print "Error. The number of calories and/or fat grams must be positive" print else: #Calculate calories from fat calfat = float(fat) * 9 #Calculate number of calories from fat caldel = calfat / cal #change calcent decimal to percentage calcent = caldel * 100 if calfat > cal: print "The calories or fat grams were incorrectly entered." else: #evaluate input if caldel <= .3: print "Your food is low in fat." elif caldel >= .3: print "Your food is high in fat." #Display percentage of calories from fat print "The percentage of calories from fat in your food is %", calcent Here's an example of the output... Please enter the number of calories in your food: 50 Please enter the number of fat grams in your food: 30 Error. The number of calories and/or fat grams must be positive Your food is low in fat. The percentage of calories from fat in your food is % 0.0 It was supposed to print The calories or fat grams were incorrectly entered since the calories from fat was greater then the total number of calories. From ptmcg at austin.rr.com Fri Oct 12 02:07:58 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 11 Oct 2007 23:07:58 -0700 Subject: matching a street address with regular expressions In-Reply-To: References: <505641.42832.qm@web51601.mail.re2.yahoo.com> <4704DD04.4020304@bigfoot.com> Message-ID: <1192169278.464170.214930@e34g2000pro.googlegroups.com> On Oct 11, 11:50 pm, John Nagle wrote: > > If anyone has a first-rate address parser in Python that will cover > most of the developed world, I'd like to talk to them. > > John Nagle > SiteTruth The pyparsing examples page includes a street address parser (http:// pyparsing.wikispaces.com/space/showimage/streetAddressParser.py) that will handle these test cases: 100 South Street 123 Main 221B Baker Street 10 Downing St 1600 Pennsylvania Ave 33 1/2 W 42nd St. 454 N 38 1/2 21A Deer Run Drive 256K Memory Lane 12-1/2 Lincoln 23N W Loop South 23 N W Loop South 25 Main St 2500 14th St 12 Bennet Pkwy Pearl St Bennet Rd and Main St 19th St -- Paul From paul.hankin at gmail.com Wed Oct 24 08:53:13 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 24 Oct 2007 12:53:13 -0000 Subject: Better writing in python In-Reply-To: <1193227780.481365.261900@q3g2000prf.googlegroups.com> References: <1193227780.481365.261900@q3g2000prf.googlegroups.com> Message-ID: <1193230393.247264.174150@e34g2000pro.googlegroups.com> On Oct 24, 1:09 pm, Alexandre Badez wrote: > I'm just wondering, if I could write a in a "better" way this code > > lMandatory = [] > lOptional = [] > for arg in cls.dArguments: > if arg is True: > lMandatory.append(arg) > else: > lOptional.append(arg) > return (lMandatory, lOptional) > > I think there is a better way, but I can't see how... import operator return filter(cls.dArguments), filter(operator.not_, cls.dArguments) Or just: mandatory = [arg for arg in cls.dArguments in arg] optional = [arg for arg in cls.dArguments in not arg] return mandatory, optional -- Paul Hankin From mishok13 at gmail.com Wed Oct 31 10:19:25 2007 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Wed, 31 Oct 2007 17:19:25 +0300 Subject: Fwd: Namespace question In-Reply-To: <192840a00710310718s1faec38pdd6080d023dcb1dd@mail.gmail.com> References: <200710311506.27887.Frank.Aune@broadpark.no> <192840a00710310718s1faec38pdd6080d023dcb1dd@mail.gmail.com> Message-ID: <192840a00710310719s4e5452dauc34070f9f83dd25c@mail.gmail.com> 2007/10/31, Frank Aune : > Hello, > > Is it possible writing custom modules named the same as modules in the > standard library, which in turn use the same module from the standard > library? > > Say I want my application to have a random.py module, which in turn must > import the standard library random.py module also, to get hold of the randint > function for example. > > My attempts so far only causes my random.py to import itself instead of the > standard library random.py > > Receipt for disaster? :) You mean something like this: >>>import random >>>def foo(): ... print '42' >>>random.randit = foo >>>random.randit() 42 am I right? -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From dwblas at gmail.com Tue Oct 23 18:11:31 2007 From: dwblas at gmail.com (dwblas at gmail.com) Date: Tue, 23 Oct 2007 15:11:31 -0700 Subject: Lists and Sublists In-Reply-To: <1193175869.803399.43650@y27g2000pre.googlegroups.com> References: <1193175869.803399.43650@y27g2000pre.googlegroups.com> Message-ID: <1193177491.149033.19130@i38g2000prf.googlegroups.com> > I am struggling to work out what is the ideal Python data structure > for the above. Any help would be greatly appreciated. The normal way is to use a dictionary of lists. The key would be the dictionary key, which would contain a list or a list of lists, that is each name would be an element of the list unless the name is more than one word, in which case each name would be converted to a list and appended to the key. Some pseudo-code if key in name_dic: name_dic[key] += [name] ## converted to list If this doesn't work, then SQLite can be used in memory. There are examples on the website. From Eric_Dexter at msn.com Fri Oct 5 19:40:40 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Fri, 05 Oct 2007 16:40:40 -0700 Subject: embedding python.. Message-ID: <1191627640.676114.319430@22g2000hsm.googlegroups.com> I compiled the c program that is supposed to allow you to call a procedure from the command line promt.. (it is from the embeding example).. I am a little confused as to what all I am supposed to distribute to make it work.. Do I just need the python .dll for the version I compiled or is it working with the installed version of python.. (I don't want to start deleting stuff to find out).. Any help on this question would be apreaceated.. tagger what tagline From Florian.Lindner at xgm.de Fri Oct 12 14:51:15 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Fri, 12 Oct 2007 20:51:15 +0200 Subject: Problem with MySQL cursor References: Message-ID: Carsten Haese wrote: > On Fri, 2007-10-12 at 13:12 +0200, Florian Lindner wrote: >> Carsten Haese wrote: >> > sql = "INSERT INTO "+DOMAIN_TABLE+"("+DOMAIN_FIELD+") VALUES (%s)" >> > executeSQL(sql, domainname) >> >> Ok, I understand it and now it works, but why is limitation? Why can't I >> just the string interpolation in any playes and the cursor function >> escapes any strings so that they can't do harm to my query? > [...] Thanks for your good explanation! Florian From dfabrizio51 at gmail.com Tue Oct 23 21:46:06 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Tue, 23 Oct 2007 18:46:06 -0700 Subject: does PyAntlr come with Antlr download Message-ID: <1193190366.660923.257490@z24g2000prh.googlegroups.com> Hello All, I want use java2python which requires PyAntlr. I can't seem to find PyAntlr mentioned on the main website for Antlr. Thanks, From python.list at tim.thechases.com Mon Oct 22 16:22:47 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 22 Oct 2007 15:22:47 -0500 Subject: Iteration for Factorials In-Reply-To: <250fcec00710221238g76f24cb8n158e8854c45d7a61@mail.gmail.com> References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <1193075845.148527.80820@k35g2000prh.googlegroups.com> <87bqarov3n.fsf@rudin.co.uk> <1193080349.610343.95430@v23g2000prn.googlegroups.com> <250fcec00710221238g76f24cb8n158e8854c45d7a61@mail.gmail.com> Message-ID: <471D0697.1010401@tim.thechases.com> > def fact(x): > if x == 0 or x == 1: > return 1 > else: > return reduce(operator.mul, xrange(1,x+1)) If obscurity is the name of the game, >>> from operator import mul >>> fact = lambda i: i > 1 and reduce(mul, xrange(1,i+1)) or i >= 0 and 1 or None >>> for i in xrange(-2,10): print '%i! = %s' % (i, fact(i)) My eyes hurt after reading that...as the order of operations is left to Python to discern (a few judiciously placed parens might improve things...though that may be like polishing coprolite) I haven't yet seen an implementation in C (using the python/C interface) or anybody handing off a python AST/opcode-list to an appropriate function :) -tkc From mail at timgolden.me.uk Thu Oct 11 11:17:22 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 11 Oct 2007 16:17:22 +0100 Subject: Python module for making Quicktime or mpeg movies from images In-Reply-To: <1192115372.754998.270520@o80g2000hse.googlegroups.com> References: <1192113745.291983.292950@50g2000hsm.googlegroups.com> <5n6r5bFfp4a6U1@mid.uni-berlin.de> <1192115372.754998.270520@o80g2000hse.googlegroups.com> Message-ID: <470E3E82.8040808@timgolden.me.uk> jeremito wrote: > On Oct 11, 10:43 am, "Diez B. Roggisch" wrote: >> jeremito wrote: >>> My Python script makes a bunch of images that I want to use as frames >>> in a movie. I've tried searching for a module that will take these >>> images and put them together in a Quicktime or mpeg movie, but haven't >>> found anything. My images are currently pdfs, but I could make them >>> into just about anything if needed. >>> Is there a module, or example of how to do this? >> http://pymedia.org/ >> >> Diez > > That initially looked promising, but it looks like nobody is working > on it anymore and it doesn't compile on Mac. (I should have mentioned > I am using a Mac.) Any other suggestions? Not really a Python module but... run them through mencoder? (Haven't tried it but it seems to be saying it's possible). http://www.mplayerhq.hu/DOCS/man/en/mplayer.1.html#EXAMPLES%20OF%20MENCODER%20USAGE TJG From kyosohma at gmail.com Tue Oct 30 15:38:12 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 30 Oct 2007 19:38:12 -0000 Subject: simple? embedding question In-Reply-To: <1193769063.364226.208300@o38g2000hse.googlegroups.com> References: <1193769063.364226.208300@o38g2000hse.googlegroups.com> Message-ID: <1193773092.878006.203990@o3g2000hsb.googlegroups.com> On Oct 30, 1:31 pm, snd... at gmail.com wrote: > suppose i have imported two modules foo and bar with > foo=PyImport_ImportModule("foo") and bar=PyImport_ImportModule("bar") > respectively. > > Now suppose I have an artitrary python expression to evaluate. > Do I need to parse that thring and check for foo. and bar. before > jumping the usual > PyModule_GetDict,PyDict_GetItemString,PyObject_CallObject hoop hoop on > the PyObject for > the prefix or there is a better way? > > btw PyRun_SimpleString("foo.baz()"); does not work: > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'foo' is not defined > > and i potentially need a PyObject* back with the result of the > expression anyway. I'm confused. What is the benefit of importing this way in the first place? Everything I've read has always been either of the following (or a variant thereof): import foo or from foo import bar Mike P.S. Yes, I did see the docs mention this method here: http://docs.python.org/api/importing.html but i have always followed http://effbot.org/zone/import-confusion.htm or http://docs.python.org/ref/import.html From tokland at gmail.com Mon Oct 22 16:10:10 2007 From: tokland at gmail.com (tokland at gmail.com) Date: Mon, 22 Oct 2007 13:10:10 -0700 Subject: Iteration for Factorials In-Reply-To: <87bqarov3n.fsf@rudin.co.uk> References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <1193075845.148527.80820@k35g2000prh.googlegroups.com> <87bqarov3n.fsf@rudin.co.uk> Message-ID: <1193083810.302605.128630@y27g2000pre.googlegroups.com> On 22 oct, 20:35, Paul Rudin wrote: > import operator > def fact(x): > return reduce(operator.mul, xrange(1,x)) Maybe: import operator def fact(x): return reduce(operator.mul, xrange(2, x+1), 1) fact(0) 1 fact(4) 24 From alexandre.badez at gmail.com Wed Oct 24 08:09:40 2007 From: alexandre.badez at gmail.com (Alexandre Badez) Date: Wed, 24 Oct 2007 12:09:40 -0000 Subject: Better writing in python Message-ID: <1193227780.481365.261900@q3g2000prf.googlegroups.com> I'm just wondering, if I could write a in a "better" way this code lMandatory = [] lOptional = [] for arg in cls.dArguments: if arg is True: lMandatory.append(arg) else: lOptional.append(arg) return (lMandatory, lOptional) I think there is a better way, but I can't see how... From steve at holdenweb.com Sat Oct 20 08:30:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Oct 2007 08:30:51 -0400 Subject: Elisp Tutorial: HTML Syntax Coloring Code Block In-Reply-To: <1192779973.14981.36.camel@viola.izb.knu.ac.kr> References: <1192680926.420317.16630@v29g2000prd.googlegroups.com> <1192779973.14981.36.camel@viola.izb.knu.ac.kr> Message-ID: <4719F4FB.7020508@holdenweb.com> Byung-Hee HWANG wrote: [... whole article quoted ...] > +1 ;; > BTW, what is G2/1.0? Is that Emacs-like editor? > I can't tell you that, but I do know that someone who quotes a whole lengthy article like that just to ask a simple question isn't being very considerate of their readers. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it From musiccomposition at gmail.com Mon Oct 15 22:39:20 2007 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 16 Oct 2007 02:39:20 -0000 Subject: Newbi Q: What is a rational for strings not being lists in Python? In-Reply-To: References: <53396d9e0710150805n6e2cfa53je05d24ec51190aa0@mail.gmail.com> Message-ID: <1192502360.503727.299990@e34g2000pro.googlegroups.com> On Oct 15, 3:03 pm, "Matt McCredie" wrote: > On 10/15/07, Dmitri O.Kondratiev wrote: > > > > > To clarify my point: > > reverse() is a lucky one - Python has variants of *this particular* > > function both for lists and strings. Yet what about other list functions? > > How in general, can I write a function that works both on list and string > > types? Both are sequences, right? Why string is not a subtype of a list > > then? > > The advantage of string being a list of elements, where element is a char is > > that all list functions will work *without any modifications* on strings as > > well as on other types of lists. > > So, I am trying to understand: what is a rational for strings not being > > lists in Python? > > > Thanks, > > -- > > Dmitri O. Kondratiev > > doko... at gmail.com > >http://www.geocities.com/dkondr > > > On 10/15/07, Dmitri O.Kondratiev wrote: > > > Gary, thanks for lots of info! > > > Python strings are not lists! I got it now. That's a pity, I need two > > different functions: one to reverse a list and one to reverse a string: > > > > def reverseList(xs): > > > if xs == []: > > > return xs > > > else: > > > return (reverseList (xs[1:])) + [xs[0]] > > > > def reverseStr(str): > > > if str == "": > > > return str > > > else: > > > return (reverseStr (str[1:])) + str[0] > > > > Ok. Now regarding in-place reversal of a list: > > > > >>> l = [1,2,3] > > > >>> l > > > [1, 2, 3] > > > >>> l.reverse() > > > >>> l > > > [3, 2, 1] > > > > That was, as I expected. Good. > > > > Then why this ? : > > > > >>> ls = [1,2,3].reverse() > > > >>> ls > > > > >>> print [1,2,3].reverse() > > > None > > > > I mean, why ls is empty after assignment? > > > > Also, I couldn't find in the Python docs what this form of slicing means: > > > xs[::-1] ? > > > > It works for creating a reversed copy of either a string or a list, but > > what does '::-1' syntax means? > > > > Thanks, > > > > Dmitri O. Kondratiev > > > doko... at gmail.com > > >http://www.geocities.com/dkondr > > > > On 10/15/07, Gary Herron < gher... at islandtraining.com> wrote: > > > > Dmitri O.Kondratiev wrote: > > > > > > The function I wrote (below) reverses lists all right: > > > > > > def reverse(xs): > > > > > if xs == []: > > > > > return [] > > > > > else: > > > > > return (reverse (xs[1:])) + [xs[0]] > > > > > > >>> reverse ([1,2,3]) > > > > > [3, 2, 1] > > > > > > Yet when I try to reverse a string I get: > > > > > > >>> reverse ("abc") > > > > > > ... > > > > > ... > > > > > ... > > > > > > File "C:\wks\python-wks\reverse.py", line 5, in reverse > > > > > > return (reverse (xs[1:])) + [xs[0]] > > > > > > File "C:\wks\python-wks\reverse.py", line 5, in reverse > > > > > > return (reverse (xs[1:])) + [xs[0]] > > > > > > File "C:\wks\python-wks\reverse.py", line 2, in reverse > > > > > > if xs == []: > > > > > > RuntimeError: maximum recursion depth exceeded in cmp > > > > > > What's wrong? Why recursion never stops? > > > > > If you are doing this as an python-learning exercise, then read on. If > > > > you are doing this reversal for real code, then try: > > > > > xs.reverse() for in-place reversal of a list (but not a string), or > > > > result = xs[::-1] for creating a reversed copy of either a string or a > > > > list > > > > > Your recursion stops when xs == [], but when you're stripping characters > > > > off a string, like 'abc', the remaining portion will be 'bc', then 'c', > > > > than '', but never [] so you 'll never stop. > > > > > Try: > > > > > if xs == []: > > > > return [] > > > > elif xs == '': > > > > return '' > > > > else: > > > > ... > > > > > Gary Herron > > > > > > Thanks, > > > > > Dima > > The example you posted won't work with tuples either because they, > like strings, are also immutable. So, the best way to get the posted > code to work (which is a bad way to go about reversing a string, but I > digress) is to cast the input parameter to a list first. The returned > value will always be a list, but you will simply have to convert it > back to the appropriate type when you are done. > > What is the purpose if immutability? It allows a value to be hashed. I > don't want to get into a discussion about methods for hashing mutable > types, if you are interested just do a search on the list archives. > Hashing allows for quick comparisons of values, but more importantly > it allows for values to be used as keys for the dict type. This is > very important because, as you will soon find out if you keep learning > the language, all namespaces in python are implemented as dicts. Good explanation, but basically strings are immutable so they can be used in dicts. > > So... if you want a mutable string, just cast it to a list, do your > operations and cast it back to a string. > > Incidentally, the proper method for converting a list of characters to > a string is by using the join method on an empty string. > > >>> s = "I am a string" > >>> x = list(s) > >>> x > > ['I', ' ', 'a', 'm', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']>>> "".join(x) > > 'I am a string' > > Matt From kyosohma at gmail.com Tue Oct 16 15:14:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 16 Oct 2007 19:14:33 -0000 Subject: Good Book In-Reply-To: References: Message-ID: <1192562073.382154.111530@k35g2000prh.googlegroups.com> On Oct 16, 3:00 am, Lars Johansen wrote: > HI are there any recommended books for an sysadmin who has been mostly > writing shell scripts, but want to move up to create more complex > programs. See also http://www.ibm.com/developerworks/aix/library/au-python/ http://www.samag.com/documents/s=8964/sam0312a/0312a.htm Mike From fw3 at hotmail.co.jp Wed Oct 10 16:38:30 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Wed, 10 Oct 2007 20:38:30 +0000 Subject: Launch file from Python In-Reply-To: References: <1186594137.971393.128780@57g2000hsv.googlegroups.com> Message-ID: I have tried to use os.system to run an application inside python on ms-window. However, the applicaion will grap the python and I could not do anything inside python shell unless I quit the application. Are there any way to avoid this? so I can still type command in python shell. Here is the command I used to open the editor: os.sytem('gvim test.py') After this command if I do not quit the gvim, I could not enter command in python shell. Thanks Frank > From: grahn+nntp at snipabacken.dyndns.org> Subject: Re: Launch file from Python> Date: Sun, 12 Aug 2007 17:44:48 +0000> To: python-list at python.org> > On Wed, 08 Aug 2007 10:28:57 -0700, jocago at gmail.com wrote:> > Good afternoon from someone who is trying to learn Python.> >> > I would like to launch an app from within a Python script. From the> > examples I have found, I should be able to do this with os.system.> >> > I use this:> > os.system("xplanet-1.2.0/xplanet.exe -fontsize 24 -label -target earth> > -lat 33.65 -lon -84.42 -radius 40 -num_times 1 -tmpdir .")> > This is copied directly from the .bat file that launches the xplanet> > app. It works there.> >> > and get this:> > 1> > That means "error", as others noted.> > It is odd that you get no printouts. Had this been on Unix, you'd> either get "file not found" or similar from the shell trying to run> the thing, or something from xplanet itself (only really badly> programs return failure without printing some kind of cause).> > Two more comments, assuming you are on Windows (you mention ".bat> files"):> > - You use the relative path xplanet-1.2.0/xplanet.exe. That should> require your program to have the parent of xplanet-1.2.0 as current> directory. Did the .bat script change directory first?> > - It is unusual to use / as a path separator on Windows --> xplanet-1.2.0\xplanet.exe is more normal. Some parts of Windows> tolerate both, others do not, IIRC. But Python itself should not> care in this case.> > /Jorgen> > -- > // Jorgen Grahn \X/ snipabacken.dyndns.org> R'lyeh wgah'nagl fhtagn!> -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ ???????????????????????????MSN ??????? http://keyword.jp.msn.com/default.aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan.behnel-n05pAM at web.de Tue Oct 9 06:52:02 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 09 Oct 2007 12:52:02 +0200 Subject: Python and UML In-Reply-To: <1191925999.268412.39470@v3g2000hsg.googlegroups.com> References: <1191915187.827445.222470@r29g2000hsg.googlegroups.com> <5n12llFfhe3hU3@mid.uni-berlin.de> <1191925999.268412.39470@v3g2000hsg.googlegroups.com> Message-ID: <470B5D52.2060306@web.de> aine_canby at yahoo.com wrote: > On 9 Okt, 12:15, "Diez B. Roggisch" wrote: >>> IMHO UML is ... crap, at least when it comes to actual developing. > > What alternatives are there? What's your use case? Stefan From gagsl-py2 at yahoo.com.ar Mon Oct 29 21:10:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Oct 2007 22:10:16 -0300 Subject: getting serialized data into and out of a database References: <887503.28306.qm@web55308.mail.re4.yahoo.com> Message-ID: En Mon, 29 Oct 2007 19:07:18 -0300, Michael Pelz Sherman escribi?: > I'm having a devil of a time getting serialized data into and out of a > database (MySQL in this case) using python and MySQLdb. > > I have some C code that has its own serialization/deserialization > functions, which we've wrapped using SWIG. > > I am able to save the serialized C structs to disk but when I try to > write the exact same data to MySQL and pull it back out, I'm getting > some strange results. The data comes back looking like this: > > array('c', '\x01r\x01\x00\x...) > > Is this a python buffer, or what? How can I access the data in there? > I've tried using [1] but that doesn't seem to work. It's an array of characters You can write it to disk again using its tofile() method -- Gabriel Genellina From pavlovevidence at gmail.com Wed Oct 10 09:38:14 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 10 Oct 2007 06:38:14 -0700 Subject: Singleton In-Reply-To: <1192023276.765950.198300@57g2000hsv.googlegroups.com> References: <1192009016.858568.58430@50g2000hsm.googlegroups.com> <1192023276.765950.198300@57g2000hsv.googlegroups.com> Message-ID: <1192023494.013843.106200@22g2000hsm.googlegroups.com> On Oct 10, 9:34 am, OnCallSupport... at gmail.com wrote: > Spring Python (http://springpython.python-hosting.com) offers a [snip spam] Too bad your bot can't be bothered to read the post it would have known the singleton wasn't the problem here. Carl Banks From python at kareta.de Sun Oct 28 08:47:21 2007 From: python at kareta.de (=?ISO-8859-15?Q?J=FCrgen_Kareta?=) Date: Sun, 28 Oct 2007 13:47:21 +0100 Subject: Using matplotlib/wxpython on XP embedded Message-ID: <472484D9.4020402@kareta.de> Hello List, my customer is looking for an application to show some simple 2d graphs based on messured data. I'm consider to use wxpython, matplotlib and py2exe to build and compile this application. Mayby I also like to use WxMPL and inosetup. The target platform is XP embedded. As I don't have XP embedded available, I can't try it out. So my question is, if somebody has experiances with the above mentioned libraries on XP embedded ? Should it work out of the box similar to a usual windows environment or do I have to do some special builds for XPe or is it even impossible to use those libraries on it? Thanks for your help. J?rgen From sluggoster at gmail.com Mon Oct 22 18:07:33 2007 From: sluggoster at gmail.com (Mike Orr) Date: Mon, 22 Oct 2007 22:07:33 -0000 Subject: if instance exists problem .. In-Reply-To: <13hdj38n7n3bv55@corp.supernews.com> References: <1192662735.463554.165450@e9g2000prf.googlegroups.com> <13hdj38n7n3bv55@corp.supernews.com> Message-ID: <1193090853.386644.11670@y27g2000pre.googlegroups.com> On Oct 17, 8:00 pm, Steven D'Aprano wrote: > On Wed, 17 Oct 2007 23:12:15 +0000, Paul Hankin wrote: > > 'if x' doesn't test if x exists, it tests if x when cast to a bool is > > True. > > To be pedantic: > > Python doesn't have type casts. bool(x) doesn't cast x as a bool, it > creates a brand new Boolean object from x. > > Also, the "if x" test looks at x.__nonzero__() first, and if that method > doesn't exist, it looks to see if x.__len__() returns 0 or not. See > > http://docs.python.org/ref/customization.html To be lazy, you can get away with 'if x:' if you *know* that neither the class nor its superclasses override .__nonzero__ or .__len__, because the instance then defaults to true. Classes that *do* override these methods are generally emulating a numeric or collection type, or are using False to signal "something isn't there". ConfigParser is doing the latter. That may or may not have been a good choice by the ConfigParser developers, because it's debatable how useful it is for empty ConfigParsers to be False. But the fact remains that it is this way, and an instance of *any* third-party class may be false for reasons you don't expect. --Mike From andrewwest at gmail.com Fri Oct 26 21:14:18 2007 From: andrewwest at gmail.com (Andrew West) Date: Sat, 27 Oct 2007 01:14:18 -0000 Subject: Finding decorators in a file Message-ID: <1193447658.249597.178110@57g2000hsv.googlegroups.com> Probably a bit of weird question. I realise decorators shouldn't be executed until the function they are defined with are called, but is there anyway for me to find all the decorates declared in a file when I import it? Or perhaps anyway to find the decorators by loading the file by other methods (with out simply parsing it by hand). Basically what I'm looking for is a way to, given a python file, look through that file and find all the decorators and the associated functions, that includes any arguments that the decorator has. Sorry if this has been asked before but I've googled no end and come up with nothing so far. From cokofreedom at gmail.com Tue Oct 23 04:10:53 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 23 Oct 2007 08:10:53 -0000 Subject: Python - why don't this script work? In-Reply-To: References: <1193108392.089611.91170@v29g2000prd.googlegroups.com> Message-ID: <1193127053.740024.144730@q5g2000prf.googlegroups.com> On Oct 23, 6:50 am, Ohmster wrote: > Adam Atlas wrote in news:1193108392.089611.91170 > @v29g2000prd.googlegroups.com: > > > I think you're executing it as a shell script. Run "python image- > > harvester.py", or add "#!/usr/bin/env python" to the top of the file. > > Hey that is a cool idea, I think I will try it. I found out what is wrong > and did not get the results I want, I think the images are protected with > script. See my other post in this thread for details. > > Shoot, the followup might have gone to alt.os.linux. I will repost for you > here. > > I figured it out, I have to run python I think first then the script and > the URL like this: > > $ python image-harvester.pyhttp://public.fotki.com/DaGennelman/ > > Now that actually seems to be doing something and it sure is busy now. It > is making a lot of little subdirectories in my test directory. I had to > copy image-harvester.py to the test directory first, then run python and > image-harvester.py w/URL and it is going to town. Tons of subfolders, so > far not images yet but it is not done. At least it is doing something now > and not bitching and hanging. I guess I had to call up python and pass it > to the script as the script does not seem to pull up python on it's own. So > far I have 60 directories and about 45 robots.txt but no jpg files yet. I > will let you know what happens. I think that these images are protected by > script, you never get a valid URL to the imgage file, just referrers, and > numbers and what not. When the image is finally displayed in your browser, > then you can save it but not until then. Pretty good way to stop a > harvester. Is this assumption pretty much correct or is there a way to make > this work? Now that I use python as the first command, I can run it in an > ssh window now and do not require an x-server. > > Feel free to jump right in with your input on how this should or won't work > and what can be done to make it better. I have all of my scripts in a > $HOME/scripts/ directory and it is in my path but running this from another > directory does not work if image-harvester.py is not in the harvest > directory where I run the script from. I can right click on the image and > save it but the amazing script trips all over itself with these wacky file > name. I am all ears if someone figures it. > > -- > ~Ohmster | ohmster /a/t/ ohmster dot com > Put "messageforohmster" in message body > (That is Message Body, not Subject!) > to pass my spam filter. Do note that the reason you may not see images is that the website has, '''correctly''', identified your program as an automated bot and blocked it access to things... From software at ginstrom.com Sat Oct 27 01:53:15 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Sat, 27 Oct 2007 14:53:15 +0900 Subject: simple question on dictionary usage In-Reply-To: <1193463043.912167.175890@57g2000hsv.googlegroups.com> References: <1193463043.912167.175890@57g2000hsv.googlegroups.com> Message-ID: <000001c8185d$ab323a80$0203a8c0@MOUSE> > On Behalf Of Edward Kozlowski > I think this should do the trick. There's probably something > more concise than this, but I can't think of it at the moment. > > egt = {} > for key in record: > if key.startswith('E'): > egt[key] = record[key] Not much more concise, but another way: egt = dict((key, record[key]) for key in record if key.startswith('E')) Regards, Ryan Ginstrom From kyosohma at gmail.com Mon Oct 8 10:02:39 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 08 Oct 2007 14:02:39 -0000 Subject: How to create a file on users XP desktop In-Reply-To: References: <1191727914.018474.172950@g4g2000hsf.googlegroups.com> <1191735169.441525.106060@o80g2000hse.googlegroups.com> <4708CAF4.7020206@bigfoot.com> <47090D86.5080805@tim.thechases.com> Message-ID: <1191852159.536423.63340@19g2000hsx.googlegroups.com> On Oct 7, 12:30 pm, Tim Golden wrote: > Tim Chase wrote: > >> You are assuming the system is not localized, that won't work if you > >> distribute your applications internationally. In my system it is not > >> "Desktop", it is "Escritorio", and I guess it will vary with every > >> locale. Does someone know a way to find out what name does the desktop > >> have? > > > I believe you need to read the Desktop value from > > > """ > > HKEY_CURRENT_USER\software\microsoft\windows\currentversion\explorer\shell > > folders > > """ > > > which should (in my understanding) hold the full path of the > > particular folder(s) of interest at that location, including > > across localizations. > > > -tkc > > Ideally, use the shell API exposed by pywin32: > > > from win32com.shell import shell, shellcon > > desktop = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0) > > > > For slight convenience: > > http://timgolden.me.uk/python/winshell.html > > TJG What happened to your winshell module? I would have thought it perfect for this. http://timgolden.me.uk/python/winshell.html Mike From george.sakkis at gmail.com Tue Oct 30 01:30:13 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 30 Oct 2007 05:30:13 -0000 Subject: A Python 3000 Question In-Reply-To: References: <87abq1mxqc.fsf@merkury.smsnet.pl> Message-ID: <1193722213.601946.184070@v29g2000prd.googlegroups.com> On Oct 29, 9:35 pm, Michael L Torrie wrote: > brad wrote: > > Not complaining. len is simple and understandable and IMO fits nicely > > with split(), strip(), etc... that's why I used it as an example, but > > list(), etc. could be used as examples as well: > > > a_string.list() instead of list(a_string) > > This is a great example of why list() needs to be a singleton and *not* > a method of any particular class. The whole discussion about list() is moot since it's not a function anyway, it's a type. As long as a list knows hows to initialize itself given any iterable, it would be useless to require it as a method to the iterables as well (unless perhaps there are significant performance improvements when one can create a list much faster than iterating through it). > Saying list() should be a method only of something iterable is not only > foolish, but wasteful. Why should I burden every iterable object with > redundant code? Does the same argument apply for len() ? Nope, you still have to define __len__. Having a builtin len() that calls the method __len__ seems (using your words) "not only foolish but wasteful". > In short, making list() a method is wrong-thinking. Reminds me of java. > Ugg. Agreed, but you're beating a dead horse with list(). > If find Python to be more OO through and through than Java. Once you > understand that functions are objects, and duck-typing, things like > len() being a function rather than a method make perfect sense. Does the fact that index() or split() are methods make perfect sense as well? I guess after some time using Python it does, but for most unbiased users the distinction seems arbitrary. George From gneuner2/ at comcast.net Wed Oct 3 13:21:47 2007 From: gneuner2/ at comcast.net (George Neuner) Date: Wed, 03 Oct 2007 13:21:47 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <13frd6vtarbee75@corp.supernews.com> <85ve9ov971.fsf@lola.goethe.zz> Message-ID: On Wed, 3 Oct 2007 09:36:40 +0000 (UTC), bcd at pvv.ntnu.no (Bent C Dalager) wrote: >In article <85ve9ov971.fsf at lola.goethe.zz>, David Kastrup wrote: >>bcd at pvv.ntnu.no (Bent C Dalager) writes: >> >>> In article , >>> Frank Goenninger wrote: >>>> >>>>Well, I didn't start the discussion. So you should ask the OP about the >>>>why. I jumped in when I came across the so often mentioned "hey, it's >>>>all well defined" statement was brought in. I simply said that if that >>>>"well-definedness" is against "common understanding" then I don't give >>>>a damn about that clever definitions. Because I have to know that there >>>>are such definitions - always also knowing that free is not really >>>>free. >>> >>> "Liberated" is a valid meaning of the word "free". >> >>No. It is a valid meaning of the word "freed". > >Only if you're being exceedingly pedantic and probably not even >then. Webster 1913 lists, among other meanings, > >Free >(...) >"Liberated, by arriving at a certain age, from the control >of parents, guardian, or master." > >The point presumably being that having been "liberated", you are now >"free". I don't think knowing the meaning of a word is being pedantic. "Freed" is derived from "free" but has a different, though associated, meaning. Words have meaning despite the many attempts by Generation X to assert otherwise. Symbolism over substance has become the mantra of the young. The English language has degenerated significantly in the last 30 years. People (marketers in particular) routinely coin ridiculous new words and hope they will catch on. I remember seeing a documentary (circa 1990?) about changes in the English language. One part of the program was about the BBC news and one of its editors, whom the staff called the "protector of language", who checked the pronunciation of words by the news anchors. The thing that struck me about this story was the number of BBC newspeople who publicly admitted that they could hardly wait for this man to retire so they could write and speak the way they wanted rather than having to be "correct". Dictionaries used to be the arbiters of the language - any word or meaning of a word not found in the dictionary was considered a colloquial (slang) use. Since the 1980's, an entry in the dictionary has become little more than evidence of popularity as the major dictionaries (OED, Webster, Cambridge, etc.) will now consider any word they can find used in print. George -- for email reply remove "/" from address From marek.rocki at wp.pl Wed Oct 24 18:19:30 2007 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Wed, 24 Oct 2007 15:19:30 -0700 Subject: Iteration for Factorials In-Reply-To: References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <5o3jalFl0n43U1@mid.uni-berlin.de> <1193056647.416562.36150@q3g2000prf.googlegroups.com> <1193057676.680959.71780@v23g2000prn.googlegroups.com> <1193064348.526006.183080@q5g2000prf.googlegroups.com> Message-ID: <1193264370.786983.242180@y27g2000pre.googlegroups.com> Tim Golden napisa (a): > It's only a moment before the metaclass and > the Twisted solution come along. :) I couldn't resist. It's not as elegant as I hoped, but hey, at least it memoizes the intermediate classes :-) class fact_0(object): value = 1 class fact_meta(object): def __new__(cls, name, bases, attrs): n = attrs['n'] class_name = 'fact_%i' % n try: return globals()[class_name] except KeyError: new_class = type(class_name, bases, {}) new_class.value = n * fact(n - 1).value new_class.__str__ = lambda self: str(self.value) globals()[class_name] = new_class return new_class class fact(object): def __new__(self, n_): class spanish_inquisition(object): __metaclass__ = fact_meta n = n_ return spanish_inquisition() print fact(5) print fact(3) print fact(1) From mccredie at gmail.com Thu Oct 18 12:41:42 2007 From: mccredie at gmail.com (Matimus) Date: Thu, 18 Oct 2007 16:41:42 -0000 Subject: Convert string to command.. In-Reply-To: <1192723746.476620.244430@e34g2000pro.googlegroups.com> References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> <5npa5cFj5bvfU1@mid.uni-berlin.de> <1192720007.177063.194550@i13g2000prf.googlegroups.com> <5npbjbFio7g9U1@mid.uni-berlin.de> <1192720659.272611.320900@v29g2000prd.googlegroups.com> <5npcq3Fjgi5nU1@mid.uni-berlin.de> <1192722434.921870.112350@k35g2000prh.googlegroups.com> <5npe2qFjhdjpU1@mid.uni-berlin.de> <1192723746.476620.244430@e34g2000pro.googlegroups.com> Message-ID: <1192725702.690339.302300@q5g2000prf.googlegroups.com> On Oct 18, 9:09 am, Abandoned wrote: > On Oct 18, 6:57 pm, "Diez B. Roggisch" wrote: > > > > > Abandoned wrote: > > > On Oct 18, 6:35 pm, "Diez B. Roggisch" wrote: > > >> Abandoned wrote: > > >> > On Oct 18, 6:14 pm, "Diez B. Roggisch" wrote: > > >> >> Abandoned wrote: > > >> >> > Thanks you all answer.. > > >> >> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19....} > > >> >> > (100.000 elements) > > >> >> > Is there any easy alternative ? > > > >> >> How big? How slow? For me, a 10000-element list takes 0.04 seconds to > > >> >> be parsed. Which I find fast. > > > >> >> Diez > > > >> > 173.000 dict elements and it tooks 2.2 seconds this very big time for > > >> > my project > > > >> Where does the data come from? > > > >> Diez > > > > Data come from database.. > > > I want to cache to speed up my system and i save the dictionary to > > > database for speed up but eval is very slow for do this. > > > Not: 2.2 second only eval operation. > > > Does the dictionary change often? > > > And you should store a pickle to the database then. Besides, making a > > database-query of that size (after all, we're talking a few megs here) will > > take a while as well - so are you SURE the 2.2 seconds are a problem? Or is > > it just that you think they are? > > > Diez- Hide quoted text - > > > - Show quoted text - > > I'm very confused :( > I try to explain main problem... > I have a table like this: > id-1 | id-2 | value > 23 24 34 > 56 68 66 > 56 98 32455 > 55 62 655 > 56 28 123 > .... ( 3 millions elements) > > I select where id=56 and 100.000 rows are selecting but this took 2 > second. (very big for my project) > I try cache to speed up this select operation.. > And create a cache table: > id-1 | all > 56 {68:66, 98:32455, 62:655} > > When i select where id 56 i select 1 row and its took 0.09 second but > i must convert text to dictionary.. > > Have you got any idea what can i do this conver operation ? > or > Have you got any idea what can i do cache for this table ? I think several people have given you the correct answer, but for some reason you aren't getting it. Instead of saving the string representation of a dictionary to the database, pickle the dictionary (not the string representation, but the actual dictionary) and save the pickled object as a BLOB to the database. using pickle to re- create the dictionary should be much faster than evaluating a string representation of it. Matt From jens.hester at googlemail.com Tue Oct 16 17:05:19 2007 From: jens.hester at googlemail.com (jens.hester at googlemail.com) Date: Tue, 16 Oct 2007 14:05:19 -0700 Subject: Embedding Python in a multithreaded managed C++ application Message-ID: <1192568719.347572.117970@q5g2000prf.googlegroups.com> Hi experts, I am currently embedding the Python interpreter 2.3.4 in a managed C++ application (I currently use an unmanaged dll which is linked to Python23.lib). Forget about Ironpython - no binary compatibility for extension modules, forget about a decent C API, by the way... After a lot of work I managed to embed the interpreter with the Global Python Interpreter lock correctly used from each thread. I have, however, still a deadlock which I am not able to find and is related to the dll I use. Does anybody have an idea how to debug the exact source of this deadlock by means of the Python debug options. Thanks a lot for any help. ThreadShredder From gagsl-py2 at yahoo.com.ar Wed Oct 3 00:00:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Oct 2007 01:00:43 -0300 Subject: setuptools without unexpected downloads References: <87ejgmklep.fsf@benfinney.id.au> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> <5lurorFa92euU1@mid.uni-berlin.de> <1190805012.275901.227570@57g2000hsv.googlegroups.com> <5luv0iFaai82U1@mid.uni-berlin.de> <1190808836.056298.232640@57g2000hsv.googlegroups.com> <1190840682.716950.131830@r29g2000hsg.googlegroups.com> <1191330684.132452.179580@y42g2000hsy.googlegroups.com> Message-ID: En Tue, 02 Oct 2007 10:11:24 -0300, escribi?: > Holden indicates that VS2003 is the current compiler used for the > official Python distribution. Do you know how to use that program to > compile an exe? Open the program, press F1 and read the documentation provided by its vendor, Microsoft. > I'm assuming the line "python setup.py bdist_wininst" > isn't sufficient since it was an answer to my somewhat naive question. Why not? As F.L. said, if the setup.py is properly built, doing so should compile and link all the required modules. Note that it's not *required* to use Visual Studio to compile Python extensions; any decent compiler would do [provided it links against the same RTL as used by VS] This recent blog post contains step-by-step instructions on using free tools to compile python extensions: -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Oct 29 00:03:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Oct 2007 01:03:35 -0300 Subject: Capturing output with input References: <1193596747.543020.78280@e34g2000pro.googlegroups.com> Message-ID: En Sun, 28 Oct 2007 15:39:07 -0300, gopala escribi?: > My initial attempts of using spawn.. , exec.. pipe.. failed since they > can't capture the std input and std output continuously. > The lab1.exe will be something like > > Enter 2 nos > 2 3 > The sum is 5 > > Now i should be able to capture all these. > Is this possible ? If so please do give me some hints on how to > achieve this. On Linux, use the "script" command. On Windows, select the region to copy using the mouse and paste it onto a notepad file. I don't think Python would help here. -- Gabriel Genellina From bh at izb.knu.ac.kr Fri Oct 19 23:53:55 2007 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Sat, 20 Oct 2007 12:53:55 +0900 Subject: Distributed RVS, Darcs, tech love In-Reply-To: <1192850894.310464.89070@e9g2000prf.googlegroups.com> References: <1192850894.310464.89070@e9g2000prf.googlegroups.com> Message-ID: <1192852435.18000.57.camel@viola.izb.knu.ac.kr> On Fri, 2007-10-19 at 20:28 -0700, Xah Lee wrote: > When i first heard about distributed revision control system about 2 > years ago, i heard of Darcs, which is written in Haskell. I was hugely > excited, thinking about the functional programing i love, and the no- > side effect pure system i idolize, and the technology of human animal > i rapture in daily. > > I have no serious actual need to use a revision system (RVS) in recent > years, so i never really tried Darcs (nor using any RVS). I just > thought the new-fangled distributed tech in combination of Haskell was > great. > > About few months ago, i was updating a 6-year old page i wrote on unix > tools: ( http://xahlee.org/UnixResource_dir/usoft.html ) and i was > trying to update myself on the current state of art of revision > systems. I read Wikipedia this passage: > > http://en.wikipedia.org/wiki/Darcs > > ? Darcs currently has a number of significant bugs (see e.g. [1]). The > most severe of them is "the Conflict bug" - an exponential blowup in > time needed to perform conflict resolution during merges, reaching > into the hours and days for "large" repositories. A redesign of the > repository format and wide-ranging changes in the codebase are planned > in order to fix this bug, and work on this is planned to start in > Spring 2007 [2]. ? > > This somewhat bursted my bubble, as there always was some doubt in the > back of my mind about just how Darcs is not just a fantasy-ware > trumpeted by a bunch of functional tech geekers. (i heard of Darcs in > irc emacs and haskell channels, who are often student and hobbiests > programers) > > Also, in my light research, it was to my surprise, that Darcs is not > the only distributed systems, and perhaps not the first one neither, > contrary to my impressions. In fact, today there are quite a LOT > distributed revision systems, actually as a norm. When one looks into > these, such as Git ( http://en.wikipedia.org/wiki/Git_(software) ) one > finds that some of them are already in practical industrial use for > large projects, as opposed to Darcs's academic/hobbist kind of > community. > > In addition to these findings, one additional that greatly pissed me > off entirely about Darcs, is the intro of the author (David Roundy)'s > essay about his (questionable-sounding) ?theory of patches? used in > Darcs. ( http://darcs.net/manual/node8.html#Patch ) > > Here's the 2 passages: > > ?I think a little background on the author is in order. I am a > physicist, and think like a physicist. The proofs and theorems given > here are what I would call ``physicist'' proofs and theorems, which is > to say that while the proofs may not be rigorous, they are practical, > and the theorems are intended to give physical insight. It would be > great to have a mathematician work on this, but I am not a > mathematician, and don't care for math.? > > ?From the beginning of this theory, which originated as the result of > a series of email discussions with Tom Lord, I have looked at patches > as being analogous to the operators of quantum mechanics. I include in > this appendix footnotes explaining the theory of patches in terms of > the theory of quantum mechanics. I know that for most people this > won't help at all, but many of my friends (and as I write this all > three of darcs' users) are physicists, and this will be helpful to > them. To non-physicists, perhaps it will provide some insight into how > at least this physicist thinks.? > > I love math. I respect Math. I'm nothing but a menial servant to > Mathematics. Who the fuck is this David guy, who proclaims that he's > no mathematician, then proceed to tell us he dosen't fucking care > about math? Then, he went on about HIS personal fucking zeal for > physics, in particular injecting the highly quacky ?quantum mechanics? > with impunity. I'm gonna like your writings with all respect. Actually your writings has the quiet force. See you often ;; -- Byung-Hee HWANG * ??? ?????? ???????? InZealBomb, Kyungpook National University, KOREA "OK. Then I have to kill him." -- Michael Corleone, "Chapter 11", page 146 From robert.kern at gmail.com Tue Oct 2 00:57:55 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 01 Oct 2007 23:57:55 -0500 Subject: gui toolkits: the real story? (Tkinter, PyGTK, etc.) In-Reply-To: <1191294265.611162.57730@g4g2000hsf.googlegroups.com> References: <1191287053.541506.88530@d55g2000hsg.googlegroups.com> <1191292451.096937.63000@50g2000hsm.googlegroups.com> <1191294265.611162.57730@g4g2000hsf.googlegroups.com> Message-ID: bramble wrote: > On Oct 1, 10:34 pm, Benjamin wrote: >> and they are still supported >> not to break compatability. > > Hm. Ok. I can see that for the 2.x releases. But Py3k is all about > breaking compatibility, so, it would seem there's more to the story. Yes, compatibility is broken, strictly speaking; however, the goal is that the majority of changes can be handled automatically using the 2to3 tool to convert the source code. You can't really do that if you remove Tkinter entirely. -- 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 Wed Oct 17 19:12:49 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Oct 2007 01:12:49 +0200 Subject: if instance exists problem .. In-Reply-To: References: Message-ID: <5nnj7qFjae1oU1@mid.uni-berlin.de> stef mientki schrieb: > hello, > > I've written a convenience wrapper around ConfigObj (which is a imporved > ConfigParser). > > Now if I use an instance of the base class, I can easily test is the > instance exists by " if ini:", > like in this example > > ini = None > if ini: > print 'ok',type(ini) > else: > print 'wrong',type(ini) > ini = ConfigObj (filename) > if ini: > print 'ok',type(ini) > else: > print 'wrong',type(ini) > > Now if I derive a new class form this: > class inifile (ConfigObj): > def __init__ (self, filename): > self.ini = ConfigObj ( filename , list_values = False, > write_empty_values = True ) > self.ini.newlines = '\r\n' # not strictly necessary > self.Section = '' > self.Modified = False > > > the test if an instance exists, always returns false. > ini = inifile (filename) > if ini: > print 'ok',type(ini) > else: > print 'wrong',type(ini) > > Why is that ? > What should I do to the same simple test for existance ? Use isinstance(obj, type). Diez From researchbase at gmail.com Mon Oct 29 06:44:47 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Mon, 29 Oct 2007 16:14:47 +0530 Subject: problem opening html file with webbrowser.open Message-ID: hello all, as I posted in my previous thread, I am generating html reports for my client software. I am yet to find a satisfactory module which can help me actually create headings, bold and italics etc without merging html with data variables. any ways I am right now doing the hamd coding myself. may be I have overlooked some module. right now I am in the process of trying templayer. but my main issue is that when I use the webbrowser.open("file:///home/myname/report.html"), webbroser opens but the page does not come up. there is certainly some thing wrong in what I am giving to the open function. can some one correct me? regards, Krishnakant. From gandalf at designaproduct.biz Wed Oct 10 05:38:28 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 10 Oct 2007 11:38:28 +0200 Subject: Static variable vs Class variable In-Reply-To: <13go2edckqnrrf0@corp.supernews.com> References: <1191946572.001076.271970@50g2000hsm.googlegroups.com> <5n1rosFftvtbU1@mid.uni-berlin.de> <13gngt29ovvcld1@corp.supernews.com> <13go2edckqnrrf0@corp.supernews.com> Message-ID: <470C9D94.3030101@designaproduct.biz> Steven D'Aprano ?rta: > On Tue, 09 Oct 2007 21:25:38 +0200, Laszlo Nagy wrote: > > >> a = 1 >> a+= 1 # The compiler will probably optimize this and the Python bytecode >> interpreter will not rebind 'a' here, just increment the integer in >> memory. >> > > No. This is Python, not C. You can't increment integers in memory. > What? Please read my post. I was talking about __implementation level__, clearly. :-) From bj_666 at gmx.net Mon Oct 29 19:52:25 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Oct 2007 23:52:25 GMT Subject: statvfs References: Message-ID: <5ona1oFneqbaU3@mid.uni-berlin.de> On Mon, 29 Oct 2007 16:52:12 -0500, Korthrun wrote: > I'm writing some scripts to populate RRD's, mainly for practicing python. > > As such I've decided to play with statvfs in order to build disk > graphs. Here is what I have and what I get. What I'm curious about > here is the meaning of the "L" charcter, as that fubars math. The L means its a `long` literal, i.e. an integer value that can be arbitrary big. Well its limited by memory of course. And it doesn't "fubar" math, the L just shows up in the string representation but you don't calculate with strings but numbers. > ###start code### > > from os import statvfs, path > from statvfs import * > > mps = [ '/', '/home', '/www', '/var', '/storage/backups', > '/storage/snd' ] > > for fs in mps: > data = statvfs(fs) > print data > > ###end code, start output### > (4096, 4096, 4883593L, 4045793L, 4045793L, 0L, 0L, 0L, 1024, 255) > (4096, 4096, 1220889L, 1114718L, 1114718L, 0L, 0L, 0L, 0, 255) > (4096, 4096, 19267346L, 18273138L, 18273138L, 0L, 0L, 0L, 0, 255) > (4096, 4096, 3662687L, 3492397L, 3492397L, 0L, 0L, 0L, 0, 255) > (4096, 4096, 3417702L, 2116063L, 2116063L, 0L, 0L, 0L, 0, 255) > (4096, 4096, 25885944L, 21799115L, 21799115L, 0L, 0L, 0L, 0, 255) > ###end output### > > Ideally I'll just do some blocksize * number of blocks math to get > the % of used space. Just go ahead and do it: In [185]: stat = os.statvfs('/') In [186]: stat.f_bsize Out[186]: 4096 In [187]: stat.f_blocks Out[187]: 2622526L In [188]: stat.f_bsize * stat.f_blocks Out[188]: 10741866496L Ciao, Marc 'BlackJack' Rintsch From besturk at gmail.com Wed Oct 3 12:22:35 2007 From: besturk at gmail.com (Abandoned) Date: Wed, 03 Oct 2007 09:22:35 -0700 Subject: Duplicate content filter.. Message-ID: <1191428555.278268.253700@g4g2000hsf.googlegroups.com> Hi.. I'm working a search engine project now. And i have a problem. My problem is Duplicate Contents.. I can find the percentage of similarity between two pages but i have a 5 millions index and i search 5 million page contents to find one duplicate :( I want to a idea for how can i find duplicate pages quickly and fast ? Please help me, i'm sorry my bad english. King regards.. From trekker182 at comcast.net Sat Oct 27 15:11:37 2007 From: trekker182 at comcast.net (Shawn Minisall) Date: Sat, 27 Oct 2007 15:11:37 -0400 Subject: while within while Message-ID: <47238D69.5010302@comcast.net> I've been having some problems with using a while statement for one menu within another while statement for the main menu, first time I've done it. It's with choice number two from the menu. When I run the program, I get a UnboundLocalError: local variable 'ai' referenced before assignment. I initialize ai as "", but then it just skips to the you choose scissors I choose and nothing shows up. As soon as I take away the while again[0] == "y": statement, the program is fine again which leads me to think I'm just placing it in the wrong place. I just want to ask the user if they would like to play again and loop them back to the weapons menu if they choose yes. If they choose no, loop them back to the main menu. I've placed the question again=raw_input("Would you like to play again? ") at the end the tasks for menu choice two. Ignore three....one step at a time. ;) thx import random def main(): #define and initialize variables #choice as int choice = 0 #weapon choice as int weaponchoice = 0 #number of wins win = 0 #number of loses lose = 0 #number of ties tie = 0 #number of rounds rounds = 0 #play again loop again = "no" #intro print "READY TO PLAY ROCK, PAPER, SCISSORS???" print #Menu loop while choice != 4: #display menu print "Please choose from the following menu: " print "1. See the rules" print "2. Play against the computer" print "3. Play a two player game" print "4. Exit" #prompt user for their menu choice choice = input("Please enter your choice here: ") print #if statements to determine which choice if choice == 1: print print "The rules of the game are as follows: " print print "Rock Covers Rock" print print "Rock Smashes Scissors" print print "Scissors Cuts Paper" print print elif choice == 2: while again[0] == "y": #display menu print "Please choose a weapon from the following menu: " print "1. Rock" print "2. Paper" print "3. Scissors" while weaponchoice != 1 and weaponchoice != 2 and weaponchoice != 3: weaponchoice = input("Please choose a weapon: ") if weaponchoice != 1 and weaponchoice != 2 and weaponchoice != 3: print print "Error. Please enter a number from 1-3." decision = (1, 2, 3) ai = str((random.choice(decision))) if ai == "1": ai = "rock" if ai == "2": ai = "paper" if ai == "3": ai = "scissors" if weaponchoice == 1: weaponchoice = "rock" elif weaponchoice == 2: weaponchoice = "paper" else: weaponchoice = "scissors" print "=====================" print "you choose " + weaponchoice print print "I choose " + ai print if weaponchoice == "rock" and ai == "scissors": win += 1 print "You WIN by SMASHING those SCISSORS!" elif weaponchoice == "paper" and ai == "rock": win += 1 print "You WIN by COVERING that ROCK!" elif weaponchoice == "scissors" and ai == "paper": win += 1 print "You WIN by CUTTING that PAPER!" elif weaponchoice == ai: tie += 1 print "YOU TIE!" else: lose += 1 print "YOU LOSE!" print "\nRounds Won: ", + win print "\nRounds Lost: ", + lose print "\nRounds Tied: ", + tie print print again=raw_input("Would you like to play again? ") elif choice == 3: print "test" elif choice == 4: print "Have a great day!" print print "Thanks for playing!" else: #invalid print "Invalid selection. Please enter a number from 1 - 4." print From hat at se-162.se.wtb.tue.nl Thu Oct 25 05:16:09 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 25 Oct 2007 11:16:09 +0200 Subject: local variable referenced before assignment References: <47205ba1$0$515$5a6aecb4@news.aaisp.net.uk> Message-ID: On 2007-10-25, Pete Bartonly wrote: > > Quick question, probably quite a simple matter. Take the follow start of > a method: > > > def review(filesNeedingReview): > > for item in filesNeedingReview: > (tightestOwner, logMsg) = item > > if (logMsg != None): > for logInfo in logMsg.changed_paths: > > > This generates the error: > > UnboundLocalError: local variable 'logMsg' referenced before assignment This should work, are you sure you didn't make a typo in one of the names? Another way to make this fail would be when the if-condition is outside the loop (is the indentation correct in your code?). A short demontration: >>> def r(fnr): ... for item in fnr: ... w,m = item ... if m == 2: ... print w ... >>> fnr = [(1,2), (3,4)] >>> r(fnr) 1 With respect to compactness and style, you can move your multi-assignment statement in the for loop, as in for tightestOwner, logMsg in filesNeedingReview: Also, brackets around conditions (in the if) are not needed, and comparing against None is usually done with 'is' or 'is not' instead of '==' or '!='. The result is then if logMsg is not None: > I thought I'd assigned it in the "(tightestOwner, logMsg) = item" line - > so in the python interpreter complaining about the fact this assignment > might not go well? No, you'd get an error at that point in that case. Sincerely, Albert From jailtu at luukku.com Sat Oct 13 09:44:00 2007 From: jailtu at luukku.com (Janne Tuukkanen) Date: Sat, 13 Oct 2007 16:44:00 +0300 Subject: Foreign Character Problems In Python 2.5 and Tkinter References: Message-ID: Sat, 13 Oct 2007 16:13:21 +0300, Juha S. kirjoitti: > Thanks for the reply. I made changes to my code according to your > example. Now any Scandinavian characters that are outputted by the > program are missing in the Tk text box. > file = codecs.open(filename, 'r', 'utf-8', 'ignore') Remove that 'ignore'. If you then get error which complains, that utf-8 codec can't handle the file, you've found the culprit. The file might be in iso-8859-1. JanneT From f.braennstroem at gmx.de Wed Oct 17 17:45:36 2007 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Wed, 17 Oct 2007 21:45:36 +0000 Subject: open remote terminal Message-ID: Hi, I would like to use python to start an terminal, e.g. xterm, and login on a remote machine using rsh or ssh. This could be done using 'xterm -e ssh machine', but after the login I would like to jump to a given directory. Does anyone have an idea how to do this with python? Regards! Fabian From fuzzyman at gmail.com Fri Oct 26 18:18:10 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: Fri, 26 Oct 2007 22:18:10 -0000 Subject: Python Windows Installation In-Reply-To: <1193333796.807911.106350@22g2000hsm.googlegroups.com> References: <1193195493.086681.40570@t8g2000prg.googlegroups.com> <1193333796.807911.106350@22g2000hsm.googlegroups.com> Message-ID: <1193437090.956730.253770@o3g2000hsb.googlegroups.com> On Oct 25, 6:36 pm, TheFlyingDutchman wrote: > On Oct 24, 11:22 pm, Tim Roberts wrote: > > > TheFlyingDutchman wrote: > > > >I am trying to install Python 2.5 on Windows XP. It installs into the > > >root directory on C:\ instead of C:\Python25 which it shows by default > > >as what it plans to install to. Selecting D:\Python25 on a previous > > >iteration put the exe in D:\ and did not create a Python25 directory. > > > Where did you get the installer? I've installed Python on Windows many, > > many times, and have never seen this issue. > > -- > > Tim Roberts, t... at probo.com > > Providenza & Boekelheide, Inc. > > from python.org. I doubt many people get this or it would be fixed > but it still is shocking how it can prompt me that the installation > directory exists - showing that it fully knows where it is supposed to > install it - and then go ahead and install it to the root directory > and claim success. It also uninstalls Python if you ask it to so any > screwy settings from a previous install should be removed after the > uninstall, but it also fails to install correctly after an uninstall. I've never had this problem with the Python.org windows installer. However I did once use a machine where Python had been installed into 'c:\Program Files\Python24'. It caused no end of problems... Michael Foord http://www.manning.com/foord From michele.simionato at gmail.com Mon Oct 8 00:06:55 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 08 Oct 2007 04:06:55 -0000 Subject: weakrefs and bound methods In-Reply-To: References: <4708f276$0$11868$3b214f66@tunews.univie.ac.at> <5msflnFepbdqU1@mid.uni-berlin.de> <1191775103.234809.311870@o80g2000hse.googlegroups.com> <13gi4vrfqhrs48d@corp.supernews.com> <1i5m4bz.18obx4r5bg0gaN%aleax@mac.com> Message-ID: <1191816415.377623.125700@o80g2000hse.googlegroups.com> On Oct 7, 11:28 pm, Steven D'Aprano wrote: > On Sun, 07 Oct 2007 12:55:29 -0700, Alex Martelli wrote: > >> What should I do when my objects need to perform some special > >> processing when they are freed, if I shouldn't use __del__? > > > The solid, reliable way is: > > > from __future__ import with_statement > > > and use module contextlib from the Python standard library (or handcode > > an __exit__ method, but that's rarely needed), generating these special > > objects that require special processing only in 'with' statements. This > > "resource acquisition is initialization" (RAII) pattern is the RIGHT way > > to ensure timely finalization (particularly but not exclusively in > > garbage-collected languages, and particularly but not exclusively to > > ease portability to different garbage collection strategies -- e.g., > > among CPython and future versions of IronPython and/or Jython that will > > support the with statement). > > Hmmm... I'm not sure I understand how a with statement is meant to > replace class.__del__ in practice. It seems to me that the two things > have different uses. with is useful when you create an object, do > something with it, dispose of it in an orderly fashion, and then > continue. How does that help when you create an unknown number of long- > lasting objects where you can't predict how and when they will be > disposed of? > > Here's a minimal example. I have a module that returns parrot objects: > > # Parrot module > class Parrot(object): > def __del__(self): > print "I'm now pushing up the daisies" > > # Callers code: > import Parrot > p = Parrot.Parrot() > alist = [Parrot.Parrot() for i in range(1000)] > # do something with p and alist > print p, alist > # instances are deleted in arbitrary order > del p > del alist[3] > del alist[853] > del alist[701] > del alist > > It seems to me that you are saying to re-write the above as something > like this: > > # Parrot module > class Parrot(object): > pass > > class killed(object): # context manager > def __exit__(self, *exc_info): > print "I'm now pushing up the daisies" > > # Callers code: > import Parrot > with killed(Parrot.Parrot()) as p: > # ... er, what do I do with alist??? > # do arbitrary stuff with p and alist > print p, alist > > Now, I don't think the above is feasible. What am I missing? Rename your __del__ to close and call it explicitely: p.close() alist[3].close() alist[853].close() alist[701].close() > > An alternative that will work in pre-2.5 Python (and, I believe but I'm > > not sure, in Jython and IronPython _today_) is to rely on the weakref > > module of the standard Python library. > > ... > > I'm going to need some time to play around with that, but it seems > reasonably straightforward. But the obvious thing I can see is that > there's an awful lot of boilerplate code that needs to be written for > each and every class that needs a "weak finalizer". > > That is to say, Python "guarantees" that __del__ will always be called > (unless it isn't... "guarantee void on planet Earth") for your objects, > so the developer doesn't need to do anything except write the finalizer. Yep, the problem is that __del__ does NOT guarantee anything. So, it *looks* easy, but it is actually very fragile and in subtle cases can betray you without telling. I, for one, I don't like to have bombs in my code waiting to explode at some unknown moment ... > To do the right thing with weakrefs means that not only does the > developer have to write the finalizer, but he has to write the code to > ensure the finalizer is called. I'm not sure that's a step forward. Yep, we would need a better support for finalizers in the standard library. For the moment, there are various recipes in the Python cookbook. See also this post: http://groups.google.com/group/comp.lang.python/browse_frm/thread/b09e02b7c67c8a3b/1ef0f64bb539cfb0?hl=en&lnk=gst&q=simionato+__del__&rnum=1#1ef0f64bb539cfb0 From nick at craig-wood.com Wed Oct 24 16:30:16 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 24 Oct 2007 15:30:16 -0500 Subject: Iteration for Factorials References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> Message-ID: Py-Fun wrote: > I'm stuck trying to write a function that generates a factorial of a > number using iteration and not recursion. Any simple ideas would be > appreciated. Here is the math geek answer ;-) import math def factorial(i): n = i + 1 return math.exp(-n)*(n**(n-0.5))*math.sqrt(2*math.pi)*(1. + 1./12/n + 1./288/n**2 - 139./51840/n**3) Works for non integer factorials also... See here for background http://mathworld.wolfram.com/StirlingsSeries.html -- Nick Craig-Wood -- http://www.craig-wood.com/nick From patrick.waldo at gmail.com Mon Oct 15 06:47:16 2007 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Mon, 15 Oct 2007 10:47:16 -0000 Subject: Simple Text Processing Help In-Reply-To: <1192396632.736910.134070@q5g2000prf.googlegroups.com> References: <1192369731.561036.31010@i38g2000prf.googlegroups.com> <1192396632.736910.134070@q5g2000prf.googlegroups.com> Message-ID: <1192445236.310797.91160@z24g2000prh.googlegroups.com> > lines = open('your_file.txt').readlines()[:4] > print lines > print map(len, lines) gave me: ['\xef\xbb\xbf200-720-7 69-93-2\n', 'kyselina mo\xc4\x8dov \xc3\xa1 C5H4N4O3\n', '\n', '200-001-8\t50-00-0\n'] [28, 32, 1, 18] I think it means that I'm still at option 3. I got the line by line part. My code is a lot cleaner now: import codecs path = "c:\\text_samples\\chem_1_utf8.txt" path2 = "c:\\text_samples\\chem_2.txt" input = codecs.open(path, 'r','utf8') output = codecs.open(path2, 'w', 'utf8') for line in input: tokens = line.strip().split() tokens[2:-1] = [u' '.join(tokens[2:-1])] #this doesn't seem to combine the files correctly file = u'|'.join(tokens) #this does put '|' in between print file + u'\n' output.write(file + u'\r\n') input.close() output.close() my sample input file looks like this( not organized,as you see it): 200-720-7 69-93-2 kyselina mocov? C5H4N4O3 200-001-8 50-00-0 formaldehyd CH2O 200-002-3 50-01-1 guanid?nium-chlorid CH5N3.ClH etc... and after the program I get: 200-720-7|69-93-2| kyselina|mocov?||C5H4N4O3 200-001-8|50-00-0| formaldehyd|CH2O| 200-002-3| 50-01-1| guanid?nium-chlorid|CH5N3.ClH| etc... So, I am sort of back at the start again. If I add: tokens = line.strip().split() for token in tokens: print token I get all the single tokens, which I thought I could then put together, except when I did: for token in tokens: s = u'|'.join(token) print s I got ?|2|0|0|-|7|2|0|-|7, etc... How can I join these together into nice neat little lines? When I try to store the tokens in a list, the tokens double and I don't know why. I can work on getting the chemical names together after...baby steps, or maybe I am just missing something obvious. The first two numbers will always be the same three digits-three digits-one digit and then two digits-two digits-one digit. This seems to be on the only pattern. My intuition tells me that I need to add an if statement that says, if the first two numbers follow the pattern, then continue, if they don't (ie a chemical name was accidently split apart) then the third entry needs to be put together. Something like if tokens[1] and tokens[2] startswith('pattern') == true tokens[2] = join(tokens[2]:tokens[3]) token[3] = token[4] del token[4] but the code isn't right...any ideas? Again, thanks so much. I've gone to http://gnosis.cx/TPiP/ and I have a couple O'Reilly books, but they don't seem to have a straightforward example for this kind of text manipulation. Patrick On Oct 14, 11:17 pm, John Machin wrote: > On Oct 14, 11:48 pm, patrick.wa... at gmail.com wrote: > > > > > Hi all, > > > I started Python just a little while ago and I am stuck on something > > that is really simple, but I just can't figure out. > > > Essentially I need to take a text document with some chemical > > information in Czech and organize it into another text file. The > > information is always EINECS number, CAS, chemical name, and formula > > in tables. I need to organize them into lines with | in between. So > > it goes from: > > > 200-763-1 71-73-8 > > n?trium-tiopent?l C11H18N2O2S.Na to: > > > 200-763-1|71-73-8|n?trium-tiopent?l|C11H18N2O2S.Na > > > but if I have a chemical like: kyselina mo?ov? > > > I get: > > 200-720-7|69-93-2|kyselina|mo?ov? > > |C5H4N4O3|200-763-1|71-73-8|n?trium-tiopent?l > > > and then it is all off. > > > How can I get Python to realize that a chemical name may have a space > > in it? > > Your input file could be in one of THREE formats: > (1) fields are separated by TAB characters (represented in Python by > the escape sequence '\t', and equivalent to '\x09') > (2) fields are fixed width and padded with spaces > (3) fields are separated by a random number of whitespace characters > (and can contain spaces). > > What makes you sure that you have format 3? You might like to try > something like > lines = open('your_file.txt').readlines()[:4] > print lines > print map(len, lines) > This will print a *precise* representation of what is in the first > four lines, plus their lengths. Please show us the output. From richyjsm at gmail.com Mon Oct 1 21:17:03 2007 From: richyjsm at gmail.com (richyjsm at gmail.com) Date: Tue, 02 Oct 2007 01:17:03 -0000 Subject: Using fractions instead of floats In-Reply-To: <1191286998.727959.8010@50g2000hsm.googlegroups.com> References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> <1191206183.441075.167450@57g2000hsv.googlegroups.com> <1191284422.899591.308960@g4g2000hsf.googlegroups.com> <1191286998.727959.8010@50g2000hsm.googlegroups.com> Message-ID: <1191287823.018676.35640@o80g2000hse.googlegroups.com> On Oct 1, 9:03 pm, "mensana... at aol.com" wrote: > On Oct 1, 7:20 pm, richy... at gmail.com wrote: > > > On Oct 1, 8:30 am, Nick Craig-Wood wrote: > > > > >>> mpq(1,3)+0.6 > > > mpq(14,15) > > > Golly! That's quite impressive. And more than a little bit magic as > > well, since 0.6 is definitely not the same as 3/5. > > It's not? Since when? The 0.6 above is a floating point number, mathematically very close to 0.6 but definitely not equal to it, since 0.6 can't be represented exactly as a float. From bartolotta52 at gmail.com Sun Oct 28 22:17:33 2007 From: bartolotta52 at gmail.com (my glass) Date: Sun, 28 Oct 2007 19:17:33 -0700 Subject: 7000+ beautiful Russian girls waiting for men Message-ID: <1193624253.311819.322490@i13g2000prf.googlegroups.com> 7000+ beautiful Russian girls waiting for men http://groups.google.com/group/all-good-things/web/beautiful-girls-and-ladies From martin at v.loewis.de Wed Oct 3 01:51:49 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Oct 2007 07:51:49 +0200 Subject: Python and SSL In-Reply-To: <1191389578.176470.161360@50g2000hsm.googlegroups.com> References: <1190959345.041723.108130@k79g2000hse.googlegroups.com> <6cydncA2Jpv082DbnZ2dnUVZ_q6dnZ2d@comcast.com> <1191224526.856466.305980@57g2000hsv.googlegroups.com> <7xzlz2q53e.fsf@ruckus.brouhaha.com> <1191251260.376954.265060@22g2000hsm.googlegroups.com> <47012255.4020502@v.loewis.de> <470174FC.5060709@v.loewis.de> <1191389578.176470.161360@50g2000hsm.googlegroups.com> Message-ID: <47032DF5.4000809@v.loewis.de> > a certificate that is signed by OpenSSL's own CA( certification > authority), that is not recognized in the program's list of root CAs, > causes an exception to be raised. What is "the program"? What programming language is it written in? What library does it use to maintain a list of root CAs, and what code does it execute to find out that a certificate is not in this list? Are you sure this is related to Python at all? Regards, Martin From peterbe at gmail.com Tue Oct 16 10:50:53 2007 From: peterbe at gmail.com (Peter Bengtsson) Date: Tue, 16 Oct 2007 07:50:53 -0700 Subject: Normalize a polish L In-Reply-To: <1192485438.934146.139740@q5g2000prf.googlegroups.com> References: <1192466006.735303.20470@i38g2000prf.googlegroups.com> <1192485438.934146.139740@q5g2000prf.googlegroups.com> Message-ID: <1192546253.808005.100090@q5g2000prf.googlegroups.com> On Oct 15, 10:57 pm, John Machin wrote: > On Oct 16, 2:33 am, Peter Bengtsson wrote: > > > > > In UTF8, \u0141 is a capital L with a little dash through it as can be > > seen in this image:http://static.peterbe.com/lukasz.png > > > I tried this:>>> import unicodedata > > >>> unicodedata.normalize('NFKD', u'\u0141').encode('ascii','ignore') > > > '' > > > I was hoping it would convert it it 'L' because that's what it > > visually looks like. And I've seen it becoming a normal ascii L before > > in other programs such as Thunderbird. > > > I also tried the other forms: 'NFC', 'NFKC', 'NFD', and 'NFKD' but > > none of them helped. > > > What am I doing wrong? > > The character in question is NOT composed (in the way that Unicode > means) of an 'L' and a little slash; hence the concepts of > "normalization" and "decomposition" don't apply. > > To "asciify" such text, you need to build a look-up table that suits > your purpose. unicodedata.decomposition() is (accidentally) useful in > providing *some* of the entries for such a table. Thank you! That explains it. From jusa.sj at gmail.com Sun Oct 28 13:05:17 2007 From: jusa.sj at gmail.com (Juha S.) Date: Sun, 28 Oct 2007 19:05:17 +0200 Subject: Weird AttributeError With Imports Message-ID: <4724C14D.5090108@gmail.com> I'm getting a "AttributeError: 'module' object has no attribute 'clock'" when importing a module from within two packages related to the line: "self.lastTime = time.clock()" in the __init__() of the class Time in the target module. The module (mytime.py) sits in a package hierarchy such as the following "packageA.packageB.mytime", and imports the Python module "time" like this: "import time" In another module outside of both packages (in a folder that holds the other package folders) I do this: from packageA.packageB import mytime timer = mytime.Time() #Throws the above AttributeError Strangely it seems that if I create a Time object in mytime.py everything works perfectly. I have no idea why I'm getting this error, so any help is welcome! From ricaraoz at gmail.com Wed Oct 31 10:28:39 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 31 Oct 2007 11:28:39 -0300 Subject: two files into an alternate list In-Reply-To: <47268B41.2000107@tim.thechases.com> References: <47268B41.2000107@tim.thechases.com> Message-ID: <47289117.7040107@bigfoot.com> Tim Chase wrote: >> i have a file : >> file 1: >> 1 >> 2 >> 3 >> 4 >> 5 >> 6 >> >> file2: >> a >> b >> c >> d >> e >> f >> how do i make the two files into list like this = >> [1,a,2,b,3,c,4,d,5,e,6,f] > > from itertools import cycle > def serialize(*sources): > while True: > for source in sources: > yield source.next() > def stripper(iterator): > for thing in iterator: > yield thing.strip() > for thing in serialize( > stripper(file('file1.txt')), > stripper(file('file2.txt')) > ): > print thing > > As a previous responder noted, there are a number of ways to > treat the edge cases when the lengths of the files don't match. > Since you left the condition underqualified, I chose to let it > expire when the first one gave out rather than try and deal with > the complications of such ambiguity. > > -tkc > Or maybe just : >>> r = [] >>> for a, b in map(None , (int(i.strip('\n')) for i in open('file1.txt')) , (i.strip('\n') for i in open('file2.txt'))) : r.append(a) r.append(b) >>> r [1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e', None, 'f'] From nikbaer at gmail.com Tue Oct 23 16:08:03 2007 From: nikbaer at gmail.com (nik) Date: Tue, 23 Oct 2007 20:08:03 -0000 Subject: tracking/ordering log files In-Reply-To: <1193165204.000752.268220@i38g2000prf.googlegroups.com> References: <1193165204.000752.268220@i38g2000prf.googlegroups.com> Message-ID: <1193170083.610513.149390@e34g2000pro.googlegroups.com> On Oct 23, 11:46 am, nik wrote: > Hi, > > I heard that there was a utility for keeping files and specifically > log files organized, but haven't been able to find anything but the > logging class. The logging class seems to help create the content of a > log file, but unless I am missing something, it doesn't keep track of > multiple log files. > > What I am looking for is some utility that allows me to create a log > file, say test.log, when the program runs. Then the next time it runs > it will see that test.log already exists and will create test.log.1 or > something similiar. Ideally it would also be able to throw out log > files that are older than a certain date or sequence, so if we got to > creating the 10th file it would delete the first one and so on. > > I am sorry for the ambiguois question, but I was told this existed, > can't find it and would like to know if I'm on a wild goose chase and > should just put something together myself. > > Thank you, > Nik I think it is called "logfile rotation" and see some links about log4py, but no description of what that is. thanks From mensanator at aol.com Mon Oct 22 18:27:29 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 22 Oct 2007 15:27:29 -0700 Subject: Iteration for Factorials In-Reply-To: <1193089188.812952.241920@v29g2000prd.googlegroups.com> References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <1193075845.148527.80820@k35g2000prh.googlegroups.com> <87bqarov3n.fsf@rudin.co.uk> <1193083810.302605.128630@y27g2000pre.googlegroups.com> <877ileq40i.fsf@rudin.co.uk> <1193089188.812952.241920@v29g2000prd.googlegroups.com> Message-ID: <1193092049.638432.116180@q5g2000prf.googlegroups.com> On Oct 22, 4:39 pm, "mensana... at aol.com" wrote: > On Oct 22, 3:38 pm, Paul Rudin wrote: > > > > > > > tokl... at gmail.com writes: > > > On 22 oct, 20:35, Paul Rudin wrote: > > > >> import operator > > >> def fact(x): > > >> return reduce(operator.mul, xrange(1,x)) > > > > Maybe: > > > > import operator > > > def fact(x): > > > return reduce(operator.mul, xrange(2, x+1), 1) > > > Or just: > > > reduce(operator.mul, xrange(1, x), 1) > > Nope, still doesn't work: > > >>> def fact(x): > > return reduce(operator.mul,xrange(1,x+1),1) Excuse me, I mistyped your proposed solution. You had xrange(1,x) not xrange(1,x+1). The former only returns correct factorials for x==0 and x==1. Sorry for the confusion. > > >>> fact(3) > 6 > >>> fact(2) > 2 > >>> fact(1) > 1 > >>> fact(0) > 1 > >>> fact(-1) > 1 > >>> fact(-2) > 1 > >>> fact(-3) > > 1 > > fact() should raise an exception if x is negative. > > My variant of your original (same as Tim Chase's except the > test for x==1 is not necessary): > > >>> def fact(x): > > if x==0: > return 1 > else: > return reduce(operator.mul,xrange(1,x+1)) > > > > >>> fact(3) > 6 > >>> fact(2) > 2 > >>> fact(1) > 1 > >>> fact(0) > 1 > >>> fact(-1) > > Traceback (most recent call last): > File "", line 1, in > fact(-1) > File "", line 5, in fact > return reduce(operator.mul,xrange(1,x+1)) > TypeError: reduce() of empty sequence with no initial value- Hide quoted text - > > - Show quoted text - From fw3 at hotmail.co.jp Wed Oct 3 13:23:00 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Wed, 3 Oct 2007 17:23:00 +0000 Subject: function to convert data into binary, hex and back. In-Reply-To: References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> Message-ID: From: fw3 at hotmail.co.jpTo: python-list at python.orgSubject: RE: module confusionDate: Wed, 3 Oct 2007 17:14:19 +0000 Hi, I am moving from Matlab to Python+numpy+scipy. In Matlab you can use function dec2bin, hex2dec, dec2hex bin2dec functions to convert decimal to binary and heximal etc. Before I try to implement my own function in Python, I want to know whether in Python such functionalities are already there. Thanks Frank MSN???????EMI Artists?????????????? SCHOOL OF SCHOOL http://music.jp.msn.com/ _________________________________________________________________ ?MSN????????????????????? ????????????? http://video.msn.co.jp/rvr/default.htm -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Oct 9 17:43:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 Oct 2007 23:43:12 +0200 Subject: Unexpected behaviour with HTMLParser... In-Reply-To: References: Message-ID: <5n2avjFfh6h8U1@mid.uni-berlin.de> Just Another Victim of the Ambient Morality schrieb: > HTMLParser is behaving in, what I find to be, strange ways and I would > like to better understand what it is doing and why. > > First, it doesn't appear to translate HTML escape characters. I don't > know the actual terminology but things like & don't get translated into > & as one would like. Furthermore, not only does HTMLParser not translate it > properly, it seems to omit it altogether! This prevents me from even doing > the translation myself, so I can't even working around the issue. > Why is it doing this? Is there some mode I need to set? Can anyone > else duplicate this behaviour? Is it a bug? Without code, that's hard to determine. But you are aware of e.g. handle_entityref(name) handle_charref(ref) ? > Secondly, HTMLParser often calls handle_data() consecutively, without > any calls to handle_starttag() in between. I did not expect this. In HTML, > you either have text or you have tags. Why split up my text into successive > handle_data() calls? This makes no sense to me. At the very least, it does > this in response to text with & like escape sequences (or whatever > they're called), so that it may successively avoid those translations. That's the way XML/HTML is defined - there is no guarantee that you get text as whole. If you must, you can collect the snippets yourself, and on the next end-tag deliver them as whole. > Again, why is it doing this? Is there some mode I need to set? Can > anyone else duplicate this behaviour? Is it a bug? No. It's the way it is, because it would require buffering with unlimited capacity to ensure this property. > These are serious problems for me and I would greatly appreciate a > deeper understanding of these issues. HTH, and read the docs. Diez From timr at probo.com Thu Oct 25 02:22:52 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Oct 2007 06:22:52 GMT Subject: Python Windows Installation References: <1193195493.086681.40570@t8g2000prg.googlegroups.com> Message-ID: TheFlyingDutchman wrote: > >I am trying to install Python 2.5 on Windows XP. It installs into the >root directory on C:\ instead of C:\Python25 which it shows by default >as what it plans to install to. Selecting D:\Python25 on a previous >iteration put the exe in D:\ and did not create a Python25 directory. Where did you get the installer? I've installed Python on Windows many, many times, and have never seen this issue. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gagsl-py2 at yahoo.com.ar Wed Oct 24 01:15:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Oct 2007 02:15:59 -0300 Subject: name space problem References: <1193179470.243479.53270@q3g2000prf.googlegroups.com> <1193181625.770328.161650@v29g2000prd.googlegroups.com> <1193193278.364108.256770@y27g2000pre.googlegroups.com> Message-ID: En Tue, 23 Oct 2007 23:34:38 -0300, BBands escribi?: > On Oct 23, 4:20 pm, marek.ro... at wp.pl wrote: > I was trying to understand why it worked when written in, but not when > included. Not *included*. When you do `import doStuff` you dont "include" anything; this is what happens (simplified): - Look into the already loaded modules; if a "doStuff" module already exists, return it. - Search some directories on disk, looking for "doStuff.py". If found, load and execute it (remember that import, class, def, etc. are *executable* statements in Python). - If still not found, raise an error. So, after successful execution of `import doStuff`, you have a new name `doStuff` that refers to the imported module. It's not the "contents" of doStuff that gets "included" into the current module; doStuff exists by itself as a separate module, and you get a name that refers to it. >> I think the right solution would be not to use 'a' as a global >> variable, but rather to pass it as an explicit parameter to the >> function. > > Does doing this make a copy of a? No! Python never makes a copy unless you explicitely say so. >> In module doStuff: >> >> def doStuff(a): >> # some calcs >> a.b = 0 >> >> In the main module: >> >> import doStuff >> # ... >> doStuff.doStuff(a) > > In my real ap a is quite large... It doesn't matter. `a` is just a name, referencing an object. It's never "copied" unless you specifically ask for it. Passing objects as arguments is absolutely common, and the right thing to do in this case; it's efficient, don't worry... -- Gabriel Genellina From bj_666 at gmx.net Tue Oct 23 18:43:49 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Oct 2007 22:43:49 GMT Subject: How to find out which functions exist? References: <1193173804.937071.278110@e9g2000prf.googlegroups.com> <5o76tgFld8c9U10@mid.uni-berlin.de> <1193176280.003067.269950@i13g2000prf.googlegroups.com> Message-ID: <5o7bp5Fld8c9U12@mid.uni-berlin.de> On Tue, 23 Oct 2007 21:51:20 +0000, mrstephengross wrote: > Ok, I see how to use issubclass(). How can I get a list of classes > present in the file? import module from inspect import getmembers, isclass classes = getmembers(module, isclass) Ciao, Marc 'BlackJack' Rintsch From alpha04 at netvigator.com Thu Oct 4 19:09:43 2007 From: alpha04 at netvigator.com (Andrey) Date: Thu, 4 Oct 2007 16:09:43 -0700 Subject: Mysql class works like php Message-ID: Hi just a quick question about using MySQL module... are there any api / class available to give a higher level in working with Mysql in python? such as db.fetch_array(), db.fetch_rows(), db.query(), for eachrow in db.fetch_array(): xxxx just as easy as PHP? I think someone might already done this, so i dont have to re-invent the wheel, but i have no luck in google, so wondering if anyone might know such thing exists... thanks Andrey From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Oct 13 14:25:31 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 13 Oct 2007 20:25:31 +0200 Subject: test if email References: <1192220077.109848.74740@e9g2000prf.googlegroups.com> <13gvqvb6shueveb@corp.supernews.com> Message-ID: <5ncgsjFh6pd4U1@mid.individual.net> Martin Marcher wrote: > No need to speek of plus addressing or older messaging systems. But don't disallow a plus in the localpart. Many do. Regards, Bj?rn -- BOFH excuse #180: ether leak From python.list at tim.thechases.com Wed Oct 3 09:43:18 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 03 Oct 2007 08:43:18 -0500 Subject: enumerate overflow In-Reply-To: <5mheq7Fd78r2U2@mid.uni-berlin.de> References: <1191411991.165082.19010@o80g2000hse.googlegroups.com> <5mheq7Fd78r2U2@mid.uni-berlin.de> Message-ID: <47039C76.2030305@tim.thechases.com> >> in python2.4, i read lines from a file with >> >> for lineNum, line in enumerate(f): ... >> >> However, lineNum soon overflows and starts counting backwards. How do >> i force enumerate to return long integer? > > Most probably you can't, because it is a C-written function I presume. > > But as python 2.4 has generators, it's ease to create an enumerate yourself: > > > def lenumerate(f): > i = 0 > for line in f: > yield i, line > i += 1 I'd consider this a bug: either in the implementation of enumerate(), or in the documentation http://docs.python.org/lib/built-in-funcs.html#l2h-24 which fails to mention such arbitrary limitations. The documentation describes what you create as an lenumerate() function. Most likely, if one doesn't want to change the implementation, one should update the documentation for enumerate() to include a caveat like xrange() has http://docs.python.org/lib/built-in-funcs.html#l2h-80 """ Note: xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs ("short" Python integers), and also requires that the number of elements fit in a native C long. """ While yes, it's easy enough to create the above lenumerate generator (just as it's only slightly more work to create an lxrange function), it would be good if the docs let you know that you might need to create such a function -tkc From fred.sells at adventistcare.org Wed Oct 10 17:00:56 2007 From: fred.sells at adventistcare.org (Sells, Fred) Date: Wed, 10 Oct 2007 17:00:56 -0400 Subject: RMI with Pyro et al In-Reply-To: <470cf535$0$25952$ba4acef3@news.orange.fr> Message-ID: <0A53725C4A497848A7B3A0874B2598313D38E4@acesxch01.ADVENTISTCORP.NET> I need a simple client/server architecture with clients on linux and servers on windows. There is no UI in this part, just business rules and access control. Pyro seems pretty cool for this due to it's simplicity. I'm just starting with it and have not been able to get the server side to "see" changes to a module. The only way I can stop the server is with the Task Manager. Can anyone offer some insight into 1. stopping/starting the server - perhaps as a windows service. 2. getting the server to recognize new modules "on the fly", i.e. when the .py file is changed. I'm not doing any UI stuff, so I don't want to deal with HTTP and a webserver. I also do not have any RDBMS involved. I like the idea of passing objects the way pyro does it. If anyone thinks there is a better python tool for doing this, I would like to know. --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From aleax at mac.com Sun Oct 14 23:25:15 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 14 Oct 2007 20:25:15 -0700 Subject: int to str in list elements.. References: <1192384956.127445.316920@e9g2000prf.googlegroups.com> Message-ID: <1i5z49f.m3i1xijzrco5N%aleax@mac.com> Abandoned wrote: > Hi.. > I have a list as a=[1, 2, 3 .... ] (4 million elements) > and > b=",".join(a) > than > TypeError: sequence item 0: expected string, int found > I want to change list to a=['1','2','3'] but i don't want to use FOR > because my list very very big. > I'm sorry my bad english. > King regards Try b=','.join(map(str, a)) -- it WILL take up some memory (temporarily) to build the huge resulting string, but there's no real way to avoid that. It does run a bit faster than a genexp with for...: brain:~ alex$ python -mtimeit -s'a=range(4000*1000)' 'b=",".join(map(str,a))' 10 loops, best of 3: 3.37 sec per loop brain:~ alex$ python -mtimeit -s'a=range(4000*1000)' 'b=",".join(str(x) for x i n a)' 10 loops, best of 3: 4.36 sec per loop Alex From lucaberto at libero.it Fri Oct 12 02:17:27 2007 From: lucaberto at libero.it (luca72) Date: Thu, 11 Oct 2007 23:17:27 -0700 Subject: cxfreeze Message-ID: <1192169847.156883.84260@q5g2000prf.googlegroups.com> Hello i use under linux cx-freeze My python program import a small module were i set the encoding to iso 8859-1. When i make the executable with cxfreeze and i run it i get this error: Traceback (most recent call last): File "/home/luca72/Desktop/Luca/python/cx_Freeze-3.0.3/initscripts/ Console.py", line 27, in exec code in m.__dict__ File "main.py", line 4, in File "form_pack_impl.py", line 13, in File "sitecustomize.py", line 3, in LookupError: unknown encoding: iso-8859-1 Can you help me Regards Luca From sunburned.surveyor at gmail.com Mon Oct 22 13:12:36 2007 From: sunburned.surveyor at gmail.com (Sunburned Surveyor) Date: Mon, 22 Oct 2007 10:12:36 -0700 Subject: Automatic Generation of Python Class Files Message-ID: <1193073156.493809.184110@z24g2000prh.googlegroups.com> I was thinking of a way I could make writing Python Class Files a little less painful. I was considering a Ptyhon script that read a file with a list of property names and method names and then generated a skeleton class file. I was even thinking of automatically generating the shell for doc strings and epydoc tags. Is there existing scripts that do something like this? If not, I will try to come up with something. If I'm sucessful I'll release the code under the GPL and will report back to the list. However, I thought I would check here first so that I don't reinvent the wheel. Thanks, Scott Huey From matthieu.brucher at gmail.com Sun Oct 28 11:56:51 2007 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Sun, 28 Oct 2007 16:56:51 +0100 Subject: how to convert tuple to a "list of single values" ? In-Reply-To: <4724AB51.6050702@gmail.com> References: <4724AB51.6050702@gmail.com> Message-ID: Use : something = self._point2ClientCoord (p1, p2 ) dc.SetClippingRegion (*something) Matthieu 2007/10/28, stef mientki : > > hello, > > The next piece of code bothers me: > > ptx, pty, rectWidth, rectHeight = self._point2ClientCoord (p1, p2 ) > dc.SetClippingRegion ( ptx, pty, rectWidth, rectHeight ) > > Because I want to write it in 1 line, > and without the use of intermediate variables (for which I have to > invent names ;-) > like this: > > dc.SetClippingRegion ( self._point2ClientCoord (p1, p2 ) ) > > Now that doesn't work, because > - dc.SetClippingRegion() requires 4 integer parameters > - _point2ClientCoord() returns a tupple of 4 integers > > I can't think of a solution, > is there any ? > > thanks, > Stef Mientki > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- French PhD student Website : http://miles.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mrstephengross at hotmail.com Tue Oct 23 17:10:04 2007 From: mrstephengross at hotmail.com (mrstephengross) Date: Tue, 23 Oct 2007 21:10:04 -0000 Subject: How to find out which functions exist? Message-ID: <1193173804.937071.278110@e9g2000prf.googlegroups.com> Let's say I have a python file with a base class, and a few derived classes: class Base: pass class Derived1(Base): pass class Derived2(Base): pass Is there a way I can find out the classes that have been derived from Base? Thanks, --Steve From heikki at osafoundation.org Fri Oct 12 18:15:11 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 12 Oct 2007 15:15:11 -0700 Subject: ANN: M2Crypto 0.18.2 Message-ID: <3qydnby-HdRsbJLanZ2dnUVZ_vWdnZ2d@comcast.com> M2Crypto is the most complete Python wrapper for OpenSSL featuring RSA, DSA, DH, HMACs, message digests, symmetric ciphers (including AES); SSL functionality to implement clients and servers; HTTPS extensions to Python's httplib, urllib, and xmlrpclib; unforgeable HMAC'ing AuthCookies for web session management; FTP/TLS client and server; S/MIME; ZServerSSL: A HTTPS server for Zope and ZSmime: An S/MIME messenger for Zope. http://chandlerproject.org/Projects/MeTooCrypto Changelog: - typedef Py_ssize_t was insufficiently guarded, now follows PEP 353. This prevented building on at least Red Hat Linux and Debian Linux (unstable). -- Heikki Toivonen From bj_666 at gmx.net Tue Oct 23 15:15:47 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Oct 2007 19:15:47 GMT Subject: Can't refer to base class attribute? References: <1193165646.296297.152000@y27g2000pre.googlegroups.com> Message-ID: <5o6vj2Fld8c9U8@mid.uni-berlin.de> On Tue, 23 Oct 2007 18:54:06 +0000, mrstephengross wrote: > I've got a Base class with an attribute "foo" (of type Foo), and a > Derived class (derived from Base). In Derived's constructor, I try to > refer to Base.foo, but python complains: > AttributeError: class Base has no attribute 'foo' Because the class `Base` doesn't have an attribute `foo`. Just believe the error message. :-) > Any ideas? (code below) > > === CODE === > #!/usr/bin/python > > class Foo: > def __init__ (self): > self.x = 3 > > class Base: > def __init__ (self): > self.foo = Foo() `Base` has no `foo` attribute but *instances* of `Base` have. > class Derived(Base): > def __init__(self): > Base.__init__(self) > Base.foo.x = 5 Instances of `Derived` have a `foo` attribute inherited from `Base`. So the last line should be ``self.foo.x = 5``. Ciao, Marc 'BlackJack' Rintsch From marlenemiller at worldnet.att.net Wed Oct 10 00:39:32 2007 From: marlenemiller at worldnet.att.net (Marlene Miller) Date: Wed, 10 Oct 2007 04:39:32 GMT Subject: The fundamental concept of continuations References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> Message-ID: <8IYOi.658994$p47.379449@bgtnsc04-news.ops.worldnet.att.net> > Can anyone explain: > > (1) its origin >From the Bibliographic Notes of Chapter 12 Continuations in a Functional Language, Theories of Programming Languages by John C. Reynolds, page 370: "A history of the repeated discoveries of continuations (occurring largely in the context of functional languages) is given in Reynolds [1993]; relevant original papers include those by van Wijngaarden [1996], F. L. Morris [1993], Strachey and Wadsworth [1974], J. H. Morris [1972], Fischer [1972; 1993], and Abdali [1976]. The operations callcc and throw first appeared in Scheme, but are descendents of Landin's [1965b] "J-operator". Both the continuation-passing transformation from direct to continuation semantics and defunctionalization were described, in the setting of programs for interpreting eager-evaluation functional languages, by Reynolds [1972a]." "Beginning with the implementation of Scheme [Sussman and Steele Jr., 1975] continuations and the continuation-passing transformation have played a major role in the design of compilers. More recently, this topic has been explored at book length by Appel [1992]." Reynolds [1993] The Discoveries of Continuations. van Wijngaarden [1996] Recursive Definition of Syntax and Semantics F. L. Morris [1993] The Next 700 Formal Language Descriptions Strachey and Wadsworth [1974] Continuations, A Mathematical Semantics for Handling Full Jumps. J. H. Morris [1972] A Bonus from van Wijngarden's Device Fischer [1972, 1993] Lambda Calculus Schemata Abdali [1976] A Lambda Calculus Model of Programming Languages - I. Simple Constructs, II. Jumps and Procedures Sussman and Steele Jr. [1975] SCHEME: An Interpreter for Extended Lambda Calculus Compiling With Continuations, Andrew W. Appel, 2007 - - - - - - - - - - > (2) its syntax and semantics in emacs lisp, common lisp, scheme The Scheme Programming Language, R. Kent Dybvig 3.3 Continuations 5.5 Continuations http://www.scheme.com/tspl3/ Scheme and the Art of Programming, Springer and Friedman Chapter 16 Introduction to Continuations Chapter 17 Using Continuations - - - - - - - - - - - - - > (6) any good readable references that explain it lucidly ? 1. Programming Languages: Application and Interpretation, Shriram Krishnamurthi Part VII Continuations http://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/2007-04-26/plai-2007-04-26.pdf 2. Essentials of Programming Languages, Friedman, Wand and Haynes Chapter 7 Continuation-Passing Interpreters Chapter 8 Continuation-Passing Style http://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/2007-04-26/plai-2007-04-26.pdf 3. Theories of Programming Languages, John C. Reynolds 5.7 Continuation Semantics [of imperative languages] Chapter 12 Continuations in a Functional Language http://www.cs.indiana.edu/eopl/ >From the Bibliographic Notes of Chapter 5 Failure, Input-Output and Continuations, Theories of Programming Languages, John C. Reynolds "Most of the literature on continuations discusses the concept in the setting of functional languages (where we will return to continuations in Section 12.1). However, the properties of continuation semantics for imperative languages are described, perhaps to excess, by Reynolds [1977]." Reynolds [1977] Semantics of the Domain of Flow Diagrams From find at my.address.elsewhere Tue Oct 9 20:47:13 2007 From: find at my.address.elsewhere (Matthias Blume) Date: Tue, 09 Oct 2007 19:47:13 -0500 Subject: The fundamental concept of continuations References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> <470b1b30$0$11022$4c368faf@roadrunner.com> <1191958673.182295.207190@22g2000hsm.googlegroups.com> Message-ID: gnuist006 at gmail.com writes: > Matthias, thanks for the reference, but I dont have access to an > engineering library. I would appreciate, if you have access to paper/ > scanner or electronic copy to help many of us out, you are > not just helping me but many will thank you. Given that you seem to be hanging out at the internets, I expect you do know how to use the google... From deets at nospam.web.de Mon Oct 22 08:28:05 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 Oct 2007 14:28:05 +0200 Subject: Iteration for Factorials References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> Message-ID: <5o3jalFl0n43U1@mid.uni-berlin.de> Py-Fun wrote: > I'm stuck trying to write a function that generates a factorial of a > number using iteration and not recursion. Any simple ideas would be > appreciated. Show us your attempts, and we might suggest a fix. Because otherwise this sounds suspiciously like homework. Diez From kay.schluehr at gmx.net Sun Oct 7 11:49:14 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 07 Oct 2007 08:49:14 -0700 Subject: Top Programming Languages of 2013 In-Reply-To: References: Message-ID: <1191772154.784564.138370@r29g2000hsg.googlegroups.com> On Oct 7, 8:05 am, Dick Moores wrote: > > > Dick Moores Despite my doubts that Ajax and .NET will be programming languages in 2013 a more interesting question is: what could push Python forward s.t. it eats such a large piece of the PL cake? From mail at microcorp.co.za Fri Oct 5 02:19:04 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 5 Oct 2007 08:19:04 +0200 Subject: module confusion References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> <874ph8sdhx.fsf@benfinney.id.au> <87hcl7r1ga.fsf@benfinney.id.au> <019401c8065c$13e82d00$03000080@hendrik> Message-ID: <015701c80722$0886e5c0$03000080@hendrik> "Steve Holden" wrote: > Hendrik van Rooyen wrote: > > "Steve Holden" wrote: > > > >> religious issues for me. It's more like "This problem has a cross head, > >> so I'll need a Philips screwdriver". > > > > As long as it is not a Pozidrive, that is a commendable attitude. > > > I said cross head, not Pozidriv (tm). But then I have been nown to use a > Manchester screwdriver[1] on occasion. Philistine! But in a way, it is more honest than the Free State method of tightening a bolt- You tighten enthusiastically until it strips, then go a quarter turn back to undo the damage. BTW, in case you have been wondering - a Free State Micrometer is a plumber's adjustable pipe wrench. - Hendrik From hniksic at xemacs.org Wed Oct 10 17:02:55 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 10 Oct 2007 23:02:55 +0200 Subject: unpickle from URL problem References: <873awjgeo8.fsf@mulj.homelinux.net> Message-ID: <87wstuhedc.fsf@mulj.homelinux.net> Alan Isaac writes: > Hrvoje Niksic wrote: >> The first upload breaks the file. You uploaded it in (presumably >> FTP's) text mode, which changes \n -> \r\n. But you download it using >> http, which specifies no such conversion in the opposite direction. > > No: I used binary upload both time. > (Unless my ftp client is broken, and I think not.) > > The first example simply keeps the Windows eols, > which are present in the pickled file on my Windows machine. That's why it doesn't work on Unix, the \r's are a problem when not removed by the platform's IO layer. Because of the newline silliness, the notion of a "text file" is, unfortunately, quite platform-specific even when the file is pure ASCII, so pickle protocol 0 being textual is a bit misleading regarding the resulting file's portability. :-( From deets at nospam.web.de Wed Oct 31 20:36:26 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 01 Nov 2007 01:36:26 +0100 Subject: setting variables in outer functions In-Reply-To: <87ir4mj24t.fsf@mulj.homelinux.net> References: <87myu1k4rm.fsf@mulj.homelinux.net> <1193830119.542006.137750@o38g2000hse.googlegroups.com> <1193870968.747606.281180@50g2000hsm.googlegroups.com> <87ir4mj24t.fsf@mulj.homelinux.net> Message-ID: <5osld0Fof544U1@mid.uni-berlin.de> Hrvoje Niksic schrieb: > "Chris Mellon" writes: > >> I have no idea why someone who already has a working, object system >> would want to implement their own on top of closures. > > This subthread is getting ridiculous -- closures are *not* useful only > for implementing object systems! The object system thing is just a > method of teaching abstractions popularized by SICP. Abstractions > normally taken for granted, such as objects, or even expression > evaluation, are implemented from scratch, using only the most basic > primitives available. In a Lisp-like language with lexical scope, the > most basic storage primitive is the lexical environment itself[1]. > > In real-life code, closures are used to implement callbacks with > automatic access to their lexical environment without the need for the > bogus additional "void *" argument one so often sees in C callbacks, > and without communication through global variables. If the callbacks > can access variables in the outer scope, it's only logical (and > useful) for them to be able to change them. Prohibiting modification > reduces the usefulness of closures and causes ugly workarounds such as > the avar[0] pattern. > > If closures were useful only for implementing bogus object systems, > neither they nor "nonlocal" would have made it to Python in the first > place. > There's a nice saying about this: """ The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil - objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's object." At that moment, Anton became enlightened. """ http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html I do love closures, and I sometimes pitty python for not allowing to set outer scope variables. But then, it's because it lacks a variable declaration scheme (as e.g. javascript has), so _some_ design decision had to be made distinguishing variable declarations from pure references. And I can live with the consequences. Diez From steve at holdenweb.com Wed Oct 3 22:22:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 03 Oct 2007 22:22:30 -0400 Subject: module confusion In-Reply-To: References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> <874ph8sdhx.fsf@benfinney.id.au> Message-ID: <47044E66.6030304@holdenweb.com> Lawrence D'Oliveiro wrote: > In message <874ph8sdhx.fsf at benfinney.id.au>, Ben Finney wrote: > >> Lawrence D'Oliveiro writes: >> >>> On my Gentoo system: >>> >>> >>> import os >>> >>> os.path >>> >>> >>> It's just a variable that happens to point to the posixpath module. >> There's no "pointing" going on. It's another name bound to the same >> object, of equal status to the 'posixpath' name. >> >> Python doesn't have pointers, and even "variable" is a misleading term >> in Python. Best to stick to "name" and "bound to". > > In Python, all names _are_ variables. They are not "bound" to objects. The > value of os.path is a pointer. It's implemented as a pointer, it has all > the semantics of a pointer. > > Honestly, why do people react to the word "pointer" as though computers have > to wear underwear to conceal something shameful going on in their nether > regions? Because they have been told by their church that all God-fearing names do what names have always done in programming languages, which is to describe areas of memory of a particular size, type and locality. You and I know that the semantics of Python names are precisely those of (to use an Algol 68 term, unless I am mistaken) automatically dereferenced pointers to objects of arbitrary type. I actually think that's one of the neatest things about Python, and I believe it's no accident that both Tim Peters and I were Icon enthusiasts. But the rest of the world clings to its illusions. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From besturk at gmail.com Wed Oct 31 17:03:59 2007 From: besturk at gmail.com (Abandoned) Date: Wed, 31 Oct 2007 14:03:59 -0700 Subject: 3 number and dot.. In-Reply-To: <1193863088.980629.127030@o38g2000hse.googlegroups.com> References: <1193860737.687984.13400@k79g2000hse.googlegroups.com> <1193863088.980629.127030@o38g2000hse.googlegroups.com> Message-ID: <1193864639.887794.205490@50g2000hsm.googlegroups.com> On Oct 31, 10:38 pm, Paul McGuire wrote: > On Oct 31, 2:58 pm, Abandoned wrote: > > > Hi.. > > I want to do this: > > for examle: > > 12332321 ==> 12.332.321 > > > How can i do? > >>> x = (12332321,) > >>> while (x[0]>0): x=divmod(x[0],1000)+x[1:] > ... > >>> x > (0, 12, 332, 321) > >>> ".".join(map(str,x[1:])) > > '12.332.321' > > -- Paul Hmm. When the number as 1023 the result is 1.23 :( How can i fix it ? From python.list at tim.thechases.com Sun Oct 28 09:01:08 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 28 Oct 2007 08:01:08 -0500 Subject: iterating over the other and finding the greatest In-Reply-To: References: Message-ID: <47248814.4040601@tim.thechases.com> > have carry out a process a>b then i should print the line and if b>c then i > should print the line and c>d then i should print....... like this i have to > continue.say for eg: 43<387 so the first row is omitted, 387 is greater then > 98 so i can print the line second row... > my code: > fh = open('364010_spacing','r') > for lines in fh.readlines(): > data = lines.strip().split('\t') > start =data[0].strip() > end = data[1].strip() > values = data[2].strip() > id = data[3].strip() > if a > b :#hanged up here > print lines though you don't really define a/b/c anywhere, other than obliquely referencing values in your 3rd column, I presume they map to the lines in the file a=1st-line, b=2nd-line, etc. You also don't disclose when you want the printing to happen, whether you want to print the highest at each line as you iterate over them (in your example, printing a,b,b,b,e,e,e,e or if you want to find the maximum and then print it at the end (just printing line e once). I don't know if you want to do if more than one row has the maximum value. Do you want to print all of the matching lines? or just the first or last one encountered? The code below iterates over the file, finding the maximum of the 3rd column, and then printing the first line that matched that. for i,line enumerate(open(filename, 'r')): c = int(line.rstrip('\n').split('\t')[2]) if i == 0: highest_id = c best_match = line else: if c > highest_id: highest_id = c best_match = line print line In your code, you parsed start/end, but didn't use them for anything...vestigial code? -tkc From gagsl-py2 at yahoo.com.ar Thu Oct 4 19:07:33 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 04 Oct 2007 20:07:33 -0300 Subject: enumerate overflow References: <1191411991.165082.19010@o80g2000hse.googlegroups.com> Message-ID: En Wed, 03 Oct 2007 08:46:31 -0300, escribi?: > in python2.4, i read lines from a file with > > for lineNum, line in enumerate(f): ... > > However, lineNum soon overflows and starts counting backwards. How do > i force enumerate to return long integer? (what kind of files are you using? enumerate overlows after more than two billion lines... is that "soon" for you?) I'm afraid neither iterate nor itertools.count will generate a long integer; upgrading to Python 2.5 won't help. I think the only way is to roll your own counter: lineNum = 0 for line in f: ... lineNum += 1 -- Gabriel Genellina From bj_666 at gmx.net Tue Oct 23 05:22:37 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Oct 2007 09:22:37 GMT Subject: How to implement function like this? References: Message-ID: <5o5sqtFld8c9U3@mid.uni-berlin.de> On Tue, 23 Oct 2007 16:28:37 +0800, Yinghe Chen wrote: > Hello gurus, > > I have a question, a function like below, it is implemented by me, :) > > def funcA(tarray): > a = [2,3,4] > if len(tarray) >=3: > return a[0],a[1], a[2] > elif len(tarray) == 2: > return a[0],a[1], funcB(1)[0] > elif len(tarray) == 1: > return a[0], funcB(2)[0], funcB(2)[1] > else: > return funcB(3)[0], funcB(3)[1], funcB(3)[2] > > > The return of funcA is always 3 values, but depending on the length of > tarray, I need to return different values accordingly. if tarray lenght is > 2, I need to get another one value from funcB, if tarray length is 0, I need > to get all three values from funcB. Untested: def func_a(t_array): result = [2, 3, 4] t_array_length = len(t_array) remaining_length = len(result) - t_array_length if t_array_length < len(result): result = (result[:t_array_length] + func_b(remaining_length)[:remaining_length]) return tuple(result) Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Wed Oct 3 23:57:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 03 Oct 2007 23:57:57 -0400 Subject: racism kontrol In-Reply-To: <47041be6$0$30382$9b4e6d93@newsspool4.arcor-online.net> References: <1191430790.537383.115880@r29g2000hsg.googlegroups.com> <1191435296.523842.160230@g4g2000hsf.googlegroups.com> <4703f631$0$7692$9b4e6d93@newsspool2.arcor-online.net> <47041be6$0$30382$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Wildemar Wildenburger wrote: > Steve Holden wrote: >> Wildemar Wildenburger wrote: >>> (I aplogize for that last remark. I have nothing against turkish >>> people, I just couldn't let the opportunity for a mean joke slip.) >> Does this mean you are an equal-opportunity racist? >> > Yeah! Well observed. :) > Although "equal-opportunity misantropist" might be a more fitting term. > Whatever suits me to express my hatred towards humans. Race, gender, > text editor ... you name it. > > /W > (By the way: Accusing a German of racism is almost too easy an insult. > Not that I had taken any, just saying.) Sorry, you just failed the German test by evidencing a sense of humor (or do I remember you warning me about that?) You are an AI named Alan Turing, and I claim the ?5,000 prize. It's like accusing a Yorkshireman of meanness (Americans: "being cheap"): it's tautologous ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it From see.signature at no.spam Fri Oct 5 04:42:23 2007 From: see.signature at no.spam (Eric Brunel) Date: Fri, 05 Oct 2007 10:42:23 +0200 Subject: tkinter question References: <1191554174.490449.251400@50g2000hsm.googlegroups.com> Message-ID: On Fri, 05 Oct 2007 05:16:14 +0200, goldtech wrote: > This works OK. But I notice that if I enlarge the window after the > script has run, the white listbox only gets "so" big while the grey > background enlarges. > > Is there a way to have it all white when I enlarge a window - like > what normally happens? > > > > from Tkinter import * > root = Tk() > root.title("Dirty Words") > scrollbar = Scrollbar(root) > scrollbar.pack(side=RIGHT, fill=Y) > listbox = Listbox(root, bg='white', font = "Courier 16", width=60) > listbox.pack() => listbox.pack(fill=BOTH, expand=1) > i='123456789abcdefghijklmnopqrstuvwxyz' > for x in range(10): > listbox.insert(END, i) > listbox.config(yscrollcommand=scrollbar.set) > scrollbar.config(command=listbox.yview) > mainloop() BTW, even for something that simple, using the grid geometry manager may be easier... It is at least easier to explain: don't ask me what the expand=1 option means, I never understood it... I just add or remove it when the pack doesn't do what I want. The sticky option with grid is easier to handle. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From basilisk96 at gmail.com Fri Oct 19 22:24:20 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Sat, 20 Oct 2007 02:24:20 -0000 Subject: where do I need to "tab"? In-Reply-To: <1192845611.102983.310980@i38g2000prf.googlegroups.com> References: <1192845611.102983.310980@i38g2000prf.googlegroups.com> Message-ID: <1192847060.804494.303600@t8g2000prg.googlegroups.com> Tab is not the issue here. By my powers of deduction, I can see that you are running this code in Python version previous to 2.5, because the construct "true_clause if condition else false_clause" did not exist until 2.5. It's a neat little construct, I highly recommend you upgrade now :) -Basilisk96 From mensanator at aol.com Thu Oct 18 22:59:29 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 18 Oct 2007 19:59:29 -0700 Subject: vote for Python - PLEASE In-Reply-To: References: Message-ID: <1192762769.971770.297830@e9g2000prf.googlegroups.com> On Oct 18, 6:12 pm, Monty Taylor wrote: > Hey everybody, > > MySQL has put up a poll onhttp://dev.mysql.comasking what your primary > programming language is. But it doesn't ask that, it asks what your primary programming language is FOR DEVELOPING MYSQL APPLICATIONS. In my case, there is no such language (even though I primarily use Python) BECAUSE I DON'T USE MYSQL. > Even if you don't use MySQL - please go stick > in a vote for Python. I'm constantly telling folks that Python needs > more love, but PHP and Java are kicking our butts... > > (I know the world would be a better place if the poll were honest, There is dishonestly and there's outright lying > but > I'd rather that people got the message that they should do more python > development work!) Maybe the Python community doesn't need your help. > > Thanks! > Monty From marcpp at gmail.com Thu Oct 11 19:47:30 2007 From: marcpp at gmail.com (marc) Date: Fri, 12 Oct 2007 01:47:30 +0200 Subject: Diferent files: GUI (wxpython) Program References: <1192145293.118368.214950@k35g2000prh.googlegroups.com> Message-ID: cmpython at gmail.com escribi?: > On Oct 11, 5:44 pm, marc wrote: >> Hi why I can call an .py GUI (wxpython) from a program and control it? >> I'm newbie in python. > > Sorry, could you restate that? Explain again what you want to do. > I would to call a python file that contains a GUI (with wx) from a file program. The programs that I've do, contains a GUI and the code to run it in the same file, but I when need to modify a GUI file (I use wxglade) I need to delete all code lines (except the GUI code lines) and it difficult the program. From joshua.davies at travelocity.com Mon Oct 8 10:17:36 2007 From: joshua.davies at travelocity.com (joshua.davies at travelocity.com) Date: Mon, 08 Oct 2007 07:17:36 -0700 Subject: Variable scoping rules in Python? Message-ID: <1191853056.970304.209350@k79g2000hse.googlegroups.com> Ok, I'm relatively new to Python (coming from C, C++ and Java). I'm working on a program that outputs text that may be arbitrarily long, but should still line up, so I want to split the output on a specific column boundary. Since I might want to change the length of a column, I tried defining the column as a constant (what I would have made a "#define" in C, or a "static final" in Java). I defined this at the top level (not within a def), and I reference it inside a function. Like this: COLUMNS = 80 def doSomethindAndOutputIt( ): ... for i in range( 0, ( len( output[0] ) / COLUMNS ) ): print output[0][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ] print output[1][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ] .. etc. etc. It works fine, and splits the output on the 80-column boundary just like I want. Well, I decided that I wanted "COLUMNS = 0" to be a special "don't split anywhere" value, so I changed it to look like this: COLUMNS = 80 def doSomethindAndOutputIt( ): ... if COLUMNS == 0: COLUMNS = len( output[ 0 ] ) for i in range( 0, ( len( output[0] ) / COLUMNS ) ): print output[0][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ] print output[1][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ] .. Now, when I run it, I get the following error: Traceback (most recent call last): File "Test.py", line 140, in ? doSomethingAndOutput( input ) File "Test.py", line 123, in doSomethingAndOutput if COLUMNS == 0: UnboundLocalError: local variable 'COLUMNS' referenced before assignment I went back and re-read chapter 13 of "Learning Python", which talks about variable scoping rules, and I can't figure out why Python is saying this variable in Unbound. It works if I insert: global COLUMNS before the "if" statement... but I don't understand why. Is the interpreter scanning my entire function definition before executing it, recognizing that I *might* assign COLUMNS to a value, and deciding that it's a local on that basis? From hainguyen2x at yahoo.com Thu Oct 11 12:40:10 2007 From: hainguyen2x at yahoo.com (hainguyen2x at yahoo.com) Date: Thu, 11 Oct 2007 09:40:10 -0700 Subject: how to get the NT event log properties with OnObjectReady() with python Message-ID: <1192120810.094251.193810@19g2000hsx.googlegroups.com> I'm trying to get a notification from the NT event for any new event using the DispatchWithEvents() function. Everything seems to be working the way I wanted, but I don't know how to get the properties of the event (ie. event type, message, etc.) from the OnObjectReady() callback. class SinkClass(object): def OnObjectReady(self, *args): #self may be the wmi_sink object print "OnObjectReady callback ..." print self #.TargetInstance.Message print args[0] def OnCompleted(self, *args): print "OnCompleted callback..." print args #.TargetInstance.Message def OnObjectPut(self, *args): print "OnObjectPut callback..." def OnProgress(self, *args): print "OnProgress callback..." wmi = win32com.client.GetObject("winmgmts: {impersonationLevel=impersonate,(security)}!//./root/cimv2") wmi_sink = win32com.client.DispatchWithEvents("WbemScripting.SWbemSink",SinkClass) wmi.ExecNotificationQueryAsync(wmi_sink,"SELECT * FROM __InstanceCreationEvent where TargetInstance ISA 'Win32_NTLogEvent'") The argument args in the OnObjectReady() seems to be the interface to a com object (may be the event object itself). I want to read the properties (ie. message, eventID, type, etc) of the triggered NT event. Please help. From monty at inaugust.com Thu Oct 18 19:12:37 2007 From: monty at inaugust.com (Monty Taylor) Date: Thu, 18 Oct 2007 16:12:37 -0700 Subject: vote for Python - PLEASE Message-ID: <4717E865.6090706@inaugust.com> Hey everybody, MySQL has put up a poll on http://dev.mysql.com asking what your primary programming language is. Even if you don't use MySQL - please go stick in a vote for Python. I'm constantly telling folks that Python needs more love, but PHP and Java are kicking our butts... (I know the world would be a better place if the poll were honest, but I'd rather that people got the message that they should do more python development work!) Thanks! Monty From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Oct 15 15:51:54 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 15 Oct 2007 21:51:54 +0200 Subject: Normalize a polish L References: <1192466006.735303.20470@i38g2000prf.googlegroups.com> Message-ID: <5nhumqFig4buU1@mid.individual.net> Thorsten Kampe wrote: > The 'L' is actually pronounced like the English "w"... '?' originally comes from "L" () and is AFAIK transcribed so. Also, a friend of mine writes himself "Lukas" (pronounced L-) even though in Polish his name is ?ukas (short Wh-). Regards, Bj?rn -- BOFH excuse #126: it has Intel Inside From mensanator at aol.com Wed Oct 31 01:32:50 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Tue, 30 Oct 2007 22:32:50 -0700 Subject: choose from a list In-Reply-To: <1193791188.338141.123020@v3g2000hsg.googlegroups.com> References: <1193767382.430635.303370@d55g2000hsg.googlegroups.com> <1193770225.374384.52290@k79g2000hse.googlegroups.com> <1193782113.429067.132740@57g2000hsv.googlegroups.com> <1193785411.032673.147860@v3g2000hsg.googlegroups.com> <1193791188.338141.123020@v3g2000hsg.googlegroups.com> Message-ID: <1193808770.776610.50280@o80g2000hse.googlegroups.com> On Oct 30, 7:39?pm, barronmo wrote: > I didn't know "result" was a list! I don't use MySQL but that's how others work. Each list item is a record, each record a tuple of field values. > Can all that info be stored in a list? If you don't fetch too many records at once. This is a test of my word database using ODBC and MS-ACCESS (the SQL is very simple since all the actual work is done in MS-ACCESS, Python is just retrieving the final results). import dbi import odbc con = odbc.odbc("words") cursor = con.cursor() cursor.execute("SELECT * FROM signature_anagram_summary") results = cursor.fetchall() Here, results (the recipient of .fetchall) is a list of tuples. The contents are: [(9, 10, 'anoretics', '10101000100001100111000000'), (9, 10, 'atroscine', '10101000100001100111000000'), (9, 10, 'certosina', '10101000100001100111000000'), (9, 10, 'creations', '10101000100001100111000000'), (9, 10, 'narcotise', '10101000100001100111000000'), (9, 10, 'ostracine', '10101000100001100111000000'), (9, 10, 'reactions', '10101000100001100111000000'), (9, 10, 'secration', '10101000100001100111000000'), (9, 10, 'tinoceras', '10101000100001100111000000'), (9, 10, 'tricosane', '10101000100001100111000000')] > How do the columns work? I don't know, I don't get column names. It looked like from your example that you can use names, I would have to use indexes, such as results[3][2] to get 'creations'. Maybe MySQL returns dictionaries instead of tuples. > I was curious to see what the data > looked like but I can't seem to print "result" from the prompt. Do > variables used inside functions live or die once the function > executes? Yeah, they die. You would have to have the function return the results list and indx, then you could use it's contents as criteria for further queries. So you might want to say name_find_results,indx = name_find(namefrag) > If they die, how do I get around this? Add 'return results,indx' to the function. Or better still, just return the record the user selected return results[indx] You wouldn't need indx anymore since there's only 1 record. > I tried defining 'r > = ""' in the module before the function and then using it instead of > "result" but that didn't help. > > Mike From steve at REMOVE-THIS-cybersource.com.au Tue Oct 23 13:25:00 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 23 Oct 2007 17:25:00 -0000 Subject: Life-time of temporary variables in list comprehensions References: <1193158968.578330.204710@t8g2000prg.googlegroups.com> Message-ID: <13hsbjceeiauj39@corp.supernews.com> On Tue, 23 Oct 2007 17:02:48 +0000, beginner wrote: > My test shows that if c is not defined before the list comprehension, it > will be created in the list comprehension; if it is defined before the > list comprehension, the value will be overwritten. In other words, temp > variables are not local to list comprehensions. That's right. > My question is why is this and is there any way to make c local to list > comp? It was a design decision that is now regretted. There is no way for you to make it local to the list comp except to wait for a new version of Python that behaves in the way you want. Or you can look at generator expressions, which are written just like list comprehensions except with round brackets (). They are not quite the same thing, but you can often use one in place of the other. -- Steven. From bblais at bryant.edu Sun Oct 21 14:14:26 2007 From: bblais at bryant.edu (Brian Blais) Date: Sun, 21 Oct 2007 14:14:26 -0400 Subject: compiler module bug? In-Reply-To: References: <7DEB606B-7856-4140-ADA9-4083EC22D380@bryant.edu> <01E5EB0B-6904-438C-B9DD-B27310C0381D@bryant.edu> Message-ID: <3183F644-5C73-4193-B19E-D2564AD2F1F3@bryant.edu> On Oct 21, 2007, at Oct 21:2:05 PM, Gabriel Genellina wrote: > The parseFile function does exactly that, along with this comment: thanks! bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremy+complangpython at jeremysanders.net Tue Oct 2 01:38:23 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 02 Oct 2007 06:38:23 +0100 Subject: Wrapper functions and arguments Message-ID: One little issue I have is to write a little wrapper which can generally pass standard and keyword arguments to a callee: def a(x, y, z): print x, y, z def b(x, y, z='fruitbat') print x, y, z for func in a, b: def wrapper(func=func, *args, **argsk): # do something func(*args, **argsk) x.append(wrapper) x[0](1, 2, 3) x[1](1, 2) ... Is there any way to do this? Can you capture arguments in a tuple and dict, but still receive other keyword arguments? The only solution I found was to implement wrapper as a class (like I would in c++): class wrapper(object): def __init__(self, func): self.func = func def __call__(self, *args, **argsk): self.func(*args, **argsk) Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From hniksic at xemacs.org Fri Oct 5 11:00:39 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 05 Oct 2007 17:00:39 +0200 Subject: remove list elements.. References: <1191594459.951323.254080@r29g2000hsg.googlegroups.com> Message-ID: <87odfdr4h4.fsf@mulj.homelinux.net> Abandoned writes: > I do this use FOR easly but the speed very imported for me. I want > to the fastest method please help me. Can you post the code snippet that was too slow for you? Are the lists sorted? From michele.simionato at gmail.com Sat Oct 27 01:42:38 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 26 Oct 2007 22:42:38 -0700 Subject: Bypassing __getattribute__ for attribute access In-Reply-To: <1193324851.162883.59500@y42g2000hsy.googlegroups.com> References: <1193324851.162883.59500@y42g2000hsy.googlegroups.com> Message-ID: <1193463758.768348.25590@o3g2000hsb.googlegroups.com> On Oct 25, 5:07 pm, Adam Donahue wrote: > As an exercise I'm attempting to write a metaclass that causes an > exception to be thrown whenever a user tries to access > 'attributes' (in the traditional sense) via a direct reference. Well, now thanks to Bruno and the others you know everything about attribute access in Python. Still, you may be interested in this recipe, which involves __setattr__ and non __getattribute__: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 Michele Simionato From george.sakkis at gmail.com Tue Oct 9 02:06:44 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 09 Oct 2007 06:06:44 -0000 Subject: property question In-Reply-To: References: Message-ID: <1191910004.776779.223170@50g2000hsm.googlegroups.com> On Oct 9, 1:20 am, "Manu Hack" wrote: > hi all, > > If I have a class A with A.x, A.y, A.z. A.y and A.z are property and > in order to compute the value of them, A.y depends on A.x while A.z > depends on A.y and A.x. If I call A.y, and A.z, the value A.y would > be computed twice. Is there a smart way to avoid that as to A.y will > be recomputed only if A.x has been changed? Now I can define more > variables to keep track of what is changed but when there are more > variables and the dependency becomes more involved it could be very > complicated. Thanks a lot. > > Manu I haven't needed to use it myself so far, but PyCells (http:// pycells.pdxcb.net/) seems it might fit the bill. George From Scott.Daniels at Acm.Org Thu Oct 11 22:59:09 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 11 Oct 2007 19:59:09 -0700 Subject: remove header line when reading/writing files In-Reply-To: <1192148900.396062.122780@i13g2000prf.googlegroups.com> References: <1192143175.137620.319470@q5g2000prf.googlegroups.com> <470EAFA2.2060409@tim.thechases.com> <1192148900.396062.122780@i13g2000prf.googlegroups.com> Message-ID: <13gtok8ea3b2dbb@corp.supernews.com> timaranz at gmail.com wrote: > ... > for zipfile in filelist: > zfiter = iter(gzip.Gzipfile(zipfile,'r')) > zfiter.next() # ignore header line > for i, line in enumerate(fziter): > outfile.write(line) Or even: writes = outfile.write for zipfile in filelist: zfiter = iter(gzip.Gzipfile(zipfile,'r')) zfiter.next() # ignore header line for line in zfiter: writes(line) From paul.nospam at rudin.co.uk Mon Oct 22 16:38:05 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 22 Oct 2007 21:38:05 +0100 Subject: Iteration for Factorials References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <1193075845.148527.80820@k35g2000prh.googlegroups.com> <87bqarov3n.fsf@rudin.co.uk> <1193083810.302605.128630@y27g2000pre.googlegroups.com> Message-ID: <877ileq40i.fsf@rudin.co.uk> tokland at gmail.com writes: > On 22 oct, 20:35, Paul Rudin wrote: > >> import operator >> def fact(x): >> return reduce(operator.mul, xrange(1,x)) > > Maybe: > > import operator > def fact(x): > return reduce(operator.mul, xrange(2, x+1), 1) Or just: reduce(operator.mul, xrange(1, x), 1) From sipickles at hotmail.com Thu Oct 18 14:13:53 2007 From: sipickles at hotmail.com (Simon Pickles) Date: Thu, 18 Oct 2007 19:13:53 +0100 Subject: Running another python interpreter In-Reply-To: <47179DBA.8040407@hotmail.com> References: <47179DBA.8040407@hotmail.com> Message-ID: <4717A261.7090303@hotmail.com> Well, I tried: os.spawnv(os.P_NOWAIT, "gateway.py", ()) and got: OSError: [Errno 8] Exec format Simon Pickles wrote: > Hello, > > I have several servers which link to each other (and of course, to clients). > > At present, I am starting them in turn manually. Is there a way with > python to say, "open gateway.py in a new interpreter window"? > > I looked at execv, etc, but they seem to replace the current process. > Ah, maybe I need spawnv(). > > I am on windows i386, python 2.5 > > Thanks > > si > From cjw at sympatico.ca Fri Oct 19 08:54:34 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 19 Oct 2007 08:54:34 -0400 Subject: class vs type Message-ID: In Python Types and Objects, Shalabh Chaturvedi says (in the Python 3.0 documentation - New Style Classes) "The term class is traditionally used to imply an object created by the class statement. However, classes are now synonymous with types. Built-in types are usually not referred to as classes. This book prefers using the term type for both built-in and user created types." Do we need two different words to describe what is essentially the same thing? Colin W. From george.sakkis at gmail.com Sat Oct 13 10:06:22 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 13 Oct 2007 14:06:22 -0000 Subject: ConnectionClosedError In-Reply-To: References: <1192220524.837248.173230@i13g2000prf.googlegroups.com> Message-ID: <1192284382.892195.234440@e9g2000prf.googlegroups.com> On Oct 13, 4:21 am, "Hendrik van Rooyen" wrote: > > If restarting the server sorts it, why don't you run the server as a > subprocess in a higher level script, and exit with an error code > if the error strikes? Well as I mentioned the process doesn't exit, it is just unresponsive from the client's side, so this doesn't solve it. > It may be that the reason for your hang up is also a > threading issue - it could be that the server is alive but > that some critical thread has been killed by the error. > But here I am guessing... I don't create explicitly any thread in my server code but Pyro itself is multithreaded. Unfortunately I don't have the resources to start digging in Pyro's internals.. George From rdm at rcblue.com Mon Oct 29 08:23:54 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 29 Oct 2007 05:23:54 -0700 Subject: Using msvcrt (in Windows), how to catch Enter key? In-Reply-To: <1193657385.878620.35180@d55g2000hsg.googlegroups.com> References: <1193657385.878620.35180@d55g2000hsg.googlegroups.com> Message-ID: <20071029122404.817D11E4012@bag.python.org> At 04:29 AM 10/29/2007, Filip Wasilewski wrote: >On Oct 29, 11:26 am, Dick Moores wrote: > > Windows XP Pro, Python 2.5.1 > > > > import msvcrt > > while True: > > if msvcrt.kbhit(): > > key = msvcrt.getch() > > if key == 'Enter' > > do something > > > > Is there a way to catch the pressing of the 'Enter' key? > >Yes there is. Just open the Python shell and see what is being >returned by `getch` or `getche` functions when you press Enter: > > >>> import msvcrt > >>> msvcrt.getch() >'\r' Terrific! Thanks. >Also try to avoid `busy waiting` and calling msvcrt.kbhit in a loop >without a sleep statement. >I don't know your case but probably this >should be enough: > >while True: > if msvcrt.getch() == '\r': I tried it and find that without the msvcrt.kbhit the first key I hit doesn't do anything. I have to hit that key again, or another key. Dick From f.braennstroem at gmx.de Sat Oct 20 06:30:21 2007 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Sat, 20 Oct 2007 10:30:21 +0000 Subject: pyparsing batch file References: <1192653445.765147.204870@y27g2000pre.googlegroups.com> Message-ID: Hi Paul, Paul McGuire wrote: > On Oct 17, 4:47 pm, Fabian Braennstroem wrote: > >> Unfortunately, it does not parse the whole file names with >> the underscore and I do not know yet, how I can access the >> line with 'define/boundary-conditions'. Every 'argument' of >> that command should become a separate python variable!? >> Does anyone have an idea, how I can achieve this!? >> Regards! >> Fabian > > You are trying to match "keps1500_500.dat" with the expression > "Word(alphanums)". Since the filename contains characters other than > alphas and numbers, you must add the remaining characters ("." and > "_") to the expression. Try changing: > > write= Word(alphanums) > > to: > > write= Word(alphanums+"._") > > > To help you to parse "/define/boundary-conditions in velocity-inlet 10 > 0.1 0.1 no 1", we would need to know just what these arguments are, > and what values they can take. I'll take a wild guess, and propose > this: > > real = Combine(integer + "." + integer) > defineBoundaryConditions = "/define/boundary-conditions" + \ > oneOf("in out inout")("direction") + \ > Word(alphanums+"-")("conditionName") + \ > integer("magnitude") + \ > real("initialX") + \ > real("initialY") + \ > oneOf("yes no")("optional") + \ > integer("normal") > > (Note I am using the new notation for setting results names, > introduced in 1.4.7 - simply follow the expression with ("name"), > instead of having to call .setResultsName.) > > And here is a slight modification to your printout routine, using the > dump() method of the ParseResults class: > > for tokens in defineBoundaryConditions.searchString(data): > print > print "Boundary Conditions = "+ tokens.conditionName > print tokens.dump() > print > print 50*"-" > > > prints: > > Boundary Conditions = velocity-inlet > ['/define/boundary-conditions', 'in', 'velocity-inlet', '10', '0.1', > '0.1', 'no', '1'] > - conditionName: velocity-inlet > - direction: in > - initialX: 0.1 > - initialY: 0.1 > - magnitude: 10 > - normal: 1 > - optional: no Great! Thanks for the very good explanation! Regards! Fabian From python at rcn.com Tue Oct 23 11:39:30 2007 From: python at rcn.com (Raymond Hettinger) Date: Tue, 23 Oct 2007 08:39:30 -0700 Subject: Set operations on object attributes question In-Reply-To: <1193147226.862501.97240@v23g2000prn.googlegroups.com> References: <1193147226.862501.97240@v23g2000prn.googlegroups.com> Message-ID: <1193153970.762375.262430@k35g2000prh.googlegroups.com> [Duane] > LoTuples1 = [(1,1,0),(1,2,1),(1,3,3)] > Set1=set(LoTuples1) > LoTuples2 = [(2,1,3),(2,2,4),(2,3,2)] > Set2=set(LoTuples2) > > What I would like to be able to do is: > > Set3 = Set1union(Set2) > Set3.intersection(Set2, ) > > to return: > set([(2,1,3), (1,3,3)]) > > How can one do this operation? Conceptually, there is more than one operation going on. First, finding the attributes shared in both sets: ca = set(t[2] for t in LoTuples1) & set(t[2] for t in LoTuples2) which gives: set([3]) Second, find any tuple which has that attribute (including multiple results for the same attribute): set(t for t in (LoTuples1 + LoTuples2) if t[2] in ca) which returns: set([(2, 1, 3), (1, 3, 3)]) Wanting multiple results for the same attribute value (i.e. both (2,1,3) and (1,3,3) have 3 in the second position) is why multiple steps are needed; otherwise, the behavior of intersection() is to return a single representative of the equivalence class. Raymond From bignose+hates-spam at benfinney.id.au Wed Oct 3 06:23:38 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 03 Oct 2007 20:23:38 +1000 Subject: module confusion References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> Message-ID: <874ph8sdhx.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > On my Gentoo system: > > >>> import os > >>> os.path > > > It's just a variable that happens to point to the posixpath module. There's no "pointing" going on. It's another name bound to the same object, of equal status to the 'posixpath' name. Python doesn't have pointers, and even "variable" is a misleading term in Python. Best to stick to "name" and "bound to". -- \ "Crime is contagious ... if the government becomes a | `\ lawbreaker, it breeds contempt for the law." -- Justice Louis | _o__) Brandeis | Ben Finney From steven.bethard at gmail.com Sun Oct 7 23:41:18 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 07 Oct 2007 21:41:18 -0600 Subject: Problem of Readability of Python In-Reply-To: <1i5mh1z.7kw0621m8tpmpN%aleax@mac.com> References: <1191780456.833563.173080@57g2000hsv.googlegroups.com> <1i5m74j.1dpt4l9sbq7zzN%aleax@mac.com> <13giput3mhtvb6c@corp.supernews.com> <1i5mh1z.7kw0621m8tpmpN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Steven D'Aprano wrote: >> class Record(object): >> __slots__ = ["x", "y", "z"] >> >> has a couple of major advantages over: >> >> class Record(object): >> pass >> >> aside from the micro-optimization that classes using __slots__ are faster >> and smaller than classes with __dict__. >> >> (1) The field names are explicit and self-documenting; >> (2) You can't accidentally assign to a mistyped field name without Python >> letting you know immediately. [snip] > If I had any real need for such things, I'd probably use a metaclass (or > class decorator) to also add a nice __repr__ function, etc... Yep. That's what the recipe I posted [1] does. Given a class like:: class C(Record): __slots__ = 'x', 'y', 'z' it adds the most obvious __init__ and __repr__ methods. Raymond's NamedTuple recipe [2] has a similar effect, though the API is different. [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 [2] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261 STeVe From andrzej.s at gazeta.pl Tue Oct 9 06:14:36 2007 From: andrzej.s at gazeta.pl (Andrzej S.) Date: Tue, 09 Oct 2007 12:14:36 +0200 Subject: Python and UML In-Reply-To: <1191915187.827445.222470@r29g2000hsg.googlegroups.com> References: <1191915187.827445.222470@r29g2000hsg.googlegroups.com> Message-ID: aine_canby at yahoo.com wrote: > I'd like to start working with and learning more with UML. Can anyone > suggest any freeware design software that I might use to do this? I > also have > Visio installed on my computer if thats of any use... Does not Visio meet your requirements? It's quite powerfull UML design tool. From hniksic at xemacs.org Thu Oct 18 12:02:56 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 18 Oct 2007 18:02:56 +0200 Subject: Convert string to command.. References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> <5npa5cFj5bvfU1@mid.uni-berlin.de> <1192720007.177063.194550@i13g2000prf.googlegroups.com> <5npbjbFio7g9U1@mid.uni-berlin.de> <1192720659.272611.320900@v29g2000prd.googlegroups.com> <873aw830lc.fsf@mulj.homelinux.net> <1192722090.740342.60950@i13g2000prf.googlegroups.com> Message-ID: <87y7e01kcv.fsf@mulj.homelinux.net> Abandoned writes: > import cPickle as pickle > a="{2:3,4:6,2:7}" > s=pickle.dumps(a, -1) > g=pickle.loads(s); > print g > '{2:3,4:6,2:7}' > > Thank you very much for your answer but result is a string ?? Because you gave it a string. If you give it a dict, you'll get a dict: >>> import cPickle as pickle >>> a = {1:2, 3:4} >>> s = pickle.dumps(a, -1) >>> g = pickle.loads(s) >>> g {1: 2, 3: 4} If your existing database already has data in the "{...}" format, then eval it only the first time. Then you'll get the dict which you can cache thruogh the use of dumps/loads. From tjreedy at udel.edu Mon Oct 29 17:18:42 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Oct 2007 17:18:42 -0400 Subject: setting variables in outer functions References: <4B003AF0-D445-48A3-BE5D-08382B1B4018@comhem.se> Message-ID: "Tommy Nordgren" wrote in message news:4B003AF0-D445-48A3-BE5D-08382B1B4018 at comhem.se... | Given the following: | def outer(arg) | avar = '' | def inner1(arg2) | # How can I set 'avar' here ? You cannot at present. You can only mutate mutable outer vars: def outer(arg): avar = [''] def inner(argi): avar[0] = str(argi) ... From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Oct 25 12:35:22 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 25 Oct 2007 18:35:22 +0200 Subject: Bypassing __getattribute__ for attribute access In-Reply-To: <1193324851.162883.59500@y42g2000hsy.googlegroups.com> References: <1193324851.162883.59500@y42g2000hsy.googlegroups.com> Message-ID: <4720c5c3$0$20084$426a74cc@news.free.fr> Adam Donahue a ?crit : > As an exercise I'm attempting to write a metaclass that causes an > exception to be thrown whenever a user tries to access > 'attributes' (in the traditional sense) via a direct reference. I guess you're new to Python, and coming from either C++ or Java. Am I wrong ?-) And without even reading further, I can tell you're doing something pretty complicated that just don't work. (Ok, I cheated - I did read further !-) > Consider: > > class X( object ): > y = 'private value' > def get_y( self ): return self.y > > Normally one can access y here via: > > X().y > > or > > X().get_y() > > I want the former case, however, to throw an exception. So called "private" or "protected" attributes (IOW, implementation stuff the client code should not mess with) are denoted by a single leading underscore. IOW, 'y' should be '_y'. It won't of course prevent anyone to access the attribute, but then it's not your responsability anymore. I know this sound surprising to C++/Java programmers, but experience prove that it just work. Now if all you want is to reproduce the Java systematic-getter-setter dance - that is, use getters/setters 'just in case' you'd want to refactor (which, FWIW, is the only rationale behind accessors), you just don't need this with Python. We do have computed attributes here, so the simplest thing is to start with a plain attribute, then refactor it into a computed one if and when the need arises. This is *totally* transparent to client code. > I figured the way to do this would be to introduce a metaclass that > overrides the default __getattrribute__ call and throws an exception. > So my first attempt was something like: > > class XType( type ): > def __my_getattribute__( self, name ): > raise AttributeError() > def __init__( klass, name, bases, dict ): > super( XType, klass ).__init__( name, bases, dict ) > setattr( klass, '__getattribute__', > klass.__my_getattribute__ ) > > But whereas the X().y attribute behaves as I intend, the X().get_y() > returns raises that exception as well: Indeed. __getattribute__ is invoked for *each and every* attribute lookup - including methods, since methods are attributes too. FWIW, __getattribute__ it's something you should not mess with unless you know what you're doing and why you're doing it. > > So it looks as if 'attribute' here means any key in self.__dict__, The '.' is the lookup operator. As soon as you have obj.anyname, you do an attribute lookup (wether it fails or succeeds is another question). And __getattribute__ is the implementation for this operator. So given how you wrote your custom __getattribute__, you just made attribute lookup impossible. And FWIW, attribute lookup is much more complex than just looking up the instance's __dict__ - it also looks up the class __dict__, then the parent's classes __dict__, then look for a custom __getattr__ method (which is used when the attribute has not been found so far). And if the attribute found is a class attribute that implements the descriptor protocol, then __getattribute__ is responsible for invoking this protocol. IOW, __getattribute__ is one of the most critical magic methods. > whether referenced via self.var, self.__dict__['var'] (because this > references __dict__), or getattr( self, 'var' ) (which is the same as > a direct self.var access, I believe). Practically, yes. > > So I tried: > > class XType( type ): > def __my_getattribute__( self, name ): > if name != '__dict__': > raise AttributeError() > return super( self.__class__, > self ).__getattribute__( name ) > def __init__( klass, name, bases, dict ): > super( XType, klass ).__init__( name, bases, dict ) > setattr( klass, '__getattribute__', > klass.__my_getattribute__ ) > > This allows me to access X().__dict__ directly (and then > X().__dict__['y']), but it still limits caller access to the get_y() > method. cf above. > It sounds then like the "solution" will be to check whether the name > referenced is called __dict__ or is a method or function type, > otherwise throw the exception, and to ensure all internal calls are > handled via self.__dict__[name] not self.name. My my my. Trouble ahead... > Something like: > > import types > class XType( type ): > def __my_getattribute__( self, name ): > if name != '__dict__' and not > isinstance( self.__dict__[name], types.FunctionType ): > raise AttributeError() > return super( self.__class__, *never* use self.__class__ (or type(self) etc) when calling super(). You *really* want to pass the exact class here - else you'll have *very* strange results. > self ).__getattribute__( name ) > def __init__( klass, name, bases, dict ): > super( XType, klass ).__init__( name, bases, dict ) > setattr( klass, '__getattribute__', > klass.__my_getattribute__ ) My my my... > Of course this is imperfect as a user can simply bypass the > __getattribute__ call too and access __dict__ directly, Indeed. The fact is that there's just no way to prevent client code to access your implementation. Period. So relax, stop fighting against the langage, and learn to use it how it is. > but it's > closer to what I was thinking. The problem is the return value for > functions is not bound - how do I bind these to the associated > instance? func.__get__(obj, obj.__class__) But that should not be done when the function is an instance attribute - only when it's a class one. And any class attribute implementing the descriptor protocol should be treated that way. > (Caveat - I am not sure whether using __get__ itself in lieu of > __getattribute__ would be a better solution; but I would like to see > how binding would be done here for general knowledge.) (simplified) In the normal case, when the attribute looked up happens to be a class attribute and implements the descriptor protocol, __getattribute__ returns attr.__get__(obj, type(obj). What attr.__get__ returns is up to whoever implemented type(attr). In the case of functions, anyway, __get__ returns a method object, which is a callable object wrapping the function, the target object and the class. When called, this method object insert the target object (or class if it's a classmethod) in front of the args list, and invoke the function with this new args list. Which is why you need to declare self (or cls) as first argument of a 'method' but not to explicitely pass it at call time. Anyway : forget about "real" privacy in Python (FWIW, neither Java nor C++ have "real" privacy - there are ways to bypass access restrictors in both languages), just use the single leading underscore convention and you'll be fine. And don't write explicit accessors - in fact, don't write accessors at all until you need them, and when you need them, use a property or a custom descriptor object, so it's transparant to client code. HTH From martin at v.loewis.de Mon Oct 1 18:30:20 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 02 Oct 2007 00:30:20 +0200 Subject: Python and SSL In-Reply-To: References: <1190959345.041723.108130@k79g2000hse.googlegroups.com> <6cydncA2Jpv082DbnZ2dnUVZ_q6dnZ2d@comcast.com> <1191224526.856466.305980@57g2000hsv.googlegroups.com> <7xzlz2q53e.fsf@ruckus.brouhaha.com> <1191251260.376954.265060@22g2000hsm.googlegroups.com> <47012255.4020502@v.loewis.de> Message-ID: <470174FC.5060709@v.loewis.de> > Actually, the SSL certificate has to be in valid format, because > OpenSSL does require that. Sure. However, in the first message, the OP mentioned that he gets error 503. That tells me that the SSL connection had been established successfully, and that he was actually seeing a HTTP error, not an SSL one (unless he made up that error code, of course). Regards, Martin From Shawn at Milochik.com Wed Oct 10 13:02:45 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Wed, 10 Oct 2007 13:02:45 -0400 Subject: [Tutor] matching a street address with regular expressions In-Reply-To: <4704DD04.4020304@bigfoot.com> References: <505641.42832.qm@web51601.mail.re2.yahoo.com> <4704DD04.4020304@bigfoot.com> Message-ID: <2dc0c81b0710101002l53febbbay4741a50b7548f958@mail.gmail.com> On 10/4/07, Ricardo Ar?oz wrote: > Christopher Spears wrote: > > One of the exercises in Core Python Programming is to > > create a regular expression that will match a street > > address. Here is one of my attempts. > > > >>>> street = "1180 Bordeaux Drive" > >>>> patt = "\d+ \w+" > >>>> import re > >>>> m = re.match(patt, street) > >>>> if m is not None: m.group() > > ... > > '1180 Bordeaux' > > > > Obviously, I can just create a pattern "\d+ \w+ \w+". > > However, the pattern would be useless if I had a > > street name like 3120 De la Cruz Boulevard. Any > > hints? > > > Also, that pattern can be easily modified to have any number of words at the end: patt = "\d+ (\w+){1,}" This would take care of 3120 De la Cruz Boulevard. From kadeko at gmail.com Wed Oct 31 11:34:16 2007 From: kadeko at gmail.com (looping) Date: Wed, 31 Oct 2007 08:34:16 -0700 Subject: Creating a temporary file in Python In-Reply-To: <6ux*naIYr@news.chiark.greenend.org.uk> References: <1193832119.872710.108920@k79g2000hse.googlegroups.com> <6ux*naIYr@news.chiark.greenend.org.uk> Message-ID: <1193844856.163400.172320@50g2000hsm.googlegroups.com> On Oct 31, 2:16 pm, Sion Arrowsmith wrote: > " [ ... ] Whether the name can be used to open the file a second time, > while the named temporary file is still open, varies across platforms > (it can be so used on Unix; it cannot on Windows NT or later)." I didn't notice this limitation when reading the doc, thanks to point me to it. So for the future newbie that look something like this, here is my final code: fd, filename = tempfile.mkstemp(suffix='.sql') f = os.fdopen(fd, 'wb') try: f.write(txt.encode('cp1252')) f.close() p = Popen([SQL_PLUS, '-s', dsn, '@', SQL_PLUS_SCRIPT, filename], stdout=PIPE, stderr=STDOUT) p.wait() finally: os.remove(filename) From nagle at animats.com Mon Oct 15 01:26:38 2007 From: nagle at animats.com (John Nagle) Date: Mon, 15 Oct 2007 05:26:38 GMT Subject: Simple HTML template engine? In-Reply-To: <1192419411.895715.138450@e9g2000prf.googlegroups.com> References: <1192419411.895715.138450@e9g2000prf.googlegroups.com> Message-ID: allen.fowler wrote: > Hello, > > Can anyone recommend a simple python template engine for generating > HTML that relies only on the Pyhon Core modules? > > No need for caching, template compilation, etc. > > Speed is not a major issue. > > I just need looping and conditionals. Template inheritance would be a > bonus. HTMLTemplate is a minimal system for that sort of thing. It doesn't drag in some big "framework". John Nagle From bj_666 at gmx.net Wed Oct 17 08:19:32 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Oct 2007 12:19:32 GMT Subject: Static variable vs Class variable References: <1191946572.001076.271970@50g2000hsm.googlegroups.com> <5n1rosFftvtbU1@mid.uni-berlin.de> <13gngt29ovvcld1@corp.supernews.com> <5n26i7FfmohvU1@mid.uni-berlin.de> <13go1jqli5up5d1@corp.supernews.com> <5n39eaFg1m0qU1@mid.uni-berlin.de> <1192606439.190757.23530@i13g2000prf.googlegroups.com> <1192608969.051177.167130@q5g2000prf.googlegroups.com> <1192612830.110577.153790@i13g2000prf.googlegroups.com> <8764165bki.fsf@mulj.homelinux.net> <871wbu55pp.fsf@mulj.homelinux.net> Message-ID: <5nmcuhFiva37U2@mid.uni-berlin.de> On Wed, 17 Oct 2007 13:41:06 +0200, Hrvoje Niksic wrote: > Duncan Booth writes: > >> Hrvoje Niksic wrote: >> >>> I've recently been bitten by [rebinding the var to what __iadd__ >>> returns], and I don't understand the reasoning behind __iadd__'s >>> design. I mean, what is the point of an *in-place* add operation >>> (and others) if it doesn't always work in-place? >>> >> A very common use case is using it to increment a number: > > I'm aware of that; but remember that there's still __add__. It would > be sufficient for numbers not to implement __iadd__. And, in fact, > they already don't: > >>>> 1 .__add__(1) > 2 >>>> 1 .__iadd__(1) > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'int' object has no attribute '__iadd__' > > The current implementation of += uses __add__ for addition and > __iadd__ for addition that may or may not be in-place. I'd like to > know the rationale for that design. Simply not to introduce special cases I guess. If you write ``x.a += b`` then `x.a` will be rebound whether an `a.__iadd__()` exists or not. Otherwise one would get interesting subtle differences with properties for example. If `x.a` is a property that checks if the value satisfies some constraints ``x.a += b`` would trigger the set method only if there is no `__iadd__()` involved if there's no rebinding. Ciao, Marc 'BlackJack' Rintsch From has.temp3 at virgin.net Mon Oct 15 18:57:04 2007 From: has.temp3 at virgin.net (has) Date: Mon, 15 Oct 2007 15:57:04 -0700 Subject: py2app help In-Reply-To: References: Message-ID: <1192489024.055715.69900@e9g2000prf.googlegroups.com> On 15 Oct, 22:21, Massimo Di Pierro wrote: > Hello, > > Two users have reported this error when used the OSX version of Gluon > (http://mdp.cti.depaul.edu/examples) > > Traceback (most recent call last): > File "/Users/jacek/src/gluon/runme.app/Contents/Resources/ > __boot__.py", line 157, in > rograms/gluon/runme.py')) > File "/Users/jacek/src/gluon/runme.app/Contents/Resources/ > __boot__.py", line 148, in _run > target, wasChanged = alias.ResolveAlias(None) > MacOS.Error: (-35, 'no such volume') > 2007-10-15 21:29:08.896 runme[8217] runme Error > 2007-10-15 21:29:08.898 runme[8217] runme Error > An unexpected error has occurred during execution of the main script > Error: (-35, 'no such volume') > > I made it with py2app and I am relatively new to OSX. > Does anybody has any idea of what could be wrong? > I would very much appreciate any help. The code is posted including > setup_py2app. Most of the files in the .app bundle are actually symlinks, so I'm guessing you built it with the --alias flag which should be used for development purposes only. You need to rebuild it as a standalone executable. See the py2app documentation for more info: http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html (You might also file a feature request with the py2app developer asking for it to give a more helpful error message when this error occurs.) HTH has -- http://appscript.sourceforge.net http://rb-appscript.rubyforge.org From bob at passcal.nmt.edu Tue Oct 23 16:04:14 2007 From: bob at passcal.nmt.edu (Bob Greschke) Date: Tue, 23 Oct 2007 14:04:14 -0600 Subject: Python on Intel A110? Message-ID: <2007102314041416807-bob@passcalnmtedu> Will the "stock" Windows version of Python install on a Samsung Q1U-EL UMPC running Vista and with an Intel A110 processor? I want to do some development and just happened to think about this. I don't know what these processors are compatible with at the binary level. Thanks! Bob From python.list at tim.thechases.com Sun Oct 21 15:55:01 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 21 Oct 2007 14:55:01 -0500 Subject: Splitting URLs In-Reply-To: <13hmp2330pgrua4@corp.supernews.com> References: <13hmp2330pgrua4@corp.supernews.com> Message-ID: <471BAE95.5000604@tim.thechases.com> > URL = 'http://steve:secret at www.domain.com.au:82/dir" + \ > 'ectory/file.html;params?query#fragment' > > If I split the URL, I would like to get the following components: > > scheme = 'http' > netloc = 'steve:secret at www.domain.com.au:82' > username = 'steve' > password = 'secret' > hostname = 'www.domain.com.au' > port = 82 > path = '/directory/file.html' > parameters = 'params' > query = 'query' > fragment = 'fragment' > > I can get *most* of the way with urlparse.urlparse: it will split the URL > into a tuple: > > ('http', 'steve:secret at www.domain.com.au:82', '/directory/file.html', > 'params', 'query', 'fragment') > > If I'm using Python 2.5, I can split the netloc field further with named > attributes. Unfortunately, I can't rely on Python 2.5 (for my sins I have > to support 2.4). Before I write code to split the netloc field by hand (a > nuisance, but doable) I thought I'd ask if there was a function somewhere > in the standard library I had missed. there are some goodies in urllib for doing some of this splitting. Example code at the bottom of my reply (though it seems to choke on certain protocols such as "mailto:" and "ssh:" because urlparse doesn't return the netloc properly) > This second question isn't specifically Python related, but I'm asking it > anyway... > > I'd also like to split the domain part of a HTTP netloc into top level > domain (.au), second level (.com), etc. I don't need to validate the TLD, > I just need to split it. Is splitting on dots sufficient, or will that > miss some odd corner case of the HTTP specification? I believe that dots are the sanctioned separator, HOWEVER, you can have a non-qualified machine-name with local scope, so you can easily have NO TLD, such as http://user:password at localhost:8000/path/to/thing There's also the ambiguity of what "TLD" means if you use IP addresses: http://user:password at 192.168.1.1:8000/path/to/thing Does that make the TLD "1"? Other odd edge-cases that are usually allowable (but frowned upon, mostly used by spammers/phishers) include using a long-int as the domain-name, such as http://user:password at 2130706433:8000/path/to/thing In an attempt to play with these functions, I present the code below. -tkc import urlparse, urllib tests = ( 'http://steve:secret at www.example.com.au:82/' 'directory/file.html;params?query#fragment', 'http://user:password at 192.168.1.2/path/to/thing/', 'http://192.168.1.2/path/to/thing/', 'http://2130706433/path/to/thing/', 'http://localhost/path/to/thing/', 'http://user:password at localhost/path/to/thing/', 'telnet://foo at bar.com', 'ssh://user at example.com', 'gopher://wais.example.edu', 'svn+ssh://user:password at svn.example.com/svn/here/there/', 'mailto:joe at example.com', ) def is_ip_address(s): for i, part in enumerate(s.split('.')): try: assert 0 <= int(i) <= 255 except: return False return i == 3 def steve_parse(url): (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) creds, host = urllib.splituser(netloc) username, password = urllib.splitpasswd(creds or '') host, port = urllib.splitport(host) if '.' in host and not is_ip_address(host): domain, tld = host.rsplit('.', 1) else: domain = host tld = '' return ( scheme, username, password, domain, tld, port, path, params, query, fragment) if __name__ == '__main__': for test in tests: print test (scheme, username, password, domain, tld, port, path, params, query, fragment) = steve_parse(test) print '\tScheme: ', scheme print '\tUsername: ', username print '\tPassword: ', password print '\tDomain: ', domain print '\tTLD: ', tld print '\tPort: ', port print '\tPath: ', path print '\tParams: ', params print '\tQuery: ', query print '\tFragment: ', fragment print '='*50 From rdm at rcblue.com Sun Oct 7 02:05:03 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 06 Oct 2007 23:05:03 -0700 Subject: Top Programming Languages of 2013 Message-ID: <20071007060510.5DC811E4006@bag.python.org> Dick Moores From akraemer at sbcglobal.net Tue Oct 9 13:44:01 2007 From: akraemer at sbcglobal.net (Andreas Kraemer) Date: Tue, 9 Oct 2007 10:44:01 -0700 (PDT) Subject: mutable objects as dictionary keys Message-ID: <496883.54652.qm@web81005.mail.mud.yahoo.com> Hi everyone, I know that the subject of mutable objects as dictionary keys has been discussed a number of times in this forum (see for instance "freezing" of classes), but I would love to hear the thoughts of the experts on the approach below. The use case that I encounter frequently is the classification of objects according to certain rules or properties: Say, I have objects A, B, C, ... (e.g. instances of a class, dict, etc), I can write d = {} d.setdefault(A,[]).append(A) d.setdefault(B,[]).append(B) ... so objects that map to the same hash key will end up in the same bucket. (A "real world" example I had to deal with recently was for instance the construction of a directed acyclic graph from many directed trees where identical subtrees needed to be identified.) The easiest way is of course to define custom __hash__() and __eq__() methods, but this breaks if objects are mutated (accidentally) after having been inserted into the dictionary. The "best" working approach I came up with so far is to generate an "immutable view" V of a mutable object O according to my classification rule, delegate O.__hash__ and O.__eq__ to V, and make sure that the V is memoized and cannot (easily) be altered later, even when O is mutated: def hashable_mutable_factory(mutable,rule): class _mutable(mutable): def __init__(self,*args,**kw): self._view_cache = {} super(_mutable,self).__init__(*args,**kw) def _view(self): id_ = id(self) if not self._view_cache.has_key(id_): self._view_cache[id_] = rule(self) return self._view_cache[id_] def __hash__(self): return hash(self._view()) def __eq__(self,other): return self._view() == other._view() return _mutable E.g.: >>> hashable_dict = hashable_mutable_factory(dict,lambda obj: frozenset(obj.iteritems())) >>> h = hashable_dict(a=1,b=2) >>> d = {} >>> d[h] = 'foo' >>> d {{'a': 1, 'b': 2}: 'foo'} >>> h['c'] = 'bar' >>> d {{'a': 1, 'c': 'bar', 'b': 2}: 'foo'} >>> g = hashable_dict(a=1,b=2) >>> h {'a': 1, 'c': 'bar', 'b': 2} >>> g {'a': 1, 'b': 2} >>> id(g) == id(h) False >>> g == h True I slightly favor the factory function idiom above over defining the rule in a super class (this would have to be done for each mutable type and rule function separately), especially since I read that future versions of python (2.6 ?, 3.0 ?) will contain class decorators and allow syntax like class A(*bases): pass Is there a better approach? Any comments are appreciated. I have been seriously using Python for one year know, mostly in the context of graph algorithms etc., and it has always been a delightful coding experience! Best regards, Andreas -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Fri Oct 5 14:51:18 2007 From: stef.mientki at gmail.com (stef mientki) Date: Fri, 05 Oct 2007 20:51:18 +0200 Subject: Howto Launch a windows application ? In-Reply-To: <66d0a6e10710042124m3364a258r92658376ad735410@mail.gmail.com> References: <47040C25.7040303@gmail.com> <66d0a6e10710042124m3364a258r92658376ad735410@mail.gmail.com> Message-ID: <470687A6.5010903@gmail.com> Nicholas Bastin wrote: > On 10/3/07, stef mientki wrote: > >> hello, >> >> I'm trying to launch a windows application, >> but as many others on this list, I've some trouble. >> I read some other threads about this topic, >> but sorry, I still don't understand all this (never heard of pipes). >> >> When I use a batch file, I can launch the bat-file from python, >> and the windows application launched from the batchfile is run perfectly. >> >> Now when I try to run the same windows application from Popen or call, >> nothing happens (or at least it's very fast and produces not the >> expected output). >> >> Please enlighten me, preferable in "windows-terminology" ;-) >> >> thanks, >> Stef Mientki >> >> from subprocess import * >> >> cmd =[] >> cmd.append ( 'D:\\PIC-tools\\JALxxx\\jalv2_3.exe' ) >> cmd.append ( '-long-start' ) >> cmd.append ( '-d') >> cmd.append ( '-clear' ) >> cmd.append ( '-sD:\\PIC-tools\\JAL\\libs2' ) >> cmd.append ( 'd:\\pic-tools\\jal\\programs\\test_rs232\\test_rs232_hw.jal' ) >> cmd.append ( '>d:\\data_actueel\\d7_test_browser\\temp.log' ) >> >> # DOESN'T WORK >> result = call ( cmd ) >> >> # Both Popen and call work >> cmd = [ 'd:\\data_actueel\\d7_test_browser\\JALcc.bat' ] >> #output = Popen ( cmd ) >> result = call ( cmd ) >> print result >> > > First, call is a convenience function, but in your case, it's probably > not that convenient. Use the actual Popen constructor so you can get > at the output directly. Also, ditch the output redirector and use a > pipe: > > p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) > (out, err) = p.stdout, p.stderr > rcode = p.wait() > print out, err, rcode > > Try that and see what happens. When it doesn't work, look carefully > in out and err and see if anything interesting is in there. I was > able to open notepad.exe in this way with no problems so my guess is > you're having some other problem, but avoiding the use of the > convenience function will give you stdout and stderr to look at. > > Thanks Nick, replacing #print out, err, rcode with for line in out: print line for line in err: print line points me to the problem issue, which is the "-s" option, although I don't understand it yet > -- > Nick > > From hniksic at xemacs.org Wed Oct 10 10:29:47 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 10 Oct 2007 16:29:47 +0200 Subject: Singleton References: <1192009016.858568.58430@50g2000hsm.googlegroups.com> Message-ID: <87d4vngi04.fsf@mulj.homelinux.net> pythoncurious at gmail.com writes: > Now when I run the 'run.py', it will print two different numbers. > sys.modules tells me that 'mod1' is imported as both 'one.mod1' and > 'mod1', which explains the result. If I were you, I'd make sure that the module duplicate problem is resolved first, for example by putting run.py somewhere outside one/. Then the singleton problem disappears as well. > It is possible to solve this by always importing with the complete > path like 'one.mod1', even when inside the 'one' directory, but > that's an error waiting to happen. Is it, really? As far as I can tell, Python handles that case rather robustly. For example: $ mkdir one $ touch one/__init__.py $ touch one/mod1.py one/mod2.py $ echo 'import mod2' > one/mod1.py $ python Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import one.mod1 >>> import sys >>> sorted(sys.modules) ['UserDict', '__builtin__', '__main__', '_codecs', '_sre', '_types', 'codecs', 'copy_reg', 'encodings', 'encodings.aliases', 'encodings.codecs', 'encodings.encodings', 'encodings.types', 'encodings.utf_8', 'exceptions', 'linecache', 'one', 'one.mod1', 'one.mod2', 'os', 'os.path', 'posix', 'posixpath', 're', 'readline', 'rlcompleter', 'signal', 'site', 'sre_compile', 'sre_constants', 'sre_parse', 'stat', 'sys', 'types', 'warnings', 'zipimport'] Although mod1 imports mod2 simply with "import mod2", the fact that mod1 itself is imported as part of "one" is respected. As a result, mod2 is imported as "one.mod2", exactly as if it were imported from outside the "one" package. run.py is an exception because it is started directly using "python run.py", so it never gets the information that it's supposed to be part of a package. To fix the problem, all you need to do is make sure that executable scripts such as run.py are either placed safely outside the package, or that they take care to always use absolute imports, such as "import one.mod1" instead of "import mod1". Placing them outside the package is a good example of preventing an error waiting to happen, like the one you hinted at. From see.signature at no.spam Mon Oct 8 04:08:34 2007 From: see.signature at no.spam (Eric Brunel) Date: Mon, 08 Oct 2007 10:08:34 +0200 Subject: tkinter question References: <1191554174.490449.251400@50g2000hsm.googlegroups.com> <470629D1.2040404@codebykevin.com> <47063964.7000809@codebykevin.com> <470904AC.9090100@codebykevin.com> Message-ID: On Sun, 07 Oct 2007 18:09:16 +0200, Kevin Walzer wrote: > Hendrik van Rooyen wrote: >> "Kevin Walzer" wrote: >> >>> I find "pack" to be more flexible than "grid," so I prefer it for >>> complex layouts. "grid" is better for simple layouts. >> *does a double take* are you serious? - my experience is that >> pack is only good for simple single row or single column stuff. I agree with Hendrik, here... > Well, I guess it depends on your viewpoint. I find "pack" flexible > because it allows me to think in terms of top, bottom, right, and left > in terms of arranging UI elements--it's an elegant way to do it in my > view. I tend to use "grid" if I have, say, a window with several > preference items: a label, an entry field, and a button, all arranged in > rows. "grid" is better for stuff like that, I agree. > > See http://www.codebykevin.com/blosxom/business/phynchronicity-new.png: > this is an application I develop. The layout is all handled by "pack" > and paned windows. Where you you use "grid" in a layout like this? I personally use grid almost everywhere, except for basic rows or columns of widgets with no resizing policy. I find pack confusing, for the very same reason you find it flexible apparently; for me, this top/bottom/left/right stuff is not clear at all, and even after all the explanations I read (including yours), I still don't get the resize policy with pack. The single 'sticky' option with the row & column weights with grid is just clearer for me. And there are layouts that you just can't do with pack (canvas or text with vertical and horizontal scrollbars, for example...). But apparently, even this is - again - a matter of taste. So I guess I'll have to stop telling everyone that grid is better... ;-) -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From xah at xahlee.org Mon Oct 22 08:50:30 2007 From: xah at xahlee.org (Xah Lee) Date: Mon, 22 Oct 2007 05:50:30 -0700 Subject: TeX pestilence (was Distributed RVS, Darcs, tech love) In-Reply-To: <1193037849.011136.282480@y27g2000pre.googlegroups.com> References: <1192850894.310464.89070@e9g2000prf.googlegroups.com> <1192914246.208743.94870@y27g2000pre.googlegroups.com> <471afd4c.179297746@news.readfreenews.net> <1192972158.250126.203980@v23g2000prn.googlegroups.com> <471b6714$0$90276$14726298@news.sunsite.dk> <1192981349.181197.308610@q5g2000prf.googlegroups.com> <1193037849.011136.282480@y27g2000pre.googlegroups.com> Message-ID: <1193057430.359962.68820@v29g2000prd.googlegroups.com> TeX, in my opinion, has done massive damage to the computing world. i have written on this variously in emails. No coherent argument, but the basic thoughts are here: http://xahlee.org/cmaci/notation/TeX_pestilence.html it's slightly repeatitous there. But i think i might summarize in gist the few fundanmental issues, all sterm from just the first one: 1. A typesetting system per se, not a mathematical expressions representation system. 2. The free nature, like cigeratte given to children, contaminated the entire field of math knowledge representation into 2 decades of stagnation. 3. Being a typesetting system, brainwashed entire generation of mathematicians into micro-spacing doodling. 4. Inargurated a massive collection of documents that are invalid HTML. (due to the programing moron's ingorance and need to idolize a leader, and TeX's inherent problem of being a typesetting system that is unsuitable of representing any structure or semantics) 5. This is arguable and trivial, but i think TeX judged as a computer language in particular its syntax, on esthetical grounds, sucks in major ways. Btw, a example of item 4 above, is Python's documentation. Fucking asses and holes. Xah xah at xahlee.org http://xahlee.org/ From tjreedy at udel.edu Thu Oct 11 15:14:14 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 11 Oct 2007 15:14:14 -0400 Subject: Python SVN down? References: <1192094652.913626.171650@v3g2000hsg.googlegroups.com> Message-ID: "Anthon" wrote in message news:1192094652.913626.171650 at v3g2000hsg.googlegroups.com... |I am trying to get at the python source code, but it seems | svn.python.org is down, at least on port 80 (http) and 3690 (svn). | This happened earlier this week and then it came back (at least | yesterday). | Are all the real ( ;-) ) developers using ssh+svn and not noticing | this? The down, up, and down again were all noted on pydev. From __peter__ at web.de Mon Oct 22 04:24:15 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Oct 2007 10:24:15 +0200 Subject: package import question References: <1193040634.402343.127660@y27g2000pre.googlegroups.com> Message-ID: Phoe6 wrote: > Hi all, > I have the following directory structure: > > wallpaper/ > -main.py > -ng/ > -- __init__.py > -- setdesktop.py > -yb/ > -- __init__.py > -- setdesktop.py > >>From main.py, I would like to do: > import ng > import yb > ng.setdesktop.run() > yb.setdesktop.run() > > But it is not working! when I import the package, the modules present > inside the package are getting imported. > > However, following the python document if I do > import ng.setdesktop > import yb.setdesktop > > ng.setdesktop.run() > yb.setdesktop.run() > Works fine. > > I would like to use the notation. > import > and use the modules inside the package in the dotted module notation. > What should I do the enable such a kind of imports. Put the line from . import setdesktop into both __init__.py files. Importing the package will then trigger the submodule to be imported. Peter From gagsl-py2 at yahoo.com.ar Sat Oct 20 18:34:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 20 Oct 2007 19:34:26 -0300 Subject: traceback over C API - still not working... References: Message-ID: En Sat, 20 Oct 2007 14:47:52 -0300, Sami Vaisanen escribi?: > This is becoming utterly painful process.... I found out that the return > value from "format_exception" function is NOT a list, i.e. PyList_Check() > fails. PySequence_Check() succeeds but then PySequence_List() gives me > back -1. So wtf? It seems very unlikely, since the traceback module is written in Python. It clearly returns a list. > py_ref fun(PyObject_GetAttrString(module.get(), > "format_exception")); > if (fun) > list = PyObject_CallFunctionObjArgs(type, value, trace, > NULL); Of course, you get a list if you actually call the function... -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Wed Oct 17 23:07:34 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 18 Oct 2007 03:07:34 -0000 Subject: if instance exists problem .. References: <1192662735.463554.165450@e9g2000prf.googlegroups.com> <13hdj38n7n3bv55@corp.supernews.com> Message-ID: <13hdjfmii2jc964@corp.supernews.com> On Thu, 18 Oct 2007 03:00:56 +0000, Steven D'Aprano wrote: > On Wed, 17 Oct 2007 23:12:15 +0000, Paul Hankin wrote: > >> 'if x' doesn't test if x exists, it tests if x when cast to a bool is >> True. > > To be pedantic: > > Python doesn't have type casts. bool(x) doesn't cast x as a bool, it > creates a brand new Boolean object from x. Actually, to be even more pedantic, True and False are both singletons, and so bool() doesn't actually create a new Boolean object but reuses the existing ones. -- Steven. From eu_my123 at hotmail.com Fri Oct 12 12:28:03 2007 From: eu_my123 at hotmail.com (TidyTrax@2) Date: Fri, 12 Oct 2007 09:28:03 -0700 Subject: Melhor Site de Downloads [ BIG SITE AND LINKS FASTED] Message-ID: <1192206483.312719.138660@z24g2000prh.googlegroups.com> www.forumgratiz.com.br www.forumgratiz.com.br www.forumgratiz.com.br Download de : Filmes Games XXX Programas Isso e muito ++ totalmente gratis http://www.forumgratiz.com.br/forumb/index.php?act=reg http://www.forumgratiz.com.br/forumb/index.php?act=reg http://www.forumgratiz.com.br/forumb/index.php?act=reg Somente Registrados Podem Ver os T?picos Por Favor Votem Tamb?m http://www.topinho.com/index.php?a=in&u=jeanmartins http://www.topinho.com/index.php?a=in&u=jeanmartins http://www.topinho.com/index.php?a=in&u=jeanmartins Pois o Site Sobrevive disso. .. From erik at myemma.com Fri Oct 26 00:04:49 2007 From: erik at myemma.com (Erik Jones) Date: Thu, 25 Oct 2007 23:04:49 -0500 Subject: OT Re: Parallel insert to postgresql with thread In-Reply-To: <13i2l4k42hvaccd@corp.supernews.com> References: <1193310044.750654.157320@22g2000hsm.googlegroups.com> <5obctcFm7sogU1@mid.uni-berlin.de> <13i12q276igp0df@corp.supernews.com> <13i2l4k42hvaccd@corp.supernews.com> Message-ID: If you're not Scott Daniels, beware that this conversation has gone horribly off topic and, unless you have an interest in PostreSQL, you may not want to bother reading on... On Oct 25, 2007, at 9:46 PM, Scott David Daniels wrote: > Erik Jones wrote: >> >> On Oct 25, 2007, at 7:28 AM, Scott David Daniels wrote: >>> Diez B. Roggisch wrote: >>>> Abandoned wrote: >>>>> Hi.. >>>>> I use the threading module for the fast operation. But .... >>> [in each thread] >>>>> def save(a,b,c): >>>>> cursor.execute("INSERT INTO ... >>>>> conn.commit() >>>>> cursor.execute(...) >>>>> How can i insert data to postgresql the same moment ?... >>>> >>>> DB modules aren't necessarily thread-safe. Most of the times, a >>>> connection (and ... cursor) can't be shared between threads. >>>> So open a connection for each thread. >>> >>> Note that your DB server will have to "serialize" your inserts, so >>> ... a single thread through a single connection to the DB is the way >>> to go. Of course it (the DB server) may be clever enough to behave >>> "as if" they are serialized, but most of your work parallelizing at >>> your end simply creates new work at the DB server end. >> >> Fortunately, in his case, that's not necessarily true.... If he >> goes the recommended route with a separate connection for each >> thread, >> then Postgres will not serialize multiple inserts coming from >> separate >> connections unless there is something like and ALTER TABLE or REINDEX >> concurrently happening on the table. >> The whole serialized inserts thing is strictly something popularized >> by MySQL and is by no means necessary or standard (as with a lot of >> MySQL). > > But he commits after every insert, which _does_ force serialization > (if > only to provide safe transaction boundaries). I understand you can > get > clever at how to do it, _but_ preserving ACID properties is exactly > what > I mean by "serialize," First, bad idea to work with your own definition of a very domain specific and standardized term. Especially when Postgres's Multi- Version Concurrency Control mechanisms are designed specifically for the purpose of preserve ACID compliance without forcing serialized transactions on the user. Second, unless he specifically sets his transaction level to serializable, he will be working in read-committed mode. What this specifically means is that two (or more) transactions writing to the same table will not block any of the others. Let's say the user has two concurrent inserts to run on the same table that, for whatever reason, take a while to run (for example, they insert the results of some horribly complex or inefficient select), if either is run in serializable mode then which ever one starts a fraction of a second sooner will run until completion before the second is even allowed to begin. In (the default) read-committed mode they will both begin executing as soon as they are called and will write their data regardless of conflicts. At commit time (which may be sometime later for transactions with multiple statements are used) is when conflicts are resolved. So, if between the two example transactions there does turn out to be a conflict betwen their results, whichever commits second will roll back and, since the data written by the second transaction will not be marked as committed, it will never be visible to any other transactions and the space will remain available for future transactions. Here's the relevant portion of the Postgres docs on all of this: http://www.postgresql.org/docs/8.2/interactive/mvcc.html > and while I like to bash MySQL as well as the > next person, I most certainly am not under the evil sway of the vile > MySQL cabal. Good to hear ;) > > The server will have to be able to abort each transaction > _independently_ of the others, and so must serialize any index > updates that share a page by, for example, landing in the same node > of a B-Tree. There is nothing inherent in B-Trees that prevents identical datum from being written in them. If there was the only they'd be good for would be unique indexes. Even if you do use a unique index, as noted above, constraints and conflicts are only enforced at commit time. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From google at mrabarnett.plus.com Sat Oct 13 14:42:41 2007 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 13 Oct 2007 11:42:41 -0700 Subject: raw_input() and utf-8 formatted chars In-Reply-To: <1192241386.568665.140500@y27g2000pre.googlegroups.com> References: <1192197233.824215.301890@e9g2000prf.googlegroups.com> <1192216685.923198.279040@v29g2000prd.googlegroups.com> <1192220315.602812.155810@z24g2000prh.googlegroups.com> <5na4jvFh28v6U2@mid.uni-berlin.de> <1192241386.568665.140500@y27g2000pre.googlegroups.com> Message-ID: <1192300961.736407.292260@q3g2000prf.googlegroups.com> On Oct 13, 3:09 am, 7stud wrote: > On Oct 12, 2:43 pm, Marc 'BlackJack' Rintsch wrote: > > > You mean literally!? Then of course I get A\xcc\x88 because that's what I > > entered. In string literals in source code the backslash has a special > > meaning but `raw_input()` does not "interpret" the input in any way. > > Then why don't I end up with the same situation as this: > > > >> > s = 'A\xcc\x88' #capital A with umlaut > > >> > print s #displays capital A with umlaut > > > And what is it that your keyboard enters to produce an 'a' with an umlaut? > > > *I* just hit the ? key. The one right next to the ? key. ;-) > > ...and what if you don't have an a-with-umlaut key? raw_input() returns the string exactly as you entered it. You can decode that into the actual UTF-8 string with decode("string_escape"): s = raw_input('Enter: ') #A\xcc\x88 s = s.decode("string_escape") It looks like your system already understands UTF-8 and will decode the UTF-8 string you print to the Unicode character. From bozonm at vscht.cz Wed Oct 10 06:32:25 2007 From: bozonm at vscht.cz (Michal Bozon) Date: Wed, 10 Oct 2007 12:32:25 +0200 Subject: struct.unpack less than 1 byte References: <1192010223.490715.205380@57g2000hsv.googlegroups.com> Message-ID: You are able to read single bits from file in C ? You'll have to read the bytes and than perform some bitwise operations on them to extract the bits > hello all, > > i need to read from a file a struct like this [1byte, 12bits, 12bits] > reading 1 byte or more is not a problem ... but the 12 bits values > are ... > > thanks From lasses_weil at klapptsowieso.net Wed Oct 3 16:27:53 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Wed, 03 Oct 2007 22:27:53 +0200 Subject: List of objects X Database In-Reply-To: References: <1191441678.264856.224900@19g2000hsx.googlegroups.com> Message-ID: <4703fb49$0$30375$9b4e6d93@newsspool4.arcor-online.net> Michael Bentley wrote: > > On Oct 3, 2007, at 1:01 PM, MindMaster32 wrote: > >> I am writing a script that has to read data from an ASCII file of >> about 50 Mb and do a lot of searches and calculations with that data. >> That would be a classic problem solved by the use of a database >> (SQLite would suit just fine), but that would require the user to >> install more packages other than python itself, and that I am trying >> to avoid. No it would not: (Well, its new in Python 2.5, but you didn't say you were restricted to some older version.) /W From bh at izb.knu.ac.kr Sat Oct 20 09:37:05 2007 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Sat, 20 Oct 2007 22:37:05 +0900 Subject: Elisp Tutorial: HTML Syntax Coloring Code Block In-Reply-To: <4719F4FB.7020508@holdenweb.com> References: <1192680926.420317.16630@v29g2000prd.googlegroups.com> <1192779973.14981.36.camel@viola.izb.knu.ac.kr> <4719F4FB.7020508@holdenweb.com> Message-ID: <1192887425.21842.3.camel@viola.izb.knu.ac.kr> Steve, On Sat, 2007-10-20 at 08:30 -0400, Steve Holden wrote: > Byung-Hee HWANG wrote: > [... whole article quoted ...] > > +1 ;; > > BTW, what is G2/1.0? Is that Emacs-like editor? > > > I can't tell you that, but I do know that someone who quotes a whole > lengthy article like that just to ask a simple question isn't being very > considerate of their readers. You're the only guy who has read the my comment. Thanks! -- Byung-Hee HWANG * ??????? InZealBomb, Kyungpook National University, KOREA "What I care about is that you obviously don't love me." -- Kay Adams, "Chapter 25", page 359 From danb_83 at yahoo.com Wed Oct 24 22:10:25 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 24 Oct 2007 19:10:25 -0700 Subject: delineating by comma where commas inside quotation marks don't count In-Reply-To: References: Message-ID: <1193278225.923337.217160@k35g2000prh.googlegroups.com> On Oct 24, 8:56 pm, "Junior" wrote: > I want to open a text file for reading and delineate it by comma. I also > want any data > surrounded by quotation marks that has a comma in it, not to count the > commas inside the > quotation marks Use the csv module. From deets at nospam.web.de Mon Oct 22 14:44:21 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 Oct 2007 20:44:21 +0200 Subject: Automatic Generation of Python Class Files In-Reply-To: <1193076352.576143.123260@z24g2000prh.googlegroups.com> References: <1193073156.493809.184110@z24g2000prh.googlegroups.com> <1193076352.576143.123260@z24g2000prh.googlegroups.com> Message-ID: <5o49cjFkqf0tU1@mid.uni-berlin.de> > You wrote: " can't think of a single reason why you would ever want to > do this, > since your "list of method and property names" would be just as > verbose as just typing the actual python code." > > I don't think I understand how this would be the same amount of > typing. Consider the following example that would generate a Monster > class file from an input text file (I only did one property and method > in generated class file.): > > Contents of input text file: > > [Name] > Fire Breathing Dragon > > [Properties] > Strength > Scariness > Endurance > > [Methods] > eatMaiden argMaiden > fightKnight argKnight Others have already given you reasons why that is a bad idea. Another one is this: how do you deal with changes to your generated classfile? It's complicated to ensure that you don't override modified code with generated. Diez From zachREMOVE at MEin.tu-clausthal.de Mon Oct 1 05:39:23 2007 From: zachREMOVE at MEin.tu-clausthal.de (Gabriel Zachmann) Date: Mon, 01 Oct 2007 11:39:23 +0200 Subject: Bug with lists of pairs of lists and append() In-Reply-To: <1191020974.172493.127040@w3g2000hsg.googlegroups.com> References: <1191020974.172493.127040@w3g2000hsg.googlegroups.com> Message-ID: > x = (list(l), list(r)) BTW: I prefer this syntax, because it makes the copy explicit, while l[:] seems to me more "implicit" ... Best regards, Gabriel. -- ______________________________________________________________ Life is so constructed that the event does not, cannot, will not match the expectation. (Charlotte Bronte) ______________________________________________________________ zach in.tu-clausthal.de __@/' www.gabrielzachmann.org ______________________________________________________________ From besturk at gmail.com Sat Oct 27 04:14:14 2007 From: besturk at gmail.com (Abandoned) Date: Sat, 27 Oct 2007 01:14:14 -0700 Subject: How can i do proxy in urllib.urlopen? Message-ID: <1193472854.889001.38550@o3g2000hsb.googlegroups.com> Hi i want to do proxy in urllib.urlopen how can i do this ? And which proxy type have i can prefer ? From deets at nospam.web.de Tue Oct 16 15:57:48 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 16 Oct 2007 21:57:48 +0200 Subject: best way of dealing with currency? In-Reply-To: References: Message-ID: <5nkje5Fi5e9cU1@mid.uni-berlin.de> Paul Miller schrieb: > I'm looking at doing some currency calculations in some Python code > integrated with a C++ application. I want to be able to come up with the > same values I get in an Excel spreadsheet. > > I've been poking around for a couple of days and haven't come across a > definitive method for dealing with currency in a precise manner. > > What do I need to do? Use rationals? Very high-precision floating-point? > mxNumber? Or something else? The module decimal. But in the end, you might not be able to recreate the same values as excel, due to the unknown intricacies of excel. Diez From paddy3118 at googlemail.com Wed Oct 17 02:29:30 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 17 Oct 2007 06:29:30 -0000 Subject: best way of dealing with currency? In-Reply-To: References: Message-ID: <1192602570.266090.309550@z24g2000prh.googlegroups.com> On Oct 16, 8:29 pm, Paul Miller wrote: > I'm looking at doing some currency calculations in some Python code > integrated with a C++ application. I want to be able to come up with the > same values I get in an Excel spreadsheet. Ouch! do really want to come up with the Excel result? Sometimes people have made expensive mistakes when doing financial calculations in Excel. Part of the problem is Excels calculation errors, and part is due to spreadsheets being inherently hard to review, and easy to silently change. I'd suggest you use Pythons decimal arithmetic module for precise calculations (i.e. to a precision that you specify), and don't blindly assume the source of any discrepancies but investigate them impartially. (Here's a link to some alarming statistics from a HM customs oficial: http://www.financeweek.co.uk/cgi-bin/item.cgi?id=5120&d=302&h=24&f=254 ). > I've been poking around for a couple of days and haven't come across a > definitive method for dealing with currency in a precise manner. > > What do I need to do? Use rationals? Very high-precision floating-point? > mxNumber? Or something else? > > Thanks for any and all input! From robert.kern at gmail.com Tue Oct 2 19:26:59 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Oct 2007 18:26:59 -0500 Subject: Using fractions instead of floats In-Reply-To: <1191360444.514028.186770@d55g2000hsg.googlegroups.com> References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> <1191206183.441075.167450@57g2000hsv.googlegroups.com> <1191284422.899591.308960@g4g2000hsf.googlegroups.com> <1191286998.727959.8010@50g2000hsm.googlegroups.com> <1191287823.018676.35640@o80g2000hse.googlegroups.com> <1191301175.225114.283340@50g2000hsm.googlegroups.com> <1191360444.514028.186770@d55g2000hsg.googlegroups.com> Message-ID: mensanator at aol.com wrote: > On Oct 2, 1:12 am, Robert Kern wrote: >> mensana... at aol.com wrote: >>> How does gmpy make the conversion from float to rational? >> gmpy has a configurable transformation between floats and the internal >> representation. I believe the default goes through str(). > > How do you do that? Is it configurable at run time or something that > has to be done when compiled? Run-time. Use gmpy.set_fcoform(). There is documentation: http://gmpy.googlecode.com/svn/trunk/doc/gmpydoc.txt However, it appears I was wrong about the default. The default will simply extract the C double and call mpf_set_d() on it to convert it to the appropriate internal mpf format. This faithfully gives: In [26]: gmpy.mpf(0.6) Out[26]: mpf('5.9999999999999998e-1') The real conversion to mpq rational numbers takes place in using gmpy.f2q(): In [28]: gmpy.f2q? Type: builtin_function_or_method Base Class: Namespace: Interactive Docstring: f2q(x[,err]): returns the 'best' mpq approximating x to within relative error err (default, x's precision); 'best' rationals as per Stern-Brocot tree; mpz if denom is 1. If err<0, error sought is 2.0 ** err. In [44]: d = gmpy.mpf(0.6) In [45]: d Out[45]: mpf('5.9999999999999998e-1') In [46]: d.getrprec() Out[46]: 53 In [47]: gmpy.f2q(d) Out[47]: mpq(3,5) In [48]: gmpy.f2q(d, -53) Out[48]: mpq(3,5) In [49]: gmpy.f2q(d, -54) Out[49]: mpq(3,5) In [50]: gmpy.f2q(d, -55) Out[50]: mpq(6002194384070353L,10003657306783922L) The procedure followed here finds mpq(3,5) because evaluating "3.0/5.0" in as binary floating point numbers in double precision gives you the same thing as evaluating "0.6". So mpq(3,5) is the most parsimonious rational number *approximating* Python's float("0.6") to within the default double-precision of binary floating point arithmetic. However, float("0.6") is a rational number that has the precise value of mpq(6002194384070353L,10003657306783922L). > But it is still wrong to say "0.6 is definitely not the same as 3/5". In the context in which it was said, I don't think it's wrong though it is incomplete and confusing if taken out of that context. > One can say 0.6 doesn't have an exact float representation and that > inexact representation is not the same as 3/5. And I suppose one can > be surprised that when this inexact representation is coerced to a > rational the result is now exact. > > Would that be a fairer way of putting it? Yes. -- 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 root at dev.nul.invalid Tue Oct 23 00:45:48 2007 From: root at dev.nul.invalid (Ohmster) Date: Tue, 23 Oct 2007 06:45:48 +0200 (CEST) Subject: Python - why don't this script work? References: Message-ID: John McMonagle wrote in news:mailman.354.1193108531.13605.python-list at python.org: > Your linux shell thinks it is running a shell script (from is not a > valid command in bash). > > To execute this script with the python interpreter type (from a shell > prompt): > > python image-harvester.py http://some.url.whatever/images_page > > Read the comments at the beginning of the script and you will discover > all sorts of important usage information. > > Regards, > > John Thanks John. -- ~Ohmster | ohmster /a/t/ ohmster dot com Put "messageforohmster" in message body (That is Message Body, not Subject!) to pass my spam filter. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Oct 10 13:27:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 10 Oct 2007 19:27:35 +0200 Subject: function wrappers In-Reply-To: <13gpi4454aajm59@corp.supernews.com> References: <13gpi4454aajm59@corp.supernews.com> Message-ID: <470d0b4f$0$32757$426a74cc@news.free.fr> Scott David Daniels a ?crit : > Ramon Crehuet wrote: >> def require_int(func): >> def wrapper(arg): >> assert isinstance(arg, int) >> return func(arg) >> return wrapper >> def p1(a): >> print a >> p2 = require_int(p1) >> >> My question is: why do p2 arguments become wrapper arguments? What is >> the flux of the arguments in the program when you pass functions as >> arguments? > I suspect you don't understand that each time require_int is called > a _new_ function named wrapper is created which remembers the 'environnement' in which it was defined - this is known as a 'closure'. > (and then returned). And when this wrapper function is called (instead of the original), it receives the arg, test it, and if approriate delegate call to the original (wrapped) function. Another way (perhaps easier to understand if you don't have any experience with higher order functions and other functional programming idioms) to get the same result would be: class require_int(object): def __init__(self, func): self._func = func def __call__(self, arg): assert isinstance(arg, int) return self._func(arg) From kw at codebykevin.com Tue Oct 2 09:22:13 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 02 Oct 2007 09:22:13 -0400 Subject: gui toolkits: the real story? (Tkinter, PyGTK, etc.) In-Reply-To: <1191287053.541506.88530@d55g2000hsg.googlegroups.com> References: <1191287053.541506.88530@d55g2000hsg.googlegroups.com> Message-ID: <47024605.9090407@codebykevin.com> bramble wrote: > > Maybe a better question is, how has Tk managed to keep beating up the > newer, more modern, more featureful, better documented toolkits > encroaching on his territory? What's Tk's secret weapon? > Wouldn't license compatability be an issue? Tk's license is BSD-style, which means it plays nice with both proprietary and open-source software (as does Python's license). Aren't PyGtk and wxPython LGPL? And PyQt is either GPL or proprietary. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From MrJean1 at gmail.com Sat Oct 27 21:17:23 2007 From: MrJean1 at gmail.com (MrJean1) Date: Sun, 28 Oct 2007 01:17:23 -0000 Subject: good example of C extension for Mac OS X In-Reply-To: <1193513492.210213.226900@y42g2000hsy.googlegroups.com> References: <1193497860.746202.111240@o38g2000hse.googlegroups.com> <1193511567.031547.245260@e34g2000pro.googlegroups.com> <1193513492.210213.226900@y42g2000hsy.googlegroups.com> Message-ID: <1193534243.638804.218720@q3g2000prf.googlegroups.com> You will need to download the MacOS X version from . It contains the source code. /Jean Brouwers On Oct 27, 12:31 pm, chewie54 wrote: > On Oct 27, 2:59 pm, MrJean1 wrote: > > > There is a C template in file Modules/xxmodule.c in Python 2.5, maybe > > earlier. > > > /Jean Brouwers > > > On Oct 27, 8:11 am, chewie54 wrote: > > > > Hi All, > > > > Does anyone now of a good example to use as template for a C program > > > extension that needs to be built on the Mac OS X. > > > > Thanks, > > I have looked at the docs on the python.org but specifically looking > for > examples showing how to deal with linked lists and more about when to > use > references Py_INCREF and Py_DECREF > > I didn't find Modules/xxmodule.c on my Mac OS X installation. > > Thanks again From aezell at gmail.com Tue Oct 9 14:13:16 2007 From: aezell at gmail.com (Alex Ezell) Date: Tue, 9 Oct 2007 13:13:16 -0500 Subject: SOAPpy and ArrayOfKeyValue Message-ID: <71dd7f400710091113xdc322d2y8e4e0a4b5788892e@mail.gmail.com> Can anyone offer any assistance as to how to convert a basic python dictionary, list, or even tuple into the SOAP type "ArrayOfKeyValue"? I am currently using SOAPpy, but would be willing to change to ZSI or something else if it made this conversion easier. I have tried with the arrayType and structType methods in SOAPpy.Types, yet they don't seem to do what I need. I suspect there might not be just a single method call, so, I wrote something like this: def dictToKeyValue(self, mydict): soap_list = [] for key,value in mydict.items(): inner = [] inner.append(SOAPpy.stringType(key,'key')) inner.append(SOAPpy.stringType(value,'value')) soap_list.append(SOAPpy.arrayType(inner)) print soap_list return SOAPpy.arrayType(soap_list) As you can see, it's pretty nasty and doesn't do what I need either. I have a client that was written in PHP which I am converting. It uses this function (which calls the PEAR SOAP library): function assocArrayToKeyValue($array) { $soap_array = array(); foreach($array as $key=>$value) { $inner = array(); $inner[] =& new SOAP_Value('key', 'string', $key); $inner[] =& new SOAP_Value('value', 'string', $value); $soap_array[] =& new SOAP_Value("item", "{{$this->wsdl_urn}}KeyValue", $inner); } return $soap_array; } Unfortunately, I don't really have a way to see exactly what $soap_array is so that I could emulate it in my Python code. Any pointers or suggestions are very much appreciated. /alex From pyth0nc0d3r at gmail.com Fri Oct 5 13:16:50 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 5 Oct 2007 11:16:50 -0600 Subject: TwistedMatrix missing OpenSSL? In-Reply-To: References: Message-ID: Where can I get it? Anyone got any idea? On 10/4/07, Lamonte Harris wrote: > > Where do I get it? I'm currently running python 2.5 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dteslenko at gmail.com Wed Oct 24 07:04:00 2007 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Wed, 24 Oct 2007 15:04:00 +0400 Subject: python 2.5 scripting in vim on windows: subprocess problem In-Reply-To: <20071022192638.GA30023@trite.hell> References: <91325fec0710220147i216df961u5f33d5c659cdb92f@mail.gmail.com> <91325fec0710220255h210f7271gd2490226e858fc75@mail.gmail.com> <471CBD17.8040601@gmx.de> <91325fec0710221148i57a700b7ufec2c05f7c9c957@mail.gmail.com> <20071022192638.GA30023@trite.hell> Message-ID: <91325fec0710240404g1eb52dc4yab2459bcfd310c69@mail.gmail.com> On 22/10/2007, Andy Kittner wrote: > >> Are you running this on vim or gvim? If you are running on gvim, my > >> guess is that the handles that you are passing are not valid. In > >> either case, try creating explicit handles that are valid (such as for > >> /dev/null) and create the process with these handles. > Just as a side note: my vim was a gvim-7.1.140 with dynamic python > support, so it doesn't look like a general problem. I've also tried *-1-140 from cream's sourceforge website and it works just like my custom-built one. > > I'm passing hadles that I get from subprocess.Popen. Just passing > > command to Popen constructor and using his handles to read data. No > > other handle-manipulations. > When exactly does it throw the exception? Directly on creation of the > Popen object, or when you try to read stdout? It throws exception on subprocess.Popen object instantiation. os.system() works fine but I want Popen functionality. From hniksic at xemacs.org Wed Oct 31 18:12:20 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 31 Oct 2007 23:12:20 +0100 Subject: 3 number and dot.. References: <1193860737.687984.13400@k79g2000hse.googlegroups.com> <1193862276.144648.43850@22g2000hsm.googlegroups.com> Message-ID: <87mytzhr23.fsf@mulj.homelinux.net> Paul McNett

writes: > Chris Mellon has given you the best response: use the locale module > for this. It may be the best choice as far as reuse is concerned, but it's not without serious drawbacks. For one, the locale model doesn't really allow forcing of the separators. Some locales, such as the "C" locale, define no thousand separators whatsoever. Since many Unix installations are set up to use the "C" locale because it is the OS default, this problem must be addressed. Chris addresse it by forcing the locale to "US", but that is a step away from the locale model because it consciously overrides the user's locale preferences. By doing that, one forces a particular way of grouping thousands, without the possibility to using a different grouping characters or to group by a different number of digits (some locales group by tens of thousands). That is quite similar to what you get when you implement the desired grouping yourself. Setting the locale makes the code platform-dependent because different platforms have different locale names. For example, Chris's code fails for me with "unsupported locale name" -- apparently, my system calls the US locale is "en_US.utf8". (Even specifying "en_US" doesn't work. It might be a Python or system problem, but it just doesn't work.). Finally, it makes the code OS-installation-dependent -- even under the same OS, different installs can and do set up different locales. If his number presentation calls for thousand separators, coding them manually is not an unreasonable implementation choice. > It seems like you are looking for a spoonfed solution rather than > looking for guidance on how to solve the problem for yourself. If > I'm wrong about that assessment, I apologize in advance. No argument here. From timr at probo.com Sun Oct 28 19:24:51 2007 From: timr at probo.com (Tim Roberts) Date: Sun, 28 Oct 2007 23:24:51 GMT Subject: Proposal: Decimal literals in Python. References: <4721ab28$0$1238$e4fe514c@dreader28.news.xs4all.nl><1193438763.190428.134710@q5g2000prf.googlegroups.com><87tzodii6i.fsf@benfinney.id.au><1193494184.618613.81090@50g2000hsm.googlegroups.com> <1193498867.815682.69050@v3g2000hsg.googlegroups.com> Message-ID: "Hendrik van Rooyen" wrote: >"Paul Hankin" wrote: > >> Even clearer is not to allow octal literals :) Is there *any* use for >> them? > >I tend to agree with this point of view - but I fear it will set up a howl >of protest amongst the Brits who cut their teeth on 24 bit ICT/ICL >equipment... As a long-time Control Data employee, I know that 60-bit words and 18-bit addresses meant that I could do octal arithmetic nearly as fast as decimal. On the other hand, Python doesn't run on the 6000s... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From freeaircon at gmail.com Tue Oct 2 13:19:26 2007 From: freeaircon at gmail.com (freeaircon at gmail.com) Date: Tue, 02 Oct 2007 17:19:26 -0000 Subject: Air Conditioners Message-ID: <1191345566.445612.323570@g4g2000hsf.googlegroups.com> http://freeaircon.blogspot.com/ From ggpolo at gmail.com Fri Oct 26 09:49:31 2007 From: ggpolo at gmail.com (Guilherme Polo) Date: Fri, 26 Oct 2007 11:49:31 -0200 Subject: .py to sqlite translator [1 of 2] In-Reply-To: <1193372359.928929.31310@19g2000hsx.googlegroups.com> References: <1193372359.928929.31310@19g2000hsx.googlegroups.com> Message-ID: 2007/10/26, smitty1e : > Disclaimer(s): the author is nobody's pythonista. This could probably > be done more elegantly. > The driver for the effort is to get PyMacs to work with new-style > classes. > This rendering stage stands alone, and might be used for other > purposes. > A subsequent post will show using the resulting file to produce (I > think valid) .el trampoline > signatures for PyMacs. > If nothing else, it shows some python internals in an interesting way. > Tested against version 2.5.1 > Maybe "lumberjack.py" would be a better name, since "It cuts down > trees, goes real slow, and uses disk galore. Wishes it'd been > webfoot[1], just like its dear author". > Cheers, > Chris > > [1] Author was born in Oregon. > > #A sample file: > class sample( object ): > """fairly trivial sample class for demonstration purposes. > """ > def __init__( self > , some_string ): > self.hold_it = some_string > > def show( self ): > print self.hold_it > > #Invocation: > # ./pysqlrender.py -f sample.py -o output > > #Script: > #!/usr/bin/python > > """Script to dump the parse tree of an input file to a SQLite > database. > """ > > from optparse import OptionParser > import os > import parser > import pprint > import re > import sqlite3 > import symbol > import token > import types > > from types import ListType \ > , TupleType > > target_table = """CREATE TABLE tbl_parse_tree ( > parse_tree_id INTEGER PRIMARY KEY > AUTOINCREMENT > , parse_tree_symbol_id > , parse_tree_indent > , parse_tree_value );""" > > target_insert = """INSERT INTO tbl_parse_tree ( > parse_tree_symbol_id > , parse_tree_indent > , parse_tree_value ) > VALUES (%s, %s, '%s' );""" > > symbol_table = """CREATE TABLE tlp_parse_tree_symbol ( > parse_tree_symbol_id INTEGER PRIMARY KEY > , parse_tree_symbol_val );""" > symbol_insert = """INSERT INTO tlp_parse_tree_symbol ( > parse_tree_symbol_id > , parse_tree_symbol_val ) > VALUES ( %s, '%s' );""" > > class symbol_manager( object ): > """ Class to merge symbols and tokens for ease of use. > """ > def __init__( self > , c ): > for k in symbol.sym_name: > sql = symbol_insert % ( k, symbol.sym_name[k] ) > try: > c.execute( sql ) > except sqlite3.IntegrityError: > pass > for k in token.tok_name: > sql = symbol_insert % ( k, token.tok_name[k] ) > try: > c.execute( sql ) > except sqlite3.IntegrityError: > pass > > def get_symbol( self > , key ): > ret = -1 > if symbol.sym_name.has_key(key): ret = symbol.sym_name[key] > elif token.tok_name.has_key(key) : ret = token.tok_name[ key] > return ret > > def recurse_it( self, tester ): > """Check to see if dump_tup should recurse > """ > if self.get_symbol(tester) > 0: > return True > return False > > class stocker( object ): > """Remembers the depth of the tree and effects the INSERTs > into the output file. > """ > def __init__( self ): > self.cur_indent = 0 > > def do_symbol( self > , c > , symbol_value > , val = "" ): > """Stuff something from the parse tree into the database > table. > """ > if symbol_value==5: self.cur_indent += 1 > elif symbol_value==6: self.cur_indent -= 1 > > try: > sql = target_insert \ > % ( symbol_value > , self.cur_indent > , re.sub( "'", "`", str(val) )) > c.execute( sql ) > except AttributeError: > print "connection bad in lexer" > except sqlite3.OperationalError: > print "suckage at indent of %s for %s" \ > % (self.cur_indent, sql) > > def dump_tup( tup > , sym > , c > , stok ): > """Recursive function to descend TUP and analyze its elements. > tup parse tree of a file, rendered as a tuple > sym dictionary rendered from symbol module > c live database cursor > stok output object effect token storage > """ > for node in tup: > typ = type( node ) > r = getattr( typ > , "__repr__" > , None ) > > if (issubclass(typ, tuple) and r is tuple.__repr__): > > if token.tok_name.has_key( node[0] ): > stok.do_symbol( c > , node[0] > , node[1] ) > elif sym.recurse_it( node[0] ): > stok.do_symbol( c > , node[0] > , '__py__' ) #If you say node[1] here, > # the sqlite file is fat > # and instructive > for node2 in node[1:]: > dump_tup( node2 > , sym > , c > , stok ) > else: > stok.do_symbol( c > , node[0] > , node[1] ) > dump_tup( node[1] > , sym > , c > , stok ) > else: > stok.do_symbol( c > , 0 > , node ) > > > def convert_python_source_tree_to_table( file_name > , target_name ): > """Retrieve information from the parse tree of a source file. > Create an output database file in sqlite. > Make a table in there, and then procede to stuff the flattened > input parse tree into it. > > file_name Name of the file to read Python source code from. > target_name Name for the sqlite database > """ > x = open( file_name ).readlines() > y = [] > [y.append( line.replace("\r\n","") ) for line in x] > > ast = parser.suite( "\n".join(y) ) > conn = sqlite3.connect( target_name ) > conn.isolation_level = None > c = conn.cursor() > c.execute( target_table ) > c.execute( symbol_table ) > sym = symbol_manager( c ) > stok = stocker() > > #pprint.pprint( ast.totuple() ) > dump_tup( ast.totuple() > , sym > , c > , stok ) > > def main(): > usage = "usage: %prog [options] arg" > parser = OptionParser(usage) > parser.add_option("-f", "--file", dest="filename" > , action="store", type="string" > , help ="read python source from FILENAME") > #TODO: test for existence of output file, eject if exists > parser.add_option("-o", "--output",dest="output" > , action="store", type="string" > , help ="name of sqlite output file") > (options, args) = parser.parse_args() > > convert_python_source_tree_to_table( options.filename > , options.output ) > > if __name__ == "__main__": > main() > > -- > http://mail.python.org/mailman/listinfo/python-list > Hello, I took a look at that script and I have made some changes. Before posting my version let me comment on somethings.. First, you probably noticed that it gets slow as you run the script with "larger" files. All the time "wasted" on this is because you set isolation level to None, so there are a lot of commits and commits make this slow. Removing that isolation level and doing only one commit after dump_tup cuts basically all time wasted; Second, don't use "%s" to insert values into your sql query string please. For sqlite you should substitute those by "?"s and pass a tuple to it; Third, don't use "yourdict.has_key(key)", use "key in yourdict". I have read the Disclamer at top, but maybe you wanted to hear something; Fourth, It could be the email client but did you use 3 spaces for indent ? :/ ; Fifth, other observations are left to the reader as exercise My version: #!/usr/bin/env python """Script to dump the parse tree of an input file to a SQLite database. """ import token import parser import symbol import sqlite3 from optparse import OptionParser TARGET_TABLE = """CREATE TABLE tbl_parse_tree ( parse_tree_id INTEGER PRIMARY KEY AUTOINCREMENT, parse_tree_symbol_id, parse_tree_indent, parse_tree_value)""" TARGET_INSERT = """INSERT INTO tbl_parse_tree (parse_tree_symbol_id, parse_tree_indent, parse_tree_value) VALUES (?, ?, ?)""" SYMBOL_TABLE = """CREATE TABLE tlp_parse_tree_symbol ( parse_tree_symbol_id INTEGER PRIMARY KEY, parse_tree_symbol_val)""" SYMBOL_INSERT = """INSERT INTO tlp_parse_tree_symbol (parse_tree_symbol_id, parse_tree_symbol_val) VALUES (?, ?)""" class SymbolManager(object): """Class to merge symbols and tokens for ease of use.""" def __init__(self, c): self.to_merge = token.tok_name.copy() self.to_merge.update(symbol.sym_name) for k, v in self.to_merge.iteritems(): c.execute(SYMBOL_INSERT, (k, v)) def get_symbol(self, key): return self.to_merge[key] if key in self.to_merge else -1 def recurse_it(self, tester): """Check to see if dump_tup should recurse""" if self.get_symbol(tester) > 0: return True return False class Stocker(object): """Remembers the depth of the tree and effects the INSERTs into the output file. """ def __init__(self): self.cur_indent = 0 def do_symbol(self, c, symbol_value, val=""): """Stuff something from the parse tree into the database table.""" if symbol_value == 5: self.cur_indent += 1 elif symbol_value==6: self.cur_indent -= 1 c.execute(TARGET_INSERT, (symbol_value, self.cur_indent, str(val).replace("'", "`"))) def dump_tup(tup, sym, c, stok): """Recursive function to descend TUP and analyze its elements. tup parse tree of a file, rendered as a tuple sym dictionary rendered from symbol module c live database cursor stok output object effect token storage """ for node in tup: typ = type(node) r = getattr(typ, "__repr__", None) if (issubclass(typ, tuple) and r is tuple.__repr__): if node[0] in token.tok_name: stok.do_symbol(c, node[0], node[1]) elif sym.recurse_it(node[0]): #If you say node[1] here, the sqlite file is fat # and instructive stok.do_symbol(c, node[0], '__py__' ) for node2 in node[1:]: dump_tup(node2, sym, c, stok) else: stok.do_symbol(c, node[0], node[1]) dump_tup(node[1], sym, c, stok) else: stok.do_symbol(c, 0, node) def python_source_tree_to_db(file_name, target_name): """Retrieve information from the parse tree of a source file. Create an output database file in sqlite. Make a table in there, and then procede to stuff the flattened input parse tree into it. file_name Name of the file to read Python source code from. target_name Name for the sqlite database """ conn = sqlite3.connect(target_name) c = conn.cursor() c.execute(TARGET_TABLE) c.execute(SYMBOL_TABLE) ast = parser.suite(''.join(open(file_name, 'rU').readlines())) sym = SymbolManager(c) stok = Stocker() #pprint.pprint(ast.totuple()) dump_tup(ast.totuple(), sym, c, stok) conn.commit() def main(): oparser = OptionParser("usage: %prog [options] arg") oparser.add_option("-f", "--file", dest="filename", help="read python source from FILENAME") oparser.add_option("-o", "--output", dest="output", help="name of sqlite output file") (options, _) = oparser.parse_args() if not options.filename or not options.output: oparser.print_help() else: try: open(options.output) print "Output file exists, chose another one." except IOError: python_source_tree_to_db(options.filename, options.output) if __name__ == "__main__": main() -- -- Guilherme H. Polo Goncalves From find at my.address.elsewhere Tue Oct 9 08:50:16 2007 From: find at my.address.elsewhere (Matthias Blume) Date: Tue, 09 Oct 2007 07:50:16 -0500 Subject: The fundamental concept of continuations References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> <470b1b30$0$11022$4c368faf@roadrunner.com> Message-ID: "." writes: > On Tue, 09 Oct 2007 05:15:49 +0000, gnuist006 wrote: > >> Again I am depressed to encounter a fundamentally new concept that I >> was all along unheard of. Its not even in paul graham's book where i >> learnt part of Lisp. Its in Marc Feeley's video. >> >> Can anyone explain: >> >> (1) its origin > One of the lambda papers, I think. I don't remember which. This is a common misconception. There is very little that originated from the "lambda" papers. But they did a marvelous job at promoting some of the ideas that existed in the PL community for years. As for the concept of continuations, there is Scott and Strachey's work on denotational semantics, and there is Landin's J operator. (There's probably more that I am forgetting right now.) >> (6) any good readable references that explain it lucidly ? > One of the most lucid explanations of definitional interpreters -- including those that are based on continuation-passing -- are explained in J. Reynolds' famous 1971 "Definitional Interpreters for Higher-Order Functions" paper. (It has been re-published in 1998 in HOSC.) The paper also explains how to perform defunctionalization, which can be seen as a way to compile (and even hand-compile) higher-order programs. Matthias From martin at marcher.name Mon Oct 29 07:46:06 2007 From: martin at marcher.name (Martin Marcher) Date: Mon, 29 Oct 2007 12:46:06 +0100 Subject: A class question In-Reply-To: <87ejfe457k.fsf@mulj.homelinux.net> References: <87ejfe457k.fsf@mulj.homelinux.net> Message-ID: <5fa6c12e0710290446u1505402ep48d9db3515bc09c3@mail.gmail.com> 2007/10/29, Hrvoje Niksic : > Sbe unpx inyhr, urer vf n cbffvoyr vzcyrzragngvba: > ... was that on purpose? martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From americanman67 at yahoo.com Wed Oct 24 23:10:36 2007 From: americanman67 at yahoo.com (Don Bro) Date: Thu, 25 Oct 2007 11:10:36 +0800 (CST) Subject: How to change IP Address by Python program on Win Platform Message-ID: <56184.27571.qm@web45510.mail.sp1.yahoo.com> is there software available to change or hide my ip add? __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bcd at pvv.ntnu.no Wed Oct 3 15:23:22 2007 From: bcd at pvv.ntnu.no (Bent C Dalager) Date: Wed, 3 Oct 2007 19:23:22 +0000 (UTC) Subject: The Modernization of Emacs: terminology buffer and keybinding References: <13frd6vtarbee75@corp.supernews.com> <85sl4sqckf.fsf@lola.goethe.zz> <85hcl8qaj7.fsf@lola.goethe.zz> Message-ID: In article <85hcl8qaj7.fsf at lola.goethe.zz>, David Kastrup wrote: >bcd at pvv.ntnu.no (Bent C Dalager) writes: > >> I have never claimed equivalence. What I have made claims about are >> the properties of one of the meanings of a word. Specifically, my >> claim is that "free" is a reasonable description of some one or some >> thing that has been "liberated". > >But it suggests that the natural state would be the unfree state. Would this be a good thing? Would it be a bad thing? What is your point? Cheers Bent D -- Bent Dalager - bcd at pvv.org - http://www.pvv.org/~bcd powered by emacs From bdesth.quelquechose at free.quelquepart.fr Wed Oct 3 09:02:45 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Oct 2007 15:02:45 +0200 Subject: [OT, definitively] Re: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <85ve9ov971.fsf@lola.goethe.zz> <47041303$0$13930$fa0fcedb@news.zen.co.uk> <8sn8g39v75hg114lf3m9m911ib2ajddaui@4ax.com> <4704fd8e$0$16099$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <47055042$0$18301$426a74cc@news.free.fr> J. Clifford Dyer a ?crit : > On Thu, Oct 04, 2007 at 04:49:50PM +0200, Wildemar Wildenburger wrote > regarding Re: The Modernization of Emacs: terminology buffer and > keybinding: > >> Steve Holden wrote: >>> Lawrence D'Oliveiro wrote: >>>> In message >>>> , Steve >>>> Holden wrote: >>>>> Lawrence D'Oliveiro wrote: >>>>>> In message <8sn8g39v75hg114lf3m9m911ib2ajddaui at 4ax.com>, >>>>>> George Neuner wrote: >>>>>>> The Christian Bible says "In the beginning was the >>>>>>> Word..." >>>>>> >>>>>> Which is an English mistranslation from the Greek "logos". >>>>> (snip) > > Yeah, different book. "In the beginning was the Word" is John's > cosmology. Written in Greek long after Genesis, and a couple decades > after Jesus was executed. > > Also, I wouldn't so much say that "word" is a mistranslation. Logos > does indeed mean "word" in common usage, it just also carries along > the baggage of reason, "logic" (for a loose definintion of which), > rationality, and so forth. So it's not so much inaccurate as > inadequate. FWIW, the canonical french translation uses 'verb' instead of 'word', and AFAICT it's more appropriate (at least in French - my English is mostly technical so I may miss some subtilities here) since it carries a notion of action too. Now another (and certainly far worse) mistranslation (for both John and Genesis) is this awful 'in the beginning was', when the less imperfect translation from Hebrew (which John's text, while written in Greek, is clearly referencing here) would be 'in the principle is'. See, nothing historic here, it's *not* the 'beginnning' of something past, it's about the present. Also, since Christ is clearly identified with the Verb by John, saying 'in the principle is the verb' is also a way of identifying God with the principle... Hem... Sorry, I disgressed... Back to Python, now !-) From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Oct 29 05:16:43 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 29 Oct 2007 10:16:43 +0100 Subject: A class question In-Reply-To: References: Message-ID: <4725a4fa$0$6568$426a74cc@news.free.fr> Donn Ingle a ?crit : > Hello, > > Is there a way I can, for debugging, access the instance variable name from > within a class? > E.g: > Class X: > def debug(self): > print "My instance var is %s" % (some magic Python stuff) > > So that: >>>> x = X() >>>> x.debug() >>>> My Instance var is x > > ( Without passing the name in like: x=X(name="x") ) What should be the "variable name" in the following situations ? a = b = c = X() X().debug() From lasses_weil at klapptsowieso.net Sun Oct 14 12:34:35 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 14 Oct 2007 18:34:35 +0200 Subject: GLE-like python package In-Reply-To: <1192378346.740393.30680@e34g2000pro.googlegroups.com> References: <47123bc8$0$4530$9b4e6d93@newsspool3.arcor-online.net> <1192378346.740393.30680@e34g2000pro.googlegroups.com> Message-ID: <4712451c$0$16115$9b4e6d93@newsspool1.arcor-online.net> Cesar G. Miguel wrote: > I think this is what you're looking for: > > http://pyx.sourceforge.net/ > It damn sure is (a straight ripoff of GLE ;))! The syntax seems a bit messier than GLE (naturally) but since it is python I'm willing to bite that bullet. Thanks :) /W From praddyjindal at gmail.com Wed Oct 31 05:27:10 2007 From: praddyjindal at gmail.com (praddy) Date: Wed, 31 Oct 2007 09:27:10 -0000 Subject: object inheritance In-Reply-To: <1193801186.600457.5660@t8g2000prg.googlegroups.com> References: <1193396171.753884.139930@e9g2000prf.googlegroups.com> <1193403117.710320.44140@e9g2000prf.googlegroups.com> <1193801186.600457.5660@t8g2000prg.googlegroups.com> Message-ID: <1193822830.710322.45860@o38g2000hse.googlegroups.com> On Oct 31, 8:26 am, Anand wrote: > On Oct 28, 1:16 am, Pradeep Jindal wrote: > > > > > On Friday 26 Oct 2007 6:21:57 pm Anand wrote: > > > > On Oct 26, 5:31 pm, "Pradeep Jindal" wrote: > > > > Can you tell any specific use case for doing this? > > > > I have many implementaions of a db interface. > > > > SimpleDB - simple implementation > > > BetterDB - optimized implementation > > > CachedDB - an implementation with caching of queries > > > RestrictedDB - implementation with permissions > > > > Now, I want to combine these implementations and use. > > > Typical use case scenarios are: > > > > db = RestrictedDB(CachedDB(SimpleDB())) > > > db = RestrictedDB(SimpleDB()) > > > db = RestrictedDB(BetterDB()) > > > db = RestrictedDB(CachedDB(BetterDB()) > > > db = CachedDB(SimpleDB()) > > > etc.. > > > I agree with Duncan. According to me, this should be called Delegation rather > > than inheritance. And delegation should work without any conflicts of > > identifier names and all that. I think, it should be all about several > > objects implementing a protocol (interface) and that should work cleanly. > > I don't think so. It is not as simple as delegation. > > In the example that I gave previously, call to self.say in A.foo > calls B.say not A.say, which I think is not possible with delegation. Let me explain what I meant, its all about several objects (e.g. "a") implementing a protocol, in your case the "say" method, and some object (e.g. "b") extending those objects by adding some more functionality but requiring that those objects, that it extends from, follow a specific protocol ("a" must have say method). Also note that, "B" or "b" is partial implementation of what its meant for, I mean, calling "b"'s "say" will not work if "b" has not yet extended from "a" or any other object implementing the same protocol. Less time, can't get into more details. Bye for now. Thanks -Pradeep From lasses_weil at klapptsowieso.net Mon Oct 8 05:33:06 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 08 Oct 2007 11:33:06 +0200 Subject: Top Programming Languages of 2013 In-Reply-To: <0vgjg3t1ki05lsgigio0csdjnacgri8mlq@4ax.com> References: <1191772154.784564.138370@r29g2000hsg.googlegroups.com> <47090141$0$4522$9b4e6d93@newsspool3.arcor-online.net> <0vgjg3t1ki05lsgigio0csdjnacgri8mlq@4ax.com> Message-ID: <4709f952$0$7685$9b4e6d93@newsspool2.arcor-online.net> Tim Roberts wrote: > Wildemar Wildenburger wrote: >> import friends >> import sex >> >> try: >> sex.have() >> except ErrectionError, PrematureError: >> pass >> finally: >> sex.brag(friends) > > Well, if "ErrectionError" ever becomes a real exception, I certainly get a > boatload of email every day from people offering to help me deal with it. Yeah, because they'va actually spell-checked it. ;) From afaNOSPAM at neuf.fr Thu Oct 4 17:28:44 2007 From: afaNOSPAM at neuf.fr (Amaury Forgeot d'Arc) Date: Thu, 04 Oct 2007 23:28:44 +0200 Subject: Is there a nicer way to do this? In-Reply-To: <87ejgawpug.fsf@keizer.soze.com> References: <87ejgawpug.fsf@keizer.soze.com> Message-ID: Hello, Stefan Arentz a ?crit : > Is there a better way to do the following? > > attributes = ['foo', 'bar'] > > attributeNames = {} > n = 1 > for attribute in attributes: > attributeNames["AttributeName.%d" % n] = attribute > n = n + 1 > > It works, but I am wondering if there is a more pythonic way to > do this. > > S. You could use enumerate() to number the items (careful it starts with 0): attributes = ['foo', 'bar'] attributeNames = {} for n, attribute in enumerate(attributes): attributeNames["AttributeName.%d" % (n+1)] = attribute Then use a generator expression to feed the dict: attributes = ['foo', 'bar'] attributeNames = dict(("AttributeName.%d" % (n+1), attribute) for n, attribute in enumerate(attributes)) Hope this helps, -- Amaury From kadeko at gmail.com Wed Oct 31 08:48:18 2007 From: kadeko at gmail.com (looping) Date: Wed, 31 Oct 2007 05:48:18 -0700 Subject: Creating a temporary file in Python In-Reply-To: <5ora0aFo7tsmU1@mid.uni-berlin.de> References: <1193832119.872710.108920@k79g2000hse.googlegroups.com> <5ora0aFo7tsmU1@mid.uni-berlin.de> Message-ID: <1193834898.945261.171310@z9g2000hsf.googlegroups.com> On Oct 31, 2:16 pm, "Diez B. Roggisch" wrote: > I'm not an expert, but I think you need to close the file first - you under > windows here, which can be picky about such stuff AFAIK. Or maybe there is > some other mode-specifier. > > Diez Actually closing the file delete it without any chance to use it... Well I changed my code this way: filename = tempfile.mktemp(suffix='.sql') f = open(filename, 'wb') try: f.write(txt.encode('cp1252')) f.close() p = Popen([SQL_PLUS, '-s', dsn, '@', SQL_PLUS_SCRIPT, f.name], stdout=PIPE, stderr=STDOUT) p.wait() finally: os.remove(filename) I understand the security issues of temporary file (as explained in Python doc) but maybe standard lib need a NamedTemporaryFile that could be used by another process. From mrstephengross at hotmail.com Tue Oct 23 14:54:06 2007 From: mrstephengross at hotmail.com (mrstephengross) Date: Tue, 23 Oct 2007 18:54:06 -0000 Subject: Can't refer to base class attribute? Message-ID: <1193165646.296297.152000@y27g2000pre.googlegroups.com> I've got a Base class with an attribute "foo" (of type Foo), and a Derived class (derived from Base). In Derived's constructor, I try to refer to Base.foo, but python complains: AttributeError: class Base has no attribute 'foo' Any ideas? (code below) === CODE === #!/usr/bin/python class Foo: def __init__ (self): self.x = 3 class Base: def __init__ (self): self.foo = Foo() class Derived(Base): def __init__(self): Base.__init__(self) Base.foo.x = 5 Derived() === EOF === From kay.schluehr at gmx.net Fri Oct 5 06:19:44 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 05 Oct 2007 03:19:44 -0700 Subject: unit testing In-Reply-To: <47054a3d$0$16347$426a74cc@news.free.fr> References: <7xlkaifz4o.fsf@ruckus.brouhaha.com> <47054a3d$0$16347$426a74cc@news.free.fr> Message-ID: <1191579584.051683.92950@o3g2000hsb.googlegroups.com> On Oct 3, 2:37 pm, Bruno Desthuilliers wrote: > Paul Rubin a ?crit : > > > brad writes: > > >>Does anyone else feel that unittesting is too much work? Not in > >>general, just the official unittest module for small to medium sized > >>projects? > > > Yeah, unittest is sort of a Java-ism. You might try the newer doctest > > module instead. > > Or py.test or nose, which are both more complete than doctest and more > pythonics than the unittest module. But you need to distribute testframeworks, when you just want to distribute tests. From jcd at sdf.lonestar.org Tue Oct 2 08:49:01 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Tue, 2 Oct 2007 08:49:01 -0400 Subject: problem with special built-in method __contains__, In-Reply-To: <1191323678.609701.258550@y42g2000hsy.googlegroups.com> References: <1191323678.609701.258550@y42g2000hsy.googlegroups.com> Message-ID: <20071002124901.GA9320@sdf.lonestar.org> On Tue, Oct 02, 2007 at 11:14:38AM -0000, eboy98 at gmail.com wrote regarding problem with special built-in method __contains__,: > > if i have a dictionary name number ....and i want to ask the list > whether a particular key already > exists. > > >>> print number > {'octal': '1234567', 'binary': '10100101', 'decimal': '1234567890', > 'hexadecimal': '1-9,a-f'} > > i got error..after execute > > >>>number._contains_("test") > > Traceback (most recent call last): > File "", line 1, in > number._contains_("test") > AttributeError: 'dict' object has no attribute '_contains_' > First of all, the special methods contain a *double* underscore before and after the name, so it's not _contains_, it's __contains__. Secondly, for most basic operations, you shouldn't have to use these special methods directly. They are bound to other funtionality in Python. So instead of: number.__contains('test') try the following: 'test' in number Cheers, Cliff From hniksic at xemacs.org Thu Oct 4 02:33:39 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 04 Oct 2007 08:33:39 +0200 Subject: migrating to packages References: <4703C661.50009@fmed.uba.ar> <27E2B61D-3D3E-466D-9650-69E0DA27E952@myemma.com> Message-ID: <87hcl7jsn0.fsf@mulj.homelinux.net> gherzig at fmed.uba.ar writes: > I will expose my case quicly. > The MYCLASES.py file contains the A class, so i can use > from MYCLASES import A > a = () > > Using the "package mode" (wich looks fine BTW), having the simple > MYCLASES/ > __init__.py > A.py > > forces my (i guess) to use the > from MYCLASES.A import A Exactly. Using mypackage.mymodule instead of just mymodule is the entire *point* of a package. That way, if someone creates another module with using the same name (mymodule), it won't conflict with yours. If you don't want to change mymodule to mypackage.mymodule, why use a package in the first place? From larry.bates at websafe.com Thu Oct 11 15:00:54 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 11 Oct 2007 14:00:54 -0500 Subject: problem with wxPanel derivation class In-Reply-To: References: Message-ID: none wrote: > wxGlade created a simple Frame with a panel a sizer and 3 wxControls , > saticText, TextCtrl, and a Button. > > The resulting code works fine. > > Now the problem. > I wish to make a separate class derrived from wxPanel that has the sized > and controls as above. It jusst won't work > > > > #!/usr/bin/env python > # -*- coding: ISO-8859-1 -*- > # generated by wxGlade 0.4cvs on Thu Oct 11 13:26:19 2007 > > import wx > > class MyFrameOne(wx.Frame): > def __init__(self, *args, **kwds): > # begin wxGlade: MyFrameOne.__init__ > kwds["style"] = wx.DEFAULT_FRAME_STYLE > wx.Frame.__init__(self, *args, **kwds) > self.panel = wx.Panel(self, -1) > self.staticbox = wx.StaticBox(self.panel, -1, "StaticBox") > self.label = wx.StaticText(self.panel, -1, "Field Name") > self.textBox = wx.TextCtrl(self.panel, -1, "Field Value") > self.button = wx.Button(self.panel, -1, "Edit") > > self.__set_properties() > self.__do_layout() > # end wxGlade > > def __set_properties(self): > # begin wxGlade: MyFrameOne.__set_properties > self.SetTitle("frame_1") > self.label.SetMinSize((-1, 15)) > # end wxGlade > > def __do_layout(self): > # begin wxGlade: MyFrameOne.__do_layout > sizer_1 = wx.BoxSizer(wx.VERTICAL) > sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL) > sizer.Add(self.label, 0, wx.ALL, 3) > sizer.Add(self.textBox, 0, wx.ALL, 3) > sizer.Add(self.button, 0, wx.ALL, 3) > self.panel.SetAutoLayout(True) > self.panel.SetSizer(sizer) > sizer.Fit(self.panel) > sizer.SetSizeHints(self.panel) > sizer_1.Add(self.panel, 1, wx.EXPAND, 0) > self.SetAutoLayout(True) > self.SetSizer(sizer_1) > sizer_1.Fit(self) > sizer_1.SetSizeHints(self) > self.Layout() > # end wxGlade > > # end of class MyFrameOne > > ## modified from BoaApp > class App(wx.App): > def OnInit(self): > wx.InitAllImageHandlers() > self.main = MyFrameOne(None) > self.main.Show() > self.SetTopWindow(self.main) > return True > > def main(): > application = App(0) > application.MainLoop() > > if __name__ == '__main__': > main() > > > > > #!/usr/bin/env python > # -*- coding: ISO-8859-1 -*- > #The commented out code from MyFrame was moved to class Panel \ > # and appropriately modified by changing self.panel to self etc > > import wx > > class MyFrameTwo(wx.Frame): > def __init__(self, *args, **kwds): > # begin wxGlade: MyFrameTwo.__init__ > kwds["style"] = wx.DEFAULT_FRAME_STYLE > wx.Frame.__init__(self, *args, **kwds) > ## self.panel = panel(self, -1) > self.panel = Panel(self, -1) > self.__set_properties() > self.__do_layout() > # end wxGlade > > def __set_properties(self): > # begin wxGlade: MyFrameTwo.__set_properties > self.SetTitle("frame_1") > self.label.SetMinSize((-1, 15)) > # end wxGlade > > def __do_layout(self): > # begin wxGlade: MyFrameTwo.__do_layout > sizer_1 = wx.BoxSizer(wx.VERTICAL) > ## sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL) > ## sizer.Add(self.label, 0, wx.ALL, 3) > ## sizer.Add(self.textBox, 0, wx.ALL, 3) > ## sizer.Add(self.button, 0, wx.ALL, 3) > #### self.panel.SetAutoLayout(True) > ## self.panel.SetSizer(sizer) > ## sizer.Fit(self.panel) > ## sizer.SetSizeHints(self.panel) > sizer_1.Add(self.panel, 1, wx.EXPAND, 0) > self.SetAutoLayout(True) > self.SetSizer(sizer_1) > sizer_1.Fit(self) > sizer_1.SetSizeHints(self) > self.Layout() > # end wxGlade > > # end of class MyFrameTwo > > > class Panel (wx.Panel): > def __init__(self, *args, **kwds): > self.staticbox = wx.StaticBox(self, -1, "StaticBox") > self.label = wx.StaticText(self, -1, "Field Name") > self.textBox = wx.TextCtrl(self, -1, "Field Value") > self.button = wx.Button(self, -1, "Edit") > __doLayout() > > def __doLayout(): > sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL) > sizer.Add(self.label, 0, wx.ALL, 3) > sizer.Add(self.textBox, 0, wx.ALL, 3) > sizer.Add(self.button, 0, wx.ALL, 3) > > # maybe comment this and uncommennt frame2's corresponding line > panel.SetAutoLayout(True) > > self.SetSizer(sizer) > sizer.Fit(self.panel) > sizer.SetSizeHints(self.panel) > > > ## modified from BoaApp > class App(wx.App): > def OnInit(self): > wx.InitAllImageHandlers() > self.main = MyFrameTwo(None) > self.main.Show() > self.SetTopWindow(self.main) > return True > > def main(): > application = App(0) > application.MainLoop() > > if __name__ == '__main__': > main() > > > > > /home/xaos/xpy/cnc/i2g/prefDialog/test/frame2.py > Traceback (most recent call last): > File "/home/xaos/xpy/cnc/i2g/prefDialog/test/frame2.py", line 82, in ? > main() > File "~/xpy/cnc/i2g/prefDialog/test/frame2.py", line 78, in main > application = App(0) > File > "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_core.py", line > 7473, in __init__ > self._BootstrapApp() > File > "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_core.py", line > 7125, in _BootstrapApp > return _core_.PyApp__BootstrapApp(*args, **kwargs) > File "~/xpy/cnc/i2g/prefDialog/test/frame2.py", line 72, in OnInit > self.main = MyFrameTwo(None) > File "~/xpy/cnc/i2g/prefDialog/test/frame2.py", line 13, in __init__ > self.panel = Panel(self, -1) > File "~/xpy/cnc/i2g/prefDialog/test/frame2.py", line 48, in __init__ > self.staticbox = wx.StaticBox(self, -1, "StaticBox") > File > "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_controls.py", > line 990, in __init__ > newobj = _controls_.new_StaticBox(*args, **kwargs) > TypeError: argument number 1: a 'wxWindow *' is expected, 'Panel' is > received > Script terminated. > > > > > It seems as though the complaint is that a 'wxWindow *' is expected, > 'Panel' is received > However, Panel IS a wx.Panel derivative which IS a wx.Window derivative! > Additionally, the methods in the code of Panel and MyFrameOne seem to be > identical. > I can't understand this. Anyone have any thoughts? > > I'm using spe as an IDE > > ~S~ > > I taught myself everything I know about Python and wxPython in the lasst > week and I still don't know everything. > > You will probably get better results if you post this to gmane.com.python.wxpython list as it is specific to wxPython. -Larry From rdm at rcblue.com Mon Oct 29 13:39:49 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 29 Oct 2007 10:39:49 -0700 Subject: Using msvcrt (in Windows), how to catch Enter key? In-Reply-To: <20071029165317.7009D1E4012@bag.python.org> References: <1193657385.878620.35180@d55g2000hsg.googlegroups.com> <1193675164.790618.194190@57g2000hsv.googlegroups.com> <20071029165317.7009D1E4012@bag.python.org> Message-ID: <20071029174011.D22641E4029@bag.python.org> At 09:53 AM 10/29/2007, Dick Moores wrote: >At 09:26 AM 10/29/2007, Gabriel Genellina wrote: > >On 29 oct, 09:23, Dick Moores wrote: > > > > > >while True: > > > > if msvcrt.getch() == '\r': > > > > > > I tried it and find that without the msvcrt.kbhit the first key I hit > > > doesn't do anything. I have to hit that key again, or another key. > > > >I'd say there is a logic error in your program then; keys don't "do > >anything" by themselves. > >Try posting a small sample, telling what you get and what you expect. > >Huh. Works now. > >import msvcrt >while True: > key = msvcrt.getch() > if key == 'h': > print 'Hello' > if key == 'b': > print 'Bye' > if key == '\r': # 'Enter' key > break > >Dick But here's a case where it seems I do need the if msvcrt.kbhit() line ========================= #!/usr/bin/env python #coding=utf-8 import time import msvcrt timeNow = time.time() oldTimeNow = timeNow while True: if msvcrt.kbhit(): key = msvcrt.getch() if key == 'h': print 'Hello' if key == 'b': print 'Bye' if key == '\r': # Enter key break timeNow = time.time() if timeNow - oldTimeNow > 5: print "5 seconds passed" oldTimeNow = timeNow ========================== Without that line: ========================== #!/usr/bin/env python #coding=utf-8 import time import msvcrt timeNow = time.time() oldTimeNow = timeNow while True: #if msvcrt.kbhit(): key = msvcrt.getch() if key == 'h': print 'Hello' if key == 'b': print 'Bye' if key == '\r': # Enter key break timeNow = time.time() if timeNow - oldTimeNow > 5: print "5 seconds passed" oldTimeNow = timeNow ============================ Without that line the "5 seconds passed" report is printed ONLY after a "b" or an "h", not what I want. Dick From Scott.Daniels at Acm.Org Sat Oct 20 10:23:55 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 20 Oct 2007 07:23:55 -0700 Subject: where do I need to "tab"? In-Reply-To: References: <1192845611.102983.310980@i38g2000prf.googlegroups.com> <13hipiq5fafqn8d@corp.supernews.com> Message-ID: <13hk3nmdg60fc50@corp.supernews.com> Gabriel Genellina wrote: > En Fri, 19 Oct 2007 23:24:30 -0300, Scott David Daniels > ... >> OK, you have a mix of Python 3,0 and current (2.5.1) Python. > > All examples are OK for 2.5 You are absolutely correct. Sorry for the misinformation. I've been working on 2.3, 2.4, 2.5, and trying 3.0 alphas and had shoved the (a if b else c) expression to the wrong group mentally. I try to stay working in the subset that exists or can be hand-implemented, so I avoid the 2.5 code so often that I forgot it was ther. -Scott David Daniels Scott.Daniels at Acm.Org From ahanwadi at comcast.net Wed Oct 10 11:55:52 2007 From: ahanwadi at comcast.net (Ashish Hanwadikar) Date: Wed, 10 Oct 2007 08:55:52 -0700 Subject: why did MIT drop scheme for python in intro to computing? In-Reply-To: <13glvegpugvbb19@corp.supernews.com> References: <1191432204.361780.129850@d55g2000hsg.googlegroups.com> <1191863837.105036.45510@22g2000hsm.googlegroups.com> <1191900533.823209.252590@o3g2000hsb.googlegroups.com> <13glvegpugvbb19@corp.supernews.com> Message-ID: "Grant Edwards" wrote in message news:13glvegpugvbb19 at corp.supernews.com... > On 2007-10-09, gnuist006 at hotmail.com wrote: > >> Does scheme have a gui library? > > Yes. It had a far, far better Tk binding than Python. > > http://kaolin.unice.fr/STk/ > > I've used both for real-world applications, and STk was _miles_ > ahead of tkinter. It was a real, native binding to the Tk > library rather than something stuck together with TCL. GUI > widgets were real Scheme objects that acted the way one > expected them to, rather than wrapped TCL objects. > > However, Tk has been largely abandoned in favor of a native > GTK+ binding > > http://www.stklos.org/ > > -- > Grant Edwards grante Yow! You should all > JUMP > at UP AND DOWN for TWO > HOURS > visi.com while I decide on a NEW > CAREER!! I couldn't find any documentation on stklos (other than a few examples) regarding its gtk+ binding. Could you please point me to appropriate link? thanks in advance, Ashish K Hanwadikar http://ashish.typepad.com/ From sunburned.surveyor at gmail.com Mon Oct 22 14:05:52 2007 From: sunburned.surveyor at gmail.com (Sunburned Surveyor) Date: Mon, 22 Oct 2007 11:05:52 -0700 Subject: Automatic Generation of Python Class Files In-Reply-To: References: <1193073156.493809.184110@z24g2000prh.googlegroups.com> Message-ID: <1193076352.576143.123260@z24g2000prh.googlegroups.com> On Oct 22, 10:26 am, "Chris Mellon" wrote: > On 10/22/07, Sunburned Surveyor wrote: > > > > > > > I was thinking of a way I could make writing Python Class Files a > > little less painful. I was considering a Ptyhon script that read a > > file with a list of property names and method names and then generated > > a skeleton class file. > > > I was even thinking of automatically generating the shell for doc > > strings and epydoc tags. > > > Is there existing scripts that do something like this? If not, I will > > try to come up with something. If I'm sucessful I'll release the code > > under the GPL and will report back to the list. > > > However, I thought I would check here first so that I don't reinvent > > the wheel. > > > Thanks, > > > Scott Huey > > I can't think of a single reason why you would ever want to do this, > since your "list of method and property names" would be just as > verbose as just typing the actual python code. > > Auto generated documentation stubs are considered harmful because they > take the place of real documentation.- Hide quoted text - > > - Show quoted text - Chris, You wrote: " can't think of a single reason why you would ever want to do this, since your "list of method and property names" would be just as verbose as just typing the actual python code." I don't think I understand how this would be the same amount of typing. Consider the following example that would generate a Monster class file from an input text file (I only did one property and method in generated class file.): Contents of input text file: [Name] Fire Breathing Dragon [Properties] Strength Scariness Endurance [Methods] eatMaiden argMaiden fightKnight argKnight Generated Python Class File: def class FireBreathingDragon: def getStrength(self): """ Docstring goes here. @return @rtype """ return self.strength def setStrength(self, argStrength): """ Docstring goes here. @param argStrength @ptype """ return self.strength def eatMaiden(self, argMaiden): """ Docstring goes here. @param argMaiden @ptype """ From dannox at gmail.com Sun Oct 7 12:54:24 2007 From: dannox at gmail.com (whatazor) Date: Sun, 07 Oct 2007 16:54:24 -0000 Subject: newbie swig c++ to python In-Reply-To: <1191774922.015497.265680@57g2000hsv.googlegroups.com> References: <1191774922.015497.265680@57g2000hsv.googlegroups.com> Message-ID: <1191776064.303325.32090@d55g2000hsg.googlegroups.com> Now it works, the problem was in the project configuration of the example, that put the directory in Addictional Dependencies while it must be in Addictional Library Directories bye w n 7 Ott, 18:35, whatazor wrote: > Hi all, > I must wrap some c++ code in python with swig. I try the swig examples > for VC++ , but when I build the project > it gives me that error: > example fatal error LNK1181: cannot open input file 'C:\Programmi > \Python25\libs.obj' > > Any idea? > > thank you > > w From paddy3118 at googlemail.com Wed Oct 31 11:41:32 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 31 Oct 2007 15:41:32 -0000 Subject: why did these companies choose Tcl over Python In-Reply-To: <4727B465.1070600@v.loewis.de> References: <1193779506.643321.216030@z9g2000hsf.googlegroups.com> <4727B465.1070600@v.loewis.de> Message-ID: <1193845292.245611.164830@22g2000hsm.googlegroups.com> On Oct 30, 10:47 pm, "Martin v. L?wis" wrote: > > I would prefer to use Python but can't deny how popular Tcl is, as > > mentioned above, so my question is why wasn't Python selected by > > these companies as the choice of scripting languages for their > > product? > > I think this question needs to be answered on a case-by-case basis, > but my guess is that it is in most cases historical. Work on Tcl > started in 1988, and it was the first (major?) embeddable scripting > language (that is also free software etc). Python wasn't released > until 1991, and wasn't first recognized as being just as easily > embeddable (and I think early releases weren't as easily embeddable > as today's Python is). > > Tcl's original objective was to support circuit design, so people > in that field clearly knew that Tcl worked, but they were likely > unaware of any alternatives (or else the future of these alternatives > may have been uncertain). > > So at that time, Tcl would have been the obvious (because only) > choice. Now these products are stuck with Tcl, and redoing all > the work (including the existing extension modules!) in a different > programming language would be a lot of work. > > Regards, > Martin Here is TCL's author talking about its roots: http://www.tcl.tk/about/history.html The Electronic Design Automation industry was in some ways ahead of other industries in adopting TCL as its major scripting language but because of this I think it might now be suffering because, as capable as TCL is, current EDA tools would benefit from reflecting what is increasingly an object oriented compiled language core, as Python objects for user manipulation. - Paddy. From bignose+hates-spam at benfinney.id.au Tue Oct 16 05:05:41 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 16 Oct 2007 19:05:41 +1000 Subject: ANN: magnitude 0.9.1 References: <873awb5wgw.fsf@benfinney.id.au> Message-ID: <87k5pn4efu.fsf@benfinney.id.au> joanmg at gmail.com (Joan M. Garcia) writes: > Ben Finney writes: > > Please don't ever recommend 'from foo import *' in end-user > > documentation. [...] > > Got it, and solved. Thanks. Thanks for the quick response. A further issue, that requires a change of interface: Please comply with PEP 8 for your module interface. In particular, please name classes with TitleCase, and functions, methods, and instance names with lower_case. Also: "precision" is the correct spelling of that word. -- \ "I got up the other day, and everything in my apartment has | `\ been stolen and replaced with an exact replica." -- Steven | _o__) Wright | Ben Finney From mail at timgolden.me.uk Wed Oct 3 10:56:52 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 03 Oct 2007 15:56:52 +0100 Subject: enumerate overflow In-Reply-To: <4703AC7E.907@holdenweb.com> References: <1191411991.165082.19010@o80g2000hse.googlegroups.com> <4703AA68.7000206@tim.thechases.com> <4703AC7E.907@holdenweb.com> Message-ID: <4703ADB4.9090801@timgolden.me.uk> Steve Holden wrote: > I wouldn't dream of suggesting it's impossible. > I just regard "soon" as less than an hour in > commuter's terms, I suppose. Sadly, speaking as a Londoner, an hour is indeed "soon" in commuter terms. TJG From tokland at gmail.com Tue Oct 23 07:58:56 2007 From: tokland at gmail.com (tokland at gmail.com) Date: Tue, 23 Oct 2007 04:58:56 -0700 Subject: Iteration for Factorials In-Reply-To: <1193089188.812952.241920@v29g2000prd.googlegroups.com> References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <1193075845.148527.80820@k35g2000prh.googlegroups.com> <87bqarov3n.fsf@rudin.co.uk> <1193083810.302605.128630@y27g2000pre.googlegroups.com> <877ileq40i.fsf@rudin.co.uk> <1193089188.812952.241920@v29g2000prd.googlegroups.com> Message-ID: <1193140736.924933.217960@v23g2000prn.googlegroups.com> On 22 oct, 23:39, "mensana... at aol.com" wrote: > Nope, still doesn't work: > > def fact(x): > return reduce(operator.mul,xrange(1,x+1),1) > > fact() should raise an exception if x is negative. So, where is the problem? if not allowing negative numbers is so important for you, add a if statement and raise a ValueError exception. From paul.hankin at gmail.com Mon Oct 1 18:24:44 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 01 Oct 2007 22:24:44 -0000 Subject: Limits on search length In-Reply-To: References: Message-ID: <1191277484.332187.289850@57g2000hsv.googlegroups.com> On Oct 1, 6:16 pm, Daryl Lee wrote: > I am trying to locate all lines in a suite of files with quoted strings of > particular lengths. A search pattern like r'".{15}"' finds 15-character > strings very nicely. But I have some very long ones, and a pattern like > r'".{272}"' fails miserably, even though I know I have at least one > 272-character string. > > In the short term, I can resort to locating the character positions of the > quotes, but this seemed like such an elegant solution I hate to see it not > work. The program is given below (sans imports), in case someone can spot > something I'm overlooking: > > # Example usage: search.py *.txt \".{15}\" > filePattern = sys.argv[1] > searchPattern = sys.argv[2] > cpat = re.compile(searchPattern) Most shells will expand *.txt to the list of files that match, so you'll end up with the first .txt file as your 'filePattern', and the second as the regexp. Could that be it? -- Paul Hankin From mpelzsherman at yahoo.com Tue Oct 30 09:25:32 2007 From: mpelzsherman at yahoo.com (Michael Pelz Sherman) Date: Tue, 30 Oct 2007 06:25:32 -0700 (PDT) Subject: getting serialized data into and out of a database In-Reply-To: Message-ID: <198365.9333.qm@web55303.mail.re4.yahoo.com> THANK YOU! I needed to use tostring() in this case but the key was realizing what kind of data I was dealing with. Gabriel Genellina wrote: En Mon, 29 Oct 2007 19:07:18 -0300, Michael Pelz Sherman escribi?: > I'm having a devil of a time getting serialized data into and out of a > database (MySQL in this case) using python and MySQLdb. > > I have some C code that has its own serialization/deserialization > functions, which we've wrapped using SWIG. > > I am able to save the serialized C structs to disk but when I try to > write the exact same data to MySQL and pull it back out, I'm getting > some strange results. The data comes back looking like this: > > array('c', '\x01r\x01\x00\x...) > > Is this a python buffer, or what? How can I access the data in there? > I've tried using [1] but that doesn't seem to work. It's an array of characters You can write it to disk again using its tofile() method -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From llothar at web.de Sun Oct 21 09:09:18 2007 From: llothar at web.de (llothar) Date: Sun, 21 Oct 2007 06:09:18 -0700 Subject: Distributed RVS, Darcs, tech love In-Reply-To: <471afd4c.179297746@news.readfreenews.net> References: <1192850894.310464.89070@e9g2000prf.googlegroups.com> <1192914246.208743.94870@y27g2000pre.googlegroups.com> <471afd4c.179297746@news.readfreenews.net> Message-ID: <1192972158.250126.203980@v23g2000prn.googlegroups.com> > I'm, not sure that I'm getting your point, but are you trying to argue that > _not_ knowing mathemathics makes you a better programmer? No but it doesn't help you very much either. They are just different skills. > Or maybe that learning math is useless to a programmer? No and at least the mathematical idea of building a universe on a basic set of axioms is pretty exciting for a programmer. But it's the idea not the real wisdom (I never had to use any serious maths in my 25 years of programming) that you need as a programmer > This must be the most ignorant post I've seen > this week. The *best* programmers I've seen actually had mathematic education. Depends. I would call Knuth as one of the worst programmers. Look at his total failures on literature programming. Software Engineering is something very different. Having a dead - i mean end of development line software like TeX - and then trying to base a theory about software engineering (which is based on changes) is so absolutely stupid ... From arkanes at gmail.com Tue Oct 23 14:59:15 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 23 Oct 2007 13:59:15 -0500 Subject: Cross-platform GUI development In-Reply-To: <1193164449.831675.200600@i38g2000prf.googlegroups.com> References: <1192176809.756259.316980@v29g2000prd.googlegroups.com> <1192178193.734126.253610@z24g2000prh.googlegroups.com> <1193164449.831675.200600@i38g2000prf.googlegroups.com> Message-ID: <4866bea60710231159h5a22b04cuf20dcb48a498dce5@mail.gmail.com> On 10/23/07, maco wrote: > On Oct 13, 12:34 am, Michael L Torrie wrote: > > Alexandre Badez wrote: > > > Personnaly, I use PyQt simply because I prefere Qt to Gtk, witch is > > > much more integrated with all desktop than Gtk. > > > In fact, your application in Qt on Mac, Win or Linux look like a > > > native app. > > > > Qt doesn't look very native on my desktop. In fact, Qt apps have always > > looked out of place on a Gnome desktop. > > > > On Windows and Mac, no question, they look pretty native. You do have > > to take pains to make the app "feel" native, though. Like follow the UI > > guidelines of the platform, etc. > > > > > > > > > Just a question of "feeling" I think; because most of those GUI > > > framework, offer quiet the same functionality. > > GTK (like Pidgin or the GIMP) looks pretty native on Windows to me. This can only be because you don't use these programs often, or you've never actually looked at them. The GIMP in particular has almost nothing in common with the native controls - it's got a different background color, a different drawing model (note nasty delayed repaints when resizing), clearly non-native dialogs like file pickers, non-standard menu icons, just a huge list. Pidgin has a fairly minimal interface so it's flaws are less obvious, but they're still there. If this doesn't bother you, more power to you, but don't make the mistake of thinking that GIMP is any way "native" on windows. > Years of using Windows is probably why I think GTK/GNOME looks better > than Qt/KDE. > > -- > http://mail.python.org/mailman/listinfo/python-list > From ashish.jha at gmail.com Wed Oct 10 06:11:04 2007 From: ashish.jha at gmail.com (ashish) Date: Wed, 10 Oct 2007 03:11:04 -0700 Subject: Python service gets interrupted function call Message-ID: <1192011064.813082.221520@50g2000hsm.googlegroups.com> Hi All, I wanted to know how to handle events like 'logoff' in the main thread so that any process which is being run by svcDoRun method of service does not get 'interrupted function call' exception. I am posting a very simple service program , and i want to know that is there a way to handle such interrupts without explicitly calling try except block over blocking calls. Here is the example which is getting interrupted exception at logoff. ======================================================= import os, time, sys import win32serviceutil, win32service import pywintypes, win32con, winerror # Use "import *" to keep this looking as much as a "normal" service # as possible. Real code shouldn't do this. from win32event import * from win32file import * from win32pipe import * from win32api import * from ntsecuritycon import * import servicemanager import traceback import thread, time class TrialService(win32serviceutil.ServiceFramework): _svc_name_ = "TrialService" _svc_display_name_ = "TrialService" _svc_description_ = "TrialService" _exe_name_ = "C:/Python24/Lib/site-packages/win32/ pythonservice.exe" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = CreateEvent(None, 0, 0, None) self.overlapped = pywintypes.OVERLAPPED() self.overlapped.hEvent = CreateEvent(None,0,0,None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) SetEvent(self.hWaitStop) def SvcDoRun(self): time.sleep(1000) def ctrl_handler(ctrl_type): return True if __name__ =='__main__': SetConsoleCtrlHandler(ctrl_handler, True) win32serviceutil.HandleCommandLine(TrialService) ======================================================== In actual call i just want to call my app in place of time.sleep but my app will have blocking code segments. Any help will be greatly appreciated . Thanks Ashish From python.list at tim.thechases.com Thu Oct 4 16:05:25 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 04 Oct 2007 15:05:25 -0500 Subject: RegEx question In-Reply-To: <50af02ed0710041248i15823f88gd6b404353ba7d472@mail.gmail.com> References: <496954360710040855t7fd68a32o75aed48a9fd91bf2@mail.gmail.com> <496954360710040858w6226424fi299f8a57ed29e72@mail.gmail.com> <1191515675.19400.39.camel@skinner.madoff.com> <496954360710040954j1f48a38du91895d55f1391f93@mail.gmail.com> <50af02ed0710041248i15823f88gd6b404353ba7d472@mail.gmail.com> Message-ID: <47054785.5020705@tim.thechases.com> >>> try @param\[(in|out)\] \w+ >>> >> This didn't work either :( >> >> The tool using this regular expression (Comment Reflower for VS2005) May be >> broken... > > How about @param\[[i|o][n|u]t*\]\w+ ? ...if you want to accept patterns like @param[iutttttt]xxxxxxx ... The regexp at the top (Adam's original reply) would be the valid regexp in python and matches all the tests thrown at it, assuming it's placed in a raw string: r = re.compile(r"@param\[(in|out)\] \w+") If it's not a python regexp, this isn't really the list for the question, is it? ;) However, things to try: - sometimes the grouping parens need to be escaped with "\" - sometimes "\w" isn't a valid character class, so use the long-hand variant of something like "[a-zA-Z0-9_]] - sometimes the "+" is escaped with a "\" - if you don't use raw strings, you'll need to escape your "\" characters, making each instance "\\" HTH, -tkc From sbellon at sbellon.de Mon Oct 22 10:54:59 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Mon, 22 Oct 2007 16:54:59 +0200 Subject: Building sparc64 32/64-bit Python Message-ID: <20071022165459.476c7a07@cube.tz.axivion.com> Hi, I'm trying to build a Sun Solaris Version of Python from the source so that both, 32-bit and 64-bit libraries are present. I can successfully build a 32-bit version in one directory and a 64-bit version in another directory. What I'd like to do is to build a version that has the 64-bit library in a sparcv9 directory but shares the other Python libraries that are ELF-code independent. Is this possible or do I really have to install two complete but separate Pythons although most of the files are the same? -- Stefan Bellon From martin at v.loewis.de Tue Oct 23 17:37:15 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 23 Oct 2007 23:37:15 +0200 Subject: Root element name not declared In-Reply-To: <1193164157.943495.226850@z24g2000prh.googlegroups.com> References: <1193164157.943495.226850@z24g2000prh.googlegroups.com> Message-ID: <471e698b$0$4996$9b622d9e@news.freenet.de> > > > > [...] > > ,,,,, [...] > Being both the file and the dtd provided by the supplier, I believe > they're correct so I don't understand what's wrong. MyMessage IS > declared... isn't it sufficient? No. MyMessage is declared above as a Parameter Entity (PE), not as an element. Look for definitions that start with then the name of the root element would not be MyMessage, but Envelope. HTH, Martin From jstroud at mbi.ucla.edu Sun Oct 14 01:27:11 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 13 Oct 2007 22:27:11 -0700 Subject: Python on imac In-Reply-To: <8ocQi.24253$054.21605@newsfe14.phx> References: <8ocQi.24253$054.21605@newsfe14.phx> Message-ID: John Velman wrote: > I'm considering moving from Linux to imac. I've recently returned to > Python (was never very expert) to develop a small gui application. At > present I plan to use PyGTK with Pango and Cairo. > > What surprises may I be in for :-) > > (Currently using slackware 11.0 on an old (8 years) slow (400mhz) machine.) > > Thanks, > > John Velman For OS X 10.4, wx has come as part of the stock python install. You may want to consider going that route if you develop exclusively for OS X--it will keep the size of your distribution down. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From paul.hankin at gmail.com Wed Oct 24 10:15:31 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 24 Oct 2007 14:15:31 -0000 Subject: Better writing in python In-Reply-To: <1193230962.271873.104900@v29g2000prd.googlegroups.com> References: <1193227780.481365.261900@q3g2000prf.googlegroups.com> <1193230962.271873.104900@v29g2000prd.googlegroups.com> Message-ID: <1193235331.202744.226950@q3g2000prf.googlegroups.com> On Oct 24, 2:02 pm, kyoso... at gmail.com wrote: > On Oct 24, 7:09 am, Alexandre Badez wrote: > > > I'm just wondering, if I could write a in a "better" way this code > > > lMandatory = [] > > lOptional = [] > > for arg in cls.dArguments: > > if arg is True: > > lMandatory.append(arg) > > else: > > lOptional.append(arg) > > return (lMandatory, lOptional) > > > I think there is a better way, but I can't see how... > > You might look into list comprehensions. You could probably do this > with two of them: > > > # completely untested > lMandatory = [arg for arg in cls.dArguments if arg is True] > lOptional = [arg for arg in cls.dArguments if arg is False] > > > Something like that. I'm not the best with list comprehensions, so I > may have the syntax just slightly off. Your list comprehensions are right, but 'arg is True' and 'arg is False' are better written as 'arg' and 'not arg' respectively. -- Paul Hankin From sakradevanamindra at gmail.com Sun Oct 14 23:47:49 2007 From: sakradevanamindra at gmail.com (Shoryuken) Date: Sun, 14 Oct 2007 20:47:49 -0700 Subject: use lines as argument to a command Message-ID: <1192420069.166779.55230@y27g2000pre.googlegroups.com> I'm new to Python, so my question may sounds naive. Here is it. I have a text file like this: www.a.com www.b.com www.c.com ... I want to read one line from this file at a time, which I know how to do. And use it as an argument to a command, for example, telnet www.a.com and so on. However I have no idea how to do this task. My purpose is to generate a brief report. Thank you in advance. From j.d.walker at comcast.net Tue Oct 23 03:17:23 2007 From: j.d.walker at comcast.net (j.d.walker) Date: Tue, 23 Oct 2007 07:17:23 -0000 Subject: The finger of suspicion In-Reply-To: <1193115090.251163.132230@v23g2000prn.googlegroups.com> References: <1193115090.251163.132230@v23g2000prn.googlegroups.com> Message-ID: <1193123843.782723.174370@k35g2000prh.googlegroups.com> On Oct 22, 9:51 pm, therm... at india.com wrote: > The time of fall > The fake anthrax letters > The absence of pentagon video, the most highly defended building > The thermate residue > The molten metal pools > The pyroclastic flow of dust > The shattering of the whole building into dust and small pieces > The spherical particles of molten iron with sulfur, potassium and > permanganate elements > > The finger of suspicion, nay certainty points to only the yank and the > anglo-saxon bastards > > And all that to steal the oil. > > Bin Laden and Adam Gadahn productions are make in the Langley HQ of > CIA. > > Al-Qaida does not exist. > > The goal is to prevent democratic order in the oil rich arab countries. From mail at microcorp.co.za Fri Oct 5 02:23:45 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 5 Oct 2007 08:23:45 +0200 Subject: Program with wx in Linux and Windows References: Message-ID: <015801c80722$0937e640$03000080@hendrik> "marcpp" wrote: > Hi I've developed a program (WXpython GUI). In Linux the GUI is correct > (various distributions), but in Windows all appears disordered. > Any recomendations? You are not going to like this recommendation. Use Tkinter instead - seems to work nicely cross platform for me. - Hendrik From piet at cs.uu.nl Thu Oct 4 17:21:35 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 04 Oct 2007 23:21:35 +0200 Subject: Owner of spawned process in threads References: Message-ID: >>>>> "Vishal Sethia" (VS) wrote: >VS> Just trying to understand the behaviour of spawn. Consider I have a >VS> function which creates two threads. And in one of the threads I make a >VS> call to pexpect.spawn. spawn would fork and create a new new child In >VS> this case who becomes the owner of this child process. >VS> Is it the thread that spawned becomes the owner or is the main program >VS> becomes the owner of that child process. Owner (parent) is the process, not a thread. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From Roland.Puntaier at br-automation.com Thu Oct 25 05:51:36 2007 From: Roland.Puntaier at br-automation.com (Roland Puntaier) Date: Thu, 25 Oct 2007 11:51:36 +0200 Subject: New to Vim and Vim-Python In-Reply-To: <1193250319.878477.91460@t8g2000prg.googlegroups.com> Message-ID: > I am new to using Vim's scripts. > > I was wondering if anyone uses Vim-Python and how to use it? This > includes things like key bindings and such. I have keys mapped - to execute the current line and return its result (F2) - to execute the visual selection within a line and return its result (F4) - to execute the current visual selection over more lines (F3) - to open a window named pyout where the results are written (F5), else they are on the bottom line This way I can quickly check whether the python lines I wrote are OK without leaving the full-fledged editor. Anyway, I would like to know which other editors or free python IDEs have the same possibility. There surely are. Can anybody name one/some? Thanks. -------------- next part -------------- A non-text attachment was scrubbed... Name: _vimrc.zip Type: application/zip Size: 2455 bytes Desc: not available URL: From larry.bates at websafe.com Wed Oct 10 17:03:07 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 10 Oct 2007 16:03:07 -0500 Subject: if then elif In-Reply-To: References: Message-ID: Shawn Minisall wrote: > I just learned about if, then elif statements and wrote this program. > The problem is, it's displaying all of the possibilities even after you > enter a 0, or if the fat grams are more then the total number of > calories , that is supposed to stop the program instead of continuing on > with the print statements that don't apply. Any idea's? thanks > > #Prompt for calories > cal = input("Please enter the number of calories in your food: ") > > #Prompt for fat > fat = input("Please enter the number of fat grams in your food: ") > > #Input validation > if cal or fat <= 0: > #Display message > print "Error. The number of calories and/or fat grams must be > positive" > print > > else: > #Calculate calories from fat > calfat = float(fat) * 9 > #Calculate number of calories from fat > caldel = calfat / cal > > #change calcent decimal to percentage > calcent = caldel * 100 > > if calfat > cal: > print "The calories or fat grams were incorrectly entered." > > else: > #evaluate input > if caldel <= .3: > print "Your food is low in fat." > elif caldel >= .3: > print "Your food is high in fat." > > #Display percentage of calories from fat > print "The percentage of calories from fat in your food is %", > calcent > > Here's an example of the output... > > Please enter the number of calories in your food: 50 > Please enter the number of fat grams in your food: 30 > Error. The number of calories and/or fat grams must be positive > > Your food is low in fat. > The percentage of calories from fat in your food is % 0.0 > > It was supposed to print The calories or fat grams were incorrectly > entered since the calories from fat was greater then the total number of > calories. Boolean problem: if cal or fat <= 0 That may be the way you say it or "think" it but it won't work. 'cal or fat' is evaluated first. Since they both have values this ALWAYS evaluates to 1 which is NEVER less than or equal to 0. You are looking for if (cal <= 0) or (fat <=0): (Note: Parenthesis not required, but it may help you understand precedence of evaluation. Also read here: http://www.ibiblio.org/g2swap/byteofpython/read/operator-precedence.html -Larry From devraj at gmail.com Tue Oct 16 23:52:38 2007 From: devraj at gmail.com (Devraj) Date: Wed, 17 Oct 2007 03:52:38 -0000 Subject: urlgrabber cookie handling? Message-ID: <1192593158.188757.129010@i38g2000prf.googlegroups.com> Hi everyone, I have been battling to make my code work with a HTTPS proxy, current my code uses urllib2 to to most things and works well, except that urllib2 doesn't handle HTTPS proxies. Urlgrabber (http://linux.duke.edu/projects/urlgrabber/help/ urlgrabber.grabber.html) looks very promising except that I can find a way to handle cookies in urlgrabber. Is there a way urlgrabber can use a HTTPCookieProcess or cookielib.CookieJar object to handle cookies? Thanks for sparing your time. Thanks. -- Code referenced in this email is available at http://code.google.com/p/gdatacopier From marcsgbrevkonto at gmail.com Sun Oct 7 11:59:11 2007 From: marcsgbrevkonto at gmail.com (MarkyMarc) Date: Sun, 07 Oct 2007 15:59:11 -0000 Subject: Newbie packages Q In-Reply-To: <4708fff0$0$4523$9b4e6d93@newsspool3.arcor-online.net> References: <1191755440.850529.288860@o3g2000hsb.googlegroups.com> <1191763497.852128.130710@k79g2000hse.googlegroups.com> <4708ebfc$0$21561$426a74cc@news.free.fr> <1191768074.585609.251570@22g2000hsm.googlegroups.com> <4708f9b7$0$4527$9b4e6d93@newsspool3.arcor-online.net> <1191771348.165051.36790@50g2000hsm.googlegroups.com> <4708fff0$0$4523$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <1191772751.926241.81230@k79g2000hse.googlegroups.com> On Oct 7, 5:49 pm, Wildemar Wildenburger wrote: > MarkyMarc wrote: > > ******************************* > > atest.py: > > > def printA(): > > print "This is Atest from Apack" > > ******************************* > > btest.py: > > from Test.apack import atest > > > def printB(): > > print "This is Btest from Bpack" > > > def printatest(): > > print atest.printA() > > > print printB() > > print printatest() > > ******************************* > > > Now only one of them imports the other, and this most be the simplest > > way of illustrating the intra-package references. > > But how do I get this to work? > > This doesn't work? What error do you get? > I've never done too complicated packaging stuff, and can't raelly > testdrive your example right now. Maybe you have to look into sys.path > if Test can be found at all. Or maybe you have to play with the import > statement (from apack import atest?). I'm just guessing here; importing > continues to remain going on being a mystery to me. > > /W I get "no module name Test.apack." But if I print the sys.path just before importing the Test.apack, I have this: /python/Test/bpack So "Test" is in my path. But it seems like it will not look up the path but only down. And there by do not read the __init__.py files. But I might be wrong. Anyone that can explain me how this import and packaging in python works?? From cokofreedom at gmail.com Fri Oct 19 04:01:52 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 19 Oct 2007 08:01:52 -0000 Subject: Noob questions about Python In-Reply-To: <1192751078.506979.170580@z24g2000prh.googlegroups.com> References: <1192649863.496557.230730@v29g2000prd.googlegroups.com> <1192658316.048082.212190@v23g2000prn.googlegroups.com> <1192687508.636842.49940@z24g2000prh.googlegroups.com> <1192751078.506979.170580@z24g2000prh.googlegroups.com> Message-ID: <1192780912.381140.101880@e34g2000pro.googlegroups.com> On Oct 19, 1:44 am, MRAB wrote: > On Oct 18, 7:05 am, Michele Simionato > wrote:> On Oct 17, 5:58 pm, Ixiaus wrote: > > > > def bin2dec(val): > > > li = list(val) > > > li.reverse() > > > res = [int(li[x])*2**x for x in range(len(li))] > > > print sum(res) > > > > It basically does the same thing int(string, 2) does. > > > > Thank you for the responses! > > > BTW, here is the reverse function dec2bin, so that you can > > bang your head on it for a while ;) > > It returns '' when number == 0, so you need to test for that case: > > > def baseN(number, N=2): > > """ > > >>> baseN(9, 2) > > '1001' > > """ > > assert 2 <= N <= 10 > > assert isinstance(number, int) and number >= 0 > > if number == 0: > return "0" > Hey, Isn't if not number: return "0" faster? From DustanGroups at gmail.com Mon Oct 22 06:59:01 2007 From: DustanGroups at gmail.com (Dustan) Date: Mon, 22 Oct 2007 10:59:01 -0000 Subject: dynamic invoke In-Reply-To: <1192793679.102637.274620@e9g2000prf.googlegroups.com> References: <1192790367.342435.243930@v29g2000prd.googlegroups.com> <1192793679.102637.274620@e9g2000prf.googlegroups.com> Message-ID: <1193050741.142411.159560@t8g2000prg.googlegroups.com> On Oct 19, 6:34 am, Nils wrote: > Use apply(): http://docs.python.org/lib/non-essential-built-in-funcs.html Did you actually read the title of the page you linked to ("Non- essential Built-in Functions")? From copkat at vidotron.cr Fri Oct 19 16:38:08 2007 From: copkat at vidotron.cr (mich) Date: Fri, 19 Oct 2007 16:38:08 -0400 Subject: DIAGNOSIS: Racism moves back to Denmark from South Africa References: <1192661865.485820.253030@v29g2000prd.googlegroups.com> Message-ID: wrote in message news:1192661865.485820.253030 at v29g2000prd.googlegroups.com... > > INCISIVE ANALYSIS: The dismantlement of Apartheid Regime in South > Africa sent the racist Dutch Afrikaners back to Denmark where they are > spreading their racist ideology -- The Apartheid "Christianity" : The Dutch went back to Denmark? From bignose+hates-spam at benfinney.id.au Mon Oct 29 01:06:45 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 29 Oct 2007 16:06:45 +1100 Subject: PEP 299 and unit testing References: <871wbehef8.fsf@benfinney.id.au> <9tmdnf3x8fMezLjanZ2dnUVZ_oninZ2d@comcast.com> <87k5p6fsxj.fsf@benfinney.id.au> Message-ID: <87fxzufr16.fsf@benfinney.id.au> Steven Bethard writes: > Ben Finney wrote: > > Thanks! I was unaware of that module. It does seem to nicely > > address the issue I discussed. > > You might try the runpy module as-is with Python 2.4. I don't know > if it works, but it's pure Python so it's worth a try. Drat. It uses (by explicit design) "the standard import mechanism" to load the module, which means it doesn't work for exactly the thing I'm trying to do: load a program file *not* named with a '.py' suffix. I've long been able to load my program modules from no-suffix filenames (or indeed any non-standard filenames) with this function:: def make_module_from_file(module_name, file_name): """ Make a new module object from the code in specified file """ from types import ModuleType module = ModuleType(module_name) module_file = open(file_name, 'r') exec module_file in module.__dict__ sys.modules[module_name] = module return module Unfortunately, it seems that "module is already present with name 'foo' in 'sys.modules'" is insufficient for the Python import mechanism. The module loader used by 'runpy' still complains that it can't find the module, which is no surprise because its filename is not that of a library module. Perhaps I need to delve into the details of the import mechanism myself :-( -- \ "With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars." -- Raymond Hettinger | Ben Finney From ironfroggy at gmail.com Sat Oct 6 13:35:19 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Sat, 6 Oct 2007 13:35:19 -0400 Subject: setuptools on mac Message-ID: <76fd5acf0710061035r1bc44175i5b1e3f676e1da6a9@mail.gmail.com> I am trying to install the newest setuptools on my macbook. 2.3 was installed by default, and 2.4 is installed and is my default version now. However, when I try to import setuptools, which is required to _install_ setuptools, I get this error: macbkpro1:~/Desktop/setuptools-0.6c7 ironfroggy$ python setup.py install Traceback (most recent call last): File "setup.py", line 7, in ? execfile(convert_path('setuptools/command/__init__.py'), d) File "setuptools/command/__init__.py", line 13, in ? from distutils.command.bdist import bdist File "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/distutils/command/bdist.py", line 29, in ? class bdist (Command): File "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/distutils/command/bdist.py", line 33, in bdist user_options = [('bdist-base=', 'b', File "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/distutils/util.py", line 78, in get_platform cfgvars = get_config_vars() File "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/distutils/sysconfig.py", line 488, in get_config_vars func() File "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/distutils/sysconfig.py", line 373, in _init_posix raise DistutilsPlatformError(my_msg) distutils.errors.DistutilsPlatformError: $MACOSX_DEPLOYMENT_TARGET mismatch: now "10.4" but "10.3" during configure macbkpro1:~/Desktop/setuptools-0.6c7 ironfroggy$ -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From chris.lyon at spritenote.co.uk Tue Oct 30 16:22:41 2007 From: chris.lyon at spritenote.co.uk (wyleu) Date: Tue, 30 Oct 2007 13:22:41 -0700 Subject: _tkinter installation in python 2.5 on mandriva with a default 2.4 Message-ID: <1193775761.764547.148730@i38g2000prf.googlegroups.com> I'm running on Mandriva 2007 (2.6.17-5mdv) and thus have python2.4.3 installed by default, I'm running code requiring yield(), so need python2.5 and have installed this sucessfully, and linked appropriately to allow me to start python2.5 by typing python2.5. However I'd like to use idle so require to be able to import _tkinter. I gather I need to modift the setup.py script in my python directory but am wary of experimenting since I've had problems with damaging the default tkinter installation before. import Tkinter Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.5/lib-tk/Tkinter.py", line 38, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter Should I need to download a later version of tkinter and/or should I alter setup.py in my python install directory and then remake? If the former how do I ensure I don't overwrite the original tkinter install thus damaging the many mandriva utilities that rely on python2.4.3 and if the later what should I be looking for within the python2.5 installation to point to and what alterations within setup.py are required? From allen.fowler at yahoo.com Tue Oct 16 00:14:12 2007 From: allen.fowler at yahoo.com (allen.fowler) Date: 15 Oct 2007 21:14:12 -0700 Subject: Simple HTML template engine? In-Reply-To: References: <1192419411.895715.138450@e9g2000prf.googlegroups.com> Message-ID: <1192492962.413427.212540@q5g2000prf.googlegroups.com> CherryPy looks nice... though I am just looking to generate static reports. Thanks anyway... I'll keep it in mind for the future. On Oct 15, 4:38 am, "Ciprian Dorin Craciun" wrote: > Have you tried CherryPy?http://www.cherrypy.org/ > > It's not a template engine, but a simple web server engine, and > you could code your conditionals and loops directly in Python... When > I have tried it, it looked very nice and easy. > > Ciprian. From 353851029352 at mms.mymeteor.ie Sun Oct 14 08:13:09 2007 From: 353851029352 at mms.mymeteor.ie (353851029352 at mms.mymeteor.ie) Date: Sun, 14 Oct 2007 12:13:09 GMT Subject: No subject Message-ID: A non-text attachment was scrubbed... Name: 01smil Type: application/smil Size: 129 bytes Desc: not available URL: From welcomestocontact at gmail.com Thu Oct 4 03:40:48 2007 From: welcomestocontact at gmail.com (welcomestocontact at gmail.com) Date: Thu, 04 Oct 2007 00:40:48 -0700 Subject: Web service client using https Message-ID: <1191483648.610569.219510@g4g2000hsf.googlegroups.com> Hi All, I am trying to connect .NET web service using HTTPS. I wrote a python script using https. For that need to send SOAP message to the server. But it is giving error 401.3 execution access is denied.(SOAP message not processing) I have a doubt can we access web services using HTTPS only, or need to have any other. I am sending the code:: [CODE] import httplib a=open('/root/Desktop/b.xml','r') #SOAP message Message=a.read() h =httplib.HTTPS('hpc.msftlabs.com') h.putrequest('PUT','/HPCBasicProfile/HPCBasicProfile.svc') h.putheader('Accept','text/soap') h.putheader('Content-type','text/jsl; charset="utf-8"') h.putheader('Content-length','%s' % str(len(Message))) h.putheader('SOAPAction','http://schemas.ggf.org/bes/2006/08/ besfactory/BESFactoryPortType/CreateActivity') .endheaders() h.send(Message) errcode,errmsg, headers = h.getreply() print errcode,errmsg, headers f = h.getfile() # Get file object for reading data data = f.read() print data f.close() [/CODE] Please guid me to access web service. Thanks Allavarapu From grante at visi.com Tue Oct 16 15:57:18 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Oct 2007 19:57:18 -0000 Subject: best way of dealing with currency? References: Message-ID: <13ha5suo9550je0@corp.supernews.com> Just send the currency to me. I'll deal with it. -- Grant Edwards grante Yow! I'm into SOFTWARE! at visi.com From nytrokiss at gmail.com Tue Oct 2 02:25:16 2007 From: nytrokiss at gmail.com (James Matthews) Date: Mon, 1 Oct 2007 23:25:16 -0700 Subject: slice last 4 items from a list In-Reply-To: <1191286234.855980.118170@g4g2000hsf.googlegroups.com> References: <1191286234.855980.118170@g4g2000hsf.googlegroups.com> Message-ID: <8a6b8e350710012325p467f9ddfu2d65503a0c7d4db2@mail.gmail.com> Very pythoninc! On 10/1/07, John Machin wrote: > > On Oct 2, 6:27 am, brad wrote: > > Is this the correct way to slice the last 4 items from a list? > > > > x = [1,2,3,4,5,6,7,8,9] > > print x[-4:] > > > > It works, but is it Pythonic? > > It's Pythonic. It's also unambiguous, unlike your specification, which > could be interpreted as 'chop off the last 4 items from a list' i.e. > del x[-4:]. What you are actually doing is 'print the last 4 items of > a list'. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/search.aspx?Search=cufflinks http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjl at pobox.com Sat Oct 13 14:45:16 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 13 Oct 2007 18:45:16 GMT Subject: urllib.ProxyHandler HTTPS issues References: <1192078997.453819.323390@22g2000hsm.googlegroups.com> <87641d8pzb.fsf@pobox.com> <1192141278.464551.182390@e9g2000prf.googlegroups.com> Message-ID: <873awedfb7.fsf@pobox.com> Devraj writes: > Thanks John. Will investigate sending the CONNECT command to handle > proxies. > > Do you recommend doing this for HTTP proxies as well No. > or should I just use the ProxyHandler for HTTP proxies? Yes. John From steve at REMOVE-THIS-cybersource.com.au Wed Oct 10 22:52:59 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 11 Oct 2007 02:52:59 -0000 Subject: if then elif References: <1192055029.856930.19230@r29g2000hsg.googlegroups.com> Message-ID: <13gr40bbqmhd430@corp.supernews.com> On Wed, 10 Oct 2007 20:42:26 -0600, Michael L Torrie wrote: > chris.monsanto at gmail.com wrote: > > >> that's the most incorrect thing i've heard all day! >> >> if cal or fat <= 0 is parsed as if (cal) or (fat <= 0) > > Which is exactly what he said. Heh, that was my first thought too, for about 3.2 milliseconds. And then I realised that, no, he actually said: 'cal or fat' is evaluated first that is, it was parsed like if (cal or fat) <= 0 which is not correct. -- Steven. From michael at jedimindworks.com Tue Oct 2 17:22:44 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 2 Oct 2007 14:22:44 -0700 Subject: List Question In-Reply-To: References: Message-ID: On Oct 2, 2007, at 2:06 PM, brad wrote: > How is this expressed in Python? > > If x is in y more than three times: > print x > > y is a Python list. # Try using help -- help(list) or help(list.count) for instance... if y.count(x) > 3: print x From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Oct 11 06:15:16 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 11 Oct 2007 12:15:16 +0200 Subject: multimethods decorator In-Reply-To: References: <470d0914$0$24295$426a74cc@news.free.fr> Message-ID: <470df778$0$11653$426a74cc@news.free.fr> gherzig at fmed.uba.ar a ?crit : >> Gerardo Herzig a ?crit : >>> Hi all. Im reading the Gido's aproach using decorators at >>> http://www.artima.com/weblogs/viewpost.jsp?thread=101605 >>> >>> It looks good to me, but the examples shows the functionality using >>> functions. >>> Now, when i try to give this decorator into a method, if i try the >>> >>> class test(object): >>> @multimethod(...) >>> def met(self, ...): >>> >>> The multimethod decorator needs the types of the arguments, and, if the >>> met method requires self as the first argument, the multimethod should >>> look like >>> @multimethod(self.__class__, bla, ble) or some like that... >>> >>> Now i know that im wrong, because i have this error >>> >@multimethod(self.__class__) >>> >NameError: name 'self' is not defined >> Indeed. Neither self (which will only be known at method call time) nor >> even the 'test' class (which is not yet defined when the decorator is >> executed) are availables. > Doh! If you're surprised, then you'd better learn way more about Python's internal (execution model && object model mostly) before continuing with multimethods. >>> So what would be the first argument to @multimethod?? >> A string ?-) > Ah? And what will that string contains? What makes sens for you. Don't forget that Python has very strong introspection features. Also note that it's not uncommon to use a 2-pass approach : marking some methods with the decorator, then doing the real processing in the metaclass (which of course implies a custom metaclass) or in the __new__ method (in which case this processing will happen on *each* instanciation). >> FWIW, there's already an implementation of multiple dispacth by Mr. Eby... > Oh yes, i found the dispatch version of multimethods, but i have not tried > it yet. Do you think is better this version than Guido's? I think that dispatch is actually used in a few packages, frameworks or applications. Is it the case of Guido's stuff ? Also, IIRC, Guido's snippet is quite less generic than dispatch (which is based on expression rules, not only on types). My 2 cents... From WilliamKF at gmail.com Fri Oct 26 12:27:32 2007 From: WilliamKF at gmail.com (WilliamKF at gmail.com) Date: Fri, 26 Oct 2007 16:27:32 -0000 Subject: Interpreter hook during evaluation Message-ID: <1193416052.060300.254560@d55g2000hsg.googlegroups.com> Hello, I would like access to a hook inside Python that would allow me to register a C++ function to be called periodically during the evaluation of a Python script. Does any such thing exist today in Python? I poked around but didn't find anything. I want to do this for interrupt handling. I'd like to be able to interrupt long running Python commands. I have a hook which would throw a C++ exception if an interrupt is detected. I would then catch this at the place where my application which embeds Python invokes a Python command. My hook is written to be very fast, so calling it every Python instruction would not be that bad in terms of performance. I'd like to avoid changing the existing Python implementation, which is why I'm looking for a hook. Otherwise, a user would not be able to substitute in their own Python implementation if they so desire instead of taking the default on our app uses. Thanks for the ideas. -William From DustanGroups at gmail.com Wed Oct 10 06:34:01 2007 From: DustanGroups at gmail.com (Dustan) Date: Wed, 10 Oct 2007 10:34:01 -0000 Subject: Last value of yield statement In-Reply-To: <1192011545.384425.189530@o80g2000hse.googlegroups.com> References: <1192011545.384425.189530@o80g2000hse.googlegroups.com> Message-ID: <1192012441.818783.149110@k79g2000hse.googlegroups.com> On Oct 10, 5:19 am, Shriphani wrote: > Hello all, > > Let us say I have a function like this: > > def efficientFiller(file): Note that you are shadowing the built-in variable 'file' here. Better use 'filename', or something to that effect. > worthless_list = [] > pot_file = open(file,'r') > pot_file_text = pot_file.readlines() > for line in pot_file_text: > if line.find("msgid") != -1: > message_id = shlex.split(line)[1] > if message_id in dictionary: > number = pot_file_text.index(line) > corresponding_crap = > dictionary.get(message_id) > final_string = 'msgstr' + " " + '"' + > corresponding_crap + '"' + '\n' > pot_file_text[number+1] = final_string > yield pot_file_text > > efficient_filler = efficientFiller("libexo-0.3.pot") > new_list = list(efficient_filler) > print new_list > > I want to plainly get the last value the yield statement generates. > How can I go about doing this please? > > Regards, > Shriphani Palakodety efficient_filler = efficientFiller("libexo-0.3.pot") new_list = list(efficient_filler) last_value = new_list[-1] print last_value # OR efficient_filler = efficientFiller("libexo-0.3.pot") for last_value in efficient_filler: pass print last_value The latter assumes that the last value is the only value you want. From cjames at callone.net Tue Oct 30 08:28:33 2007 From: cjames at callone.net (c james) Date: Tue, 30 Oct 2007 07:28:33 -0500 Subject: appending into a list In-Reply-To: References: Message-ID: Beema shafreen wrote: > 2721520 2721569 A_16_P21360235 199 -49 > 2721768 2721821 A_16_P03641971 139 -53 > 2721960 2722004 A_16_P21360237 312 -44 > I need to append the column D and E into a list: > in such a way that the list should have > [D,E,D,E,D,E........] > How do i do it. > > regards > shafreen Without a header, you could use something like data = [x.split()[-2:] for x in open(filename).readlines()] With header f = open(filename) f.readline() data = [x.split()[-2:] for x in f.readlines()] From bignose+hates-spam at benfinney.id.au Wed Oct 17 21:50:14 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 Oct 2007 11:50:14 +1000 Subject: Pull Last 3 Months References: <1192638812.176235.232060@z24g2000prh.googlegroups.com> <47167F80.8080208@tim.thechases.com> <1192665202.277171.132880@t8g2000prg.googlegroups.com> <87zlyhz2fd.fsf@benfinney.id.au> <4716b996@news.eftel.com.au> Message-ID: <87ve95yyw9.fsf@benfinney.id.au> John Machin writes: > It's a bit hard to see how anybody could imagine that in the expression > [months[(month - i - 1) % 12] for i in range(n)] > the number 12 referred to anything but the number of months in a year. Exactly, that's what people *will* assume. But what if they're wrong, and you're using the number 12 for some other semantic purpose? If the programmer has encountered this type of betrayed assumption before, they'll never be entirely sure that a bare '12' in the code means what they think it means. And the code doesn't say anything about why the number was used, so they're left to guess. Of course, in such a trivial example, it is almost unthinkable that the number 12 would mean anything else; but the entire point of the principle of not using magic numbers is that you don't have to wonder about when that line is crossed. Better to be explicit about it, in every case, IMO. -- \ "Money is always to be found when men are to be sent to the | `\ frontiers to be destroyed: when the object is to preserve them, | _o__) it is no longer so." -- Voltaire, _Dictionnaire Philosophique_ | Ben Finney From namesagame-usenet at yahoo.com Tue Oct 16 16:56:42 2007 From: namesagame-usenet at yahoo.com (gamename) Date: Tue, 16 Oct 2007 20:56:42 -0000 Subject: ctypes & Wrapping Complex Datatypes Message-ID: <1192568202.660884.165770@e34g2000pro.googlegroups.com> Hi, I've just started using ctypes and so far, its great. But I'm running to some problems with complex datatypes. I'm not sure how to wrap something like this: /* This defines the Handle type in a header file. I don't think this needs wrapping, its just to show the handle definition for context*/ typedef struct DFFTSHandle_s *DFFTSHANDLE; ... /* Then, the handle is used like this later on. This *is* what I want to wrap.*/ status = DFFTSCreateSession(&Handle); status = DFFTSSetSessionOption(Handle, DFFTSOPT_ITERATIONS, &iteration, sizeof(iteration)); Any ideas? TIA, -T From patrick.waldo at gmail.com Tue Oct 16 08:47:51 2007 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Tue, 16 Oct 2007 12:47:51 -0000 Subject: Simple Text Processing Help In-Reply-To: References: <1192369731.561036.31010@i38g2000prf.googlegroups.com> <1192396632.736910.134070@q5g2000prf.googlegroups.com> <1192445236.310797.91160@z24g2000prh.googlegroups.com> <1192482484.987399.112620@k35g2000prh.googlegroups.com> Message-ID: <1192538871.985374.46760@e34g2000pro.googlegroups.com> And now for something completely different... I've been reading up a bit about Python and Excel and I quickly told the program to output to Excel quite easily. However, what if the input file were a Word document? I can't seem to find much information about parsing Word files. What could I add to make the same program work for a Word file? Again thanks a lot. And the Excel Add on... import codecs import re from win32com.client import Dispatch path = "c:\\text_samples\\chem_1_utf8.txt" path2 = "c:\\text_samples\\chem_2.txt" input = codecs.open(path, 'r','utf8') output = codecs.open(path2, 'w', 'utf8') NR_RE = re.compile(r'^\d+-\d+-\d+$') #pattern for EINECS number tokens = input.read().split() def iter_elements(tokens): product = [] for tok in tokens: if NR_RE.match(tok) and len(product) >= 4: product[2:-1] = [' '.join(product[2:-1])] yield product product = [] product.append(tok) yield product xlApp = Dispatch("Excel.Application") xlApp.Visible = 1 xlApp.Workbooks.Add() c = 1 for element in iter_elements(tokens): xlApp.ActiveSheet.Cells(c,1).Value = element[0] xlApp.ActiveSheet.Cells(c,2).Value = element[1] xlApp.ActiveSheet.Cells(c,3).Value = element[2] xlApp.ActiveSheet.Cells(c,4).Value = element[3] c = c + 1 xlApp.ActiveWorkbook.Close(SaveChanges=1) xlApp.Quit() xlApp.Visible = 0 del xlApp input.close() output.close() From bearophileHUGS at lycos.com Sun Oct 28 07:56:47 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 28 Oct 2007 04:56:47 -0700 Subject: Need some help... In-Reply-To: <1193560272.637389.315680@e34g2000pro.googlegroups.com> References: <1193560272.637389.315680@e34g2000pro.googlegroups.com> Message-ID: <1193572607.910074.317980@22g2000hsm.googlegroups.com> > I want to create a program that I type in a word. You can see that Python has a command to input strings from the command line. > chaos > each letter equals a number.... > A=1 > B=20 > and so on. > So Chaos would be > C=13 H=4 A=1 O=7 S=5 > I want to then have those numbers > 13+4+1+7+5 added together to be 30. > How can I do that? Python has a dictionary data structure called dict(), or {}, that you can use to map your letters to those numbers. With it you can created the letter-number association. Then you can scan the characters of the input string one after the other, and sum their values into a single total value. Try writing that code, and then show it to us, we can give more suggestions if you need them... Bye, bearophile From steven.bethard at gmail.com Sun Oct 28 23:20:33 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 28 Oct 2007 21:20:33 -0600 Subject: PEP 299 and unit testing In-Reply-To: <871wbehef8.fsf@benfinney.id.au> References: <871wbehef8.fsf@benfinney.id.au> Message-ID: <9tmdnf3x8fMezLjanZ2dnUVZ_oninZ2d@comcast.com> Ben Finney wrote: > What it doesn't allow is for the testing of the 'if __name__ == > "__main__":' clause itself. No matter how simple we make that, it's > still functional code that can contain errors, be they obvious or > subtle; yet it's code that *can't* be touched by the unit test (by > design, it doesn't execute when the module is imported), leading to > errors that won't be caught as early or easily as they might. You could always use runpy.run_module. STeVe From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Oct 24 08:20:51 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 24 Oct 2007 14:20:51 +0200 Subject: building a linux executable References: <1193223316.020001.77940@i13g2000prf.googlegroups.com> Message-ID: <5o8rl3Flhd8uU1@mid.individual.net> Prateek wrote: > I'm trying to package my python program into a linux executable > using cx_freeze. The goal is that the user should require python > on their system. > > I've managed to make the binaries on Fedora Core 6 and they run > fine. However, when I move to Ubuntu (tested on Ubuntu Server 7.04 > and xUbuntu Desktop 7.04), the program fails to run with the > following error: I'm sorry I cannot help, but how many linux distros have no python installed or no packages of it? Regards, Bj?rn -- BOFH excuse #151: Some one needed the powerstrip, so they pulled the switch plug. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Oct 19 11:25:39 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 19 Oct 2007 17:25:39 +0200 Subject: write whitespace/tab to a text file References: <1192804409.415321.257150@k35g2000prh.googlegroups.com> Message-ID: <5ns0jjFjut8fU1@mid.individual.net> dirkheld wrote: > f=open('/User/home/Documents/programming/python/test.txt','w') > for x in range(len(names)): > f.write(tags[x]) > f.close() Definitely consider the Python tutorial. Also, please provide working code examples. I don't think yours will work ;) names = ['John','Steve','asimov','fred','jim'] f = open('/User/home/Documents/programming/python/test.txt','w') f.write('\t'.join(names)) f.close() A better alternative could be the csv module. Regards, Bj?rn -- BOFH excuse #388: Bad user karma. From steve at holdenweb.com Thu Oct 4 22:39:31 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 04 Oct 2007 22:39:31 -0400 Subject: PYTHONPATH, opensuse10.2, gtk not working In-Reply-To: <1191536138.690185.59080@22g2000hsm.googlegroups.com> References: <1191536138.690185.59080@22g2000hsm.googlegroups.com> Message-ID: Silfheed wrote: > Heyas > > So I'm trying to do two things, install a little gnome taskbar applet > (timer-applet) that was written in python and experiment with writing > python gtk apps. I've installed (through yast) gtk, gtk2, gtk2-devel, > python-gtk, python-gtk-devl, python-gtk-doc but I still cant get > python to import gtk. I set PYTHONPATH = /usr/lib/python2.5/site- > packages/ and that got importing pygtk to work, but the little app I > downloaded wants to import gtk and I just cant figure out what I'm > supposed to set PYTHONPATH to in order to get `import gtk` to work. > Anyone know what I'm doing wrong or missing? > > Thanks > set PYTHONPATH to /usr/lib/python2.5/lib/site-packages:gtk-root-dir By the way, do you really think that it's necessary to put site-packages on the path? You might find it's already on there as Python starts up. You can tell by printing sys.path from Python. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it From george.sakkis at gmail.com Fri Oct 12 10:22:49 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 12 Oct 2007 14:22:49 -0000 Subject: decorating container types (Python 2.4) In-Reply-To: <1192138976.165419.25820@19g2000hsx.googlegroups.com> References: <1192138976.165419.25820@19g2000hsx.googlegroups.com> Message-ID: <1192198969.356877.225160@q3g2000prf.googlegroups.com> On Oct 11, 5:42 pm, timar... at gmail.com wrote: > Hi, > > I have a container class A and I want to add functionality to it by > using a decorator class B, as follows: > > class A(object): > def __len__(self): > return 5 > > class B(object): > def __init__(self, a): > self._a = a > > def __getattr__(self, attr): > return getattr(self._a, attr) > > def other_methods(self): > blah blah blah > > I was expecting len(B) to return 5 but I get > AttributeError: type object 'B' has no attribute '__len__' > instead. > I was expecting len() to call B.__len__() which would invoke > B.__getattr__ to call A.__len__ but __getattr__ is not being called. > I can work around this, but I am curious if anyone knows _why_ > __getattr__ is not being called in this situation. > > Thanks > Tim Unfortunately __getattr__ is not called for special attributes; I'm not sure if this is by design or a technical limitation. You have to manually delegate all special methods (or perhaps write a metaclass that does this for you). George From david.trem at gmail.com Sat Oct 13 05:55:28 2007 From: david.trem at gmail.com (David Tremouilles) Date: Sat, 13 Oct 2007 11:55:28 +0200 Subject: Cross-platform GUI development In-Reply-To: References: <1192176809.756259.316980@v29g2000prd.googlegroups.com> Message-ID: <129e1cd10710130255q7654a4c7veabc43284ebab06f@mail.gmail.com> No issue with pygtk on mac! Actually I develop on this platform everyday. Macport take care of the installation for me http://www.macports.org/ (Fink should do the work too). Of course native GTK on OSX could be nice but definitely not needed at this point in time. David 2007/10/13, Dave Cook : > On 2007-10-13, David Tremouilles wrote: > > > I would recommend pyGTK http://www.pygtk.org/ > > Native GTK on OSX is still in its infancy. For early adopters only at > this point. See > > http://www.oreillynet.com/articles/author/2414 > > That leaves PyQt and WxPython as the only other realistic choices. > Licensing issues aside, I think Qt has the most polished and well > thought out API. The OSX Tiger dev tools include WxPython, though you > may want to install a newer version. I suggest installing both and > trying some of the included examples. > > Another possibility is Jython, if you like the Java way of doing > things. > > Dave Cook > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From besturk at gmail.com Sun Oct 7 09:03:06 2007 From: besturk at gmail.com (Abandoned) Date: Sun, 07 Oct 2007 06:03:06 -0700 Subject: Pil image module, "mode" bug.. Message-ID: <1191762186.617411.309700@g4g2000hsf.googlegroups.com> Hi.. I find the picture color with: im=Image.open("/%s" %name) color=im.mode #p=black & beyaz rgb=color L=grey This usually work true but in these pictures: http://malatya.meb.gov.tr/images/alt/ilsis_logo.gif http://malatya.meb.gov.tr/images/meb.gif Say me P (black&white) but these pictures are color.. What is the reason of this ? I'm sorry my bad english From gslindstrom at gmail.com Wed Oct 31 12:06:37 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Wed, 31 Oct 2007 11:06:37 -0500 Subject: PyCon 2008 - Call for Tutorials Message-ID: PyCon 2008 is being held in Chicago this year. The general conference is March 14-16 with the proceeding day, March 13th, being the traditional "tutorial day". We have had a lot of input on topics to cover and now we are looking for qualified instructors to sign up to present the sessions. Tutorials are 3 hours long (with break) and instructors are paid for their effort ($1000.00 + conference registration). PyCon is planned and run by volunteers just like you. Why not get involved? Pop on over to us.pycon.org for conference details or email us at pycon-tutorials at python.org and let us know what you would like to present as a tutorial. Thanks, --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Sun Oct 7 03:31:12 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 07 Oct 2007 00:31:12 -0700 Subject: ANN: pyparsing 1.4.8 released Message-ID: <1191742272.784760.208020@w3g2000hsg.googlegroups.com> I'm happy to announce that I have just uploaded the latest release (v1.4.8) of pyparsing. This release has a few new features and corresponding demonstration examples. There are also a few minor bug-fixes, and a performance speedup in the operatorPrecedence method. Here are the notes: - Added new helper method nestedExpr to easily create expressions that parse lists of data in nested parentheses, braces, brackets, etc. - Added withAttribute parse action helper, to simplify creating filtering parse actions to attach to expressions returned by makeHTMLTags and makeXMLTags. Use withAttribute to qualify a starting tag with one or more required attribute values, to avoid false matches on common tags such as

You might want to look at PAMIE instead. It sounds like a Python project that's aimed at automating Internet Explorer: http://sourceforge.net/projects/pamie/ But if you really like COM, I found this tutorial: http://www.evilbitz.com/2006/10/22/python-ie-automation-thorough-tutorial/ I'm not very good with COM, but I would recommend that you do some research on it. From the traceback, I would guess that you don't have administrator privileges (of some sort) on the machine you're running the script on. Mike From danielwong at berkeley.edu Wed Oct 10 18:16:17 2007 From: danielwong at berkeley.edu (danielx) Date: Wed, 10 Oct 2007 22:16:17 -0000 Subject: Pythonic way for handling file errors In-Reply-To: <1192044529.831420.86020@57g2000hsv.googlegroups.com> References: <1192041679.657266.320210@o80g2000hse.googlegroups.com> <1192044529.831420.86020@57g2000hsv.googlegroups.com> Message-ID: <1192054577.892611.35620@o3g2000hsb.googlegroups.com> On Oct 10, 12:28 pm, Paul Hankin wrote: > On Oct 10, 7:41 pm, wink wrote: > > > I would like to know what would be considered the most > > Pythonic way of handling errors when dealing with files, > > solutions that seem reasonable using 2.5: > > The best way to handle errors is to catch the exceptions that are > raised by the code that handles the error. Your examples push the > problem elsewhere: you're setting an error code which has to be tested > for. But perhaps your application needs to do this for some reason > (judging from your error codes, this is some sort of web script). > > > ... > > try: > > with open('afile', 'r') as f: > > content = f.read() > > error = 200 > > except Exception: > > error = 404 > > Of all your examples, this is the best. But the catch-all exception > handler is bad: it's better to catch just file io exceptions. Also, I > think it's better to put the OK case (error 200) in an else clause to > make it clearer that it's only set when no error occurs. It's also > better to use constants in place of magic numbers. > > import httplib > > try: > with open('afile', 'r') as f: > content = f.read() > except IOError: > error = httplib.NOT_FOUND > else: > error = httplib.OK > > -- > Paul Hankin Wink, One of the problems your facing is knowing whether you managed to open the file before reaching the finally block where you close your file. To avoid this, I open my files right before try/finally. For me, the only purpose in having the try/finally is to make sure my files are properly closed, although when I'm lazy, I just let the file close it self during garbage collection. This is what it looks like: file = open('filename') try: # read and/or process file finally: file.close() Of course, this example does not handle any exceptions. In many cases, you want these errors to propogate upward so the users of your functions/methods can decide what needs to be done. On the other hand, you could wrap this code with try/except/else if you wanted to handle the exception "at the source". From tfb+google at tfeb.org Tue Oct 9 06:00:32 2007 From: tfb+google at tfeb.org (Tim Bradshaw) Date: Tue, 09 Oct 2007 03:00:32 -0700 Subject: The fundamental concept of continuations In-Reply-To: <1191911662.983658.79540@g4g2000hsf.googlegroups.com> References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> <470b1b30$0$11022$4c368faf@roadrunner.com> <1191911662.983658.79540@g4g2000hsf.googlegroups.com> Message-ID: <1191924032.449463.13290@22g2000hsm.googlegroups.com> On Oct 9, 7:34 am, gnuist... at gmail.com wrote: > which lambda paper ? Are you Ilias? I think you probably are. From jeffrey at fro.man Thu Oct 4 16:49:40 2007 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 04 Oct 2007 13:49:40 -0700 Subject: unit testing References: Message-ID: <13gakf52n1fv2e2@corp.supernews.com> Chris Mellon wrote: > Doctest is commonly given as the alternative to people who feel this > way. Personally, I find that anything worth testing is worth having a > test directory and independent unit tests for. I like keeping my tests separate as well, and doctest does allow this, using doctest.testfile(). That is, despite the name, doctests do not necessarily need to appear in docstrings :-) Jeffrey From gardsted at yahoo.com Wed Oct 17 14:44:46 2007 From: gardsted at yahoo.com (gardsted) Date: Wed, 17 Oct 2007 20:44:46 +0200 Subject: readline support on openSuSE In-Reply-To: References: Message-ID: <4716581e$0$7604$157c6196@dreader2.cybercity.dk> Milos Prudek wrote: > This question concerns compilation of Python from sources. Specifically Python > 2.3.6. > > On Kubuntu 7.04, ./configure outputs these lines about readline: > checking for rl_pre_input_hook in -lreadline... yes > checking for rl_completion_matches in -lreadline... yes > > On openSuSE 10.3, ./configure outputs these lines about readline: > checking for rl_pre_input_hook in -lreadline... no > checking for rl_completion_matches in -lreadline... no > > And, of course, line editing in Python shell is possible on Kubuntu and > impossible on openSuSE. > > I do have libreadline5 and readline-devel RPM installed on openSuSE. What else > might I need to have readline support? > This is not an answer but I have 10.3 installed, and I found that a lot of my (not python-) compiling troubles went away after installing 'a lot' from the development patterns presented by yast. I am so demented that I tend not to get the dependencies straight when installing from the 'personal memory';-) kind retards jorgen / de mente something completely different: myspace.com/dementedk From martin at marcher.name Tue Oct 23 04:38:57 2007 From: martin at marcher.name (Martin Marcher) Date: Tue, 23 Oct 2007 10:38:57 +0200 Subject: C++ version of the C Python API? In-Reply-To: <496954360710211417v72d9bdd1ia9ff9bdde30892c1@mail.gmail.com> References: <471B8711.1020509@v.loewis.de> <496954360710211250x1389a594m1551b3389cc9d5dd@mail.gmail.com> <471BB1FA.1020704@v.loewis.de> <496954360710211349p4278f4f3g675c657f7740980f@mail.gmail.com> <471BBD55.9030601@v.loewis.de> <496954360710211417v72d9bdd1ia9ff9bdde30892c1@mail.gmail.com> Message-ID: <5fa6c12e0710230138v16f159e2lcdf6a77aca974080@mail.gmail.com> 2007/10/21, Robert Dailey : > On 10/21/07, "Martin v. L?wis" wrote: > > No, I literally meant that the Python C API is object-oriented. > > You don't need an object-oriented language to write object-oriented > > code. > > I disagree with this statement. C is not an object oriented language, > and I've seen attempts to make it somewhat object oriented, however it > failed miserably in readability and manageability overhead. just FYI. What about the linux kernel? It's (in large parts) perfectly designed by OO principles (the vfs for example). And I can't remember that it was written in C++. Make a struct with some funtion pointers in it and you are at a basic OO level. the pointers could then manipulate the variables in the struct (remember a C++ struct ist just a class with all things being public). How does that differ from python? - I can't remember having visibility modifiers in python.... (so that would lead to that python isn't object oriented as any programmer could at any time directly manipulate any method/variable/whatsoever of your classes) -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From bj_666 at gmx.net Sat Oct 27 08:58:31 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Oct 2007 12:58:31 GMT Subject: simple question on dictionary usage References: <472327af$0$31482$426a74cc@news.free.fr> <1193487810.194444.277900@o38g2000hse.googlegroups.com> Message-ID: <5ogqvnFmgu6mU2@mid.uni-berlin.de> On Sat, 27 Oct 2007 05:23:30 -0700, bearophileHUGS wrote: > My take too :-) > > dict(item for item in record.iteritems() if item[0][0] == 'E') ``s.startswith('E')`` is a little safer than ``s[0] == 'E'`` as the former returns `False` if `s` is empty while the latter raises an `IndexError`. Ciao, Marc 'BlackJack' Rintsch From nytrokiss at gmail.com Thu Oct 11 15:30:55 2007 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 11 Oct 2007 12:30:55 -0700 Subject: Library for crawling forums In-Reply-To: <1192130023.125026.271530@r29g2000hsg.googlegroups.com> References: <1192130023.125026.271530@r29g2000hsg.googlegroups.com> Message-ID: <8a6b8e350710111230v91bdf6fsb56088bfa6175433@mail.gmail.com> Well i know some that do half the job urllib or urllib2 to download the page htmlparser or beautifulsoup For html parsing Enjoy On 10/11/07, BlueCrux wrote: > > I'm trying to write a utility to crawl forums and strip posts to be > gone through offline. Just the content, I don't need to get who posted > or sigs or any identifying info. > > Can anyone suggest a library that is already geared toward this? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/search.aspx?Search=Cufflinks http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From zaz600 at gmail.com Thu Oct 25 02:28:16 2007 From: zaz600 at gmail.com (NoName) Date: Thu, 25 Oct 2007 06:28:16 -0000 Subject: about functions question Message-ID: <1193293696.450188.108330@q3g2000prf.googlegroups.com> I try it: def b(): ... a() ... def a(): ... b() ... b() it's not work. Is it possible pre-define function like in c++ or place functions code after main block? int a(); int b(); int main () { ... a(); ... } int a() { ... b(); ... } int b() { ... a(); ... } =) sorry for my eng;) From mahs at telcopartners.com Thu Oct 4 19:35:35 2007 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 04 Oct 2007 16:35:35 -0700 Subject: Dynamically creating class properties In-Reply-To: References: Message-ID: Karlo Lozovina wrote: > > Any idea how to do that with metaclasses and arbitrary long list of > attributes? I just started working with them, and it's driving me nuts :). > > Thanks for the help, > best regards. > Try implementing a property factory function before worrying about the metaclass. Assuming you need a standard getter and setter, then the following (untested) example may be useful. If you need custom get/set behavior then you would rewrite the factory to accept passed-in functions. >>> def make_data_property(cls, prop_name): ... ... # create default methods that get and set a 'private' instance ... # attribute ... def _set(self, value): ... setattr(self, "_%s" % prop_name, value) ... def _get(self): ... # None is default. Alternatively handle AttributeError ... return getattr(self, "_%s" % prop_name, None) ... ... setattr(cls, prop_name, property(_get, _set)) ... ... # optionally, fix the internal names of the _get and _set for better ... # introspection ... _set.func_name = setname = "set%s" % prop_name ... _get.func_name = getname = "get%s" % prop_name ... ... # optionally, make _get and _set members of the class, if you want to ... # call them directly (but then, why have the property?) ... setattr(cls, setname, _set) ... setattr(cls, getname, _get) ... >>> class A(object): ... pass ... >>> a=A() >>> a.item1 Traceback (most recent call last): File "", line 1, in AttributeError: 'A' object has no attribute 'item1' >>> make_data_property(A,"item1") >>> a.item1 >>> a.item1 = 42 >>> a.item1 42 >>> make_data_property(A,"item2") >>> a.item2 >>> a.item2 = 43 >>> >>> a.item2 43 >>> If you can get this piece working, then multiple attributes should be easy. Then, if you like, you can call your property factory from the metaclass __init__ method. HTH Michael From sjmachin at lexicon.net Wed Oct 17 21:40:32 2007 From: sjmachin at lexicon.net (John Machin) Date: Thu, 18 Oct 2007 11:40:32 +1000 Subject: Pull Last 3 Months In-Reply-To: <87zlyhz2fd.fsf@benfinney.id.au> References: <1192638812.176235.232060@z24g2000prh.googlegroups.com> <47167F80.8080208@tim.thechases.com> <1192665202.277171.132880@t8g2000prg.googlegroups.com> <87zlyhz2fd.fsf@benfinney.id.au> Message-ID: <4716b996@news.eftel.com.au> On 18/10/2007 10:33 AM, Ben Finney wrote: > Paul Hankin writes: > >> import datetime >> >> months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split() >> >> def last_months(n): >> month = datetime.date.today().month >> return [months[(month - i - 1) % 12] for i in range(n)] >> >> print last_months(3) > > Heck you don't even need the magic number 12 in there. > > import datetime > > months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split() Heck if you really want to be anal, you could even guard against a typo (or one of those spaces actually being '\xA0' [seen it happen]) by adding in here: MONTHS_IN_YEAR = 12 assert len(months) == MONTHS_IN_YEAR > def last_months(n): > month = datetime.date.today().month > return [months[(month - i - 1) % len(months) > for i in range(n)] > > In general I try to avoid magic numbers: always be explicit about the > semantic purpose of the number, either by binding a meaningful name to > it and only using that reference thereafter, or showing how that value > is derived. > It's a bit hard to see how anybody could imagine that in the expression [months[(month - i - 1) % 12] for i in range(n)] the number 12 referred to anything but the number of months in a year. From sgifford at suspectclass.com Mon Oct 1 13:28:07 2007 From: sgifford at suspectclass.com (Scott Gifford) Date: Mon, 01 Oct 2007 13:28:07 -0400 Subject: which language allows you to change an argument's value? References: <1191149233.346818.246170@22g2000hsm.googlegroups.com> Message-ID: Summercool writes: > I wonder which language allows you to change an argument's value? [...] > What about Java and Perl? Perl will let you change the value of a passed-in object directly. Others have already answered about Java. > is there any way to prevent a function from changing the argument's > value? Make a copy of the object, and pass in the copy. Without making a copy, of the languages I know, C++ comes closest to supporting an unmodifiable argument passed by reference. Using a const reference or const pointer indicates that the reference won't be changed, but even that can be subverted by the function's author with casting. -----Scott. From pydecker at gmail.com Sun Oct 28 10:05:14 2007 From: pydecker at gmail.com (Peter Decker) Date: Sun, 28 Oct 2007 10:05:14 -0400 Subject: Need some help... In-Reply-To: <1193560272.637389.315680@e34g2000pro.googlegroups.com> References: <1193560272.637389.315680@e34g2000pro.googlegroups.com> Message-ID: On 10/28/07, hyozan.ux3 at gmail.com wrote: > I want to then have those numbers > 13+4+1+7+5 added together to be 30. > > How can I do that? > > Also, just curious, but, how could I then have the 3 and 0 added > together to be 3? > > Please help me out. Will you put our names on your homework when you hand it in? -- # p.d. From Graham.Dumpleton at gmail.com Thu Oct 25 18:44:46 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 25 Oct 2007 22:44:46 -0000 Subject: sys.path not properly initialized (was: PyImport_ImportModule/embedding: surprising behaviors) In-Reply-To: References: <1174767636.080416.74740@n59g2000hsh.googlegroups.com> Message-ID: <1193352286.069324.151930@q5g2000prf.googlegroups.com> On Oct 26, 6:53 am, David Abrahams wrote: > > David Abrahams wrote: > >> I'm seeing highly surprising (and different!) behaviors of > >> PyImport_ImportModule on Linux and Windows when used in a program with > >> python embedding. > > >> On Linux, ... > > > > Unfortunately, nothing you have written below or on the pages you > reference seems to help in Windows. Here's a simple program that > demonstrates: > > import.c > 1KDownload > > 'import site' failed; use -v for traceback > Traceback (most recent call last): > File "", line 1, in > ImportError: __import__ not found > > >> I can work around the problem by setting PYTHONPATH to point to the > >> python library directory: > > >> set PYTHONPATH=c:\Python25\Lib > > > This happens because Python calculates the initial import path by > > looking for an executable file named "python" along PATH. > > C:\Python25, which contains python.exe, is in the PATH. If it's > really looking for an executable named "python" along PATH, that can > never succeed on Windows, since (I think) only files ending in .exe, > .bat, and .cmd are executable there. > > > You can > > change this by calling Py_SetProgramName(filename) before calling > > Py_Initialize(). This is documented in API reference manual: > > Uncomment that line in my program above and you'll see it makes > absolutely no difference. > > >http://docs.python.org/api/embedding.html > > > That page also describes a few hooks that you can overwrite to > > modify the initial search path. They are described in more detail > > on this page: > > >http://docs.python.org/api/initialization.html > > The only thing mentioned there that seems to have any effect at all is > > set PYTHONHOME=C:\Python25 > > and even then, it only eliminates the first line of the error, which > then reads: > > Traceback (most recent call last): > File "", line 1, in > ImportError: __import__ not found > > My only known workaround is to set PYTHONPATH. This just doesn't seem > right; isn't anyone doing embedding under Windows? The problem with not finding site.py on Windows will often come up when you have gone through a cycle of installing/removing different versions of Python and the registry entries get mucked. Also can be a problem where Python was not installed as administrator originally and now trying to run stuff as user different to what Python was installed as. A lot of the time problems go away by deinstalling Python and reinstalling as administrator. Also watch out for where you have some third party application which provides its own version of Python and that version or its DLL is being found first in your PATH. Graham From barronmo at gmail.com Tue Oct 30 20:39:48 2007 From: barronmo at gmail.com (barronmo) Date: Wed, 31 Oct 2007 00:39:48 -0000 Subject: choose from a list In-Reply-To: <1193785411.032673.147860@v3g2000hsg.googlegroups.com> References: <1193767382.430635.303370@d55g2000hsg.googlegroups.com> <1193770225.374384.52290@k79g2000hse.googlegroups.com> <1193782113.429067.132740@57g2000hsv.googlegroups.com> <1193785411.032673.147860@v3g2000hsg.googlegroups.com> Message-ID: <1193791188.338141.123020@v3g2000hsg.googlegroups.com> I didn't know "result" was a list! Can all that info be stored in a list? How do the columns work? I was curious to see what the data looked like but I can't seem to print "result" from the prompt. Do variables used inside functions live or die once the function executes? If they die, how do I get around this? I tried defining 'r = ""' in the module before the function and then using it instead of "result" but that didn't help. Mike From steve at REMOVE-THIS-cybersource.com.au Mon Oct 15 10:14:31 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 15 Oct 2007 14:14:31 -0000 Subject: Newbi Q: Recursively reverse lists but NOT strings? References: <53396d9e0710141406p6182bdat789fe1706225f345@mail.gmail.com> <471308FA.3070705@islandtraining.com> <53396d9e0710150238v2ccd3df7y42f89e776c31e524@mail.gmail.com> <13h6nlmd8aku2ea@corp.supernews.com> Message-ID: <13h6te7sk7iun42@corp.supernews.com> On Mon, 15 Oct 2007 14:47:30 +0200, Francesco Guerrieri wrote: >> def myreversed(sequence): >> if isinstance(sequence, basestring): >> return type(sequence)().join(reversed(sequence)) >> else: >> return type(sequence)(reversed(sequence)) >> >> (in fact, that's so simple I wonder why the built-in reversed() doesn't >> do that). > > simple: > In the face of ambiguity, refuse the temptation to guess. What ambiguity? What guess? The above is completely unambiguous: it returns a sequence of the same type as the input. It doesn't support xrange objects, but that's not really a great loss. -- Steven. From zaxfuuq at invalid.net Sun Oct 21 08:01:45 2007 From: zaxfuuq at invalid.net (Wade Ward) Date: Sun, 21 Oct 2007 05:01:45 -0700 Subject: ACM SIGAPL / APL2007 Conference / Montreal / one week away References: <47133159.9010204@acm.org> <1192920380.625668.221960@i13g2000prf.googlegroups.com> <1192954949.817248.242120@y27g2000pre.googlegroups.com> <471b2ef9$0$5050$39db0f71@news.song.fi> Message-ID: "Veli-Matti" wrote in message news:471b2ef9$0$5050$39db0f71 at news.song.fi... > Gosi wrote: > .. >> I can not use the APL character set at all. >> It is too mixed up with my national characters. > > What about a unicode version of APL? > > Honestly, I cannot use J because it mixes with all > the characters I use... ;) > -Veli-Matti what the fuck ever. Re:Attention, Sir/Madam This Is To Officially Inform You That We Have Verified Your ontract/Inheritance File And Discovered Reasons Why You Are Yet To Receive Your Payment. It Is Because Of Irregularities And Complications Discovered On Your Payment File By Our Technical Experts In Respect To Your Contract /Inheritance Payment Requirements Which Have Just Been Duly Rectified. Meanwhile, We Have Been Informed That You Are Still Dealing With Impostors And Non Recommended Officials In The Bank. Such Acts Must Stop For Security Reasons If You Wish To receive Your Payment. Since We Have Decided To Bring A Solution To Your Problem, Right Now We Have Arranged Your Payment Through Our ATM Swift Card Payment Center OCEANIC BANK INTERNATIONAL PLC ( Under Reserve Bank Operation Act 2005 ), That Is The Latest Instruction By Our President Chief,Umaru Musa Yar Adua (GCFR) Federal Republic Of Nigeria. Below Is The Arrangements ;... You are advised to contact our accredited payment office via the contact information provided below for immediate payment to you. Dr James Smith. Oceanic Bank International Plc. 802 Ozumba Mbadiwe Close, Lagos, NIGERIA. Direct Phone number: +234-802-712-7674 Email: info_atmpaymentcenter at mybestmail.com The Swift card Center Will Send You An ATM Card Which You Will Use To Withdrew Your Money From Any ATM Machine In Any Part Of The World, But The Maximum Is Six Thousand Dollars Per Day, So If You Like To Receive Your Fund This Way Please Do Let Us Know By getting back to us ASAP with this information's stated below: 1) Your full name. 2) Phone, fax and mobile #. 3) Profession, age and marital status. 4) Copy of Drivers License I .D. 5) Amount of fund that you are expecting 6) Address Where You Want Them To Send The Card Through Diplomatic Courier Please Indicate To The Card Center The Total Sum You Are Expecting And For Your Information You Have To Stop Any Further Communication With Any Institution Or Office Until You Receive The ATM Card. Note: Because of Impostors, We Hereby Issue You Our Code of Conduct Tag Number Which Is(805) So You Must Have To Indicate This Code When Contacting The Card Center.We Await Your Urgent Response. Mr. Anthony Eke Special Adviser To The President Federal Republic Of Nigeria Phone +234-703-096-5403 f'up set. -- wade ward wade at zaxfuuq.net "Der Katze tritt die Treppe hoch; Der Kater tritt sie krumm.% % De Teufel geit um; er bringt der menschen allet dummer." schau, schauer From bruno.42.desthuilliers at wtf.websiteburo.oops.com Sat Oct 6 09:13:05 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Sat, 06 Oct 2007 15:13:05 +0200 Subject: Yet another comparison of Python Web Frameworks In-Reply-To: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> References: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> Message-ID: <470789c2$0$28579$426a74cc@news.free.fr> Michele Simionato a ?crit : > At work we are shopping for a Web framework, so I have been looking at > the available options > on the current market. In particular I have looked at Paste and Pylons > and I have written my > impressions here: > > http://www.phyast.pitt.edu/~micheles/python/yet-another-comparison-of-web-frameworks.html > > I do not speak too well of Pylons, so if you thing I am wrong feel > free to correct me here ;) > Well... Last year, I had a look at Pylons, then played a bit with wsgi and building my own framework over it. I finally dropped that code and went back to Pylons, which I felt could become far better than my own efforts. Now since then I had way too much to do at work (using other technos) and didn't find the time to work on my own projects, so I still don't know how well Pylons will pass the "real world" test, but it seems to me that it's rapidly progressing and mostly in the right direction. I still wait for an opportunity to check this out !-) While we're at it: - talking about routes, you say: """ I have no Ruby On Rails background, so I don't see the advantages of routes. """ I don't have any RoR neither, but as far as I'm concerned, one of the big points with routes is url_for(), that avoids having too much hard-coded urls. - about FormEncode : that's a package I've used before without Pylons, and while it has a few dark corners, it's mostly doing TheRightThing for most current validation/conversion tasks. I'll still use it with or without Pylons - about SQLAlchemy : here again, I used this package prior any experience with Pylons. FWIW, I used it in the most basic, 'low-level' way, ie without any ORM stuff, and I found it to be a pretty good alternative to db-api. It's a bit complex, but powerful, and having the possibility to handle sql requests as Python objects (instead of raw strings) really helps. From gagsl-py2 at yahoo.com.ar Sun Oct 21 15:42:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Oct 2007 16:42:05 -0300 Subject: Problem with format string / MySQL cursor References: <1192732348.392303.151430@i38g2000prf.googlegroups.com> <1192736676.035569.188300@e9g2000prf.googlegroups.com> <1192740053.589994.109050@q5g2000prf.googlegroups.com> <13hgqs4fdq7h76e@corp.supernews.com> <13hktelmt556eb5@corp.supernews.com> Message-ID: En Sat, 20 Oct 2007 18:40:38 -0300, Dennis Lee Bieber escribi?: > On Fri, 19 Oct 2007 18:50:20 -0300, "Gabriel Genellina" > declaimed the following in comp.lang.python: >> If the MySQLdb adapter actually converts and inserts the arguments >> itself >> into the supplied SQL sentence, generating a new string for each call, >> this advantage -and many others- are cancelled, defeating the purpose of >> bound variables. > > Okay, I'm a bit behind the time... The book I keep on the floor next > to my computer is the old brown/black version covering version 3.x and > introducing ver 4.0 (my newer books are across the room in shelves > behind the couch that take time to reach) > > It can't be fully blamed on the MySQLdb adapter... After crawling > through too many reference books, it looks like MySQL itself didn't > support "prepared statements" until sometime in the ver 4.1.x period -- > I believe the MySQLdb adapter is still ver 3.x compatible, using the > mysql_query(connection, SQL_string) call, rather than the half-dozen > newer functions for separately binding parameters to prepared > statements. Yes, if the database doesn't allow for prepared statements the poor adapter can't do much... > Since, to my experience, db-api 2 doesn't expose the concepts of > prepared statements to the user, about the only place using them would > offer a true speed-up would be in the .executemany() call (and even then > it would seem to depend upon which is more costly: formatting a properly > [...] Some databases automatically cache SQL statements. I know DB2 does that, and I think Oracle does too (or is it the JDBC layer?). So it's not required that user code explicitely prepares SQL statements. Prepared statements have other advantages, apart from the speed gain when using repetitive queries: they help to keep the statement length below some size limit, they help to lower the cpu load on the server (by not having to parse and optimize the query again), and they avoid SQL injection (else, you have to rely on the quoting and escaping being well done, even on the DB-API adapter). > If the api exposed them to the user, I could see a potential use for > them: an application with, say, multiple forms (each of one or more DB > tables)... By preparing and saving a set of statements for each form > (parameterized select, update, insert, delete, say) during application > startup (or conditionally on first entry to a form) one would only need > to reference the prepared statements for the forms as the end-user > navigates the forms. But DB-API 2.0 already allows that. PEP 249 says, when describing cursor.execute: "A reference to the operation will be retained by the cursor. If the same operation object is passed in again, then the cursor can optimize its behavior. This is most effective for algorithms where the same operation is used, but different parameters are bound to it (many times)." So nothing special is required to enable prepared statements; the adapter is free to prepare and re-use queries if desired. BTW, the situation is similar to the re module: you can pre-compile your regular expressions, but it's not required, as the re module caches compiled expressions, reusing them later when the same r.e. is seen. > {At least we're not discussing Firebird... 1000+ page book on it and the > closest it comes to discussing a C-language API is to mention that the C > header file defining the functions is included with the binary > install... And for other APIs it just gives URLs} Nice book! :) -- Gabriel Genellina From mensanator at aol.com Tue Oct 9 13:31:38 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Tue, 09 Oct 2007 10:31:38 -0700 Subject: pytz has so many timezones! In-Reply-To: <13gmd5hjk5chi4f@corp.supernews.com> References: <1191828739.635927.86590@57g2000hsv.googlegroups.com> <1191865263.572366.270820@y42g2000hsy.googlegroups.com> <13gmd5hjk5chi4f@corp.supernews.com> Message-ID: <1191951098.067501.37490@y42g2000hsy.googlegroups.com> On Oct 9, 2:58 am, Dennis Lee Bieber wrote: > On Mon, 08 Oct 2007 10:41:03 -0700, "mensana... at aol.com" > declaimed the following in comp.lang.python: > > > > > There are only 25 timezones: -12, -11, ... -1, 0 (GMT), +1, ... +11, > > +12. > > Uhm... -12 and +12 would be the same, wouldn't they? No, they are seperated by the International Date Line, so although zones -12 & +12 have the same clock time, they are different dates. > > There are only 24 divisions 15deg wide in longitude, 7.5deg to each > size of zone center, and Greenwich is center of 0... And zones -12 & +12 are each nominally 7.5deg wide, so 23*15 + 2*7.5 gives you 25 zones spanning 360deg. > > However, consider that the former Soviet Union is reputed to have > used only ONE timezone for the entire width of the country (sunrise at > 6AM say in Moscow would be near sunset on the east coast) When was this, in the days before air travel when it took 3 weeks to cross Siberia by train? > > So while there are only 24 hourly offsets, there can be many "zones" > to reflect variations in daylight time changes or non-standard > offsets... The point I was trying to make is that although there may be 400 zones, there aren't 400 offsets. And aren't these offsets part of the timezone record? > -- > 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 deets at nospam.web.de Sat Oct 27 12:19:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 27 Oct 2007 18:19:52 +0200 Subject: how to creating html files with python In-Reply-To: References: Message-ID: <5oh6pqFmmgjrU2@mid.uni-berlin.de> krishnakant Mane schrieb: > hello, > I have one strange requirement, > I need to create html files through python and add some data from the database. > it is a GUI based application developed in WX python. > and the reports need to come out in html for some strange reason which > is off topic to discuss here. > but the point is that how do I do it? > should I create a normal file object and write the html with the data Essentially, yes. > into it or are there some modules to do it? There are a bazillion templating systems out there. Beginning with python's own string interpolation, to KID, genshi, Mako, tenjin, cheeta, ... Search this NG for python templating engines, and you'd be overwhelmed by the answers. Happy chosing your evil, Diez From vinay_sajip at yahoo.co.uk Fri Oct 5 07:15:57 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 05 Oct 2007 04:15:57 -0700 Subject: Version 0.3.7 of the config module has been released Message-ID: Version 0.3.7 of the Python config module has been released. What Does It Do? ================ The config module allows you to implement a hierarchical configuration scheme with support for mappings and sequences, cross-references between one part of the configuration and another, the ability to flexibly access real Python objects, facilities for configurations to include and cross-reference one another, simple expression evaluation and the ability to change, save, cascade and merge configurations. You can easily integrate with command line options using optparse. This module has been developed on python 2.3 but should work on version 2.2 or greater. A test suite using unittest is included in the distribution. A very simple configuration file (simple.cfg): # starts here message: Hello, world! #ends here a very simple program to use it: from config import Config cfg = Config(file('simple.cfg')) print cfg.message results in: Hello, world! Configuration files are key-value pairs, but the values can be containers that contain further values. A simple example - with the example configuration file: messages: [ { stream : `sys.stderr` message: 'Welcome' name: 'Harry' } { stream : `sys.stdout` message: 'Welkom' name: 'Ruud' } { stream : $messages[0].stream message: 'Bienvenue' name: Yves } ] a program to read the configuration would be: from config import Config f = file('simple.cfg') cfg = Config(f) for m in cfg.messages: s = '%s, %s' % (m.message, m.name) try: print >> m.stream, s except IOError, e: print e which, when run, would yield the console output: Welcome, Harry Welkom, Ruud Bienvenue, Yves The above example just scratches the surface. There's more information about this module available at http://www.red-dove.com/python_config.html Comprehensive API documentation is available at http://www.red-dove.com/config/index.html As always, your feedback is most welcome (especially bug reports, patches and suggestions for improvement). Enjoy! Cheers Vinay Sajip Red Dove Consultants Ltd. Changes since the last release posted on comp.lang.python[.announce]: ===================================================== Added Mapping.__delitem__ (patch by John Drummond). Mapping.__getattribute__ no longer returns "" when asked for "__class__" - doing so causes pickle to crash (reported by Jamila Gunawardena). Allow negative numbers (reported by Gary Schoep; had already been fixed but not yet released). From mail at microcorp.co.za Sun Oct 21 02:33:48 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 21 Oct 2007 08:33:48 +0200 Subject: what is the difference between the two kinds of brackets? References: <1192875315.887877.210550@y27g2000pre.googlegroups.com> <1192898800.059965.272700@q3g2000prf.googlegroups.com> Message-ID: <009901c813ac$57236820$03000080@hendrik> "Paul Hankin" wrote: > If everything else is equal, use tuples. Interesting point of view - mine is just the opposite. I wonder if its the philosophical difference between: "Anything not expressly allowed is forbidden" and "Anything not expressly forbidden is allowed" ? - Hendrik From Michael.J.Fromberger at Clothing.Dartmouth.EDU Mon Oct 22 13:40:36 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Mon, 22 Oct 2007 13:40:36 -0400 Subject: Iteration for Factorials References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> Message-ID: In article <1193055966.362489.252080 at v29g2000prd.googlegroups.com>, Py-Fun wrote: > I'm stuck trying to write a function that generates a factorial of a > number using iteration and not recursion. Any simple ideas would be > appreciated. Well, first think about the recursive implementation: def fact(n): if n > 0: return n * fact(n - 1) else: return 1 To turn this into an iterative computation, you must first get rid of the deferred operations -- in this case, the multiplication step after the recursive call to fact(n - 1). Since multiplication commutes, we can re-write this recursion to keep an accumulating parameter instead of deferring the operation: def fact2(n, acc = 1): if n > 0: return fact2(n - 1, acc * n) else: return acc This is a little bit better, because now the recursive call is in tail position, and so in principle no state needs to be saved across recursive calls: Once the inner call to fact2 is complete, its value is simply returned. But we're not done yet, because Python _does_ save state across recursive calls, even in this construction. By a gentle twist of perspective, the inner call to "fact2(n - 1, acc * n)" is really just a kind of "jump" back to the beginning of the function. In another (hypothetical) language, you might write it like this: # Not legal Python code. def fact3(n, acc = 1): TOP: if n > 0 n = n - 1 acc = acc * n goto TOP else: return acc Naturally, of course, Python does not provide a "goto" statement. But it does have one that's similar: while TEST: BODY is equivalent in meaning to the pseudo-code: X: if TEST: BODY goto X Can you now see how you would re-write "fact3" into legal Python code, using this equivalence? Once you have done so, you will also be able to get rid of the extra accumulating parameter, and then you will have what you wanted. I hope this helps. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From arkanes at gmail.com Wed Oct 3 14:44:56 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 3 Oct 2007 13:44:56 -0500 Subject: gui toolkits: the real story? (Tkinter, PyGTK, etc.) In-Reply-To: <1191435649.384615.51680@n39g2000hsh.googlegroups.com> References: <1191287053.541506.88530@d55g2000hsg.googlegroups.com> <13g5uvh698l9h1c@corp.supernews.com> <13g7irlht5ruj3a@corp.supernews.com> <1191435649.384615.51680@n39g2000hsh.googlegroups.com> Message-ID: <4866bea60710031144w5cfafbfdo115e40327acd8144@mail.gmail.com> On 10/3/07, bramble wrote: > On Oct 3, 1:39 pm, "Chris Mellon" wrote: > > On 10/3/07, Grant Edwards wrote: > > > > > On 2007-10-03, Chris Mellon wrote: > > > > On 10/2/07, Grant Edwards wrote: > > > >> On 2007-10-02, Chris Mellon wrote: > > > > > >> > PyGtk has poor cross platform support, a very large footprint (the > > > >> > largest of all these libraries) > > > > > >> It's larger than wxWidgets on top of Gtk? > > > > > > No, but it's larger than wx on top of the native API, > > > > > A moot point for X11. > > > > wxWidgets actually does have a raw X11 implementation, > > Wait though. If I want to use wxPython, my python code calls wxWidgets > code which calls gtk. So, it would seem simpler to remove 1 layer and > just call the gtk code directly via PyGTK. > By the same argument, you could say that Gtk just calls xlib, so why not write against xlib directly? More direct is not always simpler. But the real reason, of course, is that wxWidgets is a platform abstraction API, and Gtk isn't. Anyway, this discussion isn't about the relative merits of wxWidgets and PyGtk in general, but specifically for inclusion in the standard library. > > > > > > so when you average it across all platforms it's quite a bit > > > > larger. > > > > > I guess that's one of the costs of portability. > > > > Eh? The point is that wxWidgets, the more portable toolkit, is > > *smaller* than Gtk. It's not really related to portability as much as > > design considerations. > > Isn't wxWidgets smaller that GTK+ simply because it's a wrapper and > doesn't do its own drawing? > Not really, no. Qt also does all of its own drawing and is a fraction of the size of Gtk. The amount of code thats responsible for drawing is minuscule. > -- > http://mail.python.org/mailman/listinfo/python-list > From http Fri Oct 5 16:09:51 2007 From: http (Paul Rubin) Date: 05 Oct 2007 13:09:51 -0700 Subject: unit testing References: <1191604175.903042.228140@g4g2000hsf.googlegroups.com> Message-ID: <7x3awpl3w0.fsf@ruckus.brouhaha.com> 7stud writes: > What are some strategies for unit testing a function that obtains user > input? For example: http://en.wikipedia.org/wiki/Expect From kyosohma at gmail.com Tue Oct 2 09:06:22 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 02 Oct 2007 13:06:22 -0000 Subject: Creating a custom python python distribution In-Reply-To: <1191208680.221428.11880@50g2000hsm.googlegroups.com> References: <1191208680.221428.11880@50g2000hsm.googlegroups.com> Message-ID: <1191330382.346531.224590@19g2000hsx.googlegroups.com> On Sep 30, 10:18 pm, shailesh wrote: > Hi, > I wish to create a Python distribution includind Python and some other > libraries (Zope 3, PyWin32, numpy, lxml, etc.) which are required for > my applications. e.g. there are Enthough and ASPN distributions of > Python. > > Unfortunately, I have not been able to find the right documentation > for this purpose. > > Could some one give an overview of what needs to be done for this > purpose? > > With regards, > -Shailesh Are you wanting to create an executable or what? There are a few different ways to distribute your work. You can use py2exe, GUI2exe (a py2exe wrapper), PyInstaller, Distutils or Python Eggs. Here are some links: http://pyinstaller.python-hosting.com/ http://www.py2exe.org/ http://xoomer.alice.it/infinity77/main/GUI2Exe.html http://docs.python.org/dist/dist.html http://peak.telecommunity.com/DevCenter/PythonEggs That should get you started. Mike From gagsl-py2 at yahoo.com.ar Fri Oct 19 20:22:47 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Oct 2007 21:22:47 -0300 Subject: __main__ : What is this? References: <496954360710191629x3fc82871s334f15c2d5a48530@mail.gmail.com> Message-ID: En Fri, 19 Oct 2007 20:29:03 -0300, Robert Dailey escribi?: > I've read various portions of the Python 2.5 documentation in an > attempt to figure out exactly what the following condition represents: > > if __name__ == "__main__": > main() > > However, I was not able to determine what it is actually checking for. > Could someone point me in the way of a tutorial or explain this for > me? Thanks. You won't find it (easily) on the 2.5 docs, but it's covered in the upcoming 2.6 tutorial: http://docs.python.org/dev/tutorial/modules.html#executing-modules-as-scripts -- Gabriel Genellina From akraemer at sbcglobal.net Thu Oct 11 01:49:23 2007 From: akraemer at sbcglobal.net (Andreas Kraemer) Date: Wed, 10 Oct 2007 22:49:23 -0700 Subject: Keeping track of subclasses and instances? In-Reply-To: References: Message-ID: <1192081763.798940.227830@r29g2000hsg.googlegroups.com> On Oct 10, 6:19 pm, Karlo Lozovina <_kar... at mosor.net> wrote: > Larry Bates wrote: > > I'm not completely sure I understand the question but here goes. > > Instances of > > classes are classes can be stored in lists or dictionaries. In lists you > > reference them via their index (or iterate over them) and in dictionaries > > you can give them a name that is used as a key. > > I wish if it were that simple :). > > Here is a longer description - I have a function that given input creates a > custom class and returns it back. The user is free to subclass that (even > more, he should do that), and of course he will make instances of those > subclasses. Now, my question is how to keep track of subclasses and their > instances, without the need for user interaction (appending them to a list, > or adding to dictionary)? > > Thanks, > > -- > Karlo Lozovina - Mosorclass Meta(type): What about the following solution? class Meta(type): def __new__(mcl,*args,**kw): class_ = super(Meta,mcl).__new__(mcl,*args,**kw) mcl._classes.append(class_) class_._instances = [] return class_ _classes = [] def factory(): class Class(object): __metaclass__ = Meta def __new__(cls,*args,**kw): instance = super(Class,cls).__new__(cls,*args,**kw) cls._instances.append(instance) return instance return Class >>> A = factory() >>> class B(A): pass ... >>> a = A() >>> b = B() >>> Meta._classes [, ] >>> A._instances [] >>> B._instances [<__main__.B object at 0xb7dbb0ec>] So, you see that you can access all classes, their subclasses, and instances from Meta. Of course in a more elaborate version _classes and _instances should store weak references, so that classes and instances can actually be deleted. I also haven't explored under which circumstances this can break ... I can imagine different use cases for this, (though they certainly are non-standard :-)). I once contemplated the (toy-) implementation of a frame-based knowledge representation system using Python's object model, where one definitely needs classes to keep track of their instances ... Cheers, Andreas From bbxx789_05ss at yahoo.com Sat Oct 27 04:05:38 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 27 Oct 2007 01:05:38 -0700 Subject: transmit an array via socket In-Reply-To: References: Message-ID: <1193472338.008579.192310@19g2000hsx.googlegroups.com> On Oct 26, 11:52 pm, "Jeff Pang" wrote: > I want to transmit an array via socket from a host to another. > How to do it? thank you. > Try this: client: ------- import socket s = socket.socket() host = 'localhost' port = 3030 s.connect( (host, port) ) arr = [1, 2, 3] for elmt in arr: send_str = "%s," % str(elmt) while send_str: chars_sent = s.send(send_str) send_str = send_str[chars_sent:] s.close() server: ------- import socket s = socket.socket() host = "localhost" port = 3030 s.bind((host, port)) s.listen(5) while("Ctrl-C hasn't been entered"): new_sock, addr = s.accept() data_list = [] while True: partial_data = new_sock.recv(1012) data_list.append(partial_data) if not partial_data: #then got all the data break data_str = ''.join(data_list)[:-1] #chop off trailing comma arr_strs = data_str.split(",") arr_ints = [int(elmt) for elmt in arr_strs] print arr_ints From gagsl-py2 at yahoo.com.ar Fri Oct 19 22:25:45 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Oct 2007 23:25:45 -0300 Subject: __main__ : What is this? References: <1192839982.488484.102860@e34g2000pro.googlegroups.com> Message-ID: En Fri, 19 Oct 2007 21:26:22 -0300, Matimus escribi?: > The common pattern: > > if __name__ == "__main__": > # do stuff > > IMHO better written: > > if "__main__" == __name__: > # do stuff I'm intrigued why do you feel the second alternative is better. Which is your native language? In English (and Spanish, and many others but still not in the majority) the usual ordering is "subject-verb-object" or SVO, which matches the first alternative: "If the name is __main__, do this..." As all the languages I know (not so many!) are SVO, I can't think of any equivalent of the second form [that I could say it's better than the first] -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Tue Oct 16 18:16:27 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 17 Oct 2007 00:16:27 +0200 Subject: Newbi Q: Recursively reverse lists but NOT strings? In-Reply-To: <47153796$0$14258$426a74cc@news.free.fr> References: <53396d9e0710141406p6182bdat789fe1706225f345@mail.gmail.com> <47153796$0$14258$426a74cc@news.free.fr> Message-ID: <47153872$0$14258$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : > answering to Dmitri O.Kondratiev (snip) > > def reverse(xs): > if xs: > return xs > else: > return (reverse (xs[1:])) + [xs[0]] I meant: def reverse(xs): if not xs: (etc...) of course... From nick at craig-wood.com Mon Oct 8 13:30:13 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 08 Oct 2007 12:30:13 -0500 Subject: changes on disk not visible to script ? References: <1191850024.006823.101610@r29g2000hsg.googlegroups.com> <1191852713.859771.109190@19g2000hsx.googlegroups.com> Message-ID: Bruce wrote: > On 8 Okt, 15:56, Richie Hindle wrote: > > [Bruce] > > > > > f.close() > > > cmd = "echo %s | %s"%(argument_file,the_program) > > > > Either: you are a VB programmer and you've actually typed "f.close" rather > > than "f.close()", > > You are right, I forgot the () in f.close() ! > thanks for pointing that out. > > VB programmer!? Thats really harsh.. I used to make that mistake a lot as an ex-perl programmer. I think ruby is the same. pychecker will warn about it though. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bj_666 at gmx.net Mon Oct 22 06:14:01 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Oct 2007 10:14:01 GMT Subject: python with braces pre-processor References: Message-ID: <5o3bf9FktnthU3@mid.uni-berlin.de> On Mon, 22 Oct 2007 09:44:27 +0000, Paul Brauner wrote: > Hi, I'm working on a project that outputs several languages including > (hopefully) python. My problem is that the generic backend architecture > has not been designed to output correctly indented code, and that would > be helpful if there were somewhere a python pre-processor that would take > python with braces as an input and output regular python code. I thought > that it must exists because everyone generating python code will > encounter more or less the same problem, but I didn't find any 'official' > thing on the subject. Maybe (almost) nobody feels the need to generate Python source code. The language is so dynamic that there are almost always ways to avoid source code generation. Maybe you can generate a token stream and use `tokenize.untokenize()` to generate the source code!? Ciao, Marc 'BlackJack' Rintsch From lasses_weil at klapptsowieso.net Sun Oct 7 11:49:04 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 07 Oct 2007 17:49:04 +0200 Subject: Newbie packages Q In-Reply-To: <1191771348.165051.36790@50g2000hsm.googlegroups.com> References: <1191755440.850529.288860@o3g2000hsb.googlegroups.com> <1191763497.852128.130710@k79g2000hse.googlegroups.com> <4708ebfc$0$21561$426a74cc@news.free.fr> <1191768074.585609.251570@22g2000hsm.googlegroups.com> <4708f9b7$0$4527$9b4e6d93@newsspool3.arcor-online.net> <1191771348.165051.36790@50g2000hsm.googlegroups.com> Message-ID: <4708fff0$0$4523$9b4e6d93@newsspool3.arcor-online.net> MarkyMarc wrote: > ******************************* > atest.py: > > def printA(): > print "This is Atest from Apack" > ******************************* > btest.py: > from Test.apack import atest > > def printB(): > print "This is Btest from Bpack" > > def printatest(): > print atest.printA() > > print printB() > print printatest() > ******************************* > > Now only one of them imports the other, and this most be the simplest > way of illustrating the intra-package references. > But how do I get this to work? > This doesn't work? What error do you get? I've never done too complicated packaging stuff, and can't raelly testdrive your example right now. Maybe you have to look into sys.path if Test can be found at all. Or maybe you have to play with the import statement (from apack import atest?). I'm just guessing here; importing continues to remain going on being a mystery to me. /W From gagsl-py2 at yahoo.com.ar Sun Oct 21 14:05:45 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Oct 2007 15:05:45 -0300 Subject: compiler module bug? References: <7DEB606B-7856-4140-ADA9-4083EC22D380@bryant.edu> <01E5EB0B-6904-438C-B9DD-B27310C0381D@bryant.edu> Message-ID: En Sun, 21 Oct 2007 14:33:00 -0300, Brian Blais escribi?: > On Oct 21, 2007, at Oct 21:1:15 PM, Gabriel Genellina wrote: >> The comment itself is not a problem; but the last line in the >> source must >> end in a newline. > > then, even if it is known problem, the docs are wrong. the two > (parseFile(path) and parse(open(path).read())) are *not* the same: > one can handle a file which doesn't end in a newline, another one > can't handle the same file. Feel free to submit a bug report to http://bugs.python.org > Can one hack it like: > > filestr=open(filename).read() > filestr+="\n" The parseFile function does exactly that, along with this comment: # XXX The parser API tolerates files without a trailing newline, # but not strings without a trailing newline. Always add an extra # newline to the file contents, since we're going through the string # version of the API. The compile function in py_compile.py that I've menctioned earlier does the same but only when needed: f = open(file, 'U') codestring = f.read() f.close() if codestring and codestring[-1] != '\n': codestring = codestring + '\n' -- Gabriel Genellina From yanzinmeister at googlemail.com Tue Oct 9 22:52:16 2007 From: yanzinmeister at googlemail.com (yanzinmeister at googlemail.com) Date: Wed, 10 Oct 2007 02:52:16 -0000 Subject: xyplot in Control desk from dspace Message-ID: <1191984736.397820.315610@19g2000hsx.googlegroups.com> Hello everyone, i'm new user of python, in fact, i'm using Control Desk from dsPACE. I just want to change the programm a bit to fit to my application. I draw xyplot using virsual instrument xyplot in Control Desk, and i want to delect any curses if it's needed. But in Control Desk the xyplot is time signal, i can not simply delect it. The visual instrument is set up from python programming. So i want to know the princip of xyplot in python, and then i can draw the needed curses in backgroud's color. In this way, the curses seems as delected. I appreciate very much if anyone can give me help or useful advice. From robert.rawlins at thinkbluemedia.co.uk Mon Oct 22 10:46:51 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 22 Oct 2007 15:46:51 +0100 Subject: Check File Change Every 10 Seconds In-Reply-To: <471CB652.5070802@timgolden.me.uk> References: <27459.1491478079$1193048158@news.gmane.org> <471CB652.5070802@timgolden.me.uk> Message-ID: <005101c814ba$632830b0$29789210$@rawlins@thinkbluemedia.co.uk> Spot on Tim, I'm running Linux, I totally forgot to mention... more detail coming in a reply to Gabriel's post. -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Golden Sent: 22 October 2007 15:40 Cc: python-list at python.org Subject: Re: Check File Change Every 10 Seconds Gabriel Genellina wrote: > En Mon, 22 Oct 2007 06:56:52 -0300, Robert Rawlins - Think Blue > escribi?: > >> I've got a requirement to check a file for a change every 10 seconds or >> so, >> and if the file has been modified since the last time I parsed its >> content >> into the application then I need to parse it in again. However, I need >> this >> process to not interrupt the rest of my application flow. > > See this article by Tim Golden: > http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html > >> What is the best way to handle this? Is there some form of file watcher >> module for python which can watch the file for me and then parse any >> changes >> into the application memory? Or should I be spawning and unjoined thread >> which contains and infinite loop which checks a date/time the file was >> modified against an internal date/time variable for when the application >> last parsed the file into memory? > > I would use a different thread waiting for notifications from > ReadDirectoryChangesW (third option in the link above) > See http://msdn2.microsoft.com/en-us/library/aa365465.aspx for more info > on ReadDirectoryChangesW > Although Robert doesn't say so here, I seem to remember that his past posts have indicated a *nix setting. Robert? TJG -- http://mail.python.org/mailman/listinfo/python-list From dlee at altaregos.com Mon Oct 1 13:16:49 2007 From: dlee at altaregos.com (Daryl Lee) Date: Mon, 01 Oct 2007 11:16:49 -0600 Subject: Limits on search length Message-ID: <47012B81.40100@altaregos.com> I am trying to locate all lines in a suite of files with quoted strings of particular lengths. A search pattern like r'".{15}"' finds 15-character strings very nicely. But I have some very long ones, and a pattern like r'".{272}"' fails miserably, even though I know I have at least one 272-character string. In the short term, I can resort to locating the character positions of the quotes, but this seemed like such an elegant solution I hate to see it not work. The program is given below (sans imports), in case someone can spot something I'm overlooking: # Example usage: search.py *.txt \".{15}\" filePattern = sys.argv[1] searchPattern = sys.argv[2] cpat = re.compile(searchPattern) for fn in glob.glob(filePattern): f = open(fn, "r") if f: lineNumber = 0 for line in f: lineNumber += 1 m = cpat.search(line) if m is not None: print fn, "(", lineNumber, ")", line f.close() -- Daryl Lee Open the Present -- it's a Gift! From duncan.booth at invalid.invalid Sun Oct 28 11:51:10 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Oct 2007 15:51:10 GMT Subject: how to convert tuple to a "list of single values" ? References: Message-ID: stef mientki wrote: > hello, > > The next piece of code bothers me: > > ptx, pty, rectWidth, rectHeight = self._point2ClientCoord (p1, p2 ) > dc.SetClippingRegion ( ptx, pty, rectWidth, rectHeight ) > > Because I want to write it in 1 line, > and without the use of intermediate variables (for which I have to > invent names ;-) > like this: > > dc.SetClippingRegion ( self._point2ClientCoord (p1, p2 ) ) Try: dc.SetClippingRegion ( *self._point2ClientCoord (p1, p2 ) ) From vinay_sajip at yahoo.co.uk Sat Oct 20 15:18:34 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sat, 20 Oct 2007 12:18:34 -0700 Subject: logging module - restricted mode error In-Reply-To: <87przflpir.fsf@rudin.co.uk> References: <87przflpir.fsf@rudin.co.uk> Message-ID: <1192907914.138999.114910@k35g2000prh.googlegroups.com> On 16 Oct, 04:14, Paul Rudin wrote: > I'm occasionally seeing tracebacks like this: > > Traceback (most recent call last): > File "logging/__init__.py", line 744, in emit > File "logging/__init__.py", line 630, in format > File "logging/__init__.py", line 421, in format > RuntimeError: instance.__dict__ not accessible in restricted mode > > I'm not sure what it means. Googling leads me to > but that says that those > modules were disabled in 2.3 and I'm running 2.5.1. In any case I'm > not using them (although it could be that one of the 3rd party modules > I'm using does something.) > > Could someone please explain what this error means? Can you say a little bit more about the execution environment? For example, are you running under mod_python? If so, which version? When googling, did you search for the exact text of the error message? For example, did you see the following post? http://mail-archives.apache.org/mod_mbox/httpd-python-dev/200404.mbox/%3C408661A5.3010001 at sjsoft.com%3E Vinay Sajip From mellit at gmail.com Sun Oct 28 13:45:29 2007 From: mellit at gmail.com (Anton Mellit) Date: Sun, 28 Oct 2007 17:45:29 -0000 Subject: Pari Python Message-ID: <1193593529.388263.211930@z9g2000hsf.googlegroups.com> Hi, I am working on a Pari-Python module (see about GP/PARI at http://pari.math.u-bordeaux.fr/). Similar project was started by Stefane Fermigier 12 years ago (you can find a post about it on this newsgroup). You can see some screenshots on my blog (http:// mellit.wordpress.com/2007/10/28/pari-python/). I reproduce the text on my blog here. I finished some working version of the pari-python module. I tried to make it is close as possible to the standard PARI shell, at the same time using the standard python syntax. Here I put some screenshots. I didn?t make a proper package distribution for python (the code still looks ugly and I still don't know how to make proper distributions), but if someone is interested to test it send me an email. This is in early alpha stage. A lot of things are not working. I imported almost all functions of gp by an automated perl script but I don?t know which of them actually work and which not. There are two special difficulties you may notice about python. The first one is the power operation. In python it is ?**?, whereas ?^? is reserved for the bitwise xor. I made some little changes to the python source so that ?^? and ?^=? now work as power, and ?^^? and ?^^=? work as xor if you still want to use it. This is done by modifying about 30 lines of source code in several files: Include/token.h, Modules/ parsermodule.c, Parser/tokenizer.c, Python/ast.c, Grammar/Grammar. The second difficulty is that expressions like ?1/2? produce 0 in python. For this my module installs my own handler for the operation ?divide? for integers and longs. That?s it. In other respects it is a normal python module. I will greatly appreciate any feedback. Anton From paul.hankin at gmail.com Wed Oct 17 19:12:15 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 17 Oct 2007 23:12:15 -0000 Subject: if instance exists problem .. In-Reply-To: References: Message-ID: <1192662735.463554.165450@e9g2000prf.googlegroups.com> On Oct 17, 11:39 pm, stef mientki wrote: > the test if an instance exists, always returns false. > ini = inifile (filename) > if ini: > print 'ok',type(ini) > else: > print 'wrong',type(ini) > > Why is that ? > What should I do to the same simple test for existance ? First, object construction always gives you an object or raises an exception, so you don't have to test for existence. If you don't know if an object has been created, you should initialise ini to None, and test with 'if ini is not None:'. 'if x' doesn't test if x exists, it tests if x when cast to a bool is True. ConfigParser acts like a container, and returns False if it's empty. Your class is (indirectly) a subclass of ConfigParser, but is never initialised as such, and so is empty. So 'if ini' returns False, and you get your confused result. You need to decide if inifile is a subclass of ConfigObj, or is a wrapper round a ConfigObj. Probably you want the former and your init method should be something like: def __init__(self, filename): ConfigObj.__init__(self, filename, list_values=False, write_empty_values=True) self.newlines = '\r\n' self.Section = '' self.Modified = False -- Paul Hankin From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Oct 4 06:38:42 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 04 Oct 2007 12:38:42 +0200 Subject: module confusion In-Reply-To: References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> <874ph8sdhx.fsf@benfinney.id.au> Message-ID: <4704c2a0$0$30562$426a74cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message , Carsten > Haese wrote: > >> On Thu, 2007-10-04 at 11:11 +1300, Lawrence D'Oliveiro wrote: >> >>> In Python, all names _are_ variables. They are not "bound" to objects. >>> The value of os.path is a pointer. >> No. "os.path" refers to the object that's known as the "path" attribute >> of the object known as "os". That object, in turn, is a module. > > No, it's a variable. It just happens to contain a pointer to a module. Lawrence, you should have a look at CPython's source code. And at other implementations too. Python's "variables" *really* are name/object pairs - most of the time key/value pairs in a dict. The name itself is just that : a name. It doesn't "contains" anything, it's *not* a label for a memory address, it's *only* a name. >>> It's implemented as a pointer, >> While it is true that namespaces are implemented in CPython as >> collections of pointers to PyObject structures, that's an irrelevant >> implementation detail. I doubt that they are implemented as pointers in >> Jython, PyPy, or IronPython. > > I'll bet they are. Since Java doesn't have pointers, you lost your bet. >>> it has all the semantics of a pointer. >> No, it doesn't. A pointer means the physical address of a memory >> location, which implies that you can overwrite that memory location. Can >> you do that in Python? > > Yes. Look up the definition of "mutable objects". I think Carsten knows this definition. But it has nothing to do with "overwriting a memory location" - like you could do in C using pointers. From gagsl-py2 at yahoo.com.ar Wed Oct 24 00:39:01 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Oct 2007 01:39:01 -0300 Subject: tracking/ordering log files References: <1193165204.000752.268220@i38g2000prf.googlegroups.com> <1193170083.610513.149390@e34g2000pro.googlegroups.com> Message-ID: En Tue, 23 Oct 2007 17:08:03 -0300, nik escribi?: > I think it is called "logfile rotation" and see some links about > log4py, but no description of what that is. See the logging package; in particular, you want a RotatingFileHandler. -- Gabriel Genellina From R.Brodie at rl.ac.uk Tue Oct 2 10:58:06 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 2 Oct 2007 15:58:06 +0100 Subject: Dictionary invalid token error References: Message-ID: "brad" wrote in message news:fdtlqo$t1t$1 at solaris.cc.vt.edu... > Why does 09 cause an invalid token while 9 does not? 9 isn't a valid octal digit. You probably want to use strings for storing telephone number like codes, if leading zeroes are significant. From bj_666 at gmx.net Mon Oct 29 11:51:24 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Oct 2007 15:51:24 GMT Subject: Built-in functions and keyword arguments References: <1193665924.886459.20710@v3g2000hsg.googlegroups.com> <1193672098.625545.321250@22g2000hsm.googlegroups.com> Message-ID: <5omdrsFneqbaU2@mid.uni-berlin.de> On Mon, 29 Oct 2007 08:34:58 -0700, Armando Serrano Lombillo wrote: > On Oct 29, 3:10 pm, Duncan Booth wrote: >> >> I don't know if the reason that most builtin functions don't accept >> keywords is just historical (someone would have to go through a lot of >> code and add keyword argument names) or if there really is any >> measurable performance difference to not using the METH_KEYWORDS option. >> Being able to write less C code may be the main factor. > > Ok. I was suspecting something like this. Performance issues aside, I > think it would be a good idea if built-in functions behaved exactly > the same as normal functions. As Steven D'Aprano showed they behave like normal functions. Even pure Python functions can have arguments without names: def spam(*args): pass Ciao, Marc 'BlackJack' Rintsch From exarkun at divmod.com Mon Oct 29 13:37:42 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 29 Oct 2007 12:37:42 -0500 Subject: Built-in functions and keyword arguments In-Reply-To: <009f01c81a4d$ff023d80$03000080@hendrik> Message-ID: <20071029173742.8162.554468338.divmod.quotient.29276@ohm> On Mon, 29 Oct 2007 19:03:34 +0200, Hendrik van Rooyen wrote: >"Tim Chase" > >> > I think you are being a little bit unfair here: help(len) says: >> > >> > len(...) >> > len(object) -> integer >> > >> > Return the number of items of a sequence or mapping. >> > >> > which implies that the argument to len has the name 'object' (although in >> > fact it doesn't have a name). >> >> And to confound matters even further for the uninitiated, >> >> http://docs.python.org/lib/built-in-funcs.html#l2h-45 >> >> says that it's "len(s)" instead (but "len(s=[])" doesn't work either) > >Looks like a gotcha to me - its the difference between a keyword >(master = 42) and an assignment (s='I am a string') > But it's not a keyword: >>> len(s=[]) Traceback (most recent call last): File "", line 1, in ? TypeError: len() takes no keyword arguments >>> I think that's the issue here. Jean-Paul From mail at timgolden.me.uk Fri Oct 5 04:42:41 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 05 Oct 2007 09:42:41 +0100 Subject: Cross platform way of finding number of processors on a machine? In-Reply-To: <1191571759.756054.319730@o80g2000hse.googlegroups.com> References: <1191554907.422787.197740@y42g2000hsy.googlegroups.com> <66d0a6e10710042102m5e7bf9a9i9c6e7ff5c796c608@mail.gmail.com> <1191571759.756054.319730@o80g2000hse.googlegroups.com> Message-ID: <4705F901.8070104@timgolden.me.uk> [Tim Golden] >> """ >> Windows Server 2003, Windows XP, and Windows 2000: >> This property is not available. >> """ >> >> since it's presumably not available in anything earlier either, >> that leaves you with Vista or the early-adopter editions of the >> next Windows Server product. Kay Schluehr wrote: > Remarkable. I've a two years old Windows XP dual core notebook and > when I'm asking Python I get the correct answer: > >>>> import os >>>> os.environ['NUMBER_OF_PROCESSORS'] > 2 > > However this feature might not be guaranteed by Microsoft for > arbitrary computers using their OS? Ahem. I was referring (and not very clearly, now I look back at my post) to a particular property within the WMI class, not to the general concept of counting processors. TJG From deets at nospam.web.de Sun Oct 14 06:08:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 14 Oct 2007 12:08:52 +0200 Subject: Entering username & password automatically using urllib.urlopen In-Reply-To: <1192333275.927370.83790@i13g2000prf.googlegroups.com> References: <1192333275.927370.83790@i13g2000prf.googlegroups.com> Message-ID: <5ne85rFhraaeU1@mid.uni-berlin.de> rodrigo schrieb: > I am trying to retrieve a password protected page using: > > get = urllib.urlopen('http://password.protected.url"').read() > > While doing this interactively, I'm asked for the username, then the > password at the terminal. > Is there any way to do this non-interactively? To hardcode the user/ > pass into the script so I can get the page automatically? > > (This is not a cracking attempt, I am trying to retrieve a page I have > legitimate access to, just doing it automatically when certain > conditions are met.) Is that HTTP-auth? Then this might help: http://www.voidspace.org.uk/python/articles/authentication.shtml BTW, use urllib2. Diez From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Oct 31 09:25:00 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 31 Oct 2007 14:25:00 +0100 Subject: marshal vs pickle References: Message-ID: <5ore1cFo0djvU2@mid.individual.net> Evan Klitzke wrote: > Can anyone elaborate more on the difference between marshal and > pickle. In what conditions would using marshal be unsafe? If one > can guarantee that the marshalled objects would be created and > read by the same version of Python, is that enough? Just use pickle. From the docs: | The marshal module exists mainly to support reading and writing | the ``pseudo-compiled'' code for Python modules of .pyc files. | Therefore, the Python maintainers reserve the right to modify the | marshal format in backward incompatible ways should the need | arise. If you're serializing and de-serializing Python objects, | use the pickle module instead. Regards, Bj?rn -- BOFH excuse #421: Domain controller not responding From Graham.Dumpleton at gmail.com Tue Oct 23 02:33:11 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 23 Oct 2007 06:33:11 -0000 Subject: Monitoring external processes In-Reply-To: <1193116191.769987.198560@z24g2000prh.googlegroups.com> References: <1193116191.769987.198560@z24g2000prh.googlegroups.com> Message-ID: <1193121191.865066.13950@v29g2000prd.googlegroups.com> On Oct 23, 3:09 pm, arunasu... at gmail.com wrote: > Hi, > > Is there a way to track external processes launched by python on the > Mac? I am using subprocess module to launch the process. > > Thanks > Sunil If using Python 2.3/2.4, you can use os.wait(). If using Python 2.5, there is also have os.wait3() and os.wait4(). See the operating system manual pages for the difference. Ie., man wait4 Graham From dinesh.vadhia at theworkssoftware.com Tue Oct 23 17:44:29 2007 From: dinesh.vadhia at theworkssoftware.com (dineshv) Date: Tue, 23 Oct 2007 14:44:29 -0700 Subject: Lists and Sublists Message-ID: <1193175869.803399.43650@y27g2000pre.googlegroups.com> We have a list of N (>2,000) keywords (of datatype string). Each of the N keywords has associated with it a list of names of varying numbers. For example, keyword(1) will have a list of L1 names associated with it, keyword(2) will have a list of L2 names associated with it and so on with L1 not equal to L2 etc. All keywords and names are immutable. Given a keyword(n) , we want to get hold of the associated list of Ln names. At anytime, we also want to add keywords to the list of N keywords, and to any of the associated Ln lists - both of which will grow to very large sizes. The data will be read into the Python data structure(s) from disk storage. I am struggling to work out what is the ideal Python data structure for the above. Any help would be greatly appreciated. Dinesh From dpholmes at gmail.com Tue Oct 23 21:10:31 2007 From: dpholmes at gmail.com (dpholmes at gmail.com) Date: Tue, 23 Oct 2007 18:10:31 -0700 Subject: web.py & postgresql error In-Reply-To: <1193103986.278189.112900@v29g2000prd.googlegroups.com> References: <1193101575.928334.17790@e9g2000prf.googlegroups.com> <1193103986.278189.112900@v29g2000prd.googlegroups.com> Message-ID: <1193188231.140130.32720@e9g2000prf.googlegroups.com> On Oct 23, 10:15 am, Adam Atlas wrote: > On Oct 22, 9:06 pm, dphol... at gmail.com wrote: > > > hi everyone, i'm very new to python and to this forum. i'm actually > > just trying to work through the tutorial on webpy.org. so far, so > > good, but as i tried to incorporate a postgresql database into the > > demo web app i'm receiving this error print out: > > > [...] > > ImportError: No module named pgdb > > > any thoughts would be greatly appreciated. > > thanks, > > doug > > It looks like you just haven't installed PyGreSQL yet. > > Future web.py questions should probably be directed to the web.py > group , though. Thanks for the help, installing PyGreSQL was the key, I was unaware that PostGreSQL was not all I needed. Thanks again. From lmierzej at o2.pl Sun Oct 14 17:57:12 2007 From: lmierzej at o2.pl (Lukasz Mierzejewski) Date: Sun, 14 Oct 2007 21:57:12 +0000 (UTC) Subject: pydev code completion problem References: <1192394167.058669.117830@q5g2000prf.googlegroups.com> Message-ID: On Sun, 14 Oct 2007 20:36:07 +0000, cyberco wrote: > Confirmed (with exactly the same software). > > Please discuss this issue at the PyDev discussion forum: > http://sourceforge.net/forum/forum.php?forum_id=293649 Thank you for replay, but I'm still not sure what to think about it... Marc 'BlackJack' Rintsch in his replay to my post says that it would be to complicated for IDE to keep track of all objects... isn't he right? From sudharsh at gmail.com Wed Oct 31 13:18:15 2007 From: sudharsh at gmail.com (sudharsh at gmail.com) Date: Wed, 31 Oct 2007 17:18:15 -0000 Subject: Building libraries that my extensions can use. [distutils] Message-ID: <1193851095.711200.268270@z24g2000prh.googlegroups.com> Hello all, I want to create a shared object that my extension modules can dynamically load with intact symbols across modules. Searching the documentation lead me to distutils.ccompiler. Quite frankly comprehending this has been difficult for the newbie in me. I did google (..and krugle) for setup scripts that use this but they seem to be designed for medium to large projects. Mine is quite small to modify the ccompiler class. o (foo.so) / \ / \ / \ / \ bar.c baz.c So in my setup script i would like to have 'foo' under the libraries list in setup(). Is there a dummy' guide for this, or atleast a pretty basic example which I might pick upon given the simplicity. I did try this libraries=[("foo", {'sources'=src_dir, 'include_dirs'=dir, 'libraries' = some_external_thingy})] And it seems to build fine but I find that symbols in the object file are not visible to the others.. Am I in a state of confusion or what...=(, Anyone please guide me out of this by pointing me to a trivial example.. Thanks, Sudharshan S From cool.vimalsmail at gmail.com Wed Oct 3 05:18:45 2007 From: cool.vimalsmail at gmail.com (vimal) Date: Wed, 03 Oct 2007 09:18:45 -0000 Subject: generating range of numbers Message-ID: <1191403125.540152.72320@22g2000hsm.googlegroups.com> hi all, i am new to python..... i just want to generate numbers in the form like: 1,2,4,8,16,32.....to a maximum of 1024 using a range function From oliphant.travis at ieee.org Mon Oct 22 18:49:15 2007 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Mon, 22 Oct 2007 17:49:15 -0500 Subject: Committing latest patch on Issue 708374 to SVN (adding offset to mmap) In-Reply-To: References: Message-ID: Travis Oliphant wrote: > Hi all, > > I think the latest patch for fixing Issue 708374 (adding offset to mmap) > should be committed to SVN. > > I will do it, if nobody opposes the plan. I think it is a very > important addition and greatly increases the capability of the mmap module. > > Thanks, > > -Travis Oliphant Sorry for the noise, I sent this to the wrong group. Any comment on the patch is welcome, however. Best regards, -Travis From byte8bits at gmail.com Fri Oct 12 16:40:54 2007 From: byte8bits at gmail.com (brad) Date: Fri, 12 Oct 2007 16:40:54 -0400 Subject: test if email In-Reply-To: References: Message-ID: Florian Lindner wrote: > Hello, > is there a function in the Python stdlib to test if a string is a valid > email address? Nope, most any string with an @ in it could be a valid email addy. Send a message to the addy, if it doesn't bounce, then it's valid. From timr at probo.com Wed Oct 31 02:54:19 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Oct 2007 06:54:19 GMT Subject: clear shell screen References: Message-ID: <3i9gi3himvb64sdu1iel5aq7ps0i3pm7r0@4ax.com> Shawn Minisall wrote: > >Does anyone know how to clear the shell screen completely ? I tried >import os and then os.system("clear") was said to have worked in Windows >XP, but it's just bringing up another window, then it turns black and >then it closes in within about a second moving the prompt at the >os.system("clear") line . I've also tried os.system("cls") with the >same results. os.system('cls') works just fine from a command shell. I just tried it. Are you running from inside Pythonwin? If so, then what you are looking at is not a "shell screen" in any way. It's a simulation, and I don't know of any way to clear it. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From cokofreedom at gmail.com Mon Oct 22 08:58:48 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 22 Oct 2007 12:58:48 -0000 Subject: Iteration for Factorials In-Reply-To: References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <5o3jalFl0n43U1@mid.uni-berlin.de> <1193056647.416562.36150@q3g2000prf.googlegroups.com> Message-ID: <1193057928.591463.107650@t8g2000prg.googlegroups.com> On Oct 22, 2:43 pm, Marco Mariani wrote: > Py-Fun wrote: > > def itforfact(n): > > while n<100: > > print n > > n+1 > > n = input("Please enter a number below 100") > > You function should probably return something. After that, you can see > what happens with the result you get. lambda n: n<=0 or reduce(lambda a,b: long(a)*long(b),xrange(1,n+1)) From scripteaze at gmail.com Mon Oct 29 05:03:14 2007 From: scripteaze at gmail.com (scripteaze at gmail.com) Date: Mon, 29 Oct 2007 09:03:14 -0000 Subject: sharing vars with different functions Message-ID: <1193648594.380143.153450@o38g2000hse.googlegroups.com> Im tryin to call a var thats sitting in a function, example: class someclass(object): somevar = open(blah, 'r').readlines() def something(): for line in somevar: print line ----------------------------------------------------------------------- i guess im not graspng the whole global or local var topic.. Any examples?? From brunobgDELETETHIS at users.sourceforge.net Thu Oct 11 11:23:30 2007 From: brunobgDELETETHIS at users.sourceforge.net (Bruno Barberi Gnecco) Date: Thu, 11 Oct 2007 12:23:30 -0300 Subject: RuntimeWarning: tp_compare In-Reply-To: References: Message-ID: Chris Mellon wrote: > On 10/9/07, Bruno Barberi Gnecco > wrote: > >> I'm getting the following exception when I call an external extension >>(pytst): >> >>/usr/lib/python2.5/threading.py:697: RuntimeWarning: tp_compare didn't return -1 or -2 for >>exception >> return _active[_get_ident()] >>Traceback (most recent call last): >> File "testDataMiner2.py", line 77, in >> testPlace() >> File "testDataMiner2.py", line 41, in testPlace >> data = db.getDescription(event['id']) >> File "testDataMiner2.py", line 28, in getDescription >> return self.getRow(query, (id,)) >> File "../database.py", line 73, in getRow >> self.readlock.acquire() >> File "/usr/lib/python2.5/threading.py", line 94, in acquire >> me = currentThread() >> File "/usr/lib/python2.5/threading.py", line 697, in currentThread >> return _active[_get_ident()] >>UnicodeEncodeError: 'ascii' codec can't encode character u'\xfa' in position 52: ordinal >>not in range(128) >>awer >> > /usr/lib/python2.5/threading.py(700)currentThread() >>-> return _DummyThread() >> >> >> Note that the error occurs *after* the call that I isolated as >>affecting it (pytst.scan(), in the case). This doesn't happen for simple, >>isolated cases, but googling for "tp_compare threading" shows a lot of >>similar issues. Does anybody here know what this could be about? Any ideas >>to debug or work around it? >> > > > The various thread issues in the traceback aside, it looks like the > problem is that you passed a unicode object to pytst, which only > accepts plain (ascii) strings. That seems to have solved it. Thanks! -- Bruno Barberi Gnecco There is no time like the pleasant. From paulgeeleher at gmail.com Mon Oct 15 11:09:23 2007 From: paulgeeleher at gmail.com (sophie_newbie) Date: Mon, 15 Oct 2007 08:09:23 -0700 Subject: Setting a timeout for a cookie Message-ID: <1192460963.317397.213010@e9g2000prf.googlegroups.com> Hi, I'm wondering how do you set a 'timeout' or expiry date/time for a cookie set using a python cgi script. I can set a cookie ok but I dunno how to set the expiry time so it always expires at the end of the session. Thanks! From http Tue Oct 23 00:59:13 2007 From: http (Paul Rubin) Date: 22 Oct 2007 21:59:13 -0700 Subject: Committing latest patch on Issue 708374 to SVN (adding offset to mmap) References: Message-ID: <7xmyua77fi.fsf@ruckus.brouhaha.com> Travis Oliphant writes: > I think the latest patch for fixing Issue 708374 (adding offset to > mmap) should be committed to SVN. I can't figure out what this is about from the issue tracker without examining the patch. It looks like the patch has been accepted; could you please also check in a doc fix explaining the new functionality? From devraj at gmail.com Thu Oct 11 18:21:18 2007 From: devraj at gmail.com (Devraj) Date: Thu, 11 Oct 2007 22:21:18 -0000 Subject: urllib.ProxyHandler HTTPS issues In-Reply-To: <87641d8pzb.fsf@pobox.com> References: <1192078997.453819.323390@22g2000hsm.googlegroups.com> <87641d8pzb.fsf@pobox.com> Message-ID: <1192141278.464551.182390@e9g2000prf.googlegroups.com> Thanks John. Will investigate sending the CONNECT command to handle proxies. Do you recommend doing this for HTTP proxies as well or should I just use the ProxyHandler for HTTP proxies? On Oct 12, 4:29 am, j... at pobox.com (John J. Lee) wrote: > Devraj writes: > > Hi everyone, > > > I have been reading various documents/posts on the web about handling > > proxy options in urllib2. Some of them suggest that urllib2 doesn't > > handle HTTPS and others say it does. I have successfully written code > > that relays HTTP connections via a proxy but have failed to do the > > same for HTTPS connections. > > urllib2 does not support "HTTPS proxies" (it does not support use of > the CONNECT method). > > > Can anyone confirm if urllib2 can handle HTTPS, > > Yes, it can. > > John From sjmachin at lexicon.net Mon Oct 15 17:11:27 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 15 Oct 2007 14:11:27 -0700 Subject: Order of tuples in dict.items() In-Reply-To: References: <47122790$0$8421$db0fefd9@news.zen.co.uk> <13h55uj8pogd4ea@corp.supernews.com> Message-ID: <1192482687.653615.182140@v29g2000prd.googlegroups.com> On Oct 16, 12:47 am, Erik Jones wrote: > Not between two consecutive reads, no. However, after any resizing > of a dict the result of Python's hash function for any given newly > inserted key is extremely likely to be different than it would have > been before the resizing, i.e. the method may be the same, but the > result is different. Could you please supply the basis for the above assertion? My reading of the docs for the built-in hash function, the docs for an object's __hash__ method, and the source (dictobject.c, intobject.c, stringobject.c) indicate (as I would have expected) that the hash of an object is determined solely by the object itself, not by the history of insertion into a dict (or multiple dicts!?). Note that position_in dict = some_function(hash(obj), size_of_dict) ... perhaps you are conflating two different concepts. From sjmachin at lexicon.net Tue Oct 16 18:26:02 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 16 Oct 2007 15:26:02 -0700 Subject: negative base raised to fractional exponent In-Reply-To: References: <1192571332.470809.279160@v23g2000prn.googlegroups.com> Message-ID: <1192573562.622390.218860@i38g2000prf.googlegroups.com> On Oct 17, 8:03 am, Steve Holden wrote: > schaefer... at gmail.com wrote: > > Does anyone know of an approximation to raising a negative base to a > > fractional exponent? For example, (-3)^-4.11111 since this cannot be > > computed without using imaginary numbers. Any help is appreciated. > > A couple of questions. > > 1. How do you approximate a complex number in the reals? That doesn't > make sense. > > 2. x ^ -4.1111 = 1 / (x ^ 4.1111), so where do complex numbers enter > into this anyway? > > 3. I think you will find the complex numbers start to emerge as you > explore fractional exponents. This is part of the story -- the other part is that the story differs depending on whether x is positive or negative. > > This being Python, and an interactive interpreter being available, you > can always just try it: > > >>> -3 ** -4.1111 > -0.010927147607830808 Steve, Trying to memorise the operator precedence table for each of several languages was never a good idea. I admit advanced age :-) and give up and use parentheses, just like the OP did: >>> (-3)**-4.11111 Traceback (most recent call last): File "", line 1, in ValueError: negative number cannot be raised to a fractional power Best regards, John From aleax at mac.com Sun Oct 7 19:58:45 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 7 Oct 2007 16:58:45 -0700 Subject: Problem of Readability of Python References: <1191780456.833563.173080@57g2000hsv.googlegroups.com> <1i5m74j.1dpt4l9sbq7zzN%aleax@mac.com> <13giput3mhtvb6c@corp.supernews.com> Message-ID: <1i5mh1z.7kw0621m8tpmpN%aleax@mac.com> Steven D'Aprano wrote: > On Sun, 07 Oct 2007 13:24:14 -0700, Alex Martelli wrote: > > > And yes, you CAN save about 1/3 of those 85 nanoseconds by having > > '__slots__=["zop"]' in your class A(object)... but that's the kind of > > thing one normally does only to tiny parts of one's program that have > > been identified by profiling as dramatic bottlenecks > > Seems to me that: > > class Record(object): > __slots__ = ["x", "y", "z"] > > > has a couple of major advantages over: > > class Record(object): > pass > > > aside from the micro-optimization that classes using __slots__ are faster > and smaller than classes with __dict__. > > (1) The field names are explicit and self-documenting; > (2) You can't accidentally assign to a mistyped field name without Python > letting you know immediately. > > > Maybe it's the old Pascal programmer in me coming out, but I think > they're big advantages. I'm also an old Pascal programmer (ask anybody who was at IBM in the '80s who was the most active poster on the TURBO FORUM about Turbo Pascal, and PASCALVS FORUM about Pascal/Vs...), and yet I consider these "advantages" to be trivial in most cases compared to the loss in flexibility, such as the inability to pickle (without bothering to code an explicit __getstate__) and the inability to "monkey-patch" instances on the fly -- not to mention the bother of defining a separate 'Record' class for each and every combination of attributes you might want to put together. If you REALLY pine for Pascal's records, you might choose to inherit from ctypes.Structure, which has the additional "advantages" of specifying a C type for each field and (a real advantage;-) creating an appropriate __init__ method. >>> import ctypes >>> class Record(ctypes.Structure): ... _fields_ = (('x',ctypes.c_float),('y',ctypes.c_float),('z',ctypes.c_float) ) ... >>> r=Record() >>> r.x 0.0 >>> r=Record(1,2,3) >>> r.x 1.0 >>> r=Record('zip','zop','zap') Traceback (most recent call last): File "", line 1, in TypeError: float expected instead of str instance See? You get type-checking too -- Pascal looms closer and closer!-) And if you need an array of 1000 such Records, just use as the type Record*1000 -- think of the savings in memory (no indirectness, no overallocations as lists may have...). If I had any real need for such things, I'd probably use a metaclass (or class decorator) to also add a nice __repr__ function, etc... Alex From mccredie at gmail.com Wed Oct 24 11:30:37 2007 From: mccredie at gmail.com (Matimus) Date: Wed, 24 Oct 2007 15:30:37 -0000 Subject: win32com.client documentation? In-Reply-To: <1193236546.344635.54080@e9g2000prf.googlegroups.com> References: <1193236546.344635.54080@e9g2000prf.googlegroups.com> Message-ID: <1193239837.697173.108200@i13g2000prf.googlegroups.com> On Oct 24, 7:35 am, Mark Morss wrote: > I am a unix person, not new to Python, but new to Python programming > on windows. Does anyone know where to find documentation on > win32com.client? I have successfully installed this module and > implemented some example code. But a comprehensive explanation of the > objects and methods available is nowhere to be found. I have been > able to find a somewhat out-of-date O'Reilly book, nothing more. > > I want to be able to script the creation of Excel spreadsheets and > Word documents, interract with Access data bases, and so forth. That book, if you are talking about "Python Programming on Win32" by Mark Hamond and Andy Robinson, is the best resource that I know of. There are a few other places for help, and two of those the help files installed on your computer with win32com and the source code. You may be able to find other tutorials and such online. What helped me though was not a better understanding of these packages, but a better understanding of COM in general. Once I had a fair understanding of COM I had a much better experience. I found "Inside COM" by Dale Rogerson to be a good general resource on learning COM, although there are many books on the subject to choose from. I can't really help you any more unless you come up with a specific example of what you are trying to do. Matt From google at mrabarnett.plus.com Fri Oct 19 19:42:24 2007 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 19 Oct 2007 16:42:24 -0700 Subject: Noob: Loops and the 'else' construct In-Reply-To: References: <1192761867.254928.115300@i38g2000prf.googlegroups.com> Message-ID: <1192837344.623098.186960@k35g2000prh.googlegroups.com> On Oct 19, 4:11 am, "Gabriel Genellina" wrote: > En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus > escribi?: > > > I have just come across a site that discusses Python's 'for' and > > 'while' loops as having an (optional) 'else' structure. > > > At first glance I interpreted it as being a bit like the 'default' > > structure in PHP's switch block... But the switch block isn't a loop, > > so, I am now confused as to the reason for using 'else' with the for > > and while loops... > > > A few quick tests basically show that statements in the else structure > > are executed at the fulfillment of the loop's expression (ie, no > > break). > > A `while` loop tests a condition: if it evaluates to true, keep cycling; > if it is false, stop. The `else` clause is executed when the condition is > false, as in any `if` statement. If you exit the loop by using `break`, > the `else` part is not executed (because you didn't get out of the loop by > determining the condition falseness) > > You can think of a `for` loop as meaning `while there are remaining > elements to be iterated, keep cycling` and the `else` clause applies when > there are no more elements. A `break` statement does not trigger the else > clause because the iteration was not exhausted. > > Once you get the idea, it's very simple. > It's useful when you want to search for an item and to do something if you don't find it, eg: for i in items: if is_wanted(i): print "Found it" break else: print "Didn't find ir" From Eric.Foster at modot.mo.gov Tue Oct 30 12:27:22 2007 From: Eric.Foster at modot.mo.gov (Eric.Foster at modot.mo.gov) Date: Tue, 30 Oct 2007 11:27:22 -0500 Subject: Python Instructor Needed for GIS Symposium in April 2008 Message-ID: I am involved with MAGIC http://www.magicgis.org/ an organization to encourage GIS development, sharing, cooperation, etc. and educate practitioners in GIS. We hold a symposium every two years in April (next is April 2008) and provide speakers and workshops in relevant GIS subjects. ESRI's ArcGIS software holds the market majority and has embrace Python language as a preferred scripting, customization language. One area we have trouble with for our symposium is getting instructors for Python workshops. The symposium is in Kansas City on April 20-24, 2008 and the hands on computer based Python course would be held for 4 hours on Sunday April 20th in the afternoon for about 30 beginner and intermediate programmers. We would like some application to ArcGIS, but just basic Python language instruction is also needed. The instructors and speakers as well as the planning committee are asked to volunteer to keep the cost down to symposium attendees. Would you be a good fit (or know anyone) as an instructor for this Introduction to Python language course? The Symposium Steering Committee would like to get a commitment by Nov. 2, 2008 in order to publish a preliminary program. Sorry for the short notice, we thought we had an instructor but do not. We need a short 1-2 paragraph summary or outline of the workshop by the Nov 2, 2008 date, but will accept later considerations. We are willing to help develop any materials needed. Contact me by phone or email if you have questions or would like to volunteer. Thanks. Eric Foster, Senior Transportation Planner MoDOT, 600 NE Colbern Rd. Lee's Summit, MO 64086 (816) 622-6330 -------------- next part -------------- An HTML attachment was scrubbed... URL: From pydecker at gmail.com Tue Oct 16 20:46:25 2007 From: pydecker at gmail.com (Peter Decker) Date: Tue, 16 Oct 2007 20:46:25 -0400 Subject: why doesn't have this list a "reply-to" ? In-Reply-To: <471530E3.9090602@gmail.com> References: <471530E3.9090602@gmail.com> Message-ID: On 10/16/07, stef mientki wrote: > I'm always have great difficulties, replying to this beautiful and > helpful list. > > When I hit the reply button, > the message is sent personally to the sender and not to the list. > I've subscribed to dozen's of lists, > and all have an "reply-to" address, that points to list and not to the > individual. Don't you write your applications so that the default behavior isn't what is expected? I'm writing this message to the *list*, not to you. Anyone who gets it only gets it from the *list*, not from me. Pretending that this message in your inbox is not from the list is just silly. The only people who defend this practice usually don't use the email interface anyway. They're also the people who whine about keeping replies on the list. But hey, we have to sacrifice the practical and useful in the name of enforcing some standards that make little if any sense. -- # p.d. From xah at xahlee.org Mon Oct 29 18:33:54 2007 From: xah at xahlee.org (Xah Lee) Date: Mon, 29 Oct 2007 15:33:54 -0700 Subject: emacs lisp as text processing language... In-Reply-To: <1193697024.171112.28490@t8g2000prg.googlegroups.com> References: <1193697024.171112.28490@t8g2000prg.googlegroups.com> Message-ID: <1193697234.759637.20120@q3g2000prf.googlegroups.com> ... continued from previous post. PS I'm cross-posting this post to perl and python groups because i find that it being a little know fact that emacs lisp's power in the area of text processing, are far beyond Perl (or Python). ... i worked as a professional perl programer since 1998. I started to study elisp as a hobby since 2005. (i started to use emacs daily since 1998) It is only today, while i was studying elisp's file and buffer related functions, that i realized how elisp can be used as a general text processing language, and in fact is a dedicated language for this task, with powers quite beyond Perl (or Python, PHP (Ruby, java, c etc) etc). This realization surprised me, because it is well-known that Perl is the de facto language for text processing, and emacs lisp for this is almost unknown (outside of elisp developers). The surprise was exasperated by the fact that Emacs Lisp existed before perl by almost a decade. (Albeit Emacs Lisp is not suitable for writing general applications.) My study about lisp as a text processing tool today, remind me of a article i read in 2000: ?Ilya Regularly Expresses?, of a interview with Dr Ilya Zakharevich (author of cperl-mode.el and a major contributor to the Perl language). In the article, he mentioned something about Perl's lack of text processing primitives that are in emacs, which i did not fully understand at the time. (i don't know elisp at the time) The article is at: http://www.perl.com/lpt/a/2000/09/ilya.html Here's the relevant excerpt: ? Let me also mention that classifying the text handling facilities of Perl as "extremely agile" gives me the willies. Perl's regular expressions are indeed more convenient than in other languages. However, the lack of a lot of key text-processing ingredients makes Perl solutions for many averagely complicated tasks either extremely slow, or not easier to maintain than solutions in other languages (and in some cases both). I wrote a (heuristic-driven) Perlish syntax parser and transformer in Emacs Lisp, and though Perl as a language is incomparably friendlier than Lisps, I would not be even able of thinking about rewriting this tool in Perl: there are just not enough text-handling primitives hardwired into Perl. I will need to code all these primitives first. And having these primitives coded in Perl, the solution would turn out to be (possibly) hundreds times slower than the built-in Emacs operations. My current conjecture on why people classify Perl as an agile text- handler (in addition to obvious traits of false advertisements) is that most of the problems to handle are more or less trivial ("system maintenance"-type problems). For such problems Perl indeed shines. But between having simple solutions for simple problems and having it possible to solve complicated problems, there is a principle of having moderately complicated solutions for moderately complicated problems. There is no reason for Perl to be not capable of satisfying this requirement, but currently Perl needs improvement in this regard. ? Xah xah at xahlee.org ? http://xahlee.org/ From gagsl-py2 at yahoo.com.ar Sun Oct 21 13:15:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Oct 2007 14:15:18 -0300 Subject: compiler module bug? References: <7DEB606B-7856-4140-ADA9-4083EC22D380@bryant.edu> Message-ID: En Sun, 21 Oct 2007 13:36:46 -0300, Brian Blais escribi?: > I am experiencing a problem with the compiler module. Is this a bug, > or am I doing something wrong? I think it's a well-known fact... > it seems like a comment at the end breaks the parse command, but not > parseFile. Is this reproducible by others? The comment itself is not a problem; but the last line in the source must end in a newline. See the py_compile/compileall modules as an example. -- Gabriel Genellina From cokofreedom at gmail.com Wed Oct 24 10:44:42 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 24 Oct 2007 14:44:42 -0000 Subject: Anagrams In-Reply-To: <1193185723.647144.302410@i13g2000prf.googlegroups.com> References: <1193127665.868582.257380@z24g2000prh.googlegroups.com> <1193185723.647144.302410@i13g2000prf.googlegroups.com> Message-ID: <1193237082.628005.327260@v29g2000prd.googlegroups.com> On Oct 24, 2:28 am, Paul Hankin wrote: > On Oct 23, 9:21 am, cokofree... at gmail.com wrote: > > > This one uses a dictionary to store prime values of each letter in the > > alphabet and for each line multiple the results of the characters > > (which is unique for each anagram) and add them to a dictionary for > > printing latter. > > > def anagram_finder(): > > primeAlpha = {'a':2, 'b':3, 'c':5, 'd':7,'e' : 11, 'f':13, 'g':17, > > 'h':19, \ > > 'i':23, 'j':29, 'k':31, 'l':37, 'm':41, 'n':43, 'o': > > 47, 'p':53, \ > > 'q':59, 'r':61, 's':67, 't':71, 'u':73, 'v':79, 'w': > > 83, 'x':89, \ > > 'y':97, 'z':101} > > ... > > A somewhat nicer start: compute primes (naively) rather than typing > out the dictionary. > > import string > from itertools import ifilter, count > > def anagram_finder(): > primes = ifilter(lambda p: all(p % k for k in xrange(2, p)), > count(2)) > primeAlpha = dict(zip(string.lowercase, primes)) > ... > > -- > Paul Hankin Towards itertools, apart from the lib page on Python does anyone know of good tutorials of their usage...(beyond exploring myself it would be nice to see good examples for usage and effective combinations...) From charlton at netplus.ch Wed Oct 31 05:29:48 2007 From: charlton at netplus.ch (Miss Pfeffe) Date: Wed, 31 Oct 2007 10:29:48 +0100 Subject: dynamically generating temporary files through python/cgi Message-ID: <001d01c81ba0$950291b0$42c50d51@peps> How do you make a python out of a banana?! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Tue Oct 23 13:35:39 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 23 Oct 2007 11:35:39 -0600 Subject: Automatic Generation of Python Class Files In-Reply-To: <471da4b7$0$22586$426a34cc@news.free.fr> References: <1193073156.493809.184110@z24g2000prh.googlegroups.com> <1193076352.576143.123260@z24g2000prh.googlegroups.com> <1193078577.129883.317680@k35g2000prh.googlegroups.com> <471d06e2$0$12275$426a74cc@news.free.fr> <471da4b7$0$22586$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Steven Bethard a ?crit : >> Bruno Desthuilliers wrote: >>> Steven Bethard a ?crit : >>> (snip) >>>> In Python, you can use property() to make method calls look like >>>> attribute access. This could be necessary if you have an existing >>>> API that used public attributes, but changes to your code require >>>> those attributes to do additional calculations now. >>>> >>>> But if you're creating a class for the first time, it should *never* >>>> use property(). There's no need to retrofit anything. >>> >>> May I kindly disagree here ?-) >> >> Of course. ;-) >> >>> Computed attributes are IMHO not only a life-saver when it comes to >>> refactoring. There are cases where you *really* have - by 'design' >>> I'd say - the semantic of a property, but know from the start you'll >>> need computation (for whatever reason). Then what would be the >>> rationale for using explicit getters/setters ? >> >> I'd be interested to hear what these use cases are. > > I once wrote a small ORM-like wrapper for LDAP access, and, for reasons > that might be obvious for anyone having worked with LDAP, I choosed to > keep the record values in the format used by the lower level LDAP lib > and let user code access them thru computed attributes (actually > custom-made descriptors). But this is trying to match an existing API, the only case that I think you *should* be using property(). > I could also list the CS101 examples, like Shape.area, > Rect.bottom_right, Person.age, etc... And yes, some of these attributes > are obviously read-only. That doesn't prevent them from being > semantically *properties*, not *behaviour*. But as I mentioned in another email here, I'd rather know which ones require computation, on the off chance that even the small amount of additional calculation matters (say, for large integers or in a very tight loop). I guess as long as your documentation is clear about which attributes require computation and which don't... STeVe From bj_666 at gmx.net Mon Oct 15 07:20:47 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Oct 2007 11:20:47 GMT Subject: Simple Text Processing Help References: <1192369731.561036.31010@i38g2000prf.googlegroups.com> <1192396632.736910.134070@q5g2000prf.googlegroups.com> <1192445236.310797.91160@z24g2000prh.googlegroups.com> Message-ID: <5nh0oeFhiqfbU3@mid.uni-berlin.de> On Mon, 15 Oct 2007 10:47:16 +0000, patrick.waldo wrote: > my sample input file looks like this( not organized,as you see it): > 200-720-7 69-93-2 > kyselina mocov? C5H4N4O3 > > 200-001-8 50-00-0 > formaldehyd CH2O > > 200-002-3 > 50-01-1 > guanid?nium-chlorid CH5N3.ClH > > etc... That's quite irregular so it is not that straightforward. One way is to split everything into words, start a record by taking the first two elements and then look for the start of the next record that looks like three numbers concatenated by '-' characters. Quick and dirty hack: import codecs import re NR_RE = re.compile(r'^\d+-\d+-\d+$') def iter_elements(tokens): tokens = iter(tokens) try: nr_a = tokens.next() while True: nr_b = tokens.next() items = list() for item in tokens: if NR_RE.match(item): yield (nr_a, nr_b, ' '.join(items[:-1]), items[-1]) nr_a = item break else: items.append(item) except StopIteration: yield (nr_a, nr_b, ' '.join(items[:-1]), items[-1]) def main(): in_file = codecs.open('test.txt', 'r', 'utf-8') tokens = in_file.read().split() in_file.close() for element in iter_elements(tokens): print '|'.join(element) Ciao, Marc 'BlackJack' Rintsch From gneuner2/ at /comcast.net Sat Oct 20 22:41:04 2007 From: gneuner2/ at /comcast.net (George Neuner) Date: Sat, 20 Oct 2007 22:41:04 -0400 Subject: Distributed RVS, Darcs, tech love References: <1192850894.310464.89070@e9g2000prf.googlegroups.com> <1192914246.208743.94870@y27g2000pre.googlegroups.com> <1192929647.405490.318720@v29g2000prd.googlegroups.com> Message-ID: On Sun, 21 Oct 2007 01:20:47 -0000, Daniel Pitts wrote: >On Oct 20, 2:04 pm, llothar wrote: >> > I love math. I respect Math. I'm nothing but a menial servant to >> > Mathematics. >> >> Programming and use cases are not maths. Many mathematics are >> the worst programmers i've seen because they want to solve things and >> much more often you just need heuristics. Once they are into exact >> world they loose there capability to see the factor of relevance in >> algorithms. >> >> And they almost never match the mental model that the average >> user has about a problem. > >I read somewhere that for large primes, using Fermat's Little Theorem >test is *good enough* for engineers because the chances of it being >wrong are less likely than a cosmic particle hitting your CPU at the >exact instant to cause a failure of the same sort. This is the >primary difference between engineers and mathematicians. An attractive person of the opposite sex stands on the other side of the room. You are told that your approach must be made in a series of discrete steps during which you may close half the remaining distance between yourself and the other person. Mathematician: "But I'll never get there!" Engineer: "I'll get close enough." -- for email reply remove "/" from address From bignose+hates-spam at benfinney.id.au Tue Oct 16 03:50:55 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 16 Oct 2007 17:50:55 +1000 Subject: ANN: magnitude 0.9.1 References: Message-ID: <873awb5wgw.fsf@benfinney.id.au> juan at juanreyero.com writes: > I am happy to announce the first release of magnitude, a library for > computing with physical quantities. It is released under the Apache > v. 2 license. Thanks for this module, it will be good to have a standard place for these constants. > Home page: http://juanreyero.com/magnitude/ > > Feedback is appreciated. Please don't ever recommend 'from foo import *' in end-user documentation. It's generally a bad practice and should only be done when the individual programmer understands the tradeoffs involved; putting it in the documentation for a module is setting a poor example. When 'from foo import *' is used, I have to keep scanning back and forth to see whether any given name that I don't recognise is defined elsewhere in the code, or whether it's not mentioned anywhere and by implication came in with the 'from foo import *'. It is especially bad for someone attempting to learn how to use a module from the examples. When attempting to read the documentation for a module to understand what it provides, I want the namespace to be explicit, so I can immediately see which things are part of the module I'm trying to learn about, and which are not. -- \ "I'm beginning to think that life is just one long Yoko Ono | `\ album; no rhyme or reason, just a lot of incoherent shrieks and | _o__) then it's over." -- Ian Wolff | Ben Finney From paul.hankin at gmail.com Thu Oct 25 19:57:56 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 25 Oct 2007 23:57:56 -0000 Subject: Delete all not allowed characters.. In-Reply-To: <13i28ainu6evk7e@corp.supernews.com> References: <1193323956.095828.265100@57g2000hsv.googlegroups.com> <13i1m1idi8f2r46@corp.supernews.com> <13i28ainu6evk7e@corp.supernews.com> Message-ID: <1193356676.894495.181990@o80g2000hse.googlegroups.com> On Oct 26, 12:05 am, Steven D'Aprano wrote: > On Thu, 25 Oct 2007 23:23:37 +0200, Michal Bozon wrote: > >> Repeatedly adding strings together in this way is about the most > >> inefficient, slow way of building up a long string. (Although I'm sure > >> somebody can come up with a worse way if they try hard enough.) > > >> Even though recent versions of CPython have a local optimization that > >> improves the performance hit of string concatenation somewhat, it is > >> better to use ''.join() rather than add many strings together: > > > String appending is not tragically slower, for strings long tens of MB, > > the speed makes me a difference in few tens of percents, so it is not > > several times slower, or so > > That is a half-truth. > > Because strings are immutable, when you concat two strings Python has to > duplicate both of them. This leads to quadratic-time behaviour, where the > time taken is proportional to the SQUARE of the number of characters. > This rapidly becomes very slow. > > *However*, as of Python 2.4, CPython has an optimization that can detect > some types of string concatenation and do them in-place, giving (almost) > linear-time performance. But that depends on: > > (1) the implementation: it only works for CPython, not Jython or > IronPython or other Python implementations; > > (2) the version: it is an implementation detail introduced in Python 2.4, > and is not guaranteed to remain in future versions; > > (3) the specific details of how you concat strings: s=s+t will get the > optimization, but s=t+s or s=s+t1+t2 will not. > > In other words: while having that optimization in place is a win, you > cannot rely on it. If you care about portable code, the advice to use > join() still stands. > > [snip] > > > Nice, I did not know that string translation exists, but Abandoned have > > defined allowed characters, so making a translation table for the > > unallowed characters, which would take nearly complete unicode character > > table would be inefficient. > > The cost of building the unicode translation table is minimal: about 1.5 > seconds ONCE, and it is only a couple of megabytes of data: > > >>> allowed = u'+0123456789 ????????????' \ > > ... u'ACBEDGFIHKJMLONQPSRUTWVYXZacbedgfihkjmlonqpsrutwvyxz' > > >>> timer = timeit.Timer('not_allowed = [i for i in range(0x110000) if > > unichr(i) not in allowed]; TABLE = dict(zip(not_allowed, u" "*len > (not_allowed)))', 'from __main__ import allowed') > > >>> timer.repeat(3, 10) > > [18.267689228057861, 16.495684862136841, 16.785034894943237] > > The translate method runs about ten times faster than anything you can > write in pure Python. If Abandoned has got as much data as he keeps > saying he has, he will save a lot more than 1.5 seconds by using > translate compared to relatively slow Python code. String translate runs 10 times faster than pure python: unicode translate isn't anywhere near as fast as it has to look up each character in the mapping dict. import timeit timer = timeit.Timer("a.translate(m)", setup = "a = u'abc' * 1000; m = dict((x, x) for x in range(256))") print timer.repeat(3, 10000) [2.4009871482849121, 2.4191598892211914, 2.3641388416290283] timer = timeit.Timer("a.translate(m)", setup = "a = 'abc' * 1000; m = ''.join(chr(x) for x in range(256))") print timer.repeat(3, 10000) [0.12261486053466797, 0.12225103378295898, 0.12217879295349121] Also, the unicode translation dict as given doesn't work on character's that aren't allowed: it should map ints to ints rather than ints to strings. Anyway, there's no need to pay the cost of building a full mapping dict when most of the entries are the same. Something like this can work: from collections import defaultdict def clear(message): allowed = u'abc...' clear_translate = defaultdict(lambda: ord(u' ')) clear_translate.update((c, c) for c in map(ord, allowed)) return message.translate(clear_translate) -- Paul Hankin From raffaele.salmaso at gmail.com Sun Oct 14 13:08:47 2007 From: raffaele.salmaso at gmail.com (Raffaele Salmaso) Date: Sun, 14 Oct 2007 17:08:47 GMT Subject: Python on imac In-Reply-To: <1i5yujj.1kardau10904n1N%aleax@mac.com> References: <8ocQi.24253$054.21605@newsfe14.phx> <1i5yujj.1kardau10904n1N%aleax@mac.com> Message-ID: <61v9u4-o33.ln1@news.marvin.home> Alex Martelli wrote: > I use Mac OSX 10.4 and this assertion seems unfounded -- I can't see any > wx as part of the stock Python (2.3.5). Maybe you mean something else? Very old version, see /System/Library/Frameworks/Python.framework/Versions/2.3/Extras/lib/python/wx-2.5.3-mac-unicode From timr at probo.com Mon Oct 8 01:46:28 2007 From: timr at probo.com (Tim Roberts) Date: Mon, 08 Oct 2007 05:46:28 GMT Subject: Top Programming Languages of 2013 References: <1191772154.784564.138370@r29g2000hsg.googlegroups.com> <47090141$0$4522$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <0vgjg3t1ki05lsgigio0csdjnacgri8mlq@4ax.com> Wildemar Wildenburger wrote: > >import friends >import sex > >try: > sex.have() >except ErrectionError, PrematureError: > pass >finally: > sex.brag(friends) Well, if "ErrectionError" ever becomes a real exception, I certainly get a boatload of email every day from people offering to help me deal with it. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jcd at sdf.lonestar.org Mon Oct 1 09:57:46 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Mon, 1 Oct 2007 09:57:46 -0400 Subject: Select as dictionary... In-Reply-To: <1191245527.228745.17100@r29g2000hsg.googlegroups.com> References: <1191245527.228745.17100@r29g2000hsg.googlegroups.com> Message-ID: <20071001135746.GA12995@sdf.lonestar.org> On Mon, Oct 01, 2007 at 06:32:07AM -0700, Besturk.Net Admin wrote regarding Select as dictionary...: > > aia.execute("SELECT id, w from list") > links=aia.fetchall() > print links > > and result > [(1, 5), (2,5).......] (2 million result) > > I want to see this result directly as a dictionary: > > {1: 5, 2: 5 .....} > > How do i select in this format ? > Try this: aia.execute("SELECT id, w from list") links=aia.fetchall() linkdict = dict() for k,v in links: linkdict[k] = v print linkdict Cheers, Cliff From bdesth.quelquechose at free.quelquepart.fr Tue Oct 23 16:19:47 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 23 Oct 2007 22:19:47 +0200 Subject: New module for method level access modifiers In-Reply-To: References: <1193159299.190539.136450@z24g2000prh.googlegroups.com> <471e43ad$0$21451$426a34cc@news.free.fr> Message-ID: <471e5795$0$26779$426a34cc@news.free.fr> J. Clifford Dyer a ?crit : > On Tue, Oct 23, 2007 at 08:54:52PM +0200, Bruno Desthuilliers wrote > regarding Re: New module for method level access modifiers: > >> TimeHorse a ?crit : >> >>> I have started work on a new module that would allow the >>> decoration of class methods to restrict access based on calling >>> context. Specifically, I have created 3 decorators named public, >>> private and protected. >> >> Lord have mercy. >> > > > I invented a new decorator too. It gets rid of many of the > limitations of python, including duck typing and hideously flat > namespaces. It's used kind of like this: > > @java > def public_com.sun.lord.have.mercy(): > pass > > Implementation forthcoming... keyboard !-) From ilochab at gmail.com Thu Oct 11 06:17:13 2007 From: ilochab at gmail.com (ilochab at gmail.com) Date: Thu, 11 Oct 2007 10:17:13 -0000 Subject: Py2exe with PyQt4 and sqlite Message-ID: <1192097833.135366.49780@v3g2000hsg.googlegroups.com> I wrote an application that uses PyQt4 to access a sqlite DB. Now I'm trying to convert it using py2exe and I found some problems. The last one, that I'm not able to avoid, is that when I launch the application's binary on a PC (that contains only a Python 2.5 installation and no QT4) I get an error trying to open the DB withi this code: db = QtSql.QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName(defines.DB_FILE) if not db.open(): # displays: Driver not loaded. I made many attempts changing options in my setup file but none of them successfull. The last one uses this options: options={"py2exe": {"includes":["sip", 'PyQt4.QtSql' ], "packages": ["sqlite3",]}} but I verified that neither QtSql, neither sqlite3 are usefull to avoid the error. My development configuration is Python 2.5 Qt4 4.2.2 PyQt 4.1.1 Any suggestion to solve this problem? Thanks in advance. Ciao. Licia. From foo at bar.biz Tue Oct 9 02:09:52 2007 From: foo at bar.biz (.) Date: 09 Oct 2007 06:09:52 GMT Subject: The fundamental concept of continuations References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> Message-ID: <470b1b30$0$11022$4c368faf@roadrunner.com> On Tue, 09 Oct 2007 05:15:49 +0000, gnuist006 wrote: > Again I am depressed to encounter a fundamentally new concept that I > was all along unheard of. Its not even in paul graham's book where i > learnt part of Lisp. Its in Marc Feeley's video. > > Can anyone explain: > > (1) its origin One of the lambda papers, I think. I don't remember which. > (2) its syntax and semantics in emacs lisp, common lisp, scheme elisp and Common Lisp don't have them (although sbcl and maybe others user continuations internally). In scheme CALL-WITH-CURRENT-CONTINUATION takes a function of one argument, which is bound to the current continuation. Calling the continuation on some value behaves like CALL-WITH-CURRENT-CONTINUATION returning that value. So (call/cc (lambda (k) (k 42))) => 42 You can think of it as turning the whatever would happen after call/cc was called into a function. The most practical use for continuations in implementing control structures, though there are some other neat tricks you can play with them. > (3) Is it present in python and java ? Certainly not Java, I dunno about Python. I've never seen someone use them in Python, but the pythonistas seem to want to add everything but a decent lambda to their language so I wouldn't be surprised if someone had added a call/cc. Ruby has it. > (4) Its implementation in assembly. for example in the manner that > pointer fundamentally arises from indirect addressing and nothing new. > So how do you juggle PC to do it. You have Lisp in Small Pieces. Read Lisp in Small Pieces. > (5) how does it compare to and superior to a function or subroutine > call. how does it differ. You use them like a function call. You can also use them like setjmp/longjmp in C. You can implement coroutines with them, or events, or simulate non-determinism or write things like ((call/cc call/cc) (call/cc call/cc)) and make your head explode, use it like goto's inbred second cousin or in general whatever perverse things you might like to do with the flow of control in your program. > > Thanks a lot. > > (6) any good readable references that explain it lucidly ? Lisp in Small Pieces for implementation details, the Scheme Programming Language for examples. From adam at krusty.madoff.com Wed Oct 3 13:04:37 2007 From: adam at krusty.madoff.com (Adam Lanier) Date: Wed, 03 Oct 2007 13:04:37 -0400 Subject: Class design question Message-ID: <1191431077.19400.20.camel@skinner.madoff.com> Relatively new to python development and I have a general question regarding good class design. Say I have a couple of classes: Class Foo: params = [ ] __init__( self, param ): ... Class Bar: data = None __init__( self, data ): ... The class is going to be a wrapper around a list of Bars() (among other things). I want the ability to pass to the constructor of Foo either: a string 'baz' a Bar object Bar( 'baz' ) a list of strings and/or bars ( 'baz', Bar( 'something else' )) Am I going to have to use isinstance() to test the parameter to __init__ to see what type of data I'm passing in, i.e., Class Foo: params = [ ] __init__( self, param ): if isinstance( param, list ): for p in param: addParam( p ) elif isinstance( param, str): addParam( param ) addParam( self, param ): if isinstance( param, Bar ): self.params.add( param ) elif isinstance( param, str ): self.params.add( Bar( param )) else: raise TypeError( "wrong type of input" ) Am I missing something here or is there a more Pythonic way to accomplish this? From aleax at mac.com Sun Oct 14 14:11:03 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 14 Oct 2007 11:11:03 -0700 Subject: Python on imac References: <8ocQi.24253$054.21605@newsfe14.phx> <1i5yujj.1kardau10904n1N%aleax@mac.com> <61v9u4-o33.ln1@news.marvin.home> Message-ID: <1i5yzhq.19hs10hfjtk63N%aleax@mac.com> Raffaele Salmaso wrote: > Alex Martelli wrote: > > I use Mac OSX 10.4 and this assertion seems unfounded -- I can't see any > > wx as part of the stock Python (2.3.5). Maybe you mean something else? > Very old version, see > /System/Library/Frameworks/Python.framework/Versions/2.3/Extras/lib/python > /wx-2.5.3-mac-unicode > Ah, I see it now, thanks. Alex From lukasz.f24 at gmail.com Fri Oct 19 06:39:27 2007 From: lukasz.f24 at gmail.com (lukasz.f24 at gmail.com) Date: Fri, 19 Oct 2007 03:39:27 -0700 Subject: dynamic invoke Message-ID: <1192790367.342435.243930@v29g2000prd.googlegroups.com> Hello, Is there any way (other then eval) to invoke a method by passing method name in a string. It's very simple in php: $oFoo = new Foo(); $dynamiMethod = "bar"; $oFoo->$dynamiMethod(); Unfortunately I can't find a good solution to do the same thing in python. Does it have some build-in function to do it? Kind Regards, Lukasz. From dfabrizio51 at gmail.com Tue Oct 30 17:25:06 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Tue, 30 Oct 2007 14:25:06 -0700 Subject: why did these companies choose Tcl over Python Message-ID: <1193779506.643321.216030@z9g2000hsf.googlegroups.com> Hello, As an electronics engineer I use some very expensive EDA CAD tool programs that are scriptable using Tcl. I was wondering why these companies have choose to use Tcl instead of Python. Some of these are: Mentor Graphics ModelTech VHDL and Verilog simulator Synopsys Design Compiler and Primetime Static Timing Analyzer Actel FPGA tools. Tcl seems to very popular in my business as the scripting language of choice. I'm in the process of deciding to use Tcl or Python for a CAD tool program that I have been working on. Most of the core of the program, the database, will be done is C as an extension to either Tcl or Python, but I intend to use Tk or wxPthon for the GUI. I do need publishing quality outputs from drawings done on a graphics device that are scaled to standard printer paper sizes. I would prefer to use Python but can't deny how popular Tcl is, as mentioned above, so my question is why wasn't Python selected by these companies as the choice of scripting languages for their product? Are there any obvious advantages like: performance, memory footprint, better cross-platform support, ease of use, Thanks in advance for your thoughts about this. From besturk at gmail.com Fri Oct 5 10:27:39 2007 From: besturk at gmail.com (Abandoned) Date: Fri, 05 Oct 2007 07:27:39 -0700 Subject: remove list elements.. Message-ID: <1191594459.951323.254080@r29g2000hsg.googlegroups.com> Hi.. I have a problem.. list1=[11, 223, 334, 4223...] 1 million element list2=[22,223,4223,2355...] 500.000 element I want to difference list1 to list2 but order very importent.. My result must be: list3=[11,334,...] I do this use FOR easly but the speed very imported for me. I want to the fastest method please help me. I'm sorry my bad english. King regards.. From exarkun at divmod.com Wed Oct 31 11:52:44 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 31 Oct 2007 10:52:44 -0500 Subject: Python bug tracker now secret? In-Reply-To: <4728A278.9080804@v.loewis.de> Message-ID: <20071031155244.8162.977210918.divmod.quotient.30148@ohm> On Wed, 31 Oct 2007 16:42:48 +0100, "\"Martin v. L?wis\"" wrote: >> I don't know why they chose to make the sf tracker private. Maybe that >> was the only way to remove write access. > >That, plus removing it means that people won't browse outdated information. > Though it also means all old links are broken and there's no obvious pointer to the new information. Jean-Paul From byte8bits at gmail.com Wed Oct 10 17:13:36 2007 From: byte8bits at gmail.com (brad) Date: Wed, 10 Oct 2007 17:13:36 -0400 Subject: I'm starting to think like a Pythonista In-Reply-To: References: Message-ID: Erik Jones wrote: > big_evens = range(10, 100, 2) > big_odds = range(11, 100, 2) Neat, but not as clever or as hard to read as mine... I'll bet it faster though... maybe not. The upto part is here: ok_numbers = low_odds + big_evens + [x for x in low_evens if x <= y] From gagsl-py2 at yahoo.com.ar Thu Oct 18 23:11:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Oct 2007 00:11:18 -0300 Subject: Noob: Loops and the 'else' construct References: <1192761867.254928.115300@i38g2000prf.googlegroups.com> Message-ID: En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus escribi?: > I have just come across a site that discusses Python's 'for' and > 'while' loops as having an (optional) 'else' structure. > > At first glance I interpreted it as being a bit like the 'default' > structure in PHP's switch block... But the switch block isn't a loop, > so, I am now confused as to the reason for using 'else' with the for > and while loops... > > A few quick tests basically show that statements in the else structure > are executed at the fulfillment of the loop's expression (ie, no > break). A `while` loop tests a condition: if it evaluates to true, keep cycling; if it is false, stop. The `else` clause is executed when the condition is false, as in any `if` statement. If you exit the loop by using `break`, the `else` part is not executed (because you didn't get out of the loop by determining the condition falseness) You can think of a `for` loop as meaning `while there are remaining elements to be iterated, keep cycling` and the `else` clause applies when there are no more elements. A `break` statement does not trigger the else clause because the iteration was not exhausted. Once you get the idea, it's very simple. -- Gabriel Genellina From hniksic at xemacs.org Fri Oct 19 09:12:14 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 19 Oct 2007 15:12:14 +0200 Subject: class vs type References: Message-ID: <87wstjtfip.fsf@mulj.homelinux.net> "Colin J. Williams" writes: > In Python Types and Objects, Shalabh Chaturvedi says (in the Python > 3.0 documentation - New Style Classes) > > "The term class is traditionally used to imply an object created by > the class statement. However, classes are now synonymous with > types. Built-in types are usually not referred to as classes. This > book prefers using the term type for both built-in and user created > types." > > Do we need two different words to describe what is essentially the > same thing? We don't, not anymore, which is why the author chooses the word "type" for both in the last sentence. But, as the author correctly explains, class and type used to not be the same thing. Classes were created with 'class', and they were fundamentally different from C types created in extension modules. All instances of old-style classes are of type 'instance', which is why they have the __class__ attribute, so you can find their actual class. (Functions like "isinstance" contain hacks to support old-style classes.) New-style classes elevate Python-level classes to types equal to the built-in ones, which is why the word "type" is now sufficient for both. From bdesth.quelquechose at free.quelquepart.fr Tue Oct 16 15:10:41 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 16 Oct 2007 21:10:41 +0200 Subject: Simple HTML template engine? In-Reply-To: References: <1192419411.895715.138450@e9g2000prf.googlegroups.com> Message-ID: <47150ce8$0$26767$426a74cc@news.free.fr> Adrian Cherry a ?crit : > "allen.fowler" wrote in > news:1192419411.895715.138450 at e9g2000prf.googlegroups.com: > > >>Hello, >> >>Can anyone recommend a simple python template engine for >>generating HTML that relies only on the Pyhon Core modules? >> >>No need for caching, template compilation, etc. >> >>Speed is not a major issue. >> >>I just need looping and conditionals. Template inheritance >>would be a bonus. >> >>I've seen Genshi and Cheetah, but they seem way too complex. >> >>Any ideas? >> > > > Did you try Cheetah? Did you read the OP's question ?-) From steve at REMOVE-THIS-cybersource.com.au Thu Oct 18 18:21:53 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 18 Oct 2007 22:21:53 -0000 Subject: Convert string to command.. References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> <1192718860.391481.139090@v29g2000prd.googlegroups.com> Message-ID: <13hfn417kkfni58@corp.supernews.com> On Thu, 18 Oct 2007 14:05:34 -0300, Sebastian Bassi wrote: > On 10/18/07, Adam Atlas wrote: >> >> Use the builtin function "eval". > > What is the difference with os.system()? Everything. eval() evaluates Python expressions like "x.append(2+3)". os.system() calls your operating system's shell with a command. -- Steven. From roy at panix.com Wed Oct 31 10:23:55 2007 From: roy at panix.com (Roy Smith) Date: Wed, 31 Oct 2007 10:23:55 -0400 Subject: why did these companies choose Tcl over Python References: <1193779506.643321.216030@z9g2000hsf.googlegroups.com> Message-ID: chewie54 wrote: > I would prefer to use Python but can't deny how popular Tcl is, as > mentioned above, so my question is why wasn't Python selected by > these companies as the choice of scripting languages for their > product? > > Are there any obvious advantages like: > > performance, > memory footprint, > better cross-platform support, > ease of use, I used to work on a project which was written mostly in Tcl. Not a huge project, but not a trivial one either. Perhaps a few 10's of KLOC over 100 Tcl source files. The domain was network monitoring using SNMP. No graphics. We also used a commercially available network simulator (Mimic) which was written in Tcl (or, at least, has Mimic as its scripting language). For us, the biggest thing was the quick learning curve (i.e. ease of use). Most of the programmers on the team were network jocks, not programmers. Getting them up to speed on enough Tcl to do their jobs was very quick. Performance was not an issue, since the application was rate limited by the network (i.e. waiting for SNMP replies to come back). We also had lots of hooks into C code. Doing that is trivial in Tcl. Yes, I know you can extend/embed Python, but it's a LOT easier in Tcl. Embedding a Tcl interpreter in a C program is literally one line of code. I sat down with the book to figure out how to do it, and had a running interpreter going in 10 minutes. Part of what makes it so easy is that everything in Tcl is a string (no need to support multiple data types). I don't think I would want to write a huge system in Tcl. For one thing, it's not object oriented (I have no direct experience with incr Tcl, so that may not be a fair critisism). It's also slow (even slower than Python). Of course, in both Tcl and Python, the key to a fast application is to do all the CPU-intensive parts in C and just script the glue code. Anyway, I like Tcl. It's certainly worth considering seriously as a scripting language. As for "which is better, Tcl or Python", there's no one right answer to that. Evaluate both and decide which fits your needs better. Often, questions like that will be decided by things which have little to do with language technology. Is your company re-organizing and there's a development group who are used to working in language X who are looking for a new project? Guess which language they're going to pick? Got a major customer (or prospect) who expresses an interest in language X for scripting extensions? Guess which language you're going to use? From rcdailey at gmail.com Fri Oct 19 19:29:03 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 19 Oct 2007 18:29:03 -0500 Subject: __main__ : What is this? Message-ID: <496954360710191629x3fc82871s334f15c2d5a48530@mail.gmail.com> Hi, I've read various portions of the Python 2.5 documentation in an attempt to figure out exactly what the following condition represents: if __name__ == "__main__": main() However, I was not able to determine what it is actually checking for. Could someone point me in the way of a tutorial or explain this for me? Thanks. From martin at marcher.name Fri Oct 12 18:02:18 2007 From: martin at marcher.name (Martin Marcher) Date: Sat, 13 Oct 2007 00:02:18 +0200 Subject: test if email In-Reply-To: <13gvqvb6shueveb@corp.supernews.com> References: <1192220077.109848.74740@e9g2000prf.googlegroups.com> <13gvqvb6shueveb@corp.supernews.com> Message-ID: <5fa6c12e0710121502v30621fd5m6ee90a1c5df494b2@mail.gmail.com> 2007/10/12, Grant Edwards : > On 2007-10-12, Florian Lindner wrote: > > > I was just asking for the correct syntax of the mail address. I know about > > the various problems actually impossibility to test for a live and valid > > address. > > Don't forget to allow uucp style "bang" addresses. :) no need to get there most forms won't accept the new top level domains (.name). No need to speek of plus addressing or older messaging systems. Heck just check for an "@" and try to deliver it. (if there's no @ you should know wether it's a local user or not....) hth martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From jcd at sdf.lonestar.org Mon Oct 29 13:29:41 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Mon, 29 Oct 2007 13:29:41 -0400 Subject: two files into an alternate list In-Reply-To: References: Message-ID: <20071029172941.GC3648@sdf.lonestar.org> That depends: What do you want when you have these two files: file 1: a b c file 2: 1 2 3 4 5 Options: *['a',1,'b',2,'c',3,None,4,None,5] *['a',1,'b',2,'c',3,4,5] *['a',1,'b',2,'c',3] *Throw an exception And what if file 1 has more lines than file 2? Cheers, Cliff 1 On Mon, Oct 29, 2007 at 09:50:51PM +0530, Beema shafreen wrote regarding two files into an alternate list: > Delivered-To: python-list at bag.python.org > Date: Mon, 29 Oct 2007 21:50:51 +0530 > From: "Beema shafreen" > To: python-list at python.org > Subject: two files into an alternate list > Precedence: list > List-Id: General discussion list for the Python programming language > > List-Unsubscribe: , > > List-Archive: > List-Post: > List-Help: > List-Subscribe: , > > Errors-To: python-list-bounces+jcd=sdf.lonestar.org at python.org > > hi everybody , > i have a file : > file 1: > 1 > 2 > 3 > 4 > 5 > 6 > file2: > a > b > c > d > e > f > how do i make the two files into list like this = > [1,a,2,b,3,c,4,d,5,e,6,f] > regards > shafreen > -- > http://mail.python.org/mailman/listinfo/python-list From mensanator at aol.com Mon Oct 22 19:05:48 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 22 Oct 2007 16:05:48 -0700 Subject: for loop In-Reply-To: <1193092630.751179.198560@q5g2000prf.googlegroups.com> References: <5o4m5kFktnthU6@mid.uni-berlin.de> <1193092630.751179.198560@q5g2000prf.googlegroups.com> Message-ID: <1193094348.431443.237740@q3g2000prf.googlegroups.com> On Oct 22, 5:37 pm, "mensana... at aol.com" wrote: > On Oct 22, 5:22 pm, Marc 'BlackJack' Rintsch wrote: > > > > > > > On Mon, 22 Oct 2007 18:17:56 -0400, Shawn Minisall wrote: > > > #Intro > > > print "*********************************************" > > > print "WELCOME TO THE POPULATION GROWTH CALCULATOR" > > > print "*********************************************" > > > > print "This program will predict the size of a population of organisms." > > > print > > > print > > > organisms=input("Please enter the starting number of organisms: ") > > > > increase=input("Please enter the average daily population increase > > > as a percentage (20% = .20): ") > > > > days=input("Please enter the number of days that they will multiply: ") > > > > print " Day Population" > > > print "----------------------------------------------------------" > > > > for p in range (days): > > > > population = organisms * population * increase > > > > print days, > > > > print "\t\t\t\t",population > > > > I'm having problems with my for loop here to calculate estimated > > > population output to a table. Instead of knowing how much I want to > > > loop it, the loop index is going to be whatever number of days the user > > > enters. When I run my program, it asks the 3 questions above but then > > > just dead stops at a prompt which leads me to believe there's something > > > wrong with my loop. > > > It should not run at all as it is indented inconsistently. If that > > problem is corrected it will stop with a `NameError` because you try to > > read `population` before anything was assigned to it. > > > Ciao, > > Marc 'BlackJack' Rintsch > > Also, I would guess that you want to print p, not days Oh, and your calculation is incorrect. You don't multiply by organisms in every loop iteration, organisms is the initial value of population, so you can solve the "Name" error by doing population = organisms before the for..loop. And since you're asking for an increase, you don't multiply by the percent (as that would decrease the population), but instead by 1+increase. Also, does day==0 represent the first day of increase or the initial value? One would normally expect day==0 to be the initial value, but as written, day==0 is the first day of increase. I would use xrange(1,days+1) instead. Lastly, you can't have a fraction of an organism, right? You might want to print your floating point population rounded to an integer. population = organisms for p in xrange(1,days+1): population = population * (1 + increase) print p, print "\t\t\t\t%0.0f" % (population) ## ********************************************* ## WELCOME TO THE POPULATION GROWTH CALCULATOR ## ********************************************* ## This program will predict the size of a population of organisms. ## ## ## Please enter the starting number of organisms: 100 ## Please enter the average daily population increase as a percentage (20% = .20): 0.25 ## Please enter the number of days that they will multiply: 8 ## Day Population ## ---------------------------------------------------------- ## 1 125 ## 2 156 ## 3 195 ## 4 244 ## 5 305 ## 6 381 ## 7 477 ## 8 596 From bdesth.quelquechose at free.quelquepart.fr Mon Oct 1 16:32:38 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 01 Oct 2007 22:32:38 +0200 Subject: slice last 4 items from a list In-Reply-To: References: Message-ID: <470159a2$0$1866$426a74cc@news.free.fr> brad a ?crit : > Is this the correct way to slice the last 4 items from a list? > > x = [1,2,3,4,5,6,7,8,9] > print x[-4:] > > It works, but is it Pythonic? Is there a more obvious (for a pythonic definition of 'obvious') way to do it ? If no, then it's pythonic... Now FWIW, I usually use 'esrever'[::-1] to reverse a string, so I may not be a reference !-) From bik.mido at tiscalinet.it Wed Oct 24 11:01:01 2007 From: bik.mido at tiscalinet.it (Michele Dondi) Date: Wed, 24 Oct 2007 17:01:01 +0200 Subject: TeX pestilence (was Distributed RVS, Darcs, tech love) References: <471afd4c.179297746@news.readfreenews.net> <1192972158.250126.203980@v23g2000prn.googlegroups.com> <471b6714$0$90276$14726298@news.sunsite.dk> <1192981349.181197.308610@q5g2000prf.googlegroups.com> <1193037849.011136.282480@y27g2000pre.googlegroups.com> <1193057430.359962.68820@v29g2000prd.googlegroups.com> Message-ID: On Mon, 22 Oct 2007 09:07:37 -0400, Lew wrote: >Xah Lee wrote: >> i have written ... No coherent argument, I've long killfiled XL to the effect that all of his threads are ignored altogether, since the guy is "nice" enough to only take part to his own rants, but occasionally some posts slip out and now from the Subject I infer that the new target for his hate is TeX, which makes me wonder, given his views on Perl (and "unixisms in general" iirc) what our "friend" would think about such a wonderful tool as PerlTeX - from his POV certainly a synergy between two of the worst devil's devices. :) Michele -- {$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr (($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^ <1193278225.923337.217160@k35g2000prh.googlegroups.com> Message-ID: "Dan Bishop" wrote in message news:1193278225.923337.217160 at k35g2000prh.googlegroups.com... > On Oct 24, 8:56 pm, "Junior" wrote: >> I want to open a text file for reading and delineate it by comma. I also >> want any data >> surrounded by quotation marks that has a comma in it, not to count the >> commas inside the >> quotation marks > > Use the csv module. Thanks for the help! I used the csv module to write this; import csv reader = csv.reader(open('testfile.txt', "rb")) for row in reader: print "var2= ", row[2] The reason I didn't use the csv module is because I read this book to learn Python, Python Programming for the Absolute Beginner, Second Edition (For the Absolute Beginner) by Michael Dawson (Author), and it did not mention the csv module it just explained how to import modules. I also read the tutorial that comes with python but it ends with the History and License section. Can you recommend a book that explains the most used modules? From timr at probo.com Thu Oct 25 02:24:04 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Oct 2007 06:24:04 GMT Subject: win32com.client documentation? References: <1193236546.344635.54080@e9g2000prf.googlegroups.com> Message-ID: "Colin J. Williams" wrote: >Mark Morss wrote: >> I am a unix person, not new to Python, but new to Python programming >> on windows. Does anyone know where to find documentation on >> win32com.client? I have successfully installed this module and >> implemented some example code. But a comprehensive explanation of the >> objects and methods available is nowhere to be found. I have been >> able to find a somewhat out-of-date O'Reilly book, nothing more. >> >> I want to be able to script the creation of Excel spreadsheets and >> Word documents, interract with Access data bases, and so forth. >> >You might download and install Mark Hammond's PythonWin. (Ummm, win32com.client is PART of Mark Hammond's PythonWin, now called PyWin32.) -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From cjw at sympatico.ca Fri Oct 12 14:41:47 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 12 Oct 2007 14:41:47 -0400 Subject: Simple question about python logic. In-Reply-To: <470F9B82.9010205@tim.thechases.com> References: <1192203159.292973.204470@v23g2000prn.googlegroups.com> <470F9B82.9010205@tim.thechases.com> Message-ID: Tim Chase wrote: >> I have a file containing following data. But the dimension can be >> different. >> >> A B C D E F G >> 3 4 1 5 6 2 4 >> 7 2 4 1 6 9 3 >> 3 4 1 5 6 2 4 >> 7 2 4 1 6 9 3 >> . >> . >> . >> . >> >> What is the best approach to make a column vector with the name such >> as A B, etc? > > > There are a couple different ways to go about it depending on > > 1) whether just one or whether both dimensions can be different > 2) whether you want to extract each column vector > > Both of the following should allow for an arbitrary number of > columns: > > To map everything, you can do something like > > ####################################### > infile = file("in.txt") > header_row = infile.next().rstrip('\n').split() > values = [[] for header in header_row] > for line in infile: > line = line.rstrip('\n').split() > for dest, value in zip(values, line): > dest.append(value) > infile.close() > results = dict(zip(header_row, values)) > ####################################### > > > which you can then use with > > results['A'] > > However, if you just want a particular column from the file and > don't care about the rest, you can do something like > > ####################################### > from itertools import islice > > column_c = [ > line.rstrip('\n').split()[2] > for line in islice(file('in'), 1, None) > ] > ####################################### > > where "2" is the zero-based column offset you want (in this case, > column C = 2) > > -tkc > > > Numpy appears to have this capability. Colin W. From nachogomez at gmail.com Wed Oct 17 17:20:06 2007 From: nachogomez at gmail.com (=?UTF-8?Q?Ra=C3=BAl_G=C3=B3mez_C.?=) Date: Wed, 17 Oct 2007 17:20:06 -0400 Subject: Bidirectional communication over unix socket (named pipe) In-Reply-To: <684b0a740710171411t2c30822ew2309254f39b53898@mail.gmail.com> References: <684b0a740710171411t2c30822ew2309254f39b53898@mail.gmail.com> Message-ID: <684b0a740710171420k72c27080mb5402d37d5a81a9c@mail.gmail.com> BTW: This is the original post: Hi, I feel like I should apologize in advance because I must be missing something fairly basic and fundamental here. I don't have a book on Python network programming (yet) and I haven't been able to find an answer on the net so far. I am trying to create a pair of programs, one (the client) will be short-lived (fairly) and the second (server) will act as a cache for the client. Both will run on the same machine, so I think a simple file socket is the easiest and most reliable method. The problem I have is that the client can send to the server, but the server can't send back to the client because it gets this error: socket.error: (107, 'Transport endpoint is not connected') This is despite the client waiting on a socket.recv() statement. Is the client really not connected, or is the server unaware of the connection? And how do I fix this? I was able to get this working by switching to AF_INET, but that is not what I want. Unix sockets are bidirectional, correct? I have never programmed one, but I know that programs like clamav use a socket to receive an email to scan and return the result. Any help would be greatly appreciated! Jeff *** server.py *** #!/usr/bin/python import socket import os, os.path import time if os.path.exists("/tmp/mysock"): os.remove("/tmp/mysock") server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) server.bind("/tmp/mysock") while True: datagram = server.recv(1024) if not datagram: break print datagram # the preceeding works, and I see the TEST TEST TEST statement the client sent time.sleep(2) # it dies on the next statement. server.send("Thank you\n") server.close() if os.path.exists("/tmp/mysock"): os.remove("/tmp/mysock") *** client.py: *** #!/usr/bin/python import socket client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) client.connect("/tmp/mysock") TX = "TEST TEST TEST" TX_sent = client.send(TX) if TX_sent <> len(TX): print "TX incomplete" while True: print "Waiting..." datagram = client.recv(1024) # the client sits here forever, I see the "waiting appear" but it doesn't advance beyond # the recv statement. if not datagram: break print "Received: ",datagram client.close() On 10/17/07, Ra?l G?mez C. wrote: > > Hi Jeffrey, > > I've been reading the Python mailing list and I've found a post of you > about Unix socket with Python, you've found the answer to you're problem by > your self, but I wonder if you still has the working code and if you would > share it? > > Thanks!... > > Raul > > > On *Wed Mar 8 18:11:11 CET 2006, **J Rice* rice.jeffrey at gmail.comwrote: > > > OK, never fails that I find a solution once I post a problem. > > If I use a stream rather than a datagram, it seems to work fine. > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Mon Oct 22 19:16:38 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 22 Oct 2007 23:16:38 -0000 Subject: calling a function from string References: <1193043242.235837.86590@e34g2000pro.googlegroups.com> Message-ID: <13hqbqmoqe18m8e@corp.supernews.com> On Mon, 22 Oct 2007 08:54:02 +0000, james_027 wrote: > hi, > > i have a function that I could like to call, but to make it more dynamic > I am constructing a string first that could equivalent to the name of > the function I wish to call. That is not the right solution to dynamic functions. There is a much better way. > how could I do that? the string could might > include name of the module. > > for example > > a_string = 'datetime.' + 'today()' > > how could I call a_string as function? Others have suggested eval() and exec. Both will work, but have MAJOR security implications. The right way to work with "dynamic functions" is to remember that Python treats functions as first-class objects just like strings and ints and lists. Here's a simple example: Suppose I have a function that takes a string and converts it to another object type. def converter(x, convert_to): if convert_to == 'int': return int(x) elif convert_to == 'float': return float(x) elif convert_to == 'list': return list(x) else: raise ValueError("don't know that type") and then use the function like this: my_float = converter('12.345', 'float') That's the wrong way to do it. This is the right way: def converter(x, convert_to): return convert_to(x) my_float = converter('12.345', float) See the subtle difference? 'float' is a string, and it has no special meaning. float() with brackets says "call the function float". float without brackets *is* the function float. You can pass it around like any other object (strings, lists, ints, etc.) and call it later. Try this example: import datetime, time functions = [int, float, datetime.time, time.time] for f in functions: print f() -- Steven From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Oct 20 17:47:49 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 20 Oct 2007 23:47:49 +0200 Subject: vote for Python - PLEASE References: <13hhk968d8mf7c9@corp.supernews.com> <13hj10bro78ltad@corp.supernews.com> <5nu52fFjfiluU2@mid.individual.net> <5nuqkeFjnho9U1@mid.uni-berlin.de> Message-ID: <5nvbc5FkbtcdU1@mid.individual.net> Diez B. Roggisch wrote: > Bjoern Schliessmann schrieb: >> Also, why would there be telephone votings in TV if they were >> meaningless to the default watcher? :) > > Because it costs 50cent to call, which makes a useless and most of > the time heavily biased poll a nice source of income. Or why do > you think even the larger TV-stations show call-in-TV-shows at > night? You're partially right. But those are mostly no polls but lotteries (often with tricky or ridiculously simple questions). Simple polls are quite rare, comparatively. Regards, Bj?rn -- BOFH excuse #301: appears to be a Slow/Narrow SCSI-0 Interface problem From bj_666 at gmx.net Mon Oct 22 18:56:03 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Oct 2007 22:56:03 GMT Subject: Regular Expression References: <1193092178.791023.163840@v29g2000prd.googlegroups.com> Message-ID: <5o4o43FktnthU7@mid.uni-berlin.de> On Mon, 22 Oct 2007 22:29:38 +0000, patrick.waldo wrote: > I'm trying to learn regular expressions, but I am having trouble with > this. I want to search a document that has mixed data; however, the > last line of every entry has something like C5H4N4O3 or CH5N3.ClH. > All of the letters are upper case and there will always be numbers and > possibly one . > > However below only gave me none. > > [?] > > test = re.compile('\u+\d+\.') There is no '\u'. 'u' doesn't have a special meaning so the '\' is pointless. Your expression matches one or more small 'u's followed by one or more digits followed by a period. Examples are 'u1.', 'uuuuuuuu42.', etc. An expression that matches your first example would be: r'([A-Z]|\d|\.)+'. That's a non-empty sequence of upper case letters, digits and periods. To limit this to just one optional period the expression gets a little longer: r'([A-Z]|\d)+\.?([A-Z]|\d)+' Does not match your second example because there is a lower case letter in it. Ciao, Marc 'BlackJack' Rintsch From byte8bits at gmail.com Mon Oct 29 16:25:56 2007 From: byte8bits at gmail.com (brad) Date: Mon, 29 Oct 2007 16:25:56 -0400 Subject: A Python 3000 Question Message-ID: Will len(a_string) become a_string.len()? I was just reading http://docs.python.org/dev/3.0/whatsnew/3.0.html One of the criticisms of Python compared to other OO languages is that it isn't OO enough or as OO as others or that it is inconsistent. And little things such as this seem to support those arguments. Not that it matters really... just seems that classes with methods used in a more consistent manner would be more appropriate in an OO langauage. Is there a reason that len cannot be a method? a_string.lower() makes sense, as does a_string.split(), a_string.strip()... why not a_string.len()? From jjl at pobox.com Wed Oct 17 16:37:25 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 17 Oct 2007 20:37:25 GMT Subject: negative base raised to fractional exponent References: <1192571332.470809.279160@v23g2000prn.googlegroups.com> <1192622126.725230.136570@i13g2000prf.googlegroups.com> Message-ID: <874pgpzddm.fsf@pobox.com> schaefer.mp at gmail.com writes: [...] > Thank you for this. Now I need to somehow express this as a real > number. For example, I can transform the real and imaginary parts into > a polar coordinate giving me the value I want: > > z = sqrt( real_part**2 + imaj_part**2 ) > > but this is an absolute terms. How does one determine the correct sign > for this value? If you mean the angle >>> import math >>> x = (-3 + 0j) ** (-37/9.) >>> math.atan2(x.imag, x.real) * (180 / math.pi) -19.99999999999995 John From ndbecker2 at gmail.com Wed Oct 31 07:59:32 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 31 Oct 2007 07:59:32 -0400 Subject: help with pyparsing Message-ID: I'm just trying out pyparsing. I get stack overflow on my first try. Any help? #/usr/bin/python from pyparsing import Word, alphas, QuotedString, OneOrMore, delimitedList first_line = '[' + delimitedList (QuotedString) + ']' def main(): string = '''[ 'a', 'b', 'cdef']''' greeting = first_line.parseString (string) print greeting if __name__ == "__main__": main() /usr/lib/python2.5/site-packages/pyparsing.py:2727: SyntaxWarning: Cannot add element of type to ParserElement return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName) /usr/lib/python2.5/site-packages/pyparsing.py:1008: SyntaxWarning: Cannot add element of type to ParserElement return other + self Traceback (most recent call last): File "", line 1, in File "/usr/tmp/python-k3AVeY.py", line 5, in first_line = '[' + delimitedList (QuotedString) + ']' File "/usr/lib/python2.5/site-packages/pyparsing.py", line 2727, in delimitedList return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName) File "/usr/lib/python2.5/site-packages/pyparsing.py", line 1008, in __radd__ return other + self File "/usr/lib/python2.5/site-packages/pyparsing.py", line 1008, in __radd__ return other + self From tjreedy at udel.edu Sun Oct 28 18:12:32 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Oct 2007 18:12:32 -0400 Subject: Questions for the Python Devs Out There References: Message-ID: "Ann Thompson" wrote in message news:BAY144-W251FCF59F93682657950E7CF900 at phx.gbl... | If you know of places that I might be able to post queries for python | developers, I'm certainly open to suggestions. Many people involved with Python and gaming subscribe to the pygame mailing list, also accessible as gmane.comp.python.pygame From mail at gedankenkonstrukt.de Sat Oct 6 06:44:05 2007 From: mail at gedankenkonstrukt.de (Thomas Wittek) Date: Sat, 06 Oct 2007 12:44:05 +0200 Subject: Yet another comparison of Python Web Frameworks In-Reply-To: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> References: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> Message-ID: Michele Simionato: > At work we are shopping for a Web framework, so I have been looking at > the available options > on the current market. At least, you missed Turbo Gears :) http://turbogears.org/ For me, it feels more integrated than Pylons. -- Thomas Wittek Web: http://gedankenkonstrukt.de/ Jabber: streawkceur at jabber.i-pobox.net GPG: 0xF534E231 From redlex at bluebottle.com Wed Oct 24 06:49:08 2007 From: redlex at bluebottle.com (Alex Hunsley) Date: Wed, 24 Oct 2007 11:49:08 +0100 Subject: trying to remember how to do inline code "testing" In-Reply-To: <5o8m51Flqaf5U1@mid.uni-berlin.de> References: <471f2243$0$514$5a6aecb4@news.aaisp.net.uk> <5o8m51Flqaf5U1@mid.uni-berlin.de> Message-ID: <471F2324.5020805@bluebottle.com> Diez B. Roggisch wrote: > Alex Hunsley wrote: > >> I can remember Python having a feature which allowed you to add some >> simple tests to your code, something like adding console output to your >> actual python script, like so: >> >> >> >>> 1+1 >> 2 >> >>> 2*7 >> 14 >> >> >> ... then python would actually run these queries and check that the >> expected results occurred. >> I can't find the docs for this feauture anywhere, but I'm certain I >> didn't imagine this one! >> Can anyone give me a reference? > > http://docs.python.org/lib/module-doctest.html > > Diez Brilliant, thanks for that Diez! Alex From ratishin at gmail.com Fri Oct 26 00:22:15 2007 From: ratishin at gmail.com (RATISH KAKKAD) Date: Thu, 25 Oct 2007 21:22:15 -0700 Subject: JOIN WWW.A2ZLEARING.ORG AND GET FREE STUFF Message-ID: <1193372535.580474.189500@q5g2000prf.googlegroups.com> Register with a2zlearning and get: * More than 1000 electronic book * Lecture notes for Arts, Commerce, Science, Management * Multiple Choice Questions for Competitive Exams * Case Studies for Management Aspirants * Slide Shows on various subjects * Kids Games, Software, Comic books etc. From travis.jensen at gmail.com Mon Oct 8 18:25:08 2007 From: travis.jensen at gmail.com (Travis Jensen) Date: Mon, 8 Oct 2007 16:25:08 -0600 Subject: pytz has so many timezones! In-Reply-To: <20071008202558.GB967@sdf.lonestar.org> References: <1191828739.635927.86590@57g2000hsv.googlegroups.com> <1191865263.572366.270820@y42g2000hsy.googlegroups.com> <1191874404.292250.87130@y42g2000hsy.googlegroups.com> <20071008202558.GB967@sdf.lonestar.org> Message-ID: <3605cb0710081525m1b763701n58386e33df177b3d@mail.gmail.com> How about a calendar entry: I've got six people in places all over the world to get on the phone together. If the app doesn't know their notion of a time zone, that will never happen. How about financial transactions: time-stamping transactions that move around the world seems pretty useful to me. How do I know when said transaction started if I can't convert the user's time into the server's time? Timezone is just another localization setting. It is no different than language or keyboard layout. It is a piece of data that describes the "world" the user lives in. Unfortunately, DST makes them very complex because DST is determined by the country and can change from year to year. I think the US' DST change this year had more of a real-world impact than Y2K (of course, people actually planned for Y2K, but that is a different story :). tj On 10/8/07, J. Clifford Dyer wrote: > > On Mon, Oct 08, 2007 at 01:13:24PM -0700, mensanator at aol.com wrote > regarding Re: pytz has so many timezones!: > > > > On Oct 8, 1:03 pm, Carsten Haese wrote: > > > On Mon, 2007-10-08 at 10:41 -0700, mensana... at aol.com wrote: > > > > For example, Windows has seperate listings for > > > > > > > Central America > > > > Central Time (US & Canada) > > > > Guadalahara, Mexico City, Monterry - New > > > > Guadalahara, Mexico City, Monterry - Old > > > > Saskatchewan > > > > > > > but they are all GMT-6 > > > > > > But they could have different rules for Daylight Saving Time. > > > > Which only matters if you're setting your clock. > > > > Maybe this is where I'm not understanding you: Do you have another use > for setting a timezone? The only thing a time zone does, as far as I can > tell, is set clocks relative to a shared conception of time. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Travis Jensen travis.jensen at gmail.com http://cmssphere.blogspot.com/ Software Maven * Philosopher-in-Training * Avenged Nerd -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Sat Oct 27 11:04:58 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sat, 27 Oct 2007 08:04:58 -0700 Subject: Going past the float size limits? In-Reply-To: <13i6e9timmvuu51@corp.supernews.com> References: <1193438154.931341.30450@50g2000hsm.googlegroups.com> <1193441374.061735.308710@o38g2000hse.googlegroups.com> <13i6e9timmvuu51@corp.supernews.com> Message-ID: <1193497498.164986.321540@v3g2000hsg.googlegroups.com> On Oct 27, 8:12?am, Steven D'Aprano wrote: > On Sat, 27 Oct 2007 10:24:41 +0200, Hendrik van Rooyen wrote: > > So 0.002625**200000 is a number so small that its about as close as you > > can practically get to bugger-all, as it is less than 10 ** -400000, and > > more than 10**-600000 > > If you read the rest of the thread, you'll see I give a much more > accurate estimate. It's approaching 10**-520000. > > > Now I have heard rumours that there are approximately 10**80 elementary > > particles in the universe, so this is much less than one of them, even > > if my rumour is grossly wrong. > > > A light year is of the order of 9.46*10**18 millimetres, and no human > > has ever been that far away from home. Call it 10**19 for convenience. > > So your number slices the last millimetre in a light year into more than > > 10**399981 parts. > > Numbers like 10**520000 (the reciprocal of the product found) is a > perfectly reasonable number if you're dealing with (say) permutations. > Admittedly, even something of the complexity of Go only has about 10**150 > possible moves, but Go is simplicity itself compared to (say) Borges' > Library of Babel or the set of all possible genomes. And numbers of that size needn't be intractable. The run time to generate a Collatz sequence is logarithmic to the starting number. A number with 53328 digits only takes about 2.5 million iterations. Of course, you can't test ALL the numbers of that size, but often we're researching only certain types, such as the ith kth Generation Type [1,2] Mersenne Hailstone: Closed form: Type12MH(k,i) Find ith, kth Generation Type [1,2] Mersenne Hailstone using the closed form equation 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 2**14348909-1 generation: 8 2**129140165-1 generation: 9 2**1162261469-1 generation:10 1.141 seconds Generation 10 has over a billion bits or >300 million digits. I had to stop there because an exponent of 32 bits gives an "outrageous exponent" error. The closed form formula only works for a very specific type of number. The research goal was to come with a generic algorithm that works with any Type and see if the algorithm obtains the same results: Verify Type12MH Hailstones: Find ith, kth Generation Type (xyz) Hailstone using the non-recursive equation (gmpy.divm(y**(k-1)-prev_gen[2],y-x,y**(k-1))/ y**(k-2))*xyz[1]**(k-1)+prev_gen[3] where i=((hailstone-geni(k,1,xyz))/(xyz[1]**k))+1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 2**14348909-1 generation: 8 2**129140165-1 generation: 9 2**1162261469-1 generation:10 4.015 seconds There are legitimate uses for such large numbers and Python's ability to handle this was what got me interested in using Python in the first place. > > It's not even what mathematicians call a "large number" -- it can be > written using ordinary notation of powers. For large numbers that can't > be written using ordinary notation, see here: > > http://en.wikipedia.org/wiki/Large_numberhttp://www.scottaaronson.com/writings/bignumbers.html > > For instance, Ackermann's Sequence starts off quite humbly: > > 2, 4, 27 ... > > but the fourth item is 4**4**4**4 (which has 10,154 digits) and the fifth > can't even be written out in ordinary mathematical notation. > > Calculating numbers like 10**520000 or its reciprocal is also a very good > exercise in programming. Anyone can write a program to multiply two > floating point numbers together and get a moderately accurate answer: > > product = X*Y # yawn > > But multiplying 200,000 floating point numbers together and getting an > accurate answer somewhere near 10**-520000 requires the programmer to > actually think about what they're doing. You can't just say: > > A,T,C,G = (0.35, 0.30, 0.25, 0.10) > product = map(operator.mul, [A*T*C*G]*200000) > > and expect to get anywhere. > > Despite my fear that this is a stupid attempt by the Original Poster's > professor to quantify the old saw about evolution being impossible > ("...blah blah blah hurricane in a junk yard blah blah Concorde blah blah > blah..."), I really like this homework question. > > -- > Steven. From george.sakkis at gmail.com Thu Oct 25 02:46:08 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 25 Oct 2007 06:46:08 -0000 Subject: about functions question In-Reply-To: <1193293696.450188.108330@q3g2000prf.googlegroups.com> References: <1193293696.450188.108330@q3g2000prf.googlegroups.com> Message-ID: <1193294768.397045.313780@e9g2000prf.googlegroups.com> On Oct 25, 2:28 am, NoName wrote: > I try it: > > def b(): > ... > a() > ... > > def a(): > ... > b() > ... > > b() > it's not work. It sure does. Please post full code and error message, something else is wrong, not the cyclic reference. George From allen.fowler at yahoo.com Mon Oct 15 20:06:28 2007 From: allen.fowler at yahoo.com (allen.fowler) Date: Mon, 15 Oct 2007 17:06:28 -0700 Subject: Simple HTML template engine? In-Reply-To: References: <1192419411.895715.138450@e9g2000prf.googlegroups.com> Message-ID: <1192493188.741846.30260@v29g2000prd.googlegroups.com> CherryPy looks nice... though I am just looking to generate static reports. Thanks anyway... I'll keep it in mind for the future. On Oct 15, 4:38 am, "Ciprian Dorin Craciun" wrote: > Have you tried CherryPy?http://www.cherrypy.org/ > > It's not a template engine, but a simple web server engine, and > you could code your conditionals and loops directly in Python... When > I have tried it, it looked very nice and easy. > > Ciprian. From eduardo.padoan at gmail.com Tue Oct 30 07:11:18 2007 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Tue, 30 Oct 2007 09:11:18 -0200 Subject: A Python 3000 Question In-Reply-To: References: Message-ID: On 10/29/07, brad wrote: > Will len(a_string) become a_string.len()? I was just reading > > http://docs.python.org/dev/3.0/whatsnew/3.0.html > > One of the criticisms of Python compared to other OO languages is that > it isn't OO enough or as OO as others or that it is inconsistent. And > little things such as this seem to support those arguments. Not that it > matters really... just seems that classes with methods used in a more > consistent manner would be more appropriate in an OO langauage. Is there > a reason that len cannot be a method? > > a_string.lower() makes sense, as does a_string.split(), > a_string.strip()... why not a_string.len()? This is a FAQ: http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From hyugaricdeau at gmail.com Mon Oct 8 10:45:13 2007 From: hyugaricdeau at gmail.com (Hyuga) Date: Mon, 08 Oct 2007 14:45:13 -0000 Subject: Howto Launch a windows application ? In-Reply-To: References: Message-ID: <1191854713.123997.50090@o80g2000hse.googlegroups.com> On Oct 3, 5:39 pm, stef mientki wrote: > > from subprocess import * > > cmd =[] > cmd.append ( 'D:\\PIC-tools\\JALxxx\\jalv2_3.exe' ) > cmd.append ( '-long-start' ) > cmd.append ( '-d') > cmd.append ( '-clear' ) > cmd.append ( '-sD:\\PIC-tools\\JAL\\libs2' ) > cmd.append ( 'd:\\pic-tools\\jal\\programs\\test_rs232\\test_rs232_hw.jal' ) > cmd.append ( '>d:\\data_actueel\\d7_test_browser\\temp.log' ) This is sort of aside from your original question, but I should also point out how unnecessary all those 'cmd.append's are. You can initialize the list all at once simply like so: cmd =['D:\\PIC-tools\\JALxxx\\jalv2_3.exe', '-long-start', '-d', '-clear', '-sD:\\PIC-tools\\JAL\\libs2', 'd:\\pic-tools\\jal\\programs\\test_rs232\\test_rs232_hw.jal', '>d:\\data_actueel\\d7_test_browser\\temp.log'] Hyuga From google at mrabarnett.plus.com Thu Oct 18 19:44:38 2007 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 18 Oct 2007 16:44:38 -0700 Subject: Noob questions about Python In-Reply-To: <1192687508.636842.49940@z24g2000prh.googlegroups.com> References: <1192649863.496557.230730@v29g2000prd.googlegroups.com> <1192658316.048082.212190@v23g2000prn.googlegroups.com> <1192687508.636842.49940@z24g2000prh.googlegroups.com> Message-ID: <1192751078.506979.170580@z24g2000prh.googlegroups.com> On Oct 18, 7:05 am, Michele Simionato wrote: > On Oct 17, 5:58 pm, Ixiaus wrote: > > > def bin2dec(val): > > li = list(val) > > li.reverse() > > res = [int(li[x])*2**x for x in range(len(li))] > > print sum(res) > > > It basically does the same thing int(string, 2) does. > > > Thank you for the responses! > > BTW, here is the reverse function dec2bin, so that you can > bang your head on it for a while ;) > It returns '' when number == 0, so you need to test for that case: > def baseN(number, N=2): > """ > >>> baseN(9, 2) > '1001' > """ > assert 2 <= N <= 10 > assert isinstance(number, int) and number >= 0 if number == 0: return "0" > b = [] > while number: > b.append(str(number % N)) > number /= N > return ''.join(reversed(b)) > > Michele Simionato From lasses_weil at klapptsowieso.net Mon Oct 29 06:09:40 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 29 Oct 2007 11:09:40 +0100 Subject: ANN: Veusz 1.0 - a scientific plotting package In-Reply-To: References: Message-ID: <4725b164$0$4359$9b4e6d93@newsspool4.arcor-online.net> Jeremy Sanders wrote: > I'm pleased to announce Veusz 1.0. Source, windows and linux i386 binaries > are available. Jeremy Sanders > > [snip] > > Veusz is a scientific plotting package written in Python, using PyQt4 > for display and user-interfaces, and numpy for handling the numeric > data. Veusz is designed to produce publication-ready Postscript/PDF > output. The user interface aims to be simple, consistent and powerful. > Not that I don't value your effort, but why another plotting package while we have pyx and matplotlib already? /W From panguohualove at sina.com Mon Oct 1 21:41:34 2007 From: panguohualove at sina.com (panguohua) Date: Mon, 01 Oct 2007 18:41:34 -0700 Subject: I earn $36800 a month with google adsense In-Reply-To: <1191240372.428917.253350@o80g2000hse.googlegroups.com> References: <1191215629.384871.280240@o80g2000hse.googlegroups.com> <1191240372.428917.253350@o80g2000hse.googlegroups.com> Message-ID: <1191289294.449262.234020@r29g2000hsg.googlegroups.com> On 10 1 , 8 06 , panguohua wrote: > On 10 1 , 1 13 , panguohua wrote: > > >www.space666.com > > > a good website for making money with your blog.more information there > > support!!!!!!!!!!!!!!!!!!!!! > !!!!!!!!!!!!!!!!!!!!!!!!! good From joshua at eeinternet.com Thu Oct 18 21:42:16 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Thu, 18 Oct 2007 17:42:16 -0800 Subject: ConfigParser preserving file ordering References: <200710190123.39177.Frank.Aune@broadpark.no> Message-ID: On Thursday 18 October 2007 15:23, Frank Aune wrote: > Hello, > > I use ConfigParser and actually quite like it, EXCEPT that it doesnt > preserve the section order of the original config file when writing a new. > This behaviour is hopeless IMO, and I've been looking for alternatives. > > I've been reading the interesting discussion on python-dev about > improvements to ConfigParser: > > http://mail.python.org/pipermail/python-dev/2006-January/060138.html > > I know there are patches to archieve what I want, but tbh I need > functionality present in the standard library or as a last option > sub-class ConfigParser to archieve ordering preservation. > > Since the thread above is nearly two years old, I'm wondering if something > has happended in this department? Have you taken a look at ConfigObj? http://www.voidspace.org.uk/python/configobj.html j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From kadeko at gmail.com Wed Oct 31 08:01:59 2007 From: kadeko at gmail.com (looping) Date: Wed, 31 Oct 2007 05:01:59 -0700 Subject: Creating a temporary file in Python Message-ID: <1193832119.872710.108920@k79g2000hse.googlegroups.com> Hi, I want to create a temporary file, read it in an external command and finally delete it (in Windows XP). I try to use tempfile module but it doesn't work, the file couldn't be open by my other process (error like: SP2-0310: unable to open file "c: \docume~1\looping\locals~1\temp\tmpau81-s.sql") Is there a way to make it work or I have to manually manage everything ? My non working code: f = tempfile.NamedTemporaryFile(suffix='.sql') f.write(txt) f.flush() p = subprocess.Popen([SQL_PLUS, '-s', dsn, '@', SQL_PLUS_SCRIPT, f.name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() f.close() Thanks for your help. From sjmachin at lexicon.net Wed Oct 10 07:05:28 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Oct 2007 21:05:28 +1000 Subject: Last value of yield statement In-Reply-To: <1192011545.384425.189530@o80g2000hse.googlegroups.com> References: <1192011545.384425.189530@o80g2000hse.googlegroups.com> Message-ID: <470cb1fd@news.eftel.com.au> On 10/10/2007 8:19 PM, Shriphani wrote: > Hello all, > > Let us say I have a function like this: > > def efficientFiller(file): > worthless_list = [] > pot_file = open(file,'r') > pot_file_text = pot_file.readlines() > for line in pot_file_text: > if line.find("msgid") != -1: > message_id = shlex.split(line)[1] > if message_id in dictionary: > number = pot_file_text.index(line) > corresponding_crap = > dictionary.get(message_id) > final_string = 'msgstr' + " " + '"' + > corresponding_crap + '"' + '\n' > pot_file_text[number+1] = final_string > yield pot_file_text > > efficient_filler = efficientFiller("libexo-0.3.pot") > new_list = list(efficient_filler) > print new_list > > > > I want to plainly get the last value the yield statement generates. > How can I go about doing this please? > I don't think that 'efficient' and 'plainly' mean what you think they mean. However to answer your question: new_list[-1] if new_list else None BTW I get the impression that the yield statement yields the whole pot_file_text list each time, so that new_list will be a list of lists; is that intentional? From george.sakkis at gmail.com Thu Oct 11 21:01:41 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 12 Oct 2007 01:01:41 -0000 Subject: Declarative properties In-Reply-To: <1192143867.686910.210320@t8g2000prg.googlegroups.com> References: <1192103298.065386.243670@o3g2000hsb.googlegroups.com> <1192143867.686910.210320@t8g2000prg.googlegroups.com> Message-ID: <1192150901.408517.262360@i13g2000prf.googlegroups.com> On Oct 11, 7:04 pm, George Sakkis wrote: > You could take it even further by removing the need to repeat the > attribute's name twice. Currently this can done only through > metaclasses but in the future a class decorator would be even > better: Replying to myself here, but actually metaclasses is not the only way; another solution involves a descriptor class: class Property(object): # cache the mapping of types to 'private' attribute names _type2attrname = {} def __init__(self, format='_%s'): self._format = format def __get__(self, obj, type=None): try: name = self._type2attrname[type(obj)] except KeyError: self._type2attrname[type(obj)] = name = self._get_propname(obj) return getattr(obj, name) def __set__(self, obj, value): try: name = self._type2attrname[type(obj)] except KeyError: self._type2attrname[type(obj)] = name = self._get_propname(obj) setattr(obj, name, value) def _get_propname(self, obj): for cls in type(obj).mro(): for name,value in cls.__dict__.iteritems(): if value is self: return self._format % name assert False # unreachable #---- example ------------------------------------ class Person(object): name = Property() def __init__(self, name): self.name = name p = Person('John') q = Person('Mike') print p.name, q.name print p.__dict__ George From josephoswald at gmail.com Tue Oct 9 09:50:03 2007 From: josephoswald at gmail.com (josephoswald+gg@gmail.com) Date: Tue, 09 Oct 2007 06:50:03 -0700 Subject: The fundamental concept of continuations In-Reply-To: <470b1b30$0$11022$4c368faf@roadrunner.com> References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> <470b1b30$0$11022$4c368faf@roadrunner.com> Message-ID: <1191937803.785801.294310@v3g2000hsg.googlegroups.com> On Oct 9, 2:09 am, "." wrote: > On Tue, 09 Oct 2007 05:15:49 +0000, gnuist006 wrote: > > (3) Is it present in python and java ? > > Certainly not Java, I dunno about Python. I've never seen someone use > them in Python, but the pythonistas seem to want to add everything but a > decent lambda to their language so I wouldn't be surprised if someone had > added a call/cc. Ruby has it. > Continuations exist in all computer languages---actually, in anything that executes code. The continuation is simply "what will happen for the rest of the program execution." What might or might not exist is an explicit linguistic mechanism to examine it, refer to the continuation as a function, or to save it for later use. > > (4) Its implementation in assembly. for example in the manner that > > pointer fundamentally arises from indirect addressing and nothing new. > > So how do you juggle PC to do it. > The continuation is typically present in the stack, which contains all the control-flow information needed to continue program execution from this point. (I.e., the function call mechanism includes a step saving the location of the instruction to execute when the function call is complete, and any registers that it will restore after the function returns because the function call might destroy them.) How you save that continuation for later, possibly repeated, use from a different location in the program is a different question. From fw3 at hotmail.co.jp Thu Oct 25 14:38:28 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Thu, 25 Oct 2007 18:38:28 +0000 Subject: parsing the output from matlab In-Reply-To: References: Message-ID: Hi, Travis, Thanks very much for your help. Since each day, my mail box is flooded with python forum email. I simply overlooked your email, eventhough I am desperately waiting for the help. Today when I googled the topic and found your reply. I am sorry that I send a similar help request to the forum today. Frank Date: Tue, 23 Oct 2007 10:08:28 -0400From: travis.brady at gmail.comTo: python-list at python.orgSubject: Re: parsing the output from matlab On 10/22/07, wang frank wrote I have a big log file generated from matlabe, for each variable, it print the name of the variable and an empty line and then the value. such as: x1 = 0.1 y = 7 z = 6.7 x1 = 0.5 I want to use python to parse the file and selectively print out the vairable and its value. For example, I want to print out all the value related with x1, so the output will be x1 = 0.1x1 = 0.5. Here is a fairly naive version with re named groups that should handle the example you pasted. In [62]: import re In [63]: px = re.compile('(?P\w+)\s=\s+(?P\d.*\d*)') In [64]: for var in px.finditer(s): print "%s = %s" %(var.group('variable'), var.group('value')) ....: ....: a = 0.1 y = 7 z = 6.7 x1 = 0.5 To filter for only the x1's just test for the group named 'variable': In [66]: for var in px.finditer(s): ....: if var.group('variable')=='x1': ....: print "%s = %s" %(var.group('variable'), var.group('value')) ....: ....: x1 = 0.5 But I'm betting these files get more complex than just the snippet you included, in which case it's probably worth looking at pyparsing http://pyparsing.wikispaces.com/ and regular expressions. -- Travis Bradyhttp://travisbrady.com/ _________________________________________________________________ ???????????????????Hotmail Plus ?????????? http://get.live.com/mail/options -------------- next part -------------- An HTML attachment was scrubbed... URL: From jfcanac at free.fr Fri Oct 5 04:48:39 2007 From: jfcanac at free.fr (Jean-Francois Canac) Date: Fri, 5 Oct 2007 10:48:39 +0200 Subject: Real time plot References: <004d01c805a1$7295e9c0$1a02a8c0@ERTF.ERTF.COM> <47051599$0$27367$ba4acef3@news.orange.fr> <4705e3f5$0$31086$afc38c87@news.optusnet.com.au> Message-ID: <4705f9fd$0$5077$ba4acef3@news.orange.fr> "Lawson Hanson" a ?crit dans le message de news: 4705e3f5$0$31086$afc38c87 at news.optusnet.com.au... > Nicholas Bastin wrote: >> On 10/4/07, Jean-Francois Canac wrote: >>> mailman.1493.1191484119.2658.python-list at python.org... >>>> I would draw dots on a suitably sized Tkinter canvas, after drawing a >>>> schematic >>>> of the race track (laborious). >>>> >>>> 20 per second will be no problem, provided the machine is half decent. >>>> >>>> What is the speed at which the com port runs? >>>> >>>> - Hendrik >>>> >>> The com port run at 19.2 kb/s. >>> My pb is more the real time aspect: to see the plot changing in real >>> time >>> than the com aspect as the installation is already running with programs >>> in >>> c++. >>> The PC on which it is running is good enought >>> For me the interest is to migrate all taht on python to be able to make >>> fast >>> changes when it is of interest >> >> The success of this will have more to do with design than programming >> language. Any GUI toolkit which allows partial screen updates can be >> made to update at least as fast as your screen refresh rate, even in >> python. >> >> -- >> Nick > > If you are using Tkinter (probably a very good choice), just remember > to make periodic (i.e., once per I/O processing loop) calls to: > > Tkinter.update_idletasks() > > which will update the display window, etc. > > Regards, > > Lawson > Finally I tried this coding and it works #========================== import time import pylab pylab.ion() lat,long,vit = pylab.load(r"c:\pytst\test1.txt",usecols=(1,2,3), unpack=True) lat_min=pylab.amin(lat) lat_max=pylab.amax(lat) long_min=pylab.amin(long) long_max=pylab.amax(long) print "start" timefig = pylab.figure(1) timesub = pylab.subplot(111) x=[] y=[] lines = pylab.plot(x,y) print lat_min,lat_max,long_min,long_max for i in range(len(lat)): x.append(long[i]) y.append(lat[i]) lines[0].set_data(x,y) timesub.set_xlim(long_min,long_max) timesub.set_ylim(lat_min,lat_max) pylab.draw() #================ The kind of data I have in the text file are just below Now I have two problems, I think my coding is not very clean as when I try yo close or manipulate the windows it generates an error secondly I think it is a bit slow. I would much prefer something quicker and to be able to adapt the speed dynamically with a sleep instruction or something as that 09:25:08.50 46.863930 3.161866 56.9 Km/h 09:45:07.75 46.863907 3.161786 11.5 Km/h 09:45:08.0 46.863914 3.161794 12.4 Km/h 09:45:08.25 46.863918 3.161804 13.4 Km/h 09:45:08.50 46.863922 3.161814 14.5 Km/h 09:45:08.75 46.863930 3.161825 15.4 Km/h 09:45:09.0 46.863934 3.161837 16.1 Km/h 09:45:09.25 46.863941 3.161848 16.6 Km/h 09:45:09.50 46.863945 3.161861 17.1 Km/h 09:45:09.75 46.863953 3.161874 17.3 Km/h From KDawg44 at gmail.com Thu Oct 11 11:53:45 2007 From: KDawg44 at gmail.com (KDawg44) Date: Thu, 11 Oct 2007 15:53:45 -0000 Subject: Script to Remove Attachments in Exchange Mailbox In-Reply-To: References: <1192110265.529187.48770@y42g2000hsy.googlegroups.com> Message-ID: <1192118025.085938.283610@19g2000hsx.googlegroups.com> On Oct 11, 10:03 am, Tim Golden wrote: > KDawg44 wrote: > > Hi, > > > I am frustrated with my users who send large files around the office > > instead of using the network shares. > > [...] > > > Which means that there are 8 copies of the same file 4MB taking up > > space, or a 4MB file turned into a 32MB file." > > > So, what I would like, is to write a script that parses the exchange > > mailbox, and removes all attachments over a certain size (say 500K) > > that are attached to messages that are more than 2 weeks old, or that > > are in sent items. I would like to write to a log file all the > > changes that are made then email that log file to the mailbox that was > > just trimmed. > > I have something v. similar, only it's at work and I'm not. Maybe tomorrow. > What it does -- I think, it's been a while -- is to rip through any > mailboxes finding attachments over a certain size, saving them to some > kind of folder structure on the user's home drive and replacing the > attachment by a link to the attachment. I have another script which, > independently, rips through users' home shares finding duplicates and > linking them to one copy. > > It's a while since they were last run to they're probably quite > dusty but it sounds like the kind of thing you're after. > > TJG That sounds great! Thanks! From mensanator at aol.com Mon Oct 1 21:03:18 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 01 Oct 2007 18:03:18 -0700 Subject: Using fractions instead of floats In-Reply-To: <1191284422.899591.308960@g4g2000hsf.googlegroups.com> References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> <1191206183.441075.167450@57g2000hsv.googlegroups.com> <1191284422.899591.308960@g4g2000hsf.googlegroups.com> Message-ID: <1191286998.727959.8010@50g2000hsm.googlegroups.com> On Oct 1, 7:20 pm, richy... at gmail.com wrote: > On Oct 1, 8:30 am, Nick Craig-Wood wrote: > > > >>> mpq(1,3)+0.6 > > mpq(14,15) > > Golly! That's quite impressive. And more than a little bit magic as > well, since 0.6 is definitely not the same as 3/5. It's not? Since when? >>> print gmpy.mpq('0.6') 3/5 > How on earth does this work? The rationals are always reduced to lowest terms. > > Richard From saptarshi.guha at gmail.com Wed Oct 3 09:43:21 2007 From: saptarshi.guha at gmail.com (sapsi) Date: Wed, 03 Oct 2007 06:43:21 -0700 Subject: LoopingCall vs internet.TimerService (Twisted) Message-ID: <1191419001.173510.49660@22g2000hsm.googlegroups.com> Hi, I guess this is not the most appropriate forum but i tried the twisted forum to not avail so here goes. I have written a server which accepts connections from clients, takes requests and adds them to a Queue (a python object of Queue.Queue). Now i have two approaches a) At startup, my server(a subclass of pb.Root) runs a "dispatcher" function using task.LoopingCall(dispatcher).start(0.1) b)Create a separate subclass of internet.TimerService whose function is dispatcher [INFO: dispatcher has methods like obj.callRemote, addCallback and addErrback] I checked the source and it seems Loopingcall is implemented through callLaters//Callbacks and TimerService has LoopingCall in it. So which is better, neater, safer? loopingcall of timerservice? also is it safe to do the calls mentioned in INFO within dispatcher? Thank you for your time Saptarshi From steve at holdenweb.com Wed Oct 17 07:11:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 17 Oct 2007 07:11:48 -0400 Subject: negative base raised to fractional exponent In-Reply-To: <1192573562.622390.218860@i38g2000prf.googlegroups.com> References: <1192571332.470809.279160@v23g2000prn.googlegroups.com> <1192573562.622390.218860@i38g2000prf.googlegroups.com> Message-ID: John Machin wrote: > On Oct 17, 8:03 am, Steve Holden wrote: >> schaefer... at gmail.com wrote: >>> Does anyone know of an approximation to raising a negative base to a >>> fractional exponent? For example, (-3)^-4.11111 since this cannot be >>> computed without using imaginary numbers. Any help is appreciated. >> A couple of questions. >> >> 1. How do you approximate a complex number in the reals? That doesn't >> make sense. >> >> 2. x ^ -4.1111 = 1 / (x ^ 4.1111), so where do complex numbers enter >> into this anyway? >> >> 3. I think you will find the complex numbers start to emerge as you >> explore fractional exponents. > > This is part of the story -- the other part is that the story differs > depending on whether x is positive or negative. > >> This being Python, and an interactive interpreter being available, you >> can always just try it: >> >> >>> -3 ** -4.1111 >> -0.010927147607830808 > > Steve, Trying to memorise the operator precedence table for each of > several languages was never a good idea. I admit advanced age :-) and > give up and use parentheses, just like the OP did: > >>>> (-3)**-4.11111 > Traceback (most recent call last): > File "", line 1, in > ValueError: negative number cannot be raised to a fractional power > > Best regards, > John > Well I guess I'd better admit to advances age too. Particularly since there was a python-dev thread about precedence, unaries and exponentiation not too long ago. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it From parnell.s at comcast.net Wed Oct 17 15:37:43 2007 From: parnell.s at comcast.net (Ixiaus) Date: Wed, 17 Oct 2007 12:37:43 -0700 Subject: Noob questions about Python Message-ID: <1192649863.496557.230730@v29g2000prd.googlegroups.com> I have recently (today) just started learning/playing with Python. So far I am excited and impressed (coming from PHP background). I have a few questions regarding Python behavior... val = 'string' li = list(val) print li.reverse() returns nothing, but, val = 'string' li = list(val) li.reverse() print li returns what I want. Why does Python do that? Also I have been playing around with Binary math and noticed that Python treats: val = 00110 as the integer 72 instead of returning 00110, why does Python do that? (and how can I get around it?) Grateful for any replies! From kyrie at uh.cu Thu Oct 11 00:05:10 2007 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Thu, 11 Oct 2007 04:05:10 +0000 Subject: Duck Typing and **kwds Message-ID: <1192075510.470da0f6a7958@comuh.uh.cu> Hi there. I just tried this test: ==== def f(**kwds): print kwds import UserDict d = UserDict.UserDict(hello="world") f(**d) ==== And it fails with a TypeError exception ("f() argument after ** must be a dictionary"). I find that weird, as UserDict should support all protocols that dict supports, yet it doesn't seem to support ** unpacking. If instead of UserDict I use a derivate class from dict (class mydict(dict):pass), the ** operator works as expected. It also works if I execute f(**dict(d)) instead. Is that behavior expected? Is there any reason (performance, perhaps?) to break duck-typing in this situation? Regards, -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie -- "Al mundo nuevo corresponde la Universidad nueva" UNIVERSIDAD DE LA HABANA 280 aniversario From steve at holdenweb.com Thu Oct 4 07:54:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 04 Oct 2007 07:54:50 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <13frd6vtarbee75@corp.supernews.com> <85ve9ov971.fsf@lola.goethe.zz> <47041303$0$13930$fa0fcedb@news.zen.co.uk> <8sn8g39v75hg114lf3m9m911ib2ajddaui@4ax.com> Message-ID: Lawrence D'Oliveiro wrote: > In message , Steve > Holden wrote: > >> Lawrence D'Oliveiro wrote: >> >>> In message <8sn8g39v75hg114lf3m9m911ib2ajddaui at 4ax.com>, George Neuner >>> wrote: >>> >>>> The Christian Bible says "In the beginning was the Word..." >>> Which is an English mistranslation from the Greek "logos". >> So, now you're telling me that the Garden of Eden was actually a >> *marketing campaign*? > > Different Bible book, different author, different original language. So Genesis was written in Hebrew? I have no clue as to where the manuscripts were found. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it From alexandre.badez at gmail.com Fri Oct 12 04:36:33 2007 From: alexandre.badez at gmail.com (Alexandre Badez) Date: Fri, 12 Oct 2007 01:36:33 -0700 Subject: Cross-platform GUI development In-Reply-To: <1192176809.756259.316980@v29g2000prd.googlegroups.com> References: <1192176809.756259.316980@v29g2000prd.googlegroups.com> Message-ID: <1192178193.734126.253610@z24g2000prh.googlegroups.com> On Oct 12, 10:13 am, "psaff... at googlemail.com" wrote: > I've been programming in Python for 5 or more years now and whenever I > want a quick-n-dirty GUI, I use Tkinter. This is partly because it's > the first toolkit I learnt, but also because it's part of the standard > Python distribution and therefore easy to get Python apps to work > cross platform - it usually requires almost no porting effort. > > However, when I need a little bit more grunt, I tend to turn to Tix, > which I thought was also fairly standard. However, this week, I wrote > a Tix application under Linux which I'd really like to work on Mac OS > and it's proving fairly painful to get it going. There is no Tix in > the standard fink or apt repositories and when I download a tar-ball, > it wouldn't build because it had a lot of unmet dependencies. I then > read a post which said that only Tkinter/Python people really use Tix > anymore and people in tcl/tk moved onto better toolkits long ago. > > My question is if Tix is old hat, what is the GUI toolkit I *should* > be using for quick-n-dirty cross platform GUI development? I guess > this is tangentially related to: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > I hope this isn't a stupid question. I'm wearing flame retardant > underwear. > > Peter Personnaly, I use PyQt simply because I prefere Qt to Gtk, witch is much more integrated with all desktop than Gtk. In fact, your application in Qt on Mac, Win or Linux look like a native app. Just a question of "feeling" I think; because most of those GUI framework, offer quiet the same functionality. From anandology at gmail.com Tue Oct 30 23:19:50 2007 From: anandology at gmail.com (Anand) Date: Wed, 31 Oct 2007 03:19:50 -0000 Subject: python in academics? In-Reply-To: <1193750524.107361.130600@50g2000hsm.googlegroups.com> References: <1193715569.261522.219520@i13g2000prf.googlegroups.com> <1193750524.107361.130600@50g2000hsm.googlegroups.com> Message-ID: <1193800790.817105.92720@e34g2000pro.googlegroups.com> On Oct 30, 6:22 pm, BartlebyScrivener wrote: > On Oct 29, 10:39 pm, sandipm wrote: > > > seeing posts from students on group. I am curious to know, Do they > > teach python in academic courses in universities? > > This came up a while back. See: > > http://tinyurl.com/2pjjua > > If that doesn't work, search the Google group for "Python taught in > schools" > > rd Here is another interesting article "Algorithm Education in Python": http://www.ece.uci.edu/~chou/py02/python.html From lucian.cancescu at gmail.com Wed Oct 31 17:10:26 2007 From: lucian.cancescu at gmail.com (elf) Date: Wed, 31 Oct 2007 21:10:26 -0000 Subject: 3 number and dot.. In-Reply-To: <1193860737.687984.13400@k79g2000hse.googlegroups.com> References: <1193860737.687984.13400@k79g2000hse.googlegroups.com> Message-ID: <1193865026.987756.210320@o3g2000hsb.googlegroups.com> On Oct 31, 9:58 pm, Abandoned wrote: > Hi.. > I want to do this: > for examle: > 12332321 ==> 12.332.321 > > How can i do? Hi, If you want to define your own function, no matter what the length of the number is or what separator you want to choose, this will work: def conv(s, sep='.'): start=len(s)%3 last=start result=s[0:start] for i in range(start+1,len(s)): if (i-start)%3==0: if last==0: result+=s[last:i] else: result+=sep+(s[last:i]) last=i if last==len(s) or last==0: result+=s[last:len(s)] else: result+=sep+s[last:len(s)] return result print conv('1234567890000000') print conv('1') print conv('123') print conv('1234') >>> 1.234.567.890.000.000 1 123 1.234 From paul.nospam at rudin.co.uk Sun Oct 21 02:50:34 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Sun, 21 Oct 2007 07:50:34 +0100 Subject: logging module - restricted mode error References: <87przflpir.fsf@rudin.co.uk> <1192907914.138999.114910@k35g2000prh.googlegroups.com> Message-ID: <87ejfphsg5.fsf@rudin.co.uk> Vinay Sajip writes: > On 16 Oct, 04:14, Paul Rudin wrote: >> I'm occasionally seeing tracebacks like this: >> >> Traceback (most recent call last): >> File "logging/__init__.py", line 744, in emit >> File "logging/__init__.py", line 630, in format >> File "logging/__init__.py", line 421, in format >> RuntimeError: instance.__dict__ not accessible in restricted mode >> >> I'm not sure what it means. Googling leads me to >> but that says that those >> modules were disabled in 2.3 and I'm running 2.5.1. In any case I'm >> not using them (although it could be that one of the 3rd party modules >> I'm using does something.) >> >> Could someone please explain what this error means? > > Can you say a little bit more about the execution environment? For > example, are you running under mod_python? If so, which version? I'm not running under mod_python - but this is using cherrypy. I also do some passing of pickled objects between two python processes, which I guess could be relevant. > > When googling, did you search for the exact text of the error message? > For example, did you see the following post? > > http://mail-archives.apache.org/mod_mbox/httpd-python-dev/200404.mbox/%3C408661A5.3010001 at sjsoft.com%3E > I hadn't noticed that particularly, but I'm still a little unclear as to what's going on. That thread dates from 3 years ago and it seems to imply that mod python is using restricted mode (in the sense of the the rexec module), which won't run in 2.5 will it? One parts that says: "Restricted mode is a strange beast, in that there isn't really anything like a "restricted mode" flag, but it looks at a pointer somwhere (don't remember now), and if it's not what is expected, it concludes that it's in restricted mode. So this behaviour is actually a sign of a bug where an object is created in one subinterpreter but is running in another... These bugs can be hard to track down." What exactly is meant by a subinterpreter? Python running in a subprocess? From ben at benfinney.id.au Sun Oct 28 18:56:48 2007 From: ben at benfinney.id.au (Ben Finney) Date: Mon, 29 Oct 2007 09:56:48 +1100 Subject: coverage.py: "Statement coverage is the weakest measure of code coverage" Message-ID: <87bqaihmq7.fsf@benfinney.id.au> Howdy all, Ned Batchelder has been maintaining the nice simple tool 'coverage.py' for measuring unit test coverage. On the same site, Ned includes documentation by the previous author, Gareth Rees, who says in the "Limitations" section: Statement coverage is the weakest measure of code coverage. It can't tell you when an if statement is missing an else clause ("branch coverage"); when a condition is only tested in one direction ("condition coverage"); when a loop is always taken and never skipped ("loop coverage"); and so on. See [Kaner 2000-10-17] for a summary of test coverage measures. So, measuring "coverage of executed statements" reports complete coverage incorrectly for an inline branch like 'foo if bar else baz', or a 'while' statement, or a 'lambda' statement. The coverage is reported complete if these statements are executed at all, but no check is done for the 'else' clause, or the "no iterations" case, or the actual code inside the lambda expression. What approach could we take to improve 'coverage.py' such that it *can* instrument and report on all branches within the written code module, including those hidden inside multi-part statements? -- \ "Technology is neither good nor bad; nor is it neutral." | `\ ?Melvin Kranzberg's First Law of Technology | _o__) | Ben Finney From chowroc.z+l at gmail.com Mon Oct 22 01:08:22 2007 From: chowroc.z+l at gmail.com (Roc Zhou) Date: Mon, 22 Oct 2007 13:08:22 +0800 Subject: A near realtime fs mirror application (for backup, written in Python, by Linux inotify) Message-ID: <7847e5160710212208w50293c85rdbc088b2543c2c31@mail.gmail.com> Hello: Recently I started an open source project "cutils" on the sourceforge: http://sourceforge.net/projects/crablfs/ The document can be found at: http://crablfs.sourceforge.net/#ru_data_man This project's mirrord/fs_mirror tool is a near realtime file system mirroring application across 2 or more hosts, something like MySQL's replication, but it's for the file system especially with a great amount of small files, such as the php scripts and images of a website or the (vitual) websites. There are several ways to use this tool. The simplest is to mirror a host's file system to another host for backup, and use the rotate function(in the future version) or rotate scripts to get a daily or hourly snapshot with the hard link. Or futhur more, you can use it this way: This graph should be displayed with monospaced fonts: +----------+ | worker | -[mirrord] -----------\ +----------+ | ...... | | +----------+ | | worker | -[mirrord] -----------\ +----------+ | V [fs_mirror] | +----------+ +----------+ | worker | -[mirrord] ---> | backup | +----------+ +----------+ | | [take_over] | | | V | +----------+ | | rescue | <------------------- NFS +----------+ This is the multi to one backup, which is cost efficient. If one of the worker hosts fails, you can subsitute the failed worker with the rescue host, with the aid of any high available method, such as heartbeat project. By this way, you can use 1 or 2 hosts to support the HA of more than 3 servers. Or you can also use it as an IDS(Intrusion Detection System) like a realtime "tripware", or you can make a mirror chain that a host B mirrors from A and be mirrored by C, etc ... I will also try to research a way to use it as a distributed implemetation with one write and multi-read model. mirrord/fs_mirror makes use of inotify, which is a function afforded by the recent Linux (from 2.6.12). It is a counterpart of FAM, since Linux FAM has stopped so long. Now it works for me, on a RHEL4 system and the LFS 6.2, I hope this tool can be useful to you too. Thanks. -- ------------------------------------------------------------------------ My Projects: http://sourceforge.net/projects/crablfs http://crablfs.sourceforge.net/ http://crablfs.sourceforge.net/#ru_data_man http://crablfs.sourceforge.net/tree.html http://cralbfs.sourceforge.net/sysadm_zh_CN.html My Blog: http://chowroc.blogspot.com/ http://hi.baidu.com/chowroc_z/ Looking for a space and platform to exert my originalities (for my projects)... -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Oct 17 04:03:27 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Oct 2007 10:03:27 +0200 Subject: Last iteration? References: <5n94u3Fh5e4gU1@mid.uni-berlin.de> <5nebmhFhp48uU1@mid.uni-berlin.de> <1192603763.894935.39680@e34g2000pro.googlegroups.com> Message-ID: Raymond Hettinger wrote: > [Diez B. Roggisch] >> > out:) But I wanted a general purpose based solution to be available that >> > doesn't count on len() working on an arbitrary iterable. > > [Peter Otten] >> You show signs of a severe case of morbus itertools. >> I, too, am affected and have not yet fully recovered... > > Maybe you guys were secretly yearning for a magical last element > detector used like this: Not secretly... > def lastdetecter(iterable): > it = iter(iterable) > value = it.next() > for nextvalue in it: > yield (False, value) > value = nextvalue > yield (True, value) as that's what I posted above... > def lastdetecter(iterable): > "fast iterator algebra" > lookahead, t = tee(iterable) # make it cope with zero-length iterables lookahead = islice(lookahead, 1, None) > return chain(izip(repeat(False), imap(itemgetter(1), > izip(lookahead, t))), izip(repeat(True),t)) and that's the "somebody call the doctor -- now!" version ;) Peter From python at hope.cz Thu Oct 4 14:50:44 2007 From: python at hope.cz (Johny) Date: Thu, 04 Oct 2007 11:50:44 -0700 Subject: Python and SSL In-Reply-To: <877im4xd0f.fsf@pobox.com> References: <1190959345.041723.108130@k79g2000hse.googlegroups.com> <6cydncA2Jpv082DbnZ2dnUVZ_q6dnZ2d@comcast.com> <1191224526.856466.305980@57g2000hsv.googlegroups.com> <7xzlz2q53e.fsf@ruckus.brouhaha.com> <1191251260.376954.265060@22g2000hsm.googlegroups.com> <47012255.4020502@v.loewis.de> <470174FC.5060709@v.loewis.de> <1191389578.176470.161360@50g2000hsm.googlegroups.com> <47032DF5.4000809@v.loewis.de> <1191396724.394393.322320@57g2000hsv.googlegroups.com> <4703884A.10905@v.loewis.de> <1191420037.564584.103300@50g2000hsm.googlegroups.com> <877im4xd0f.fsf@pobox.com> Message-ID: <1191523844.528308.98180@y42g2000hsy.googlegroups.com> Martin and John, Thank you both for your replies Must I have OpenSSL imported in my Python program? So far I have been using only SSL support. Built-in SSL support works OK if I connect from my Python program directly to SSL server ( but not via proxy). L. From aleax at mac.com Sun Oct 7 15:55:29 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 7 Oct 2007 12:55:29 -0700 Subject: weakrefs and bound methods References: <4708f276$0$11868$3b214f66@tunews.univie.ac.at> <5msflnFepbdqU1@mid.uni-berlin.de> <47090d70$0$11610$3b214f66@tunews.univie.ac.at> Message-ID: <1i5m6dd.i5hymvsbitihN%aleax@mac.com> Mathias Panzenboeck wrote: ... > I only inserted them so I can see if the objects are really freed. How can > I see that without a __del__ method? You can use weakref.ref instances with finalizer functions - see the long post I just made on this thread for a reasonably rich and complex example. Alex From Frank.Aune at broadpark.no Thu Oct 18 19:23:38 2007 From: Frank.Aune at broadpark.no (Frank Aune) Date: Fri, 19 Oct 2007 01:23:38 +0200 Subject: ConfigParser preserving file ordering Message-ID: <200710190123.39177.Frank.Aune@broadpark.no> Hello, I use ConfigParser and actually quite like it, EXCEPT that it doesnt preserve the section order of the original config file when writing a new. This behaviour is hopeless IMO, and I've been looking for alternatives. I've been reading the interesting discussion on python-dev about improvements to ConfigParser: http://mail.python.org/pipermail/python-dev/2006-January/060138.html I know there are patches to archieve what I want, but tbh I need functionality present in the standard library or as a last option sub-class ConfigParser to archieve ordering preservation. Since the thread above is nearly two years old, I'm wondering if something has happended in this department? Thanks, Frank From besturk at gmail.com Wed Oct 17 09:39:35 2007 From: besturk at gmail.com (Abandoned) Date: Wed, 17 Oct 2007 06:39:35 -0700 Subject: Order by value in dictionary Message-ID: <1192628375.254492.183140@i38g2000prf.googlegroups.com> Hi.. I have a dictionary like these: a={'a': '1000', 'b': '18000', 'c':'40', 'd': '600'} ...... 100.000 element I want to sort this by value and i want to first 100 element.. Result must be: [b, a, d, c .....] ( first 100 element) I done this using FOR and ITERATOR but it tooks 1 second and this is very big time to my project. I want to learn the fastest method.. I'm sorry my bad english. Please help me. King regards.. From bdesth.quelquechose at free.quelquepart.fr Tue Oct 16 18:29:41 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 17 Oct 2007 00:29:41 +0200 Subject: Newbi Q: Recursively reverse lists but NOT strings? In-Reply-To: <13h6nlmd8aku2ea@corp.supernews.com> References: <53396d9e0710141406p6182bdat789fe1706225f345@mail.gmail.com> <471308FA.3070705@islandtraining.com> <53396d9e0710150238v2ccd3df7y42f89e776c31e524@mail.gmail.com> <13h6nlmd8aku2ea@corp.supernews.com> Message-ID: <47153b8c$0$1277$426a34cc@news.free.fr> Steven D'Aprano a ?crit : (snip) > def myreversed(sequence): > if isinstance(sequence, basestring): > return type(sequence)().join(reversed(sequence)) > else: > return type(sequence)(reversed(sequence)) > > (in fact, that's so simple I wonder why the built-in reversed() doesn't > do that). Because it returns an iterator, not a sequence. Building back the appropriate sequence type from when needed it is usually a definitive no-brainer, and there are case where you definitively *don't* want a full sequence to be built (like when iterating backward over a millions-element long list...). Definitively the right design choice here IMHO. My 2 cents From tim.arnold at sas.com Mon Oct 29 12:37:43 2007 From: tim.arnold at sas.com (Tim Arnold) Date: Mon, 29 Oct 2007 12:37:43 -0400 Subject: elementtree w/utf8 References: <47245EE6.7050808@web.de> Message-ID: "Stefan Behnel" wrote in message news:47245EE6.7050808 at web.de... > Tim Arnold wrote: >> On a related note, I have another question--where/how can I get the >> cElementTree.py module? Sorry for something so basic, but I tried >> installing >> cElementTree, but while I could compile with setup.py build, I didn't end >> up >> with a cElementTree.py file anywhere. > > That's because it compiles into a binary extension module, not a plain > Python > module (mind the 'c' in its name, which stands for the C language here). > > I don't know what the standard library extension is under HP-UX, but look > a > little closer at the files that weren't there before, you'll find it. > Depending on what you did to build it, it might also end up in the "build" > directory or as an installable package in the "dist" directory. > > >> The directory structure on my system >> (HPux, but no root access) doesn't work well with setup.py install. > > That shouldn't be a problem as long as you keep the binary in your > PYTHONPATH. > > As suggested before, if you have Python 2.5, you don't even need to > install it > yourself. > > Stefan very nice--thanks. I saw the cElementTree.sl file, but didn't realize it would work as-is. thanks, --Tim From http Thu Oct 11 12:32:15 2007 From: http (Paul Rubin) Date: 11 Oct 2007 09:32:15 -0700 Subject: Fwd: NUCULAR fielded text searchable indexing References: <7xtzoynm64.fsf@ruckus.brouhaha.com> <1192108745.766895.156050@19g2000hsx.googlegroups.com> Message-ID: <7xlka9629c.fsf@ruckus.brouhaha.com> aaron.watters at gmail.com writes: > > ...but it looks a little more akin to Solr than to Lucene. ... > > I'm not sure but I think nucular has aspects of both since > it implements both the search engine itself and also provides > XML and HTTP interfaces That sounds reasonable. > As a test I built an index with 10's of millions of entries > using nucular and most queries through CGI processes clocked > in in 100's of milliseconds or better -- which is quite acceptable, > for many purposes. How many items did each query return? When I refer to large result sets, I mean you often get queries that return 10k items or more (a pretty small number: typing "python" into google gets almost 30 million hits) and you need to actually examine each item, as opposed to displaying ten at a time or something like that (e.g. you want to present faceted results). > > So we're back to the perennial topic of parallelism in Python... > > ...Which is not such a big problem if you rely on disk caching > to provide the RAM access and use multiple processes to access > the indices. Right, another helpful strategy might be to use a solid state disk: http://www.newegg.com/Product/Product.aspx?Item=N82E16820147021 From mak at trisoft.com.pl Tue Oct 30 20:29:11 2007 From: mak at trisoft.com.pl (Grzegorz Makarewicz) Date: Wed, 31 Oct 2007 01:29:11 +0100 Subject: sgmlop - xmlrpclib - bang Message-ID: <4727CC57.1000608@trisoft.com.pl> simple data for simple test - my version fails after 10 loops after removing sgmlop.pyd from DLLs - everything is working as expected mak #python data='''\ mws.ScannerLogout 7 ''' import xmlrpclib def main(): i = 1 while 1: print i params, method = xmlrpclib.loads(data) i+=1 main() From deets at nospam.web.de Wed Oct 17 10:10:55 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 17 Oct 2007 16:10:55 +0200 Subject: Write by logging.FileHandler to one file by many processess References: <1192628746.196204.207620@t8g2000prg.googlegroups.com> Message-ID: <5nmjffFiouurU4@mid.uni-berlin.de> Alexandre Badez wrote: > On Oct 17, 3:33 pm, Rafa Zawadzki wrote: >> Hello. >> >> As I saw in logging source - there is no lock per file during making >> emit() (only lock per thread). >> >> So, my question is - is it safe to log into one file using many >> processess uses logging logger? >> >> Cheers, >> -- >> bluszczhttp://vegan-planet.net > > Well, there a dummy response: there is no true thread in Python (I > mean CPython). So there is no problems in this case (cf global > interpreter lock or GIL). You didn't read the statement of the OP - he explicitly doesn't ask about threads, but multiple processes writing to one file. I presume things get messed up... but I don't know for sure. Diez From xah at xahlee.org Thu Oct 18 00:15:26 2007 From: xah at xahlee.org (Xah Lee) Date: Wed, 17 Oct 2007 21:15:26 -0700 Subject: Elisp Tutorial: HTML Syntax Coloring Code Block Message-ID: <1192680926.420317.16630@v29g2000prd.googlegroups.com> Elisp Tutorial: HTML Syntax Coloring Code Block Xah Lee, 2007-10 This page shows a example of writing a emacs lisp function that process a block of text to syntax color it by HTML tags. If you don't know elisp, first take a gander at Emacs Lisp Basics. HTML version with color and links is at: http://xahlee.org/emacs/elisp_htmlize.html --------------------------------------- THE PROBLEM SUMMARY I want to write a elisp function, such that when invoked, the block of text the cursor is on, will have various HTML style tags wrapped around them. This is for the purpose of publishing programing language code in HTML on the web. DETAIL I write a lot computer programing tutorials for several computer languages. For example: Perl and Python tutorial, Java tutorial, Emacs Lisp tutorial, Javascript tutorial. In these tutorials, often there are code snippets. These code need to be syntax colored in HTML. For example, here's a elisp code snippet: (if (< 3 2) (message "yes") ) Here's what i actually want as raw HTML: (if (< 3 2) (message "yes") ) Which should looks like this in a web browser: (if (< 3 2) (message "yes") ) There is a emacs package that turns a syntax-colored text in emacs to HTML form. This is extremely nice. The package is called htmlize.el and is written (1997,...,2006) by Hrvoje Niksic, available at http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el. This program provides you with a few new emacs commands. Primarily, it has htmlize-region, htmlize-buffer, htmlize-file. The region and buffer commands will output HTML code in a new buffer, and the htmlize- file version will take a input file name and output into a file. When i need to include a code snippet in my tutorial, typically, i write the code in a separate file (e.g. ?temp.java?, ?temp.py?), run it to make sure the code is correct (compile, if necessary), then, copy the file into the HTML tutorial page, inside a ?pre? block. In this scheme, the best way for me to utilize htmlize.el program is to use the ?html-buffer? command on my temp.java, then copy the htmlized output and paste that into my HTML tutorial file inside a ?pre? block. Since many of my tutorials are written haphazardly over the years before seeing the need for syntax coloration, most exist inside ?pre? tags already without a temp code file. So, in most cases, what i do is to select the text inside the ?pre? tag, paste into a temp buffer and invoke the right mode for the language (so the text will be fontified correctly), then do htmlize-buffer, then copy the html output, then paste back to replace the selected text. This process is tedious. A tutorial page will have several code blocks. For each, i will need to select text, create a buffer, switch mode, do htmlize, select again, switch buffer, then paste. Many of the steps are not pure push-buttons operations but involves eye-balling. There are few hundred such pages. It would be better, if i can place the cursor on a code block in a existing HTML page, then press a button, and have emacs magically replace the code block with htmlized version colorized for the code block's language. We proceed to write this function. --------------------------------------- SOLUTION For a elisp expert who knows how fontification works in emacs, the solution would be writing a elisp code that maps emacs's string's fontification info into html tags. This is what htmlize.el do exactly. Since it is already written, a elisp expert might find the essential code in htmlize.el. (the code is licensed under GPL) . Unfortunately, my lisp experience isn't so great. I spent maybe 30 minutes tried to look in htmlize.html in hope to find a function something like htmlize-str that is the essence, but wasn't successful. I figured, it is actually faster if i took the dumb and inefficient approach, by writing a elisp code that extracts the output from htmlize-buffer. Here's the outline of the plan of my function: * 1. Grab the text inside a
...
tag. * 2. Create a new buffer. Paste the code in. * 3. Make the new buffer ?lang? mode (and fontify it) * 4. Call htmlize-buffer * 5. Grab the (htmlized) text inside ?pre? tag in the htmlize created output buffer. * 6. Kill the htmlize buffer and my temp buffer. * 7. Delete the original text, paste in the new text. To achieve the above, i decided on 2 steps. A: Write a function ?htmlize-string? that takes a string and mode name, and returns the htmlized string. B: Write a function ?htmlize-block? that does the steps of grabbing text and pasting, and calls ?htmlize-string? for the actual htmlization. Here's the code of my htmlize-string function: (defun htmlize-string (ccode mn) "Take string ccode and return htmlized code, using mode mn.\n This function requries the htmlize-mode.el by Hrvoje Niksic, 2006" (let (cur-buf temp-buf temp-buf2 x1 x2 resultS) (setq cur-buf (buffer-name)) (setq temp-buf "xout-weewee") (setq temp-buf2 "*html*") ;; the buffer that htmlize-buffer creates ; put the code in a new buffer, set the mode (switch-to-buffer temp-buf) (insert ccode) (funcall (intern mn)) (htmlize-buffer temp-buf) (kill-buffer temp-buf) (switch-to-buffer temp-buf2) ; extract the core code (setq x1 (re-search-forward "
"))
    (setq x1 (+ x1 1))
    (re-search-forward "
") (setq x2 (re-search-backward "")) (setq resultS (buffer-substring-no-properties x1 x2)) (kill-buffer temp-buf2) (switch-to-buffer cur-buf) resultS ) ) The major part in this code is knowing how to create, switch, kill buffers. Then, how to set a mode. Lastly, how to grab text in a buffer. Current buffer is given by ?buffer-name?. To create or switch buffer is done by ?switch-to-buffer?. Kill buffer is ?kill-buffer?. To activate a mode, the code is ?(funcall (intern my-mode-name))?. I don't know why this is so in detail, but it is interesting to know. The grabbing text is done by locating the desired beginning and ending locations using re-search functions, and buffer-substring-no- properties for actually extracting the string. Here, note the ?no-properties? in ?buffer-substring-no-properties?. Emacs's string can contain information called properties, which is essentially the fontification information. Reference: Elisp Manual: Buffers. Reference: Elisp Manual: Text-Properties. Here's the code of my htmlize-block function: (defun htmlize-block () "Replace the region enclosed by
 tag to htmlized code.
For example, if the cursor somewhere inside the tag:

codeXYZ...
after calling, the ?codeXYZ...? block of text will be htmlized. That is, wrapped with many tags. The opening tag must be of the form
.
The ?lang-str? determines what emacs mode is used to colorize
the code.
This function requires htmlize.el by Hrvoje Niksic."

(interactive)
(let (mycode tag-begin styclass code-begin code-end tag-end mymode)
  (progn
    (setq tag-begin (re-search-backward "
"))
    (re-search-forward "
") (setq code-end (re-search-backward "<")) (setq tag-end (re-search-forward "
")) (setq mycode (buffer-substring-no-properties code-begin code-end)) ) (cond ((equal styclass "elisp") (setq mymode "emacs-lisp-mode")) ((equal styclass "perl") (setq mymode "cperl-mode")) ((equal styclass "python") (setq mymode "python-mode")) ((equal styclass "java") (setq mymode "java-mode")) ((equal styclass "html") (setq mymode "html-mode")) ((equal styclass "haskell") (setq mymode "haskell-mode")) ) (save-excursion (delete-region code-begin code-end) (goto-char code-begin) (insert (htmlize-string mycode mymode)) ) ) ) The steps of this function is to grab the text inside a ?pre? block, call htmlize-string, then insert the result replacing text. Originally, i wrote the code to grab text by inside plain ?
...? tags, then use some heuristics to determine what language it is,
then call htmlize-string with the mode-name passed to it. However,
since my html pages already has the language information in the form
of ?
...
? (for CSS reasons), so, now i search text by that form, and use the ?lang? part to determine a mode. Emacs is beautiful. Postscript: The story given above is slightly simplified. For example, when i began my language notes and commentaries, they were not planned to be some systematic or sizable tutorial. As the pages grew, more quality are added in editorial process. So, a plain un-colored code inside ?pre? started to have ?language comment? strings colorized (e.g. ?#...), by using a simple elisp code that wraps a tag on them, and this function is mapped to shortcut key for easy execution. As pages and languages grew, i find colorizing comment isn't enough, then i started to look for a syntax-coloring html solution. There are solutions in Perl, Python, PHP, but I find emacs solution best suites my needs in particular because it integrates with emacs's interactive nature, and my writing work is done in a accumulative, editorial process. In the beginning i used htmlize-region and htmlize-buffer as they are for new code. Note that this is still a laborious process. Gradually i need to colorized my old code. The problem is that many already contain my own ?span class="cmt"? tags, and strings common in computer languages such as ?<=? have already been transformed into required html encoding ?<=?. So, the elisp code will first ?un-htmlize? these in my htmlize-block code. But once all my existing code has been so newly colorized, the part of code to transform strings for un- htmlize is no longer necessary, so they are taken out in htmlize-block and resumes a cleaner state. Also, htmlize-block went thru many revisions over the year. Sometimes in recent past, i had one code wrapper for each language. For example, i had htmlize-me-perl, htmlize- me-python, htmlize-me-java, etc. The need for unification into a single coherent wrapper code didn't materialize. In general, it is my experience, in particular in writing elisp customization for emacs, that tweaking code periodically thru the year is practical, because it adapts to the constant changes of requirements, environment, work process. For example, eventually i might write my own htmlize.el, if i happen to need more flexibility, or if my elisp experience sufficiently makes the job relatively easy. Also note: a whole-sale solution is to write a program, in say, Python, that process html files and replace proper sections by htmlized string. This is perhaps more efficient if all the existing html files are in some uniform format. However, i need to work on my tutorials on a case-by-case basis. In part, because, some pages contain multiple languages or contains pseudo-code that i do not wish colorized. (For example, some pages contains codes of the Mathematica? language. Mathematica code is normally done in Mathematica's mathematical typesetting capable ?front-end? IDE called ?Notebook? and is not ?syntax-colored? as such.) Xah xah at xahlee.org ? http://xahlee.org/ From jcd at sdf.lonestar.org Mon Oct 22 06:54:38 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 22 Oct 2007 06:54:38 -0400 Subject: if..else stmt In-Reply-To: <1193048673.332023.67960@y27g2000pre.googlegroups.com> References: <1193048673.332023.67960@y27g2000pre.googlegroups.com> Message-ID: <471C816E.8000206@sdf.lonestar.org> bigden007 wrote: > Hi, > I have a if..else statement in my script. The statements all execute > fine, but the problem is , even if the IF part of the statement is > true, the else part executes as well. The verion of pythin i use 2.5 > Any help is appreciatiated. > > Regards > > Big Den. > > Your else statement is incorrectly indented. The interpreter treats it as part of the for-loop construct inside the if statement rather than as part of the if statement itself. See the recent thread about for-else constructs for more details. If your problem is not obvious yet, make sure you aren't mixing spaces and tabs. :) From jcd at sdf.lonestar.org Fri Oct 26 19:29:47 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 26 Oct 2007 19:29:47 -0400 Subject: Proposal: Decimal literals in Python. In-Reply-To: <87tzodii6i.fsf@benfinney.id.au> References: <4721ab28$0$1238$e4fe514c@dreader28.news.xs4all.nl> <1193438763.190428.134710@q5g2000prf.googlegroups.com> <87tzodii6i.fsf@benfinney.id.au> Message-ID: <4722786B.7050101@sdf.lonestar.org> Ben Finney wrote: > Matimus writes: > > >> The trailing L [for 'long' literals] is going away in Python 3.0. >> > > Yes. On the other hand, we are gaining '0bNNNN' for binary literals, > to go along with '0oNNNN' for octal and '0xNNNN' for hexadecimal. > > So, the original poster might get further by proposing an '0dNNN.NNN' > syntax for 'decimal.Decimal' literals. It would rather be remarkably inconsistent and confusing. Python 3.0a1 (py3k:57844, Aug 31 2007, 16:54:27) [MSC v.1310 32 bit (Intel)] on win32 >>> type(0b1) >>> type(0o1) >>> type(0x1) >>> assert 0b1 is 0x1 >>> >>> type(0d1) >>> assert 0b1 is 0d1 Traceback (most recent call last): File "", line 1, in assert 0b1 is 0d1 AssertionError It would also be unkind to people with dyslexia. Cheers, Cliff From adurdin at gmail.com Wed Oct 17 09:13:28 2007 From: adurdin at gmail.com (Andrew Durdin) Date: Wed, 17 Oct 2007 14:13:28 +0100 Subject: Inheriting automatic attributes initializer considered harmful? In-Reply-To: References: Message-ID: <59e9fd3a0710170613p1a6df25ejbefb72a1a09429f@mail.gmail.com> On 10/17/07, Thomas Wittek wrote: > > Writing such constructors for all classes is very tedious. > So I subclass them from this base class to avoid writing these constructors: > > class AutoInitAttributes(object): > def __init__(self, **kwargs): > for k, v in kwargs.items(): > getattr(self, k) # assure that the attribute exits > setattr(self, k, v) > > Is there already a standard lib class doing (something like) this? > Or is it even harmful to do this? It depends on your kwargs and where they're coming from. You could do something like this, for example: def fake_str(self): return "not a User" u = User(__str__=fake_str) str(u) Does SQLAlchemy let you get a list of column names? If so you could do: class AutoInitAttributes(object): def __init__(self, **kwargs): valid_attrs = set(get_column_names_from_sqlalchemy()) # Only set valid attributes, ignoring any other kwargs for k in set(kwargs.keys()) & valid_attrs: setattr(self, k, kwargs[k]) Andrew From bj_666 at gmx.net Wed Oct 17 03:58:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Oct 2007 07:58:07 GMT Subject: Static variable vs Class variable References: <1191946572.001076.271970@50g2000hsm.googlegroups.com> <5n1rosFftvtbU1@mid.uni-berlin.de> <13gngt29ovvcld1@corp.supernews.com> <5n26i7FfmohvU1@mid.uni-berlin.de> <13go1jqli5up5d1@corp.supernews.com> <5n39eaFg1m0qU1@mid.uni-berlin.de> <1192606439.190757.23530@i13g2000prf.googlegroups.com> Message-ID: <5nltkfFiva37U1@mid.uni-berlin.de> On Wed, 17 Oct 2007 00:33:59 -0700, paul.melis wrote: > On Oct 10, 8:23 am, "Diez B. Roggisch" wrote: >> > However, it is not true that += "always leads to a rebinding of a to the >> > result of the operation +". The + operator for lists creates a new list. >> > += for lists does an in-place modification: >> >> It still is true. >> >> a += b >> >> rebinds a. Period. Which is the _essential_ thing in my post, because >> this rebinding semantics are what confused the OP. > > Doesn't this depend on wether "a" supports __iadd__ or not? No. As shown several times in this thread already. > Section 3.4.7 of the docs say > > """ > If a specific method is not defined, the augmented operation falls > back to the normal methods. For instance, to evaluate the expression x > +=y, where x is an instance of a class that has an __iadd__() method, > x.__iadd__(y) is called. If x is an instance of a class that does not > define a __iadd__() method, x.__add__(y) and y.__radd__(x) are > considered, as with the evaluation of x+y. > """ > > So if a.__iadd__ exists, a += b is executed as a.__iadd__(b), in which > case there's no reason to rebind a. `__iadd__` *may* doing the addition in place and return `self` but it is also allowed to return a different object. So there is always a rebinding. > However, this confuses the heck out of me: > >>>> class A: > ... l = [] > ... >>>> class B(A): pass > ... >>>> B.__dict__ > {'__module__': '__main__', '__doc__': None} >>>> B.l > [] >>>> B.l.append('1') >>>> B.l > ['1'] >>>> B.__dict__ > {'__module__': '__main__', '__doc__': None} >>>> B.l.__iadd__('2') > ['1', '2'] Here you see that the method actually returns an object! >>>> B.l > ['1', '2'] >>>> B.__dict__ > {'__module__': '__main__', '__doc__': None} >>>> B.l += '3' >>>> B.__dict__ > {'__module__': '__main__', '__doc__': None, 'l': ['1', '2', '3']} > > Why is B.l set for the += case only? B.l.__iadd__ obviously exists. Because there is always a rebinding involved. Ciao, Marc 'BlackJack' Rintsch From Scott.Daniels at Acm.Org Wed Oct 10 23:39:58 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 10 Oct 2007 20:39:58 -0700 Subject: Version specific or not? In-Reply-To: References: Message-ID: <13gr6kqsdlue6db@corp.supernews.com> Steven W. Orr wrote: > We have an app and I'm trying to decide where the app ... . > /usr/lib/python2.3/site-packages > or > /usr/lib/site-python > > The latter would solve a lot of problems for me. Fewer than you suspect > If there are multiple versions of python installed on the same machine, > having a shebang that just looked for /usr/bin/python would make my life > a lot easier. > * Since we distribute .pyo files, is there an issue if the .pyo was > built with 2.3.5 and then executed by 2.4 or 2.5? Each python M.N.X has its own byte code for distinct values of M and/or N. So, if you had a shared directory, not only would your users have to be able to write to the shared directory (when they import mumble, and mumble.pyc or mumble.pyo has been generated by a different version of Python, they will recompile mumble.py and rewrite mumble.pyc (or .pyo). -Scott David Daniels Scott.Daniels at Acm.Org From arkanes at gmail.com Fri Oct 12 16:21:48 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 12 Oct 2007 15:21:48 -0500 Subject: Declarative properties In-Reply-To: References: <1192103298.065386.243670@o3g2000hsb.googlegroups.com> <5n6j5nFghr61U4@mid.uni-berlin.de> <1192107893.492826.233730@d55g2000hsg.googlegroups.com> <5n6np4Fghr61U6@mid.uni-berlin.de> <470f2522$0$12106$426a74cc@news.free.fr> Message-ID: <4866bea60710121321y7a0b2215t9268942d9d21337b@mail.gmail.com> On 10/12/07, Dan Stromberg wrote: > On Fri, 12 Oct 2007 09:42:28 +0200, Bruno Desthuilliers wrote: > > >>> So what? Otherwise you carry *always* the baggage of a public > >>> property and a private attribute whether you need this or not. At > >>> least for me it would be unnecessary in most cases. > >> > >> That "baggage" of carrying around "unneeded" methods is something the > >> computer carries for you - IE, no big deal in 99.99% of all cases. > > > > 1/ Accessing the value of a property is not free. Accessing a plain > > attribute is much cheaper. > > Python's current performance characteristics have no bearing on what is > good software engineering practice in general, and little bearing on what > is good software engineering practice in python. Even from a > strictly "what's good for python" perspective, if we limit our view of > "good SE practice" to what python can express well right now (and IMO, > python can express this fine, but you seem to be arguing it cannot), > that needlessly limits python's evolution. > > I'm not omniscient, and neither is anyone else; when one initially codes a > class, one doesn't know to what purposes it will need to be bent in the > future; using accessor methods instead of exposed attributes is > significantly more flexible for the future of your class. This is simply not true in Python, and anyone who thinks it is hasn't the slightest understanding of the consequences of dynamic vs static lookup. The best practice (in C++, which Java inherited) of using accessors is because changing a public attribute to a property broke your interface, and all the clients of your code needed to be altered. Later languages, like C#, introduced syntax support for properties, which improved the situation such that clients didn't need to be re-written, but only recompiled. Python, however, uses truly dynamic attribute lookup and there is *zero* cost to clients in a change from a public attribute to a property. Writing accessors in a language that doesn't have the pressures that introduced them is cargo cult programming, not Software Engineering. >In fact, I may > even go so far as to say that public attributes would be good to leave out > of future languages that don't have a lot of backward compatibility > baggage. > >From a reasonable point of view, Python doesn't have public attributes, it just has things that syntactically look like them. Discuss! > It may not be traditional to use accessor methods in python. It may even > be a more expensive operation. But neither of these make accessor methods > a bad idea in the abstract. > Of course not, that's why Python supports properties. What's being called the anti-pattern here is the creation-by-default of trivial accessors. > > 2/ cluttering the class's namespace with useless names and the source > > code with useless code is definitively not a good thing. > > Adding two clear and flexible methods and eliminating one clear and > inflexible attribute is not namespace clutter. It's paydirt. > No, you kept the attribute and also added (at least) 2 methods. > The performance expense in the vast majority of cases is tiny compared to > the human expense of going back and fixing a design bug if anything > significant has been hinging on your exposed implementation detail. > You still don't know what language you're writing in, do you? There is zero additional cost associated with changing a public attribute to a property. > Unless, that is, you don't think your code is important enough to be > stretched to another, previously unforeseen purpose someday. If you're > coding for a hobby, and enjoy coding for the sake of coding irrespective > of how long it takes, rather than as a means to a valuable end, maybe > needlessly exposing attributes is a Really Good Idea. > Ah, the old "my code is way more important than yours, so what I do is right" approach. You hang out in the Java world a lot, don't you? > My implementation may or may not be lacking (feel free to improve it - in > fact, please do!), but that's irrelevant to the heart of the matter, which > is "what you didn't think to plan for now most definitely can hurt you > later". > Your implementation is, quite possibly, the worst possible implementation of automatic properties in Python, both in terms of readability and code size (and thus maintenance), as well as performance and flexibility. The fact that you consider it, even for a moment, to be better than writing accessors when and if you need them (and not writing them otherwise) belies a dreadful lack of self awareness. > If you have a program that needs to perform well, you're much better off > coding your classes the best way you know how from a Software Engineering > perspective, and using pysco or shedskin or pypy or similar to > improve performance. If that's not enough, then you're better off > profiling the program, and only after that should you recode the critical > portions into something like pyrex or a C extension module, or -maybe- > some python "tricks". I'd argue that trick-free C or C++ is normally > better than python with tricks from a performance vantage -and- from an SE > viewpoint. > You're not going to teach anyone on this list anything about optimizing, I suspect. > Little hackish tricks for performance's sake scattered throughout a > program are very wasteful of something more precious than CPU time. > It's truly bizarre to hear someone refer to *not* writing code as a "hackish trick". Especially when the alternative they prevent depends on eval! > From ldo at geek-central.gen.new_zealand Thu Oct 4 03:54:09 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Oct 2007 20:54:09 +1300 Subject: Web service client using https References: <1191483648.610569.219510@g4g2000hsf.googlegroups.com> Message-ID: In message <1191483648.610569.219510 at g4g2000hsf.googlegroups.com>, welcomestocontact at gmail.com wrote: > I am trying to connect .NET web service using HTTPS. I wrote a > python script using https. For that need to send SOAP message to the > server. But it is giving error 401.3 execution access is denied.(SOAP > message not processing) Does it work over non-secure HTTP, just for comparison? (I know, don't do it for production use, only for testing.) Are you able to compare your code with some other working code? You could try concatenating the complete request into a text file and sending that with wget, to see if it works. From raims at dot.com Sat Oct 6 10:04:38 2007 From: raims at dot.com (Lawrence Oluyede) Date: Sat, 6 Oct 2007 16:04:38 +0200 Subject: Yet another comparison of Python Web Frameworks References: <1191659602.789748.59150@g4g2000hsf.googlegroups.com> <1i5kbfo.xq3fut1f7ouujN%raims@dot.com> Message-ID: <1i5kk06.enf7ws1juj4zkN%raims@dot.com> Jorge Godoy wrote: > What is good, since a lot of good things from Pylons will work with TG and a > lot of good TG things will remain (and possibly be compatible with Pylons). > If you take a better look at "the next version", you'll also see that the > major concern was with WSGI support and reinventing / "rewriting" the wheel > (what TG developers don't want to do all the time). Not reinventing the wheel just don't feel as a universal dogma to me. I developed quite a bit with Django and I was glad they started from scratch. On the paper reusing different and existing projects is great but not always is good or done the right way. Anyway I don't know TG at all so I'm speaking in a figurative way. We (Michele, myself and our colleagues) have a series of stuff we need to stick to so the choosing of a web framework ain't that easy. Most of the frameworks are a vision of the author of how to do things from scratch but a framework (by definition an evolution of a library) is not always meant to be used when the scratch is far from your starting point. I'd like to read some commenting of Michele's thoughts, they would be really useful. :-) -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From shafik23 at gmail.com Fri Oct 5 13:36:10 2007 From: shafik23 at gmail.com (Shafik) Date: Fri, 05 Oct 2007 10:36:10 -0700 Subject: Starting a thread before wxPython bootup ... interesting. In-Reply-To: <13gb3284gqn0j6b@corp.supernews.com> References: <1191516769.594037.191880@22g2000hsm.googlegroups.com> <13gb3284gqn0j6b@corp.supernews.com> Message-ID: <1191605770.166713.284950@22g2000hsm.googlegroups.com> My apologies for not supplying more info, I am at work and I am technically not allowed to surf the web for anything. I am using Python 2.5.1, the latest wx version (2.8.xx, I dont recall exactly). This is running under windows XP under the latest version of cygwin (that could be the source of the issues too). I was just looking for a general way to approach wx and multithreading, not a detailed solution to my problem. There are lots of tutorials online that describe how to perform a time-consuming task in a separate thread in a wx-gui, but nothing that describes any other use cases. The real goal is to start the gui in a different thread, and have the main thread regain control. That seems like a feasible thing to be able to do, though I have been unsuccessful ... if anyone would like to suggest something without being covertly insulting, I'm all ears. Thanks, --Shafik On Oct 4, 5:58 pm, "[david]" wrote: > Since the observed behaviour is clearly undefined, > I forgive you for the poorly specified behaviour > description: asking for a close description of random > behaviour is just ridiculous. > > The most obvious point is that wx is not re-entrant > or thread safe: you have to make it so by using > wx.CallAfter() > > Since you are talking about a bug in your screen > display while using a screen library, it would > also be interesting it you described the environment: > Which operating system? Which windowing system? > Which wx library? Which Python? Which IDE? What code? > > [david] > > Shafik wrote: > > Hello folks, > > > I'm having an issue with mixing wxPython and threading ... I realize > > multi-threading always introduces subtle bugs, but the following > > scenario is just odd: > > > I start a dummy thread, that does nothing but increment a counter and > > print its value to the screen, then afterwards, I start the wxPython > > application. I get nothing but weird behavior: sometimes the gui just > > crashes, sometimes I get an exception, sometimes it runs for a little > > but very slowly ... > > > Anyone know whats going on? I have a dual-core T5500, so multi > > threading is piece of cake for it hardware -wise. > > > Cheers, > > --Shafik From lycka at carmen.se Tue Oct 2 09:09:48 2007 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 02 Oct 2007 15:09:48 +0200 Subject: python 2.5 and 3gb switch In-Reply-To: References: Message-ID: neil wrote: > I see python is not really there for 64 bit yet but most of the people I think you mean "Windows is not really there for 64 bit yet". Python works well on real 64 bit operating system. Blender does too I presume. From martin at v.loewis.de Wed Oct 31 14:46:55 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 31 Oct 2007 19:46:55 +0100 Subject: _tkinter installation in python 2.5 on mandriva with a default 2.4 In-Reply-To: <1193853812.998544.113780@y27g2000pre.googlegroups.com> References: <1193775761.764547.148730@i38g2000prf.googlegroups.com> <4727b1e6$0$13390$9b622d9e@news.freenet.de> <1193813238.978699.154830@57g2000hsv.googlegroups.com> <47288E4D.6010301@v.loewis.de> <1193847896.441329.315560@o80g2000hse.googlegroups.com> <4728afce$0$7845$9b622d9e@news.freenet.de> <1193853812.998544.113780@y27g2000pre.googlegroups.com> Message-ID: <4728cda0$0$4583$9b622d9e@news.freenet.de> > Those TK libraries tcllib=None tklib=None tcl_includes=None > tk_includes=None This also contradicts your earlier statement that you have libtk8.4.so on your machine. > I don't understand why the headers report None as the file tk.h is > in /usr/include ... or is the lack of the word generic more of a > problem? Please read detect_tkinter in detail: if it already fails to find tklib or tcllib, it won't check for header files at all. You should now trace through find_library_file with print statements. Check whether compiler.find_library_file returns not None, if yes, report what it returns. Otherwise, annotate compiler.find_library_file. Print compiler.find_library_file to see what specific function it is; likely something in unixccompiler.py. If so, print out shared, dylib, static, and os.path.exists of each one. HTH, Martin From michele.simionato at gmail.com Fri Oct 19 00:43:59 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 19 Oct 2007 04:43:59 -0000 Subject: Noob questions about Python In-Reply-To: <1192751078.506979.170580@z24g2000prh.googlegroups.com> References: <1192649863.496557.230730@v29g2000prd.googlegroups.com> <1192658316.048082.212190@v23g2000prn.googlegroups.com> <1192687508.636842.49940@z24g2000prh.googlegroups.com> <1192751078.506979.170580@z24g2000prh.googlegroups.com> Message-ID: <1192769039.357773.156100@q5g2000prf.googlegroups.com> On Oct 18, 7:44 pm, MRAB wrote: > It returns '' when number == 0, so you need to test for that case: > > > def baseN(number, N=2): > > """ > > >>> baseN(9, 2) > > '1001' > > """ > > assert 2 <= N <= 10 > > assert isinstance(number, int) and number >= 0 > > if number == 0: > return "0" > > > b = [] > > while number: > > b.append(str(number % N)) > > number /= N > > return ''.join(reversed(b)) Right, or you can just change the last line: return ''.join(reversed(b)) or '0' Michele Simionato From thermostat at gmail.com Wed Oct 24 13:26:03 2007 From: thermostat at gmail.com (Dan) Date: Wed, 24 Oct 2007 17:26:03 -0000 Subject: optparse help output In-Reply-To: References: <1193240835.563154.113810@e9g2000prf.googlegroups.com> Message-ID: <1193246763.834306.68660@i13g2000prf.googlegroups.com> On Oct 24, 12:06 pm, Tim Chase wrote: > > I've been using optparse for a while, and I have an option with a > > number of sub-actions I want to describe in the help section: > > > parser.add_option("-a", "--action", > > help=\ > > [snipped formatted help]> """) > > > Unfortunately, when I run the script with --help, this is what I get > > for the -a option: > > [snipped munged formatting of help] > > > Is there any way to get the formatting I want? > > I had the same issue: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > and was directed by Ben Finney to check out a custom formatter. > I got it working to my satisfaction and posted it in that thread: > > http://groups.google.com/group/comp.lang.python/msg/09f28e26af0699b1 > > It may be a little more kind in what it does with your help-text. > If you need variant behavior you can take my code and mung it > even further. > > The changes are basically a copy&paste (including the comments, > which Steven D'Aprano suggested might be better made into > docstrings) of the format_description() and format_option() calls > from the standard-library's source, and changing a few small > lines to alter the behavior of calls to textwrap.* > > Hope this helps, > > -tkc Thanks, Tim! That was incredibly helpful. I did alter it to format paragraphs, but maintain the double newlines. Also, I made a few changes to work with the 2.3 version of optparse. Posted below for anyone who might want it. (Also to work as a standalone .py file) -Dan # From Tim Chase via comp.lang.python. from optparse import IndentedHelpFormatter import textwrap class IndentedHelpFormatterWithNL(IndentedHelpFormatter): def format_description(self, description): if not description: return "" desc_width = self.width - self.current_indent indent = " "*self.current_indent # the above is still the same bits = description.split('\n') formatted_bits = [ textwrap.fill(bit, desc_width, initial_indent=indent, subsequent_indent=indent) for bit in bits] result = "\n".join(formatted_bits) + "\n" return result def format_option(self, option): # The help for each option consists of two parts: # * the opt strings and metavars # eg. ("-x", or "-fFILENAME, --file=FILENAME") # * the user-supplied help string # eg. ("turn on expert mode", "read data from FILENAME") # # If possible, we write both of these on the same line: # -x turn on expert mode # # But if the opt string list is too long, we put the help # string on a second line, indented to the same column it would # start in if it fit on the first line. # -fFILENAME, --file=FILENAME # read data from FILENAME result = [] opts = option.option_strings opt_width = self.help_position - self.current_indent - 2 if len(opts) > opt_width: opts = "%*s%s\n" % (self.current_indent, "", opts) indent_first = self.help_position else: # start help on same line as opts opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts) indent_first = 0 result.append(opts) if option.help: help_text = option.help # Everything is the same up through here help_lines = [] help_text = "\n".join([x.strip() for x in help_text.split("\n")]) for para in help_text.split("\n\n"): help_lines.extend(textwrap.wrap(para, self.help_width)) if len(help_lines): # for each paragraph, keep the double newlines.. help_lines[-1] += "\n" # Everything is the same after here result.append("%*s%s\n" % ( indent_first, "", help_lines[0])) result.extend(["%*s%s\n" % (self.help_position, "", line) for line in help_lines[1:]]) elif opts[-1] != "\n": result.append("\n") return "".join(result) From jeremy+complangpython at jeremysanders.net Mon Oct 29 05:34:18 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 29 Oct 2007 09:34:18 +0000 Subject: ANN: Veusz 1.0 - a scientific plotting package Message-ID: I'm pleased to announce Veusz 1.0. Source, windows and linux i386 binaries are available. Jeremy Sanders Veusz 1.0 --------- Velvet Ember Under Sky Zenith ----------------------------- http://home.gna.org/veusz/ Veusz is Copyright (C) 2003-2007 Jeremy Sanders Licenced under the GPL (version 2 or greater). Veusz is a scientific plotting package written in Python, using PyQt4 for display and user-interfaces, and numpy for handling the numeric data. Veusz is designed to produce publication-ready Postscript/PDF output. The user interface aims to be simple, consistent and powerful. Veusz provides a GUI, command line, embedding and scripting interface (based on Python) to its plotting facilities. It also allows for manipulation and editing of datasets. Feature changes from 0.99.0: * Import of Text datasets * Labels can be plotted next to X-Y points * Numbers can be directly plotted by entering into X-Y datasets as X and Y * More line styles * Loaded document and functions are checked for unsafe Python features * Contours can be labelled with numbers * 2D dataset creation to make 2D datasets from x, y, z 1D datasets Bug and minor fixes from 0.99.0: * Zooming into X-Y images works now * Contour plots work on datasets with non equal X and Y sizes * Various fixes for datasets including NaN or Inf * Large changes to data import filter to support loading strings (and dates later) * Reduce number of undo levels for memory/speed * Text renderer rewritten to be more simple * Improved error dialogs * Proper error dialog for invalid loading of documents Features of package: * X-Y plots (with errorbars) * Line and function plots * Contour plots * Images (with colour mappings and colorbars) * Stepped plots (for histograms) * Fitting functions to data * Stacked plots and arrays of plots * Plot keys * Plot labels * LaTeX-like formatting for text * EPS/PDF/PNG export * Scripting interface * Dataset creation/manipulation * Embed Veusz within other programs * Text, CSV and FITS importing Requirements: Python (2.3 or greater required) http://www.python.org/ Qt >= 4.3 (free edition) http://www.trolltech.com/products/qt/ PyQt >= 4.3 (SIP is required to be installed first) http://www.riverbankcomputing.co.uk/pyqt/ http://www.riverbankcomputing.co.uk/sip/ numpy >= 1.0 http://numpy.scipy.org/ Microsoft Core Fonts (recommended for nice output) http://corefonts.sourceforge.net/ PyFITS >= 1.1 (optional for FITS import) http://www.stsci.edu/resources/software_hardware/pyfits For documentation on using Veusz, see the "Documents" directory. The manual is in pdf, html and text format (generated from docbook). Issues: * Reqires a rather new version of PyQt, otherwise dialogs don't work. * Can be very slow to plot large datasets if antialiasing is enabled. Right click on graph and disable antialias to speed up output. * The embedding interface appears to crash on exiting. If you enjoy using Veusz, I would love to hear from you. Please join the mailing lists at https://gna.org/mail/?group=veusz to discuss new features or if you'd like to contribute code. The latest code can always be found in the SVN repository. From timr at probo.com Thu Oct 25 02:19:47 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Oct 2007 06:19:47 GMT Subject: Python on Intel A110? References: <2007102314041416807-bob@passcalnmtedu> Message-ID: Bob Greschke wrote: > >Will the "stock" Windows version of Python install on a Samsung Q1U-EL >UMPC running Vista and with an Intel A110 processor? ANYTHING that runs Vista will run Python. >I want to do some >development and just happened to think about this. I don't know what >these processors are compatible with at the binary level. Binary compatibility isn't so important. Python can be built from source. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From horpner at yahoo.com Wed Oct 31 08:44:53 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 31 Oct 2007 12:44:53 GMT Subject: A Python 3000 Question References: Message-ID: On 2007-10-30, Jean-Paul Calderone wrote: > On Tue, 30 Oct 2007 15:25:54 GMT, Neil Cerutti wrote: >>On 2007-10-30, Eduardo O. Padoan wrote: >>> This is a FAQ: >>> http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm >> >>Holy Airy Persiflage Batman! >> >>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 timeit >>>>> timeit.Timer('len(seq)', 'seq = range(100)').timeit() >>0.20332271187463391 >>>>> timeit.Timer('seq.__len__()', 'seq = range(100)').timeit() >>0.48545737364457864 > > Not sure what you're trying to demonstrate. That len as a builtin can be faster than len as an attribute, and doesn't need any further explanation than that. > Here's another pointless transcript, though: > > exarkun at charm:~$ python -m timeit -s ' > seq = range(100) > ' 'len(seq)' > 1000000 loops, best of 3: 0.211 usec per loop > exarkun at charm:~$ python -m timeit -s ' > seq = range(100) > ' 'seq.__len__()' > 1000000 loops, best of 3: 0.317 usec per loop > exarkun at charm:~$ python -m timeit -s ' > class X(object): > def __len__(self): return 100 > seq = X() > ' 'seq.__len__()' > 1000000 loops, best of 3: 0.427 usec per loop > exarkun at charm:~$ python -m timeit -s ' > class X(object): > def __len__(self): return 100 > seq = X() > ' 'len(seq)' > 1000000 loops, best of 3: 0.701 usec per loop > exarkun at charm:~$ > > I guess we've learned that sometimes something is faster than > something else, and other times the contrary. It demonstratess that len is faster than __len__ for lists (and probably for all builtin types) but not for user defined type X (and probably not for any user defined type). Or it may demonstrate that I'm all wet. If so, I've brought my shampoo. But if I'm wrong about the performance benefits then I guess I'm still in the dark about why len is a builtin. The only compelling thing in the linked explation was the signatures of the guys who wrote the artible. (Guido does admit he would, "hate to lose it as a builtin," but doesn't explain why that should be a bad thing). -- Neil Cerutti It isn't pollution that is hurting the environment; it's the impurities in our air and water that are doing it. --Dan Quayle From brenNOSPAMbarn at NObrenSPAMbarn.net Sun Oct 28 03:24:36 2007 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Sun, 28 Oct 2007 07:24:36 GMT Subject: Unicode raw string containing \u References: <13i8e4fovg17u1f@corp.supernews.com> Message-ID: Steven D'Aprano wrote: >> How can I specify a unicode raw string literal that >> contains a >> single backslash followed by the word "universe"? > > The usual way. > >>>> word = u'\\universe' len(word) 9 word[0] u'\\' word[1] u'u' >>>> print word \universe word u'\\universe' That doesn't answer my question, since I asked for a unicode RAW string literal. Is this not possible? (I was able to get what I want using ur"\u005Cuniverse", although this is not totally ideal.) -- --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 lmierzej at o2.pl Sun Oct 14 15:45:07 2007 From: lmierzej at o2.pl (Lukasz Mierzejewski) Date: Sun, 14 Oct 2007 19:45:07 +0000 (UTC) Subject: pydev code completion problem Message-ID: Hi, I need help with pydev code completion... Let's assume that we have something like this: class One: def fun(self): return 1 class Two: li = [] li.append(One()) one = li[0] print one.fun() one2 = li.pop() print one2.fun() one3 = One() print one3.fun() Only for 'one3' variable code completion is working fine (as expected it show fun()). For 'one' code completion shows something (but not fun()). For 'one2' code completion shows nothing :-( I use Eclipse 3.3.1 with PyDev 1.3.9 on Ubuntu 7.04. Can anyone confirm or deny this behavior of PyDev? From jusa.sj at gmail.com Sun Oct 14 03:23:42 2007 From: jusa.sj at gmail.com (Juha S.) Date: Sun, 14 Oct 2007 10:23:42 +0300 Subject: Foreign Character Problems In Python 2.5 and Tkinter In-Reply-To: <1192300347.953402.172130@k35g2000prh.googlegroups.com> References: <1192300347.953402.172130@k35g2000prh.googlegroups.com> Message-ID: <4711C3FE.8080803@gmail.com> nickel_and_dime_2death at yahoo.com wrote: > As a noob I've struggled a bit, but basically what I've come up with > is => if the information is strings and especially strings stored in > any style of list/dict, it takes a loop to write the lines to file > myfile[ i ] + '\n' to keep each line for Python I/O purposes. If > you're done with Python manipulation and want WIN, MAC, or UNIX to > begin file I/O, then, you need the consideration of > from the os module, or code it in yourself, e.g. '\r\n'. The fact you > are using codec iso-latin-1 (or iso-8859-1) doesn't change the '\n' > from Python's viewpoint -- that is: '\n' is still '\n'. When your > efforts are I/O with binary encoding the data, it's all Python's > viewpoint. > > Ah, it was so simple. I replaced any '\n' characters with 'os.linesep' in the source as you suggested, and now everything works beautifully. Thanks for the help, guys! From fanglicheng at gmail.com Wed Oct 10 10:48:17 2007 From: fanglicheng at gmail.com (Licheng Fang) Date: Wed, 10 Oct 2007 14:48:17 -0000 Subject: Problem of Readability of Python In-Reply-To: <1i5m74j.1dpt4l9sbq7zzN%aleax@mac.com> References: <1191780456.833563.173080@57g2000hsv.googlegroups.com> <1i5m74j.1dpt4l9sbq7zzN%aleax@mac.com> Message-ID: <1192027697.413492.90430@g4g2000hsf.googlegroups.com> On Oct 8, 4:24 am, al... at mac.com (Alex Martelli) wrote: > Licheng Fang wrote: > > ... > > > Python Tutorial says an empty class can be used to do this. But if > > namespaces are implemented as dicts, wouldn't it incur much overhead > > if one defines empty classes as such for some very frequently used > > data structures of the program? > > Just measure: > > $ python -mtimeit -s'class A(object):pass' -s'a=A()' 'a.zop=23' > 1000000 loops, best of 3: 0.241 usec per loop > > $ python -mtimeit -s'a=[None]' 'a[0]=23' > 10000000 loops, best of 3: 0.156 usec per loop > > So, the difference, on my 18-months-old laptop, is about 85 nanoseconds > per write-access; if you have a million such accesses in a typical run > of your program, it will slow the program down by about 85 milliseconds. > Is that "much overhead"? If your program does nothing else except those > accesses, maybe, but then why are your writing that program AT ALL?-) > > And yes, you CAN save about 1/3 of those 85 nanoseconds by having > '__slots__=["zop"]' in your class A(object)... but that's the kind of > thing one normally does only to tiny parts of one's program that have > been identified by profiling as dramatic bottlenecks, to shave off the > last few nanoseconds in the very last stages of micro-optimization of a > program that's ALMOST, but not QUITE, fast enough... knowing about such > "extreme last-ditch optimization tricks" is of very doubtful value (and > I think I'm qualified to say that, since I _do_ know many of them...:-). > There ARE important performance things to know about Python, but those > worth a few nanoseconds don't matter much. > > Alex This is enlightening. Surely I shouldn't have worried too much about performance before doing some measurement. From jeffober at gmail.com Tue Oct 30 08:53:09 2007 From: jeffober at gmail.com (Jeff) Date: Tue, 30 Oct 2007 12:53:09 -0000 Subject: Proxying downloads In-Reply-To: References: Message-ID: <1193748789.274409.12900@o80g2000hse.googlegroups.com> You use a temp directory to store the file while downloading, then move it to the cache so the addition of the complete file is atomic. The file name of the temp file should be checked to validate that you don't overwrite another process' download. Currently downloading urls should be registered with the server process (a simple list or set would work). New requests should be checked against that; if there is a matching url in there, the process must wait until that download is finished and that file should be delivered to both Alice and Bob. You need to store the local file path and the url it was downloaded from and checking against that when a request is made; there might be two foobar.iso files on the Internet or the network, and they may be different (such as in differently versioned directories). From martin at marcher.name Wed Oct 24 16:23:55 2007 From: martin at marcher.name (Martin Marcher) Date: Wed, 24 Oct 2007 22:23:55 +0200 Subject: crontab library In-Reply-To: References: <5fa6c12e0710241212v7c675a1dp9c87d3c9f98df261@mail.gmail.com> Message-ID: <5fa6c12e0710241323n7a7773e4k203bcf3ad14d07cb@mail.gmail.com> 2007/10/24, Guilherme Polo : > 2007/10/24, Martin Marcher : > > I had a look at the crontab docs and never realized how complex it > > actually is. So before I spend time in creating such a thing maybe > > someone did it already :) > > > > When you say complex, are you talking about the possible ways to > define when your job runs ? You could use a parser for the time format > it uses, like this: > http://umit.svn.sourceforge.net/viewvc/umit/branch/ggpolo/umitCore/CronParser.py?revision=1175&view=markup This looks nice for starters. But the crontab(5) manpage has a lot more - that's what I meant by complex. I guess it's just quite some typing work :) * lists * 1,2,4 * ranges * 1-3 * steps * 1-12/2 * "*/3" * specials * @annually * @weekly * @daily * ... * mixes there of * 1-4,6,16-22/3 (this actually depends on which cron you use, the lowest common denominator would be to use either lists or ranges (or ranges with steps)) Then there is the difference of roots crontab where whe have a line like this: # minute hour dom month dow user command 0 * * * * nobody echo foo A users crontab # minute hour dom month dow command 0 * * * * echo foo and all the variables one could use. with a few of them being mandatory (LOGNAME, or USER depending on the OS), some of them being standard variables (SHELL, PATH) and of course custom variables. -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From mlongjr at verizon.net Wed Oct 24 21:56:38 2007 From: mlongjr at verizon.net (Junior) Date: Thu, 25 Oct 2007 01:56:38 GMT Subject: delineating by comma where commas inside quotation marks don't count Message-ID: I want to open a text file for reading and delineate it by comma. I also want any data surrounded by quotation marks that has a comma in it, not to count the commas inside the quotation marks if the file testfile.txt contains the following; 5,Tuesday,"May is a spring month",Father's Day 1,Saturday,"June,July and August",Independance Day and I write the following program fname = open('testfile.txt', 'r') ct=1 while ct != 3: rd=(fname.readline()) filedata=rd.split(',') print "var2=",filedata[2] ct +=1 fname.close filedata[2] will = "May is a spring month"; on the first pass and filedata[2] will = "June; on the second pass How do I get filedata[2] to = "June,July and August" on the second pass and filedata[3] to = Independance Day From lasses_weil at klapptsowieso.net Wed Oct 3 12:23:06 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Wed, 03 Oct 2007 18:23:06 +0200 Subject: generating range of numbers In-Reply-To: <1191403125.540152.72320@22g2000hsm.googlegroups.com> References: <1191403125.540152.72320@22g2000hsm.googlegroups.com> Message-ID: <4703c1ea$0$30380$9b4e6d93@newsspool4.arcor-online.net> vimal wrote: > hi all, > > i am new to python..... > i just want to generate numbers in the form like: > > 1,2,4,8,16,32.....to a maximum of 1024 > > using a range function > Homework? /W From wojciech at gmail.com Thu Oct 4 11:29:01 2007 From: wojciech at gmail.com (Wojciech Gryc) Date: Thu, 04 Oct 2007 15:29:01 -0000 Subject: Python "implements " equivalent? In-Reply-To: <1191511635.118779.124240@22g2000hsm.googlegroups.com> References: <1191510706.528876.261780@57g2000hsv.googlegroups.com> <1191511635.118779.124240@22g2000hsm.googlegroups.com> Message-ID: <1191511741.151025.172190@y42g2000hsy.googlegroups.com> Thank you Carl and thank you Jarek. This makes me feel much better -- on to coding, I shall go. :) Thanks again, Wojciech On Oct 4, 11:27 am, Carl Banks wrote: > On Oct 4, 11:11 am, Wojciech Gryc wrote: > > > Hi, > > > I recently started using Python and am extremely happy with how > > productive it's made me, even as a new user. I'm hoping to continue > > using the language for my research, and have come across a bit of a > > stumbling block. > > > I'm a seasoned Java programmer and quite a big fan of interfaces... > > i.e. The idea that if I make a number of distinct classes that > > implement interface X, I can pass them all as parameters to functions > > or whatnot that require an X object. > > > Is there something similar in Python? > > Yes: you do it pretty much the same way you'd do it in Java, except > for two differences: > * leave out the "implements Interface" part > * don't actually create an Interface class > > And then, voila!, you can write functions that can accept any class > that implements your interface. > > > What I'd like to do is create a feature detection system for my work > > -- specifically, a general class / interface called "Feature" and then > > subclasses that implement functions like isFeaturePresent() in all of > > their different and unique ways. I'd love to hear how I can do this in > > Python. > > Just define isFeaturePresent() in any class you want. That's all you > have to do; any class that defines this method can be passed to any > function that invokes it, without having to "implement" or "subclass" > anything. > > This is known as "duck typing" in Python lingo. > > Carl Banks From byte8bits at gmail.com Tue Oct 30 08:56:02 2007 From: byte8bits at gmail.com (brad) Date: Tue, 30 Oct 2007 08:56:02 -0400 Subject: A Python 3000 Question In-Reply-To: References: Message-ID: Eduardo O. Padoan wrote: > This is a FAQ: > http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm Thanks to all for the feedback. I'm no language designer. I just see and hear these criticisms and I wanted to think through it a bit by posting here. I now better understand generic functions and why they are used in some cases. From tommy.nordgren at comhem.se Mon Oct 29 16:19:50 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Mon, 29 Oct 2007 21:19:50 +0100 Subject: setting variables in outer functions Message-ID: <4B003AF0-D445-48A3-BE5D-08382B1B4018@comhem.se> Given the following: def outer(arg) avar = '' def inner1(arg2) # How can I set 'avar' here ? ------------------------------------- This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren tommy.nordgren at comhem.se From gagsl-py2 at yahoo.com.ar Sun Oct 7 00:08:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Oct 2007 01:08:49 -0300 Subject: embedding python.. References: <1191627640.676114.319430@22g2000hsm.googlegroups.com> Message-ID: En Fri, 05 Oct 2007 20:40:40 -0300, Eric_Dexter at msn.com escribi?: > I compiled the c program that is supposed to allow you to call a > procedure from the command line promt.. (it is from the embeding > example).. I am a little confused as to what all I am supposed to > distribute to make it work.. Do I just need the python .dll for the > version I compiled or is it working with the installed version of > python.. (I don't want to start deleting stuff to find out).. Any > help on this question would be apreaceated.. If you only provide pythonXX.dll (and probably msvcr71.dll), any Python code that tries to import any module apart from builtin modules will fail. If you provide the Python standard library in full, almost any program could be run. It's up to you to decide how much you require/allow/want to provide. -- Gabriel Genellina From http Mon Oct 29 10:54:12 2007 From: http (Paul Rubin) Date: 29 Oct 2007 07:54:12 -0700 Subject: Handle Exceptions Inside List Comprehension References: <1193669272.221535.281940@d55g2000hsg.googlegroups.com> Message-ID: <7xfxzuynsb.fsf@ruckus.brouhaha.com> beginner writes: > [f(x) for x in xs] > > I want to skip the point if f(x) raises an exception. How can I do > that without totally removing the list comprehension? def ff(xs): for x in xs: try: yield f(x) except: pass [x for x in ff(xs)] or alternatively list(ff(xs)) From paulgeeleher at gmail.com Sun Oct 21 12:50:54 2007 From: paulgeeleher at gmail.com (sophie_newbie) Date: Sun, 21 Oct 2007 09:50:54 -0700 Subject: Error when python script run as cgi script Message-ID: <1192985454.957211.219450@z24g2000prh.googlegroups.com> Hi, I'm running a python script which if I run from the command line as root runs fine. But if I run it through the web-browser as a cgi script gives the following error "Error in X11: unable to start device PNG". Now I should say that this python script is calling fucntions in R (a scripting languange used in statistics) using the python module RPy, so this I dunno if this is entirely a Python question, because as far as I can see the error is being thrown by R. But then as I say, when the script is run by the root user from the command line everything goes off without a hitch. So I dunno is there some way to run a CGI script as root, maybe thats a bad idea because of security? But any ideas would be welcome. -Thanks. From marco at sferacarta.com Mon Oct 22 11:31:04 2007 From: marco at sferacarta.com (Marco Mariani) Date: Mon, 22 Oct 2007 17:31:04 +0200 Subject: Iteration for Factorials In-Reply-To: <1193064348.526006.183080@q5g2000prf.googlegroups.com> References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> <5o3jalFl0n43U1@mid.uni-berlin.de> <1193056647.416562.36150@q3g2000prf.googlegroups.com> <1193057676.680959.71780@v23g2000prn.googlegroups.com> <1193064348.526006.183080@q5g2000prf.googlegroups.com> Message-ID: From the cookbook, this time. It satisfies the requirements nicely ;) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 def tail_recursion(g): ''' Version of tail_recursion decorator using no stack-frame inspection. ''' loc_vars ={"in_loop":False,"cnt":0} def result(*args, **kwd): loc_vars["cnt"]+=1 if not loc_vars["in_loop"]: loc_vars["in_loop"] = True while 1: tc = g(*args,**kwd) try: qual, args, kwd = tc if qual == 'continue': continue except (TypeError, ValueError): loc_vars["in_loop"] = False return tc else: if loc_vars["cnt"]%2==0: return ('continue',args, kwd) else: return g(*args,**kwd) return result @tail_recursion def factorial(n, acc=1): "calculate a factorial" if n == 0: return acc res = factorial(n-1, n*acc) return res From steven.bethard at gmail.com Mon Oct 8 14:22:29 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 08 Oct 2007 12:22:29 -0600 Subject: Don't use __slots__ (was Re: Problem of Readability of Python) In-Reply-To: References: <1191780456.833563.173080@57g2000hsv.googlegroups.com> <2tqdncU0D6K8v5TanZ2dnUVZ_hGdnZ2d@comcast.com> Message-ID: Aahz wrote: > In article <2tqdncU0D6K8v5TanZ2dnUVZ_hGdnZ2d at comcast.com>, > Steven Bethard wrote: >> You can use __slots__ [...] > > Aaaugh! Don't use __slots__! > > Seriously, __slots__ are for wizards writing applications with huuuge > numbers of object instances (like, millions of instances). You clipped me saying that __slots__ are for performance tweaks: You can use __slots__ to make objects consume less memory and have slightly better attribute-access performance. Classes for objects that need such performance tweaks should start like... I fully agree that __slots__ are for applications with huge numbers of instances. But if you have that situation, you really do want to be using __slots__. STeVe From deets at nospam.web.de Tue Oct 2 04:48:36 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Oct 2007 10:48:36 +0200 Subject: gui toolkits: the real story? (Tkinter, PyGTK, etc.) References: <1191287053.541506.88530@d55g2000hsg.googlegroups.com> Message-ID: <5meev4Fcr2anU1@mid.uni-berlin.de> > Maybe a better question is, how has Tk managed to keep beating up the > newer, more modern, more featureful, better documented toolkits > encroaching on his territory? What's Tk's secret weapon? There is no secret weapon. It's a question about dependencies, maintenance, stability and supported platforms. Using one of the other Toolkits would mean that an awful lot of libraries need to be included as well - even nowadays, people complain about the size of a python distribution. Then something in the core libraries has to be actively & reliably maintained to not endanger the overall release cycles. Linked to that is the question of stability - not so much as "it doesn't crash" but more on the lines of "it doesn't move so fast people cry for newer versions all the time" And last but not least is Tk available on a wide range of platforms, larger than more or less every other toolkit. I know of a popular source control software which vendor chose Tk for the same reason. Diez From JKPeck at gmail.com Wed Oct 24 19:59:32 2007 From: JKPeck at gmail.com (JKPeck) Date: Wed, 24 Oct 2007 23:59:32 -0000 Subject: Wrapping stdout in a codec In-Reply-To: <5o2tp4FktnthU1@mid.uni-berlin.de> References: <1193020877.138550.53890@z24g2000prh.googlegroups.com> <5o2tp4FktnthU1@mid.uni-berlin.de> Message-ID: <1193270372.916624.310800@y27g2000pre.googlegroups.com> On Oct 22, 12:20 am, Marc 'BlackJack' Rintsch wrote: > On Mon, 22 Oct 2007 02:41:17 +0000, JKPeck wrote: > > We want to wrap the stdout device in a codec in order to decode output > > transparently according to a particular code page (which might not be > > the system code page). However, codec.open requires a filename, and > > stdout may be a tty or otherwise anonymous. How can we accomplish > > this wrapping? > > The `codecs` module has more than just the `codecs.open()` function. Try > something like this:: > > sys.stdout = codecs.getwriter('utf-8')(sys.stdout) > > Ciao, > Marc 'BlackJack' Rintsch Thanks, codecs.getwriter is just the ticket. Our app may not be running in the system encoding, so the file system encoding is not appropriate. From kyosohma at gmail.com Wed Oct 24 11:13:25 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 24 Oct 2007 15:13:25 -0000 Subject: win32com.client documentation? In-Reply-To: <1193236546.344635.54080@e9g2000prf.googlegroups.com> References: <1193236546.344635.54080@e9g2000prf.googlegroups.com> Message-ID: <1193238805.436906.253370@e9g2000prf.googlegroups.com> On Oct 24, 9:35 am, Mark Morss wrote: > I am a unix person, not new to Python, but new to Python programming > on windows. Does anyone know where to find documentation on > win32com.client? I have successfully installed this module and > implemented some example code. But a comprehensive explanation of the > objects and methods available is nowhere to be found. I have been > able to find a somewhat out-of-date O'Reilly book, nothing more. > > I want to be able to script the creation of Excel spreadsheets and > Word documents, interract with Access data bases, and so forth. Actually, the out-of-date book is still very relevant for most applications. Chun's book, Core Python Programming also has a section on using Python to manipulate Office documents. The docs for PyWin32 currently reside here: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32_modules.html The com documents specifically can be found here: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/com.html As Tim Golden has mentioned before, Pywin32 is bound so closely to the win32 calls that you can basically just look on MSDN and use the syntax there in Python, for the most part. Mike From rzzzwilson at gmail.com Sun Oct 28 01:03:42 2007 From: rzzzwilson at gmail.com (rzzzwilson) Date: Sat, 27 Oct 2007 22:03:42 -0700 Subject: elementtree w/utf8 In-Reply-To: References: Message-ID: <1193547822.283497.115800@i13g2000prf.googlegroups.com> Tim Arnold wrote: > On a related note, I have another question--where/how can I get the > cElementTree.py module? Sorry for something so basic, but I tried installing > cElementTree, but while I could compile with setup.py build, I didn't end up > with a cElementTree.py file anywhere. The directory structure on my system > (HPux, but no root access) doesn't work well with setup.py install. > > thanks, > --Tim Arnold I had the same question a while ago .... and the answer is ElementTree is now part of the standard library. http://docs.python.org/lib/module-xml.etree.ElementTree.html Ross From martin at marcher.name Wed Oct 24 17:36:58 2007 From: martin at marcher.name (Martin Marcher) Date: Wed, 24 Oct 2007 23:36:58 +0200 Subject: Test for a unicode string In-Reply-To: <1193252964.441263.179350@e9g2000prf.googlegroups.com> References: <1193252964.441263.179350@e9g2000prf.googlegroups.com> Message-ID: <5fa6c12e0710241436y37389819p82d2c1b78e250cff@mail.gmail.com> 2007/10/24, goldtech : > Question: Is there a way to test a string for unicode chars (ie. test > if a string will throw the error cited above). yes there ist :) >>> isinstance(u"a", basestring) True >>> isinstance(u"a", unicode) True >>> isinstance("a", unicode) False >>> isinstance("a", str) True >>> isinstance(u"a", str) False -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From george.sakkis at gmail.com Tue Oct 30 09:21:20 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 30 Oct 2007 13:21:20 -0000 Subject: Readline and record separator In-Reply-To: <1193746908.551018.130240@z9g2000hsf.googlegroups.com> References: <1193746908.551018.130240@z9g2000hsf.googlegroups.com> Message-ID: <1193750480.643207.144590@57g2000hsv.googlegroups.com> On Oct 30, 8:21 am, Johny wrote: > Is it possible to change record separator when using readline? > As far as I know readline reads characters until found '\n' and it is > the end of record for readline. > My problem is that my record consits several '\n' and when I use > readline it does NOT read the whole my record. > So If I could change '\n' as a record separator for readline, it > would solve my problem. > Any idea? > Thank you > L. Check out this recipe, it's pretty generic: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877. George From rcdailey at gmail.com Wed Oct 10 16:29:06 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 10 Oct 2007 15:29:06 -0500 Subject: for loop question In-Reply-To: <496954360710101328q4ec95c8pdc9f0b271d2b83e6@mail.gmail.com> References: <496954360710101256w2502c99dh5341ade1c0aaa88d@mail.gmail.com> <1192047136.3388.19.camel@dot.uniqsys.com> <496954360710101327s7ee23520u9bb4d74833110071@mail.gmail.com> <496954360710101328q4ec95c8pdc9f0b271d2b83e6@mail.gmail.com> Message-ID: <496954360710101329q1a39d65bs19ce22425f819048@mail.gmail.com> All the ideas presented here are workable. I definitely have a lot of solutions to choose from. Thanks everyone for your help. I wasn't sure if there was some sort of language feature to naturally do this, so I had to post on the mailing list to make sure. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Frank.Aune at broadpark.no Thu Oct 18 18:46:54 2007 From: Frank.Aune at broadpark.no (Frank Aune) Date: Fri, 19 Oct 2007 00:46:54 +0200 Subject: python logging module and custom handler specified in config file In-Reply-To: <1192728419.133020.133590@q5g2000prf.googlegroups.com> References: <1192728419.133020.133590@q5g2000prf.googlegroups.com> Message-ID: <200710190046.54903.Frank.Aune@broadpark.no> On Thursday 18 October 2007 19:26:59 Vinay Sajip wrote: > The same technique applies to the arguments passed to the constructor. > > Hope this helps, > Thank you! This seems like exactly what I was looking for. Very impressive logging framework btw - I use it whenever I can =) Cheers, Frank From allen.fowler at yahoo.com Wed Oct 17 18:59:18 2007 From: allen.fowler at yahoo.com (allen.fowler) Date: Wed, 17 Oct 2007 15:59:18 -0700 Subject: CGI and external JavaScript nightmare In-Reply-To: <1192639690.306271.298190@z24g2000prh.googlegroups.com> References: <1192083786.137629.24550@r29g2000hsg.googlegroups.com> <1192529804.759199.76350@i13g2000prf.googlegroups.com> <1192639690.306271.298190@z24g2000prh.googlegroups.com> Message-ID: <1192661958.052525.163760@e34g2000pro.googlegroups.com> > > One CGI question - since all of my CGIs are spitting out HTML is their > source code safe? wget and linking to the source deliver the output > HTML. Are there any other methods of trying to steal the source CGI I > need to protect against? > > Thank you. Not sure I fully understand the question. Can you post the CGI code here? From aaron.watters at gmail.com Tue Oct 9 07:26:18 2007 From: aaron.watters at gmail.com (aaron.watters at gmail.com) Date: Tue, 09 Oct 2007 04:26:18 -0700 Subject: NUCULAR fielded text searchable indexing In-Reply-To: References: <1191875335.134872.302660@d55g2000hsg.googlegroups.com> Message-ID: <1191929178.103375.308840@50g2000hsm.googlegroups.com> On Oct 8, 7:00 pm, "Delaney, Timothy (Tim)" wrote: > aaron.watt... at gmail.com wrote: > > ANNOUNCE: > > NUCULAR fielded text searchable indexing > > Does "NUCULAR" stand for anything? The (apparent) misspelling of > "nuclear" has already turned me off wanting to find out more about it. > > Tim Delaney No, it doesn't stand for anything. I guess it's not for you :(. Sorry about that. (see the graphic at the bottom of http://nucular.sourceforge.net) -- Aaron Watters === An apple every 8 hours will keep 3 doctors away. (kliban) From steve at REMOVE-THIS-cybersource.com.au Mon Oct 8 08:38:52 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 08 Oct 2007 12:38:52 -0000 Subject: Don't use __slots__ (was Re: Problem of Readability of Python) References: <1191780456.833563.173080@57g2000hsv.googlegroups.com> <2tqdncU0D6K8v5TanZ2dnUVZ_hGdnZ2d@comcast.com> Message-ID: <13gk96sks58ad9f@corp.supernews.com> On Sun, 07 Oct 2007 21:27:31 -0700, Aahz wrote: > In article <2tqdncU0D6K8v5TanZ2dnUVZ_hGdnZ2d at comcast.com>, Steven > Bethard wrote: >> >>You can use __slots__ [...] > > Aaaugh! Don't use __slots__! > > Seriously, __slots__ are for wizards writing applications with huuuge > numbers of object instances (like, millions of instances). For an > extended thread about this, see > > http://groups.google.com/group/comp.lang.python/browse_thread/ thread/8775c70565fb4a65/0e25f368e23ab058 Well, I've read the thread, and I've read the thread it links to, and for the life of me I'm still no clearer as to why __slots__ shouldn't be used except that: 1 Aahz and Guido say __slots__ are teh suxxor; 2 rumour (?) has it that __slots__ won't make it into Python 3.0; 3 inheritance from classes using __slots__ doesn't inherit the slot- nature of the superclass. Point 1 is never to be lightly dismissed, but on the other hand Guido doesn't like reduce(), and I'm allergic to "Cos I Said So" arguments. History is full of things which were invented for one purpose being used for something else. So, that being the case, suppose I accept that using __slots__ is not the best way of solving the problem, and that people of the skill and experience of Guido and Aahz will roll their eyes and snicker at me. But is there actually anything *harmful* that can happen if I use __slots__? -- Steven. From horpner at yahoo.com Tue Oct 16 08:44:36 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 16 Oct 2007 12:44:36 GMT Subject: Newbi Q: What is a rational for strings not being lists in Python? References: <53396d9e0710150805n6e2cfa53je05d24ec51190aa0@mail.gmail.com> <1192502360.503727.299990@e34g2000pro.googlegroups.com> Message-ID: On 2007-10-16, Simon Brunning wrote: > On 10/16/07, Benjamin wrote: > >> Good explanation, but basically strings are immutable so they can be >> used in dicts. > > Nope. Value types should always be immutable. > > And strings are considered value objects because... -- Neil Cerutti From besturk at gmail.com Thu Oct 18 13:01:12 2007 From: besturk at gmail.com (Abandoned) Date: Thu, 18 Oct 2007 10:01:12 -0700 Subject: Convert string to command.. In-Reply-To: <87przc1im7.fsf@mulj.homelinux.net> References: <1192717399.296654.270350@k35g2000prh.googlegroups.com> <5npa5cFj5bvfU1@mid.uni-berlin.de> <1192720007.177063.194550@i13g2000prf.googlegroups.com> <5npbjbFio7g9U1@mid.uni-berlin.de> <1192720659.272611.320900@v29g2000prd.googlegroups.com> <873aw830lc.fsf@mulj.homelinux.net> <1192722090.740342.60950@i13g2000prf.googlegroups.com> <87y7e01kcv.fsf@mulj.homelinux.net> <1192724835.765738.141790@q5g2000prf.googlegroups.com> <87przc1im7.fsf@mulj.homelinux.net> Message-ID: <1192726872.921589.249670@i38g2000prf.googlegroups.com> On Oct 18, 7:40 pm, Hrvoje Niksic wrote: > Abandoned writes: > > Sorry i can't understand :( > > Yes my database already has data in the "{..}" format and i select > > this and i want to use it for dictionary.. > > But, do you use Python to create that data? If so, simply convert it > to pickle binary format instead of "{...}". As explained in my other > post: > > > id-1 | all > > 56 {68:66, 98:32455, 62:655} > > If you use Python to create this cache table, then simply don't dump > it as a dictionary, but as a pickle: > > id-1 | all > 56 > > When you load it, convert the string to dict with cPickle.loads > instead of with eval. Yes i understand and this very very good ;) But i have a problem.. a=eval(a) a=pickle.dumps(a, -1) cursor.execute("INSERT INTO cache2 VALUES ('%s')" % (a)) conn.commit() and give me error: psycopg2.ProgrammingError: invalid byte sequence for encoding "UTF8": 0x80 HINT: This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding". From grante at visi.com Fri Oct 19 10:43:07 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 19 Oct 2007 14:43:07 -0000 Subject: Noob questions about Python References: <1192649863.496557.230730@v29g2000prd.googlegroups.com> <1192658316.048082.212190@v23g2000prn.googlegroups.com> <1192659838.773066.160060@i38g2000prf.googlegroups.com> <1192663840.916445.207420@k35g2000prh.googlegroups.com> <1192729918.586875.187520@e34g2000pro.googlegroups.com> Message-ID: <13hhgjrtn3j9pb7@corp.supernews.com> On 2007-10-19, Hendrik van Rooyen wrote: > "Arnaud Delobelle" wrote: > >> In binary 2 is 10. When you multiply by 10, you shift all your digits >> left by 1 place. >> When you multiply by 10**n (which is 1 followed by n zeroes), you >> shift all your digits left by n places. > > I read somewhere: > > Only 1 person in 1000 understands binary. > The other 111 don't have a clue. There are only 10 kinds of people: those who understand binary and those who don't. -- Grant Edwards grante Yow! Will this never-ending at series of PLEASURABLE visi.com EVENTS never cease? From brunovianarezende at gmail.com Sat Oct 6 08:02:57 2007 From: brunovianarezende at gmail.com (Bruno Rezende) Date: Sat, 06 Oct 2007 05:02:57 -0700 Subject: my Python lib is broken Message-ID: <1191672177.389263.185790@g4g2000hsf.googlegroups.com> Hi, I think I've broken my python installation (don't know how). All the packages that are under 'lib' in python installation doesn't work the way expected: >>> import xml >>> xml.dom Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'dom' but, if I import * from xml, it starts to work again: >>> from xml import * >>> xml.dom Does someone know why is this happening? (I can reinstall my python 2.5, but would like to know how the python lib got broken). regards, Bruno From cyberco at gmail.com Sun Oct 14 16:36:07 2007 From: cyberco at gmail.com (cyberco) Date: Sun, 14 Oct 2007 20:36:07 -0000 Subject: pydev code completion problem In-Reply-To: References: Message-ID: <1192394167.058669.117830@q5g2000prf.googlegroups.com> Confirmed (with exactly the same software). Please discuss this issue at the PyDev discussion forum: http://sourceforge.net/forum/forum.php?forum_id=293649 2B From nick at craig-wood.com Mon Oct 8 10:30:13 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 08 Oct 2007 09:30:13 -0500 Subject: changes on disk not visible to script ? References: <1191850024.006823.101610@r29g2000hsg.googlegroups.com> Message-ID: Bruce wrote: > I am trying to have my script automate a task, by using os.system, but > I cant get it to work. > > manually, outside the script I can do this thing by > > C:\echo argument_file | the_program > > This works very well when argument_file is created before my script is > started > > In the script I try to do it like this: > f = open("argument_file",'w') > f.write(argument) > f.close() > cmd = "echo %s | %s"%(argument_file,the_program) > os.system(cmd) > > The script works if the argument_file is already in the directory > before os.system(cmd), but the script must create argument_file before > using os.system. Problem is the_program cannot find argument_file or > the_program cannot find anything inside argument_file. Send some real code, plus a sequence of steps to be followed to replicate the problem and you'll get some real help. The above is just too vague. The above code has a syntax error in it so obviously isn't from working code. PS I really doubt the problem is windows not seeing the created file... -- Nick Craig-Wood -- http://www.craig-wood.com/nick From truthismidway at aim.com Fri Oct 19 11:34:53 2007 From: truthismidway at aim.com (Sushant) Date: Fri, 19 Oct 2007 11:34:53 -0400 Subject: dynamic invoke In-Reply-To: <5nrvdoFjmq4tU1@mid.uni-berlin.de> References: <1192790367.342435.243930@v29g2000prd.googlegroups.com> <5nrvdoFjmq4tU1@mid.uni-berlin.de> Message-ID: <200710191134.53856.truthismidway@aim.com> I did not know about getattr and it is the right thing. getattr seems to be converting string into function pointer and I am just saying that string cannot be used as a function pointer in Python as may be in PHP. I copied the PHP code so I did not replace arrow with dot. Good point :) -Sushant. On Friday 19 October 2007 11:05 am, Diez B. Roggisch wrote: > Sushant wrote: > > Python will not allow string to be used a function pointer. It is type > > unsafe. Best way is to convert string into function pointers manually. > > > > if dynamicMethod == 'bar': > > method = oFoo->bar > > else: > > method = oFoo->default > > method() > > Sorry to say so, but that answer is bogus. It's not even Python! > > Jarek has already shown how to solve this problem. And type-safety-issues > have nothing to do with it at all. > > Diez From steve at holdenweb.com Tue Oct 2 18:31:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 02 Oct 2007 18:31:20 -0400 Subject: module confusion In-Reply-To: References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > In message , Robert > Kern wrote: > >> Not all of the modules in a package are imported by importing the >> top-level package. > > You can't import packages, only modules. > >> os.path is a particularly weird case because it is just an alias to the >> platform-specific path-handling module; os is not a package. > > os is a module, os.path is a variable within that module. That's all there > is to it. The Python documentation could probably be a little more expansive on the import front, but it's an area where historically many different attempts have been made to fix up the problems, or create new and more usable layers [that suffer from different problems]. You *can* import a package, and a package is just a *little* different from a module in that the __init__.py file in the package directory provides the source for the first-import execution instead of the modulename.py file. The global namespace during this process is the package's global namespace, so if further imports are executed by the __init__ module the names of the imported objects are created in the package global namespace (along with the names of defined classes and functions, and other names bound by assignment) and can therefore be referenced relative to it. The package in which the package import was executed will end up defined in the namespace in which the import statement was executed. I will grant that you can't basically do anything in the __init__.py that you can't do in a module's modulename.py file. It is possible to define a hierarchy of namespaces concordant with the package's directory structure, but it doesn't matter whether package import creates the hierarchical namespace or assignment does. You can access module namespaces in a hierarchical way. That's about all that can be said without delving into the murky land of relative vs. absolute imports. That can be for another day. And another writer, probably. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From kyosohma at gmail.com Wed Oct 24 09:55:57 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 24 Oct 2007 13:55:57 -0000 Subject: Better writing in python In-Reply-To: <1193230962.271873.104900@v29g2000prd.googlegroups.com> References: <1193227780.481365.261900@q3g2000prf.googlegroups.com> <1193230962.271873.104900@v29g2000prd.googlegroups.com> Message-ID: <1193234157.142175.11020@k35g2000prh.googlegroups.com> On Oct 24, 8:02 am, kyoso... at gmail.com wrote: > On Oct 24, 7:09 am, Alexandre Badez wrote: > > > I'm just wondering, if I could write a in a "better" way this code > > > lMandatory = [] > > lOptional = [] > > for arg in cls.dArguments: > > if arg is True: > > lMandatory.append(arg) > > else: > > lOptional.append(arg) > > return (lMandatory, lOptional) > > > I think there is a better way, but I can't see how... > > You might look into list comprehensions. You could probably do this > with two of them: > > > # completely untested > lMandatory = [arg for arg in cls.dArguments if arg is True] > lOptional = [arg for arg in cls.dArguments if arg is False] > > > Something like that. I'm not the best with list comprehensions, so I > may have the syntax just slightly off. See the following links for > more information: > > http://www.secnetix.de/olli/Python/list_comprehensions.hawkhttp://docs.python.org/tut/node7.html > > Mike After reading the others replies, it makes me think that I'm barking up the wrong tree. Ah well. Mike From beema.shafreen at gmail.com Mon Oct 29 05:24:09 2007 From: beema.shafreen at gmail.com (Beema shafreen) Date: Mon, 29 Oct 2007 14:54:09 +0530 Subject: sorting data Message-ID: hi all, I have problem to sort the data.. the file includes data as follow. file: chrX: 123343123 123343182 A_16_P41787782 chrX: 123343417 123343476 A_16_P03762840 chrX: 123343460 123343519 A_16_P41787783 chrX: 12334336 12334395 A_16_P03655927 chrX: 123343756 123343815 A_16_P03762841 chrX: 123343807 123343866 A_16_P41787784 chrX: 123343966 123344024 A_16_P21578670 chrX: 123344059 123344118 A_16_P21578671 chrX: 12334438 12334497 A_16_P21384637 chrX: 123344776 123344828 A_16_P21578672 chrX: 123344811 123344870 A_16_P03762842 chrX: 123345165 123345224 A_16_P41787789 chrX: 123345360 123345419 A_16_P41787790 chrX: 123345380 123345439 A_16_P03762843 chrX: 123345481 123345540 A_16_P41787792 chrX: 123345873 123345928 A_16_P41787793 chrX: 123345891 123345950 A_16_P03762844 how do is sort the file based on the column 1 and 2 with values...... using sort option works for only one column and not for the other how do is sort both 1 and 2nd column so that the third column does not change..... my script:#sorting the file start_lis = [] end_lis = [] fh = open('chromosome_location_346010.bed','r') for line in fh.readlines(): data = line.strip().split('\t') start = data[1].strip() end = data[2].strip() probe_id = data[3].strip() start_lis.append(start) end_lis.append(end) start_lis.sort() end_lis.sort() for k in start_lis: for i in end_lis print k , i , probe_id(this doesnot worK) result = start#end#probe_id ------->this doesnot work... print result What is the error and how do is sort a file based on the two column to get the fourth column also with that. regards shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From rpw3 at rpw3.org Fri Oct 12 23:11:00 2007 From: rpw3 at rpw3.org (Rob Warnock) Date: Fri, 12 Oct 2007 22:11:00 -0500 Subject: The fundamental concept of continuations References: <1191906949.179197.217470@57g2000hsv.googlegroups.com> <85zlyrutux.fsf@lola.goethe.zz> <85lka8p2h4.fsf@lola.goethe.zz> Message-ID: David Kastrup wrote: +--------------- | George Neuner writes: | > Upward continuations can be stack implemented. On many CPU's, using | > the hardware stack (where possible) is faster than using heap | > allocated structures. For performance, some Scheme compilers go to | > great lengths to identify upward continuations and nested functions | > that can be stack implemented. | | There is a Scheme implementation (I keep forgetting the name) which | actually does both: it actually uses the call stack but never returns, | and the garbage collection includes the stack. +--------------- You're thinking of "Chicken Scheme": http://www.call-with-current-continuation.org/ Chicken Scheme is actually using the C call stack *as* the heap[1], and thus all its continuations are *heap*-allocated, and thus not actually "stack-allocated" at all. But that's not what George Neuner is talking about, as I read it, but rather probably about such things as Kent Dybvig's PhD thesis: http://www.cs.indiana.edu/~dyb/papers/3imp.pdf "Three Implementation Models for Scheme" R. Kent Dybvig, UNC Chapel Hill, 1987 (thesis) (190pp) ... Chapter 4: The Stack-Based Model ... Early Scheme implementors believed that because of the need to support first class functions, the standard techniques used for block-structured languages were not suitable for Scheme. The need to optimize tail calls and support continuations further convinced early implementors that the standard stack techniques were unsuitable. However, as this chapter will show, these techniques can be made to work for Scheme with a few modications. The resulting implementation model allows most function calls to be performed with little or no allocation, and allows variable references to be performed in one or two memory references. Heap allocation remains necessary to support closures, assigned variables, and continuations. Since function calls and variable references are faster and heap allocation is limited, the running time for most programs is greatly decreased. ... -Rob [1] As suggested in: http://home.pipeline.com/~hbaker1/CheneyMTA.html "CONS Should Not CONS Its Arguments, Part II: Cheney on the M.T.A" Henry G. Baker (1994) ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From tjreedy at udel.edu Wed Oct 24 00:08:32 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Oct 2007 00:08:32 -0400 Subject: Speed of Nested Functions & Lambda Expressions References: <1193154050.424718.298030@i13g2000prf.googlegroups.com> <471E1BFC.7080101@islandtraining.com> Message-ID: "Gary Herron" wrote in message news:471E1BFC.7080101 at islandtraining.com... | beginner wrote: | > Hi All, | > | > It is really convenient to use nested functions and lambda | > expressions. What I'd like to know is if Python compiles fn_inner() | > only once and change the binding of v every time fn_outer() is called | > or if Python compile and generate a new function object every time. If | > it is the latter, will there be a huge performance hit? Would someone | > give some hint about how exactly Python does this internally? Python the language does not 'do' anything. The details could be implementation specific. | > def fn_outer(v): | > a=v*2 | > def fn_inner(): | > print "V:%d,%d" % (v,a) | > | > fn_inner() | > | > Thanks, | > Geoffrey | > | > | The code is compiled only once when the file is initially read in. | During execution of fn_outer, v will be bound to a value, then a, then | fn_inner will be bound (to an already compiled code object) and so on. In CPython, I believe, fn_inner is bound to a *new* *function* object, not the once-compiled code object. It has to be a new object because fn_outer could return the inner function, as is not uncommon. And function objects are somewhat mutable. And each returned function might have different values of enclosed outer variables. However, each function object has the same .func_code member. >>> def outer(n): def inner(m): return n+m return inner >>> add3 = outer(3) >>> add3(4) 7 >>> type(add3) | Really, from the point of view of Python while executing fn_outer, the | def of fn_inner looks just like an assignment with fn_inner as the | variable name and a code object as the value. Again, the value is a function object. Terry Jan Reedy From pavlovevidence at gmail.com Wed Oct 31 11:11:04 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 31 Oct 2007 08:11:04 -0700 Subject: shouldn't 'string'.find('ugh') return 0, not -1 ? In-Reply-To: References: Message-ID: <1193843464.345398.94430@k35g2000prh.googlegroups.com> On Oct 31, 9:31 am, jelle wrote: > the subject pretty much says it all. > if I check a string for for a substring, and this substring isn't found, > should't the .find method return 0 rather than -1? > this breaks the > > if check.find('something'): > do(somethingElse) > > idiom, which is a bit of a pity I think. string.find has always been kind of a wart in Python; that's why they're getting rid of it. For testing for the presence of a substring, use the in operator: if "something" in check: do(somethingElse) When you need the position of a substring, using the index methods: i = check.index("something") index returns an exception of the substring is not there, so no need to worry about what it returns. Finally, it really won't kill you to do this: if check.find("something") >= 0: do(somethingElse) Carl Banks From bdesth.quelquechose at free.quelquepart.fr Tue Oct 30 15:55:48 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 30 Oct 2007 20:55:48 +0100 Subject: python in academics? In-Reply-To: <1193749612.124199.172020@o38g2000hse.googlegroups.com> References: <1193715569.261522.219520@i13g2000prf.googlegroups.com> <1193749612.124199.172020@o38g2000hse.googlegroups.com> Message-ID: <47278c71$0$29610$426a74cc@news.free.fr> kyosohma at gmail.com a ?crit : > On Oct 29, 10:39 pm, sandipm wrote: > >>seeing posts from students on group. I am curious to know, Do they >>teach python in academic courses in universities? >> >>in undergrad comp science courses, We had scheme language as scheme >>is neat and beautiful language to learn programming. We learnt other >>languages ourselve with basics set right by scheme.. >> >>sandip > > > They didn't at either of the colleges I went to. They seemed to be > focused on C++, COBOL and Visual Basic. All are used all over the > place, but only Visual Basic is easy for complete newbs. And alas one of the worst languages for a beginner - because you'll probably need years to unlearn it. > I hope more > colleges adopt Python or Ruby as a teaching language, but I don't > think it's a good idea to ignore COBOL or C++ since their used so > extensively in big business. being widely used doesn't imply being a good language for teaching CS (nor even being a good language for anything). From grante at visi.com Wed Oct 3 13:05:03 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 03 Oct 2007 17:05:03 -0000 Subject: gui toolkits: the real story? (Tkinter, PyGTK, etc.) References: <1191287053.541506.88530@d55g2000hsg.googlegroups.com> <1191370407.188678.86820@n39g2000hsh.googlegroups.com> Message-ID: <13g7itvdl8m3870@corp.supernews.com> On 2007-10-03, Chris Mellon wrote: > On 10/2/07, bramble wrote: >> On Oct 2, 11:07 am, "Chris Mellon" wrote: >> > >> > PyGtk has poor cross platform support, a very large footprint (the >> > largest of all these libraries) as well as a complicated runtime >> > environment. >> >> What's complicated about it? >> > > There's an enormous amount of dependencies and runtime configuration, > such as finding theme engines and handling preferences. There's > solutions for managing all of that of course, but it's still much more > overhead than dirt-simple Tk. You've got to admit that Tk "just works", although as a result it looks ugly and foreign on all platforms. -- Grant Edwards grante Yow! So this is what it at feels like to be potato visi.com salad From debajit1 at gmail.com Wed Oct 17 17:03:56 2007 From: debajit1 at gmail.com (Debajit Adhikary) Date: Wed, 17 Oct 2007 21:03:56 -0000 Subject: Appending a list's elements to another list using a list comprehension In-Reply-To: References: <1192652834.150718.205050@t8g2000prg.googlegroups.com> Message-ID: <1192655036.279184.255720@q3g2000prf.googlegroups.com> On Oct 17, 4:41 pm, Carsten Haese wrote: > On Wed, 2007-10-17 at 20:27 +0000, Debajit Adhikary wrote: > > I have two lists: > > > a = [1, 2, 3] > > b = [4, 5, 6] > > > What I'd like to do is append all of the elements of b at the end of > > a, so that a looks like: > > > a = [1, 2, 3, 4, 5, 6] > > > I can do this using > > > map(a.append, b) > > > How do I do this using a list comprehension? > > You don't. > > > (In general, is using a list comprehension preferable (or more > > "pythonic") as opposed to using map / filter etc.?) > > In general, a list comprehension is more Pythonic nowadays, but in your > particular case the answer is neither map nor a list comprehension, it's > this: > > a += b > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net Thanks a ton :) What in general is a good way to learn about little things like these? (I'm fairly new to the language) A google search for 'python list methods" did not turn up the + operator anywhere for me. Where could I find the official documentation for built in structures like the list? (I just noticed that the + operator for lists is mentioned in Beazley's Python Essential Reference -- in the opening pages, which I didn't look at when I was writing the earlier code.) How does "a.extend(b)" compare with "a += b" when it comes to performance? Does a + b create a completely new list that it assigns back to a? If so, a.extend(b) would seem to be faster. How could I verify things like these? From david.trem at gmail.com Sun Oct 7 15:58:21 2007 From: david.trem at gmail.com (David Tremouilles) Date: Sun, 7 Oct 2007 21:58:21 +0200 Subject: Need help to find origin of a memory leakage In-Reply-To: <129e1cd10710040829v263acf1btd42b16350381e7b8@mail.gmail.com> References: <129e1cd10710040829v263acf1btd42b16350381e7b8@mail.gmail.com> Message-ID: <129e1cd10710071258x5ba2a43as1db5ae5776ca8ca2@mail.gmail.com> Finaly catch the memory leak I was fighting with !!!! Was a tricky one, but the solution was simple: I had to include the contents of the notebook tab in a frame. Otherwise the memory is not released when you remove the tab. Any idea why is it like that??? Could it be kind of pygtk bug? I attach the corrected example for the records. Davic 2007/10/4, David Tremouilles : > hello, > > I'm struggling with a memory leakage of my app for quite some > time. Could somebody help? > > I join a demo program in attachment. > The problem is that the memory consumption keeps on increasing while > opening and closing tabs. > In the demo attached a click on "button" will open a new tab. If, for > example, you open ten new tabs, then close ten tabs, and open again > ten tab, and repeat this many times you will see the memory > consumption increases after each 10 close-10 open cycles. > Could somebody help me on finding the origin of this leak? > > Note: I already post on pygtk list and did not get any useful help at > this point in time. > I use > Python 2.5.1 > GTK: (2, 12, 0) > pyGTK: (2, 12, 0) > I already observed the same issue with older versions... > It's been a long time I try to solve it... > > Thanks in advance, > > -------------- next part -------------- A non-text attachment was scrubbed... Name: mem_leak.py Type: application/octet-stream Size: 2842 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: fenetre.glade Type: application/octet-stream Size: 1956 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: element.glade Type: application/octet-stream Size: 1798 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: mem_leak_solved.py Type: application/octet-stream Size: 2916 bytes Desc: not available URL: From thorsten at thorstenkampe.de Mon Oct 15 14:20:30 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 15 Oct 2007 19:20:30 +0100 Subject: Normalize a polish L References: <1192466006.735303.20470@i38g2000prf.googlegroups.com> Message-ID: * Peter Bengtsson (Mon, 15 Oct 2007 16:33:26 -0000) > In UTF8, \u0141 is a capital L with a little dash through it as can be > seen in this image: > http://static.peterbe.com/lukasz.png > I tried this: > >>> import unicodedata > >>> unicodedata.normalize('NFKD', u'\u0141').encode('ascii','ignore') > '' > > I was hoping it would convert it it 'L' because that's what it > visually looks like. And I've seen it becoming a normal ascii L before > in other programs such as Thunderbird. The 'L' is actually pronounced like the English "w"... > I also tried the other forms: 'NFC', 'NFKC', 'NFD', and 'NFKD' but > none of them helped. >>> unicodedata.decomposition(u'\N{LATIN CAPITAL LETTER C WITH CEDILLA}') '0043 0327' >>> unicodedata.normalize('NFKD', u'\N{LATIN CAPITAL LETTER C WITH CEDILLA}').encode('ascii','ignore') 'C' >>> unicodedata.decomposition(u'\N{LATIN CAPITAL LETTER L WITH STROKE}') '' From DustanGroups at gmail.com Fri Oct 5 07:19:44 2007 From: DustanGroups at gmail.com (Dustan) Date: Fri, 05 Oct 2007 11:19:44 -0000 Subject: novice list In-Reply-To: References: Message-ID: <1191583184.675377.3550@o3g2000hsb.googlegroups.com> On Oct 5, 6:01 am, Istv?n wrote: > Could somebody suggest me a novice Python list, please? > Thanks, Istvan You're there. From robert.kern at gmail.com Mon Oct 22 20:57:08 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Oct 2007 19:57:08 -0500 Subject: parallel NumPy: PyMPI, myMPI or something else? In-Reply-To: <1193094391.758441.124940@q5g2000prf.googlegroups.com> References: <1193001446.939761.122290@t8g2000prg.googlegroups.com> <1193094391.758441.124940@q5g2000prf.googlegroups.com> Message-ID: smithken04 at yahoo.com wrote: > Robert, > the answer could not have been shorter, but I got exactly the > information I was looking for :-) > Thank you so much! > > Just a single followup question: >>> Or do I have to split each problem myself to make use of the >>> parallelism? >> Pretty much. > Does "pretty much" imply that actually *some* parts of NumPy do make > use of the parallel environment without any MPI handling from the > user? I didn't find an indication for this during my short skimming > over the NumPy documentation. Sorry, that's really just American teenager idiom that's followed me into adulthood; it means, roughly, "Yes, this is entirely, unequivocally true," much like "Literally!" usually means "Figuratively!" No part of numpy proper takes advantage of parallelism. Eric Jones has been toying with using threads to split up some operations on large arrays between cores on an SMP system, but it is not ready to merge into the trunk. The performance numbers haven't been that good. The cost of thread locks is high. But then, only one approach has been tried; if you are interested in trying others, we'd be more than happy to help you along on the numpy-discussion mailing list. http://svn.scipy.org/svn/numpy/branches/multicore/ http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From matt at tplus1.com Thu Oct 18 23:10:40 2007 From: matt at tplus1.com (Matthew Wilson) Date: Fri, 19 Oct 2007 03:10:40 GMT Subject: I can't get minimock and nosetests to play nice Message-ID: I'm curious if anyone has ever tried using nosetests along with minimock. I'm trying to get the two to play nice and not making progress. I also wonder if I'm using minimock incorrectly. Here's the code I want to test, saved in a file dtfun.py. class Chicken(object): "I am a chicken." def x(self): return 1 def z(self): return 1 def g(): """ Verify that we call method x on an instance of the Chicken class. # First set up the mockery. >>> from minimock import Mock >>> Chicken = Mock('Chicken') >>> Chicken.mock_returns = Mock('instance_of_chicken') Now this stuff is the real test. >>> g() Called Chicken() Called instance_of_chicken.x() """ # This is what the function does. c = Chicken() c.x() if __name__ == "__main__": # First set up the mockery. from minimock import Mock Chicken = Mock('Chicken') Chicken.mock_returns = Mock('instance_of_chicken') # Now run the tests. import doctest doctest.testmod() Here's the results when I run the code using doctest.testmod (which passes) and nosetests --with-doctest (KABOOM): $ python dtfun.py # Nothing is a good thing here. $ nosetests --with-doctest dtfun.py F ====================================================================== FAIL: Doctest: dtfun.g ---------------------------------------------------------------------- Traceback (most recent call last): File "doctest.py", line 2112, in runTest raise self.failureException(self.format_failure(new.getvalue())) AssertionError: Failed doctest test for dtfun.g File "/home/matt/svn-checkouts/scratch/python/dtfun/dtfun.py", line 13, in g ---------------------------------------------------------------------- File "/home/matt/svn-checkouts/scratch/python/dtfun/dtfun.py", line 22, in dtfun.g Failed example: g() Expected: Called Chicken() Called instance_of_chicken.x() Got nothing ---------------------------------------------------------------------- Ran 1 test in 0.015s FAILED (failures=1) It seems like nose isn't building the mock objects. Any ideas? Matt From ldo at geek-central.gen.new_zealand Thu Oct 4 04:07:31 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Oct 2007 21:07:31 +1300 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <13frd6vtarbee75@corp.supernews.com> <85hcl8qaj7.fsf@lola.goethe.zz> Message-ID: In message , Bent C Dalager wrote: > Unfortunately, these days English almost always means American English... North American or South American? Seems like USAmericans speak a little different English from other Americans... From edreamleo at charter.net Sat Oct 27 07:14:52 2007 From: edreamleo at charter.net (Edward K Ream) Date: Sat, 27 Oct 2007 06:14:52 -0500 Subject: ANN: Leo 4.4.4 beta 4 released Message-ID: Leo 4.4.4 beta 4 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 This beta 4 version fixes all bugs reported against Leo 4.4.4 beta 3. Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html Leo 4.4.4 contains many important features originally planned for later releases. The highlights of Leo 4.4.4: ---------------------------- - The Great Graph Aha (tm): simple scripts allow Leo outlines to represent arbitrary directed graphs. There is no need for a separate 'graph world'. The graphed.py plugin is a direct result of this Aha. The graphed.py plugin allows you to create general graphs from Leo outlines. - @menus trees in settings files create all of Leo's menus. It is now dead easy to make Leo's menus look the way you want. - @buttons trees in settings files create common @button nodes created in all Leo outlines. - @auto nodes eliminate sentinels in derived files, thereby allowing people to collaborate using Leo more easily. - New commands for resolving cvs conflicts. - A threading_colorizer plugin replaces the __jEdit_colorizer__ plugin. This plugin features much better performance and a new, elegant algorithm. - Leo is now compatible with jython. - Better support for icons in headlines. - The usual assortment of bug fixes and other minor improvements. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ 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 kyosohma at gmail.com Thu Oct 25 13:43:53 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 25 Oct 2007 17:43:53 -0000 Subject: Python Windows Installation In-Reply-To: <1193333796.807911.106350@22g2000hsm.googlegroups.com> References: <1193195493.086681.40570@t8g2000prg.googlegroups.com> <1193333796.807911.106350@22g2000hsm.googlegroups.com> Message-ID: <1193334233.504846.229800@o80g2000hse.googlegroups.com> On Oct 25, 12:36 pm, TheFlyingDutchman wrote: > On Oct 24, 11:22 pm, Tim Roberts wrote: > > > TheFlyingDutchman wrote: > > > >I am trying to install Python 2.5 on Windows XP. It installs into the > > >root directory on C:\ instead of C:\Python25 which it shows by default > > >as what it plans to install to. Selecting D:\Python25 on a previous > > >iteration put the exe in D:\ and did not create a Python25 directory. > > > Where did you get the installer? I've installed Python on Windows many, > > many times, and have never seen this issue. > > -- > > Tim Roberts, t... at probo.com > > Providenza & Boekelheide, Inc. > > from python.org. I doubt many people get this or it would be fixed > but it still is shocking how it can prompt me that the installation > directory exists - showing that it fully knows where it is supposed to > install it - and then go ahead and install it to the root directory > and claim success. It also uninstalls Python if you ask it to so any > screwy settings from a previous install should be removed after the > uninstall, but it also fails to install correctly after an uninstall. I've never had any problems getting Python to install on Windows XP SP2. I have had a few issues with getting Python in the system path, especially when I have multiple versions of Python installed. My guess is that Windows itself may be getting goofy. I know that if I use Windows heavily for a year and a half or so (uninstalling and installing lots of programs), it usually starts acting flakey. A fresh install of the OS always helps those situations. Alternatively, you could just change the directory to "C:\Py", install it there and then rename it "C:\Python25". Then go to the registry and do a search and replace as well as make sure the Environmental Settings are fixed accordingly. Yes, it is a pain. Mike From mensanator at aol.com Wed Oct 24 17:32:48 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Wed, 24 Oct 2007 14:32:48 -0700 Subject: Iteration for Factorials In-Reply-To: References: <1193055966.362489.252080@v29g2000prd.googlegroups.com> Message-ID: <1193261568.712027.234520@e9g2000prf.googlegroups.com> On Oct 24, 4:05 pm, Lou Pecora wrote: > In article , > Nick Craig-Wood wrote: > > > > > > > Py-Fun wrote: > > > I'm stuck trying to write a function that generates a factorial of a > > > number using iteration and not recursion. Any simple ideas would be > > > appreciated. > > > Here is the math geek answer ;-) > > > import math > > > def factorial(i): > > n = i + 1 > > return math.exp(-n)*(n**(n-0.5))*math.sqrt(2*math.pi)*(1. + 1./12/n + > > 1./288/n**2 - 139./51840/n**3) > > > Works for non integer factorials also... > > > See here for background > > > http://mathworld.wolfram.com/StirlingsSeries.html > > Well, that's Sterling's formula. You do have to worry about > convergence/accuracy. > > How about (for intergers - simple-minded version): > > def factorial(i): > fact=1.0 > for n in xrange(i): > fact=n*fact > return fact Simple minded indeed. >>> factorial(3) 0.0 > > There might even be an array method that can be adapted to get the > product. Is there a product method? (analogous to a sum method) > > Then you could use, > > arr=arange(i)+1 > fact=arr.product() # or something like that > > -- > -- Lou Pecora- Hide quoted text - > > - Show quoted text - From ldo at geek-central.gen.new_zealand Sat Oct 6 04:18:28 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 06 Oct 2007 21:18:28 +1300 Subject: supplying password to subprocess.call('rsync ...'), os.system('rsync ...') References: <1191594819.381604.20680@o80g2000hse.googlegroups.com> Message-ID: In message <1191594819.381604.20680 at o80g2000hse.googlegroups.com>, timw.google wrote: > I want to write a python script that runs rsync on a given directory > and host. I build the command line string, but when I try to run > subprocess.call(cmd), or p=subprocess.Popen(cmd, shell=True),or > os.system(cmd), I get prompted for my login password. Why not set up a public/private SSH key pair between the accounts on the two machines? Then you can get in without a password. From smithken04 at yahoo.com Mon Oct 22 19:06:31 2007 From: smithken04 at yahoo.com (smithken04 at yahoo.com) Date: Mon, 22 Oct 2007 16:06:31 -0700 Subject: parallel NumPy: PyMPI, myMPI or something else? In-Reply-To: References: <1193001446.939761.122290@t8g2000prg.googlegroups.com> Message-ID: <1193094391.758441.124940@q5g2000prf.googlegroups.com> Robert, the answer could not have been shorter, but I got exactly the information I was looking for :-) Thank you so much! Just a single followup question: > > Or do I have to split each problem myself to make use of the > > parallelism? > > Pretty much. Does "pretty much" imply that actually *some* parts of NumPy do make use of the parallel environment without any MPI handling from the user? I didn't find an indication for this during my short skimming over the NumPy documentation. Ken From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Oct 3 07:04:28 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 03 Oct 2007 13:04:28 +0200 Subject: A total bullshit (was : A Must Read!!!) In-Reply-To: <1191403384.456238.92870@22g2000hsm.googlegroups.com> References: <1191403384.456238.92870@22g2000hsm.googlegroups.com> Message-ID: <47037730$0$21878$426a74cc@news.free.fr> richard.james861 at gmail.com a ?crit : > I have found an excellent resource on Object Oriented Programming. > > (url snipped to protect the innocents) Let's see: "An object has methods, properties and events." Hem... "oriented programming probably existed before the concept of a class came into being but today the concept of a class is essential to object orientation." Hem hem... This is total bullshit. From grante at visi.com Fri Oct 5 12:11:07 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 05 Oct 2007 16:11:07 -0000 Subject: Python Magazine: Issue 1 Free! References: <13gcjeqbhmh152c@corp.supernews.com> Message-ID: <13gcogrm9uloj4b@corp.supernews.com> On 2007-10-05, Steve Holden wrote: >> >>> I've just been told by the editors at Python Magazine that the >>> first issue is out. >> >> The first issue is issue number 10? >> >> That's a bit silly. > > It's the October edition. They obviously decided to make sure > the month numbering was consistent across the volumes. I presumed that was the reasoning. It just seems counter-intuitive (and sort of un-Pythonic) to start numbering a sequence of objects at 10. ;) -- Grant Edwards grante Yow! Hmmm ... a CRIPPLED at ACCOUNTANT with a FALAFEL visi.com sandwich is HIT by a TROLLEY-CAR ... From MrJean1 at gmail.com Tue Oct 30 13:15:26 2007 From: MrJean1 at gmail.com (MrJean1) Date: Tue, 30 Oct 2007 17:15:26 -0000 Subject: Solaris 10 + Sun Studio 12 Pyrhon 2.4.4 64-bit build problem In-Reply-To: <1193637835.936397.307160@e9g2000prf.googlegroups.com> References: <1193637835.936397.307160@e9g2000prf.googlegroups.com> Message-ID: <1193764526.526065.274250@t8g2000prg.googlegroups.com> Building 64-bit Python 2.4.4 on Solaris 10 and SUC C/C++ using the instructions from worked just fine on Ultra 20 Opteron machine. The test result summary is below. /Jean Brouwers .... 249 tests OK. 2 tests failed: test_cmath test_pty 40 tests skipped: test_aepack test_al test_applesingle test_bsddb test_bsddb185 test_bsddb3 test_bz2 test_cd test_cl test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_crypt test_curses test_dl test_gdbm test_gl test_imageop test_imgfile test_linuxaudiodev test_macfs test_macostools test_nis test_normalization test_ossaudiodev test_pep277 test_plistlib test_rgbimg test_scriptpackages test_socket_ssl test_socketserver test_tcl test_timeout test_unicode_file test_urllib2net test_urllibnet test_winreg test_winsound 5 skips unexpected on sunos5: test_tcl test_bz2 test_crypt test_dl test_nis plumb and tree wrote: > I've been trying for days to build 64 bit python with Solaris 10 + Sun > Studio 12. > > Can anyone helpl please. > From jcd at sdf.lonestar.org Mon Oct 29 14:09:37 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Mon, 29 Oct 2007 14:09:37 -0400 Subject: Built-in functions and keyword arguments In-Reply-To: References: <1193665924.886459.20710@v3g2000hsg.googlegroups.com> <4725ec3a$0$6623$426a74cc@news.free.fr> Message-ID: <20071029180936.GD3648@sdf.lonestar.org> On Mon, Oct 29, 2007 at 02:27:50PM +0000, Duncan Booth wrote regarding Re: Built-in functions and keyword arguments: > > Bruno Desthuilliers > wrote: > > > In the second case, the name of the argument *is* 'object'. Which is not > > the case for the builtin len (which, fwiw, has type > > 'builtin_function_or_method', not 'function', so inspect.getargspec > > couldn't tell me more). > > > > > > While we're at it, you should avoid using builtin's names for > > identifiers - here, using 'object' as the arg name shadows the builtin > > 'object' class). > > > > I think you are being a little bit unfair here: help(len) says: > > len(...) > len(object) -> integer > > Return the number of items of a sequence or mapping. > > which implies that the argument to len has the name 'object' (although in > fact it doesn't have a name). The OP was simply asking about the difference > in calling conventions, not proposing to write code using 'object' as the > argument name. Hmm.... To my mind, that just implies that the *type* of the expected input is an object. Just like the "-> integer" tells you that the type of the output is an integer. If the documentation read "len(s=object) -> integer", then I would expect a keyword argument s typed as an object. Now that might also be misleading, as not all objects have a length (integers, for example raise a TypeError). But the documentation has to say something, which doesn't imply that every argument has to be a keyword. Cheers, Cliff From josiah.carlson at gmail.com Tue Oct 23 11:34:19 2007 From: josiah.carlson at gmail.com (Josiah Carlson) Date: Tue, 23 Oct 2007 15:34:19 -0000 Subject: Adding idle timeout capabilities to asyncore In-Reply-To: <1193081330.701282.149040@v29g2000prd.googlegroups.com> References: <1193081330.701282.149040@v29g2000prd.googlegroups.com> Message-ID: <1193153659.869282.34310@v23g2000prn.googlegroups.com> On 22 Ott, 12:28, Giampaolo Rodola' wrote: > Hi there. > We're talking about an asyncore-based server. > Just for the heck of it I'd like to set a timeout which will > disconnects the clients if they're inactive (i.e., no command or data > transfer in progress) for a long period of time. > I was thinking about putting the timeout value into an attribute: > > def settimeout(self, secs): > self.timeout = time.time() + secs > > And then have the readable method call time.time() at every loop to > check if time has passed or not: > > def readable(self): > if time.time() >= self.timeout: > self.send("Timeout") > self.close() > return 1 > > My only concern is if it's a good idea calling time.time() so often. > Since A LOT of clients could be connected simultaneously, couldn't it > be a too much resource-intensive operation? > I'd also be curious to know how Twisted implemented this kind of > stuff. > By calling time.time() at every loop? > > Thanks in advance. Calling time.time() is relatively inexpensive in comparison to pure Python function calls, but indeed, it could be a bottleneck. I don't know what Twisted does, but what I would do is to add two variables to each instance of the class you want to add timeouts to; self.timeout and self.lastdata . self.lastdata would hold the time for the last time you sent or received data on the socket, and self.timeout would hold the delay between when you last sent/received data and when it should be closed due to idle timeout. Now, since you are smart, you don't need to alter your handle_send() or handle_receive() methods in your asyncore subclass. Instead, you rewrite asyncore.poll() to update .lastdata for every socket that is in either the reader or writer list, which will result in one time.time() call. Further, to check for timeouts, you only ever need to check those sockets that are *not* in the readable or writable lists... To be precise, add the following block to your own copy of asyncore.poll just after the 'for fd in e:' block... #handle timeouts rw = set(r) + set(w) now = time.time() for f in (i for i in rw if i in map): map[f].lastdata = now for j in (map[i] for i in map if i not in rw): if j.timeout+j.lastdata > now: #timeout! j.handle_close() You ARE going to need to initialize .timeout and .lastdata members for every instance, but that shouldn't be so bad (for a socket that doesn't time out, I would actually suggest a 1 hour or 1 day timeout). - Josiah From arne at vajhoej.dk Sun Oct 21 10:39:53 2007 From: arne at vajhoej.dk (=?UTF-8?B?QXJuZSBWYWpow7hq?=) Date: Sun, 21 Oct 2007 10:39:53 -0400 Subject: Distributed RVS, Darcs, tech love In-Reply-To: References: <1192850894.310464.89070@e9g2000prf.googlegroups.com> <1192914246.208743.94870@y27g2000pre.googlegroups.com> <471afd4c.179297746@news.readfreenews.net> <1192972158.250126.203980@v23g2000prn.googlegroups.com> Message-ID: <471b64b2$0$90272$14726298@news.sunsite.dk> Lew wrote: >> very >> different. Having a dead - i mean end of development line software >> like TeX - and > > Based on what do you call it "dead end". It's used, it's outlasted many > other flashes in the pan, it does what its users require. You will need > evidence for such a claim. According to wikipedia the last version is from december 2002. That level of activity could be considered dead. It would for almost any other software. Tex has some "absolute" over it, so I am not sure normal software practices apply. But you could argue based on that. Arne From kyosohma at gmail.com Wed Oct 10 14:26:16 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 10 Oct 2007 18:26:16 -0000 Subject: Building Binary Packages In-Reply-To: References: <1192026935.627151.160810@19g2000hsx.googlegroups.com> Message-ID: <1192040776.147586.268680@y42g2000hsy.googlegroups.com> On Oct 10, 11:53 am, "Jim B. Wilson" wrote: > On Wed, 10 Oct 2007 14:35:35 +0000, kyosohma wrote: > > I am trying to figure out how to build binaries for Python packages and > > I've done it with MinGW. > > Apparently, you still can:http://tinyurl.com/yb4bps That's a wealth of information. It'll take a while for me to grasp it all, but thanks a lot! Maybe I'll compile with both for a while to see if there's any obvious differences. Mike From kar1107 at gmail.com Thu Oct 4 02:12:32 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Thu, 04 Oct 2007 06:12:32 -0000 Subject: A question about subprocess In-Reply-To: <1191429980.784610.39020@22g2000hsm.googlegroups.com> References: <1191429980.784610.39020@22g2000hsm.googlegroups.com> Message-ID: <1191478352.018857.217720@g4g2000hsf.googlegroups.com> On Oct 3, 9:46 am, JD wrote: > Hi, > > I want send my jobs over a whole bunch of machines (using ssh). The > jobs will need to be run in the following pattern: > > (Machine A) (Machine B) (Machine C) > > Job A1 Job B1 Job C1 > > Job A2 Job B2 etc > > Job A3 etc > > etc > > Jobs runing on machine A, B, C should be in parallel, however, for > each machine, jobs should run one after another. > > How can I do it with the subprocess? subprocess is not network aware. What you can do is write a simple python script say run_jobs.py which can take in a command-line argument (say A or B or C) and will fire a sequence of subprocesses to execute a series of jobs. This will ensure the serialization condition like A2 starting after A1's completion. Now you can write a load distributer kind of script which uses ssh to login to the various machines and run run_jobs.py with appropriate argument (Here I assume all machines have access to run_jobs.py -- say it may reside on a shared mounted file-system). e.g. in outer script: ssh machine-A run_jobs.py A ssh machine-B run_jobs.py B ssh machine-B run_jobs.py C ... You may want to fire all these at once so that they all execute in parallel. Karthik > > Thanks, > > JD From duane.kaufman at gmail.com Tue Oct 23 09:47:06 2007 From: duane.kaufman at gmail.com (TheSeeker) Date: Tue, 23 Oct 2007 06:47:06 -0700 Subject: Set operations on object attributes question Message-ID: <1193147226.862501.97240@v23g2000prn.googlegroups.com> Hi, I have run into something I would like to do, but am not sure how to code it up. I would like to perform 'set-like' operations (union, intersection, etc) on a set of objects, but have the set operations based on an attribute of the object, rather than the whole object. For instance, say I have (pseudo-code): LoTuples1 = [(1,1,0),(1,2,1),(1,3,3)] Set1=set(LoTuples1) LoTuples2 = [(2,1,3),(2,2,4),(2,3,2)] Set2=set(LoTuples2) What I would like to be able to do is: Set3 = Set1union(Set2) Set3.intersection(Set2, ) to return: set([(2,1,3), (1,3,3)]) How can one do this operation? Thanks, Duane From rhyde at cs.ucr.edu Thu Oct 4 22:28:46 2007 From: rhyde at cs.ucr.edu (rhyde at cs.ucr.edu) Date: Thu, 04 Oct 2007 19:28:46 -0700 Subject: Announcing the RosAsm Library Project In-Reply-To: <1191548200.284561.102430@w3g2000hsg.googlegroups.com> References: <1191536947.116741.32130@g4g2000hsf.googlegroups.com> <1191548200.284561.102430@w3g2000hsg.googlegroups.com> Message-ID: <1191551326.248715.177640@w3g2000hsg.googlegroups.com> On Oct 4, 6:36 pm, Evenbit wrote: > > This is extremely easy to answer. The average RosAsm coder tends to > only make use of the libraries documented here: > > http://msdn2.microsoft.com/en-us/library/aa383749.aspx Which is a bit limiting, wouldn't you agree? > > If you wish to revue the source code, then bring that issue up with > Microsoft. Please let us know of any positive results. ;) Actually, at one time I *had* the NT sources on my machine (research at UCR in the OS research time). Let's just say that at 35 million lines of code (at the time, this was NT 4.0) it may as well have been closed source. :-) > > If a programmer feels that a project requires him to use a large > amount of pre-written "library" code and advanced programming features/ > tools, then he must seriously question why he is using assembly > language (rather than a High-Level Language) in the first place. Why is that? You do realize that with every OS API call you're making, you're doing exactly this -- making use of a large amount of pre-written "library" code. > After a programmer has made the choice to code at the ASM level, he > has already -- by default/definition -- decided to avoid the trappings > of the HLL world. What makes you think this? You do realize, don't you, that the *vast* majority of people who write assembly code are actually writing functions to be called from HLLs, right? And what "trappings" of the HLL world are you talking about? I've seen *very* little code posted to this group or to any assembly language site that couldn't be done in almost exactly the same way in a HLL. > > You are indeed one pecular person. On the one hand [http://www.artofasm.com > ], you have taught, written a book, built an advanced assembler, and > generally answer many questions about assembly language. However, on > the other hand, you spend a great deal of time here in alt.lang.asm > denigrating assembler tools and "bashing" those who write assembly > language. Well, I wonder why that is? > > So, the question is [this goes also for all those regular a.l.a > trolls]: Are you here to _support_ the *assembly language* > community? > Or, are you here to encourage everyone to "give up" on ASM > and adopt an easy HLL instead? I'm all for people using the appropriate tools for a given task. If an "easy HLL" is more appropriate than assembly language for the task, I'm all for having them adopt an "easy HLL" instead. The argument that all applications should be written in assembly language was lost over a decade and a half ago, I'm afraid. Although I feel that far more code should be written in assembly language than we see today, only a fool would claim that all code should be written in assembly language. Today, the main reason for learning assembly language is *not* so you can write all your code in assembly, but so that you can understand what HLL compilers are doing with your source code when they translate it into machine code. This allows you to write much better HLL source code. What's funny, despite Rene's constant dream about an "assembly rebirth" is that today people are viewing languages like C (and even C+ +) the same way assembly language was viewed 15 years ago. I suspect that in another 10 years, you'll hear the old time C programmers arguing about how programs ought to be written in C rather than in the latest gee-whiz interpreted scripting language. As much as I would like to see things turn out otherwise, the bottom line is that assembly language is really dying off. Anyone who doesn't see this just isn't paying attention. Oh sure, we had a big burst of activity when the Iczelion Tutorials were first announced, and lately there *have* been a couple of new books appear, but how many people are *truly* developing assembly language code (of any kind -- libraries, OSes, system tooks, apps, whatever)? In one resect, Rene is right. Where are all the assembly apps? And I add "written with any assembler?" Or sure, a few crackpots (myself included) still do it, but everyone in this newsgroup is out on the fringe. Though *writing* assembly language code isn't so bad, the real problem with most people is the issues of testing, debugging, and maintenance. I don't care what debugger you use, one simple fact is that debugging assembly language code is a heck of a lot more work than debugging HLL code. The reason is pretty simple -- you can't do things like screw up the stack in most HLLs; you generally get *some* sort of type checking in those HLLs that is missing from assembly (including HLA, I might add). Having just developed a test suite for the HLA stdlib, I can tell you that it's a heck of a lot more work to test and debug assembly code that it is to debug the equivalent C code. Then, on top of that, code has to be maintained. Very few projects in this world are like HLA/HLA stdlib where a single person works on the code for 10 years. In most environments, you have some senior engineers who develop something, get it working reasonably well, and then they dump the result on someone else for maintenance and enhancement. Now matter how good *you* are at assembly language, the sad fact is that most people, to whom the code is going to be dumped on later, don't know assembly language or, at best, have a passing knowledge of it. That, alone, is probably the major reason why assembly language *has died out*. Yes, there are still some *very* good reasons for learning assembly language. And for certain projects there are some good reasons why one should use assembly language. But assembly language really has become a "niche within a niche". The reasons for using assembly language today have little to do with "avoiding the trappings of a HLL." Indeed, the main reason HLLs have caught on is to avoid the trappings of assembly language. Today, there are only a few valid reasons for using assembly language on a real project. I'm kind of a special case, I use assembly language (for example, I'm writing a terminal emulator for General Atomics right now in assembly language) for a couple of reasons that have little to do with the project: 1) I enjoy working in assembly language 2) I get to further test the HLA compiler and stdlib by using it on work-related projects and then, of course, the biggie: 3) Job Security! :-) (the last is a joke, if you didn't catch on to that.) Soon, I expect to be working on a rewrite of the Triga Mark II digital console software (currently written in C under QNX4) to Linux. I'm contemplating doing this project in assembly language because it will force me to write a lot of assembly code under Linux and really shake out the HLA system under Linux. I'm currently weighing the benefits of that against the "unprofessionalism" of delivering an application written in assembly language to the next person who comes along and works on the project. Bottom line is that you want to always advocate using the right tool for the job. Some times, the right tool *is* assembly language; most of the time it is not (opinions in this newsgroup not withstanding). Yes, facilities like the HLA standard library make it possible to use assembly language where it absolutely did not make sense before, but by and large, assembly's day has passed. Now as to "denigrating tools around here", well, some tools (e.g., RosAsm) are pure crap and they do even more harm to assembly's reputation and a practical development tool. Such crap definitely deserves appropriate comments; especially when it's being pushed as a "solution" to perceived problems. One of those perceived problems, and hence this satrical thread, is this crazy notion that assembly language libraries are bad. This is absolutely insane. The only reason Rene would even make such a claim is because he's never gotten around to providing such a library for RosAsm users. If he doesn't have something, his reaction is to attack those who do. hLater, Randy Hyde From trimarchimichael at yahoo.it Wed Oct 10 09:08:07 2007 From: trimarchimichael at yahoo.it (Michael Trimarchi) Date: Wed, 10 Oct 2007 13:08:07 +0000 (GMT) Subject: Python on embedded system Message-ID: <459969.8467.qm@web26214.mail.ukl.yahoo.com> hi, I'd like to reduce python and just compile this modules: Modulo 59 Nota Tecnica Rev.2 Data 01/03 _main_ _buildin_ marshal imp sys os float md5 socket asyncore select thread threading time termios I set up the PYTHON_DISABLE_MODULES with _PYTHON_DISABLED_MODULES=readline pyexpat dbm gdbm bsddb \ _curses _curses_panel _tkinter nis zipfile _codecsmodule \ cryptmodule _randommodule grpmodule regexmodule parsermodule \ dbmodule glmodule pwdmodule gcmodule rgbimgmodule _heapqmodule \ imageop cPickle audioop multybytecodec and using the buildroot patch that disable modules. At the and I having a 12 Mb of stuff. I don't understand how to avoid the installation of a lot of not useful py file. It is possible to reduce the size of python enviroment? Regards Michael ___________________________________ L'email della prossima generazione? Puoi averla con la nuova Yahoo! Mail: http://it.docs.yahoo.com/nowyoucan.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From ricaraoz at gmail.com Wed Oct 31 12:49:01 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 31 Oct 2007 13:49:01 -0300 Subject: appending into a list In-Reply-To: References: Message-ID: <4728B1FD.2020409@bigfoot.com> Beema shafreen wrote: > hi everybody, > I have a file : > A B C D E > > 2717353 2717412 A_16_P03641964 214 -59 > 2717626 2717685 A_16_P41563655 25 -59 > 2717710 2717754 A_16_P03641965 1250 -44 > 2719004 2719063 A_16_P03641966 -36 -59 > 2719027 2719086 A_16_P21360229 289 -59 > 2719375 2719428 A_16_P03641967 60 -53 > 2719488 2719542 A_16_P21360231 418 -54 > 2719960 2720014 A_16_P03641968 727 -54 > 2720741 2720786 A_16_P03641969 494 -45 > 2721280 2721339 A_16_P03641970 -28 -59 > 2721311 2721370 A_16_P21360234 150 -59 > 2721520 2721569 A_16_P21360235 199 -49 > 2721768 2721821 A_16_P03641971 139 -53 > 2721960 2722004 A_16_P21360237 312 -44 > I need to append the column D and E into a list: > in such a way that the list should have > [D,E,D,E,D,E........] > How do i do it. > > regards > shafreen > >>> r = [] >>> for D, E in (i.split()[-2:] for i in open('file')) : r.append(D) r.append(E) >>> r ['214', '-59', '25', '-59', '1250', '-44', '-36', '-59', '289', '-59', '60', '-53', '418', '-54', '727', '-54', '494', '-45', '-28', '-59', '150', '-59', '199', '-49', '139', '-53', '312', '-44'] HTH From gagsl-py2 at yahoo.com.ar Fri Oct 19 20:48:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Oct 2007 21:48:04 -0300 Subject: Running another python interpreter References: <47179DBA.8040407@hotmail.com> <4717A261.7090303@hotmail.com> <1192742192.830006.95130@e9g2000prf.googlegroups.com> Message-ID: --- Simon Pickles escribi?: > os.spawnl(os.P_NOWAIT, sys.executable, > sys.executable, "gateway.py") >... works but both process output to the same > interpreter window. Is there a way to run another > interpreter window containing gateway.py? Use the subprocess module, passing CREATE_NEW_CONSOLE into creationflags: subprocess.call([sys.executable, "gateway.py", "other", "arguments"], creationflags = subprocess.CREATE_NEW_CONSOLE) -- Gabriel Genellina From robert.rawlins at thinkbluemedia.co.uk Mon Oct 22 10:45:49 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 22 Oct 2007 15:45:49 +0100 Subject: Check File Change Every 10 Seconds In-Reply-To: References: <27459.1491478079$1193048158@news.gmane.org> Message-ID: <005001c814ba$3d09bca0$b71d35e0$@rawlins@thinkbluemedia.co.uk> Thanks for your time Gabriel, That certainly looks to be the type of thing that I'm looking to achieve, however, I forgot to mention I'm running this on a Linux platform and not a Win32 one :-( Sorry. I'm sure similar things are achievable, I've used os.stat before now to get the time stamp for when a file was last changed, if I perhaps combine this with the while 1: inside a thread I can achieve the same end result? Sound like a good idea? I just wasn?t sure how safe it was to spawn a thread like this which contains an infinite loop. Thanks again for your time, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Gabriel Genellina Sent: 22 October 2007 15:29 To: python-list at python.org Subject: Re: Check File Change Every 10 Seconds En Mon, 22 Oct 2007 06:56:52 -0300, Robert Rawlins - Think Blue escribi?: > I've got a requirement to check a file for a change every 10 seconds or > so, > and if the file has been modified since the last time I parsed its > content > into the application then I need to parse it in again. However, I need > this > process to not interrupt the rest of my application flow. See this article by Tim Golden: http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html > What is the best way to handle this? Is there some form of file watcher > module for python which can watch the file for me and then parse any > changes > into the application memory? Or should I be spawning and unjoined thread > which contains and infinite loop which checks a date/time the file was > modified against an internal date/time variable for when the application > last parsed the file into memory? I would use a different thread waiting for notifications from ReadDirectoryChangesW (third option in the link above) See http://msdn2.microsoft.com/en-us/library/aa365465.aspx for more info on ReadDirectoryChangesW -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From daniel.j.larsson at gmail.com Mon Oct 22 22:06:05 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Tue, 23 Oct 2007 04:06:05 +0200 Subject: Python - why don't this script work? In-Reply-To: References: Message-ID: <2bfa72fa0710221906l45c36252g2e91b6f134c7fa15@mail.gmail.com> Try: $ python image-harvester.py On 10/23/07, Ohmster wrote: > > I am trying to use this cool script that some MIT guy wrote and it just > does not work, I get a stream of errors when I try to run it. It is > supposed to visit a URL and snag all of the pictures on the site. Here is > the script: > http://web.mit.edu/pgbovine/www/image-harvester/image-harvester.py > > Here is my output when I try to run it on my Fedora 6 machine: > > [ohmster at ohmster bench]$ image-harvester.py > http://public.fotki.com/DaGennelman/ > /home/ohmster/scripts/image-harvester.py: line 59: from: command not found > [ohmster at ohmster bench]$ > > The script is to be folowed up with another one to weed out the small > thumbnails and banner images, here is the base URL: > http://web.mit.edu/pgbovine/www/image-harvester/ > > Line 59 in image-harvester.py reads as follows: > > 59: from sgmllib import SGMLParser > 60: import urllib > 70: from urlparse import urlparse, urljoin > 71: import re > 72: import os > > > Can anyone tell me what is wrong with this script and why it will not run? > It does not like the command "from", is there such a command in python? > Does this mean that python has the "import" command but not the "from" > command or do we not know this yet as it hangs right away when it hits the > very first word of the script, "from"? Maybe this is not a Linux script or > something? I wonder why it needs the x-server anyway, I tried running it > from an ssh term window and it had a fit about no x-server so now I am > doing this in a gnome term window. This looked so cool too. :( > > Please be patient with me, I do not know python at all, I just want for > this script to work and if I see enough working examples of python, I may > just take up study on it, but for right now, I do not know the language. > Total newbie. > > Thanks. > > > -- > ~Ohmster | ohmster /a/t/ ohmster dot com > Put "messageforohmster" in message body > (That is Message Body, not Subject!) > to pass my spam filter. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Wed Oct 31 10:22:17 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 31 Oct 2007 15:22:17 +0100 Subject: shouldn't 'string'.find('ugh') return 0, not -1 ? References: Message-ID: <87lk9jmkiu.fsf@mulj.homelinux.net> jelle writes: > the subject pretty much says it all. > if I check a string for for a substring, and this substring isn't found, > should't the .find method return 0 rather than -1? How would you treat the case of 'something' being at the beginning of the string? After all, find returns the index. > this breaks the > > if check.find('something'): > do(somethingElse) > > idiom, which is a bit of a pity I think. if 'something' in check: do(somethingElse) From byte8bits at gmail.com Mon Oct 1 16:27:43 2007 From: byte8bits at gmail.com (brad) Date: Mon, 01 Oct 2007 16:27:43 -0400 Subject: slice last 4 items from a list Message-ID: Is this the correct way to slice the last 4 items from a list? x = [1,2,3,4,5,6,7,8,9] print x[-4:] It works, but is it Pythonic? From sipickles at hotmail.com Thu Oct 18 13:54:02 2007 From: sipickles at hotmail.com (Simon Pickles) Date: Thu, 18 Oct 2007 18:54:02 +0100 Subject: Running another python interpreter Message-ID: <47179DBA.8040407@hotmail.com> Hello, I have several servers which link to each other (and of course, to clients). At present, I am starting them in turn manually. Is there a way with python to say, "open gateway.py in a new interpreter window"? I looked at execv, etc, but they seem to replace the current process. Ah, maybe I need spawnv(). I am on windows i386, python 2.5 Thanks si From smitty1e at gmail.com Fri Oct 26 00:19:19 2007 From: smitty1e at gmail.com (smitty1e) Date: Fri, 26 Oct 2007 04:19:19 -0000 Subject: .py to sqlite translator [1 of 2] Message-ID: <1193372359.928929.31310@19g2000hsx.googlegroups.com> Disclaimer(s): the author is nobody's pythonista. This could probably be done more elegantly. The driver for the effort is to get PyMacs to work with new-style classes. This rendering stage stands alone, and might be used for other purposes. A subsequent post will show using the resulting file to produce (I think valid) .el trampoline signatures for PyMacs. If nothing else, it shows some python internals in an interesting way. Tested against version 2.5.1 Maybe "lumberjack.py" would be a better name, since "It cuts down trees, goes real slow, and uses disk galore. Wishes it'd been webfoot[1], just like its dear author". Cheers, Chris [1] Author was born in Oregon. #A sample file: class sample( object ): """fairly trivial sample class for demonstration purposes. """ def __init__( self , some_string ): self.hold_it = some_string def show( self ): print self.hold_it #Invocation: # ./pysqlrender.py -f sample.py -o output #Script: #!/usr/bin/python """Script to dump the parse tree of an input file to a SQLite database. """ from optparse import OptionParser import os import parser import pprint import re import sqlite3 import symbol import token import types from types import ListType \ , TupleType target_table = """CREATE TABLE tbl_parse_tree ( parse_tree_id INTEGER PRIMARY KEY AUTOINCREMENT , parse_tree_symbol_id , parse_tree_indent , parse_tree_value );""" target_insert = """INSERT INTO tbl_parse_tree ( parse_tree_symbol_id , parse_tree_indent , parse_tree_value ) VALUES (%s, %s, '%s' );""" symbol_table = """CREATE TABLE tlp_parse_tree_symbol ( parse_tree_symbol_id INTEGER PRIMARY KEY , parse_tree_symbol_val );""" symbol_insert = """INSERT INTO tlp_parse_tree_symbol ( parse_tree_symbol_id , parse_tree_symbol_val ) VALUES ( %s, '%s' );""" class symbol_manager( object ): """ Class to merge symbols and tokens for ease of use. """ def __init__( self , c ): for k in symbol.sym_name: sql = symbol_insert % ( k, symbol.sym_name[k] ) try: c.execute( sql ) except sqlite3.IntegrityError: pass for k in token.tok_name: sql = symbol_insert % ( k, token.tok_name[k] ) try: c.execute( sql ) except sqlite3.IntegrityError: pass def get_symbol( self , key ): ret = -1 if symbol.sym_name.has_key(key): ret = symbol.sym_name[key] elif token.tok_name.has_key(key) : ret = token.tok_name[ key] return ret def recurse_it( self, tester ): """Check to see if dump_tup should recurse """ if self.get_symbol(tester) > 0: return True return False class stocker( object ): """Remembers the depth of the tree and effects the INSERTs into the output file. """ def __init__( self ): self.cur_indent = 0 def do_symbol( self , c , symbol_value , val = "" ): """Stuff something from the parse tree into the database table. """ if symbol_value==5: self.cur_indent += 1 elif symbol_value==6: self.cur_indent -= 1 try: sql = target_insert \ % ( symbol_value , self.cur_indent , re.sub( "'", "`", str(val) )) c.execute( sql ) except AttributeError: print "connection bad in lexer" except sqlite3.OperationalError: print "suckage at indent of %s for %s" \ % (self.cur_indent, sql) def dump_tup( tup , sym , c , stok ): """Recursive function to descend TUP and analyze its elements. tup parse tree of a file, rendered as a tuple sym dictionary rendered from symbol module c live database cursor stok output object effect token storage """ for node in tup: typ = type( node ) r = getattr( typ , "__repr__" , None ) if (issubclass(typ, tuple) and r is tuple.__repr__): if token.tok_name.has_key( node[0] ): stok.do_symbol( c , node[0] , node[1] ) elif sym.recurse_it( node[0] ): stok.do_symbol( c , node[0] , '__py__' ) #If you say node[1] here, # the sqlite file is fat # and instructive for node2 in node[1:]: dump_tup( node2 , sym , c , stok ) else: stok.do_symbol( c , node[0] , node[1] ) dump_tup( node[1] , sym , c , stok ) else: stok.do_symbol( c , 0 , node ) def convert_python_source_tree_to_table( file_name , target_name ): """Retrieve information from the parse tree of a source file. Create an output database file in sqlite. Make a table in there, and then procede to stuff the flattened input parse tree into it. file_name Name of the file to read Python source code from. target_name Name for the sqlite database """ x = open( file_name ).readlines() y = [] [y.append( line.replace("\r\n","") ) for line in x] ast = parser.suite( "\n".join(y) ) conn = sqlite3.connect( target_name ) conn.isolation_level = None c = conn.cursor() c.execute( target_table ) c.execute( symbol_table ) sym = symbol_manager( c ) stok = stocker() #pprint.pprint( ast.totuple() ) dump_tup( ast.totuple() , sym , c , stok ) def main(): usage = "usage: %prog [options] arg" parser = OptionParser(usage) parser.add_option("-f", "--file", dest="filename" , action="store", type="string" , help ="read python source from FILENAME") #TODO: test for existence of output file, eject if exists parser.add_option("-o", "--output",dest="output" , action="store", type="string" , help ="name of sqlite output file") (options, args) = parser.parse_args() convert_python_source_tree_to_table( options.filename , options.output ) if __name__ == "__main__": main() From jstroud at mbi.ucla.edu Thu Oct 11 19:03:26 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 11 Oct 2007 16:03:26 -0700 Subject: decorating container types (Python 2.4) In-Reply-To: <1192138976.165419.25820@19g2000hsx.googlegroups.com> References: <1192138976.165419.25820@19g2000hsx.googlegroups.com> Message-ID: timaranz at gmail.com wrote: > Hi, > > I have a container class A and I want to add functionality to it by > using a decorator class B, as follows: > > class A(object): > def __len__(self): > return 5 > > class B(object): > def __init__(self, a): > self._a = a > > def __getattr__(self, attr): > return getattr(self._a, attr) > > def other_methods(self): > blah blah blah > > I was expecting len(B) to return 5 but I get > AttributeError: type object 'B' has no attribute '__len__' > instead. > I was expecting len() to call B.__len__() which would invoke > B.__getattr__ to call A.__len__ but __getattr__ is not being called. > I can work around this, but I am curious if anyone knows _why_ > __getattr__ is not being called in this situation. > > Thanks > Tim > You will need a metaclass with a __len__ class attribute class longmeta(type): def __len__(cls): return 7 class A(object): __metaclass__ = longmeta pass py> class longmeta(type): ... def __len__(cls): ... return 7 ... py> class A(object): ... __metaclass__ = longmeta ... pass ... py> len(A) 7 James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From kw at codebykevin.com Sun Oct 7 12:09:16 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sun, 07 Oct 2007 12:09:16 -0400 Subject: tkinter question In-Reply-To: References: <1191554174.490449.251400@50g2000hsm.googlegroups.com><470629D1.2040404@codebykevin.com> <47063964.7000809@codebykevin.com> Message-ID: <470904AC.9090100@codebykevin.com> Hendrik van Rooyen wrote: > "Kevin Walzer" wrote: > >> I find "pack" to be more flexible than "grid," so I prefer it for >> complex layouts. "grid" is better for simple layouts. > > *does a double take* are you serious? - my experience is that > pack is only good for simple single row or single column stuff. > > - Hendrik > > Well, I guess it depends on your viewpoint. I find "pack" flexible because it allows me to think in terms of top, bottom, right, and left in terms of arranging UI elements--it's an elegant way to do it in my view. I tend to use "grid" if I have, say, a window with several preference items: a label, an entry field, and a button, all arranged in rows. "grid" is better for stuff like that, I agree. See http://www.codebykevin.com/blosxom/business/phynchronicity-new.png: this is an application I develop. The layout is all handled by "pack" and paned windows. Where you you use "grid" in a layout like this? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bcd at pvv.ntnu.no Wed Oct 3 14:41:48 2007 From: bcd at pvv.ntnu.no (Bent C Dalager) Date: Wed, 3 Oct 2007 18:41:48 +0000 (UTC) Subject: The Modernization of Emacs: terminology buffer and keybinding References: <13frd6vtarbee75@corp.supernews.com> <85sl4sqckf.fsf@lola.goethe.zz> Message-ID: In article <85sl4sqckf.fsf at lola.goethe.zz>, David Kastrup wrote: >bcd at pvv.ntnu.no (Bent C Dalager) writes: > >Not as much "been" liberated, but "turned" liberated. I expect that either way you split this hair, using "free" in the sense of "possessing liberty" is still going to be quite reasonable. >But picking just a single word from a whole explanation of _one_ >naming and declaring it as equivalent is not really being careful with >language at all. I have never claimed equivalence. What I have made claims about are the properties of one of the meanings of a word. Specifically, my claim is that "free" is a reasonable description of some one or some thing that has been "liberated". As an example, when a slave becomes a free man, this is not commonly understood to mean that he now has a low or zero monetary cost. >And even when using a Thesaurus, it should be clear that the offered >alternatives are not supposed to or capable of capturing all nuances >of the keyword. I have never claimed to be providing a full definition of the word. Indeed, I quite clearly conceded very early on that "free" is commonly associated with what might otherwise be called "gratis" - that is "free of charge". My effort has been to point out that the word also has other meanings. Cheers Bent D -- Bent Dalager - bcd at pvv.org - http://www.pvv.org/~bcd powered by emacs From besturk at gmail.com Tue Oct 23 09:48:04 2007 From: besturk at gmail.com (Abandoned) Date: Tue, 23 Oct 2007 06:48:04 -0700 Subject: How can i protect text format ? In-Reply-To: References: <1193146218.068145.61540@y27g2000pre.googlegroups.com> Message-ID: <1193147284.487902.206210@e9g2000prf.googlegroups.com> On Oct 23, 4:41 pm, "J. Clifford Dyer" wrote: > On Tue, Oct 23, 2007 at 06:30:18AM -0700, Abandoned wrote regarding How can i protect text format ?: > > > > > Hi.. > > I want to do a forum with python but i have a problem.. > > > I have a
%d%s
1One
2two
3Three
4Four
5Five
> > > onclick="javascript:performPdfPreview(2);"/> > >
or
. - Added new examples nested.py and withAttribute.py to demonstrate the new features. - Added performance speedup to grammars using operatorPrecedence, instigated by Stefan Reich?r - thanks for the feedback, Stefan! - Fixed bug/typo when deleting an element from a ParseResults by using the element's results name. - Fixed whitespace-skipping bug in wrapper classes (such as Group, Suppress, Combine, etc.) and when using setDebug(), reported by new pyparsing user dazzawazza on SourceForge, nice job! - Added restriction to prevent defining Word or CharsNotIn expressions with minimum length of 0 (should use Optional if this is desired), and enhanced docstrings to reflect this limitation. Issue was raised by Joey Tallieu, who submitted a patch with a slightly different solution. Thanks for taking the initiative, Joey, and please keep submitting your ideas! - Fixed bug in makeHTMLTags that did not detect HTML tag attributes with no '= value' portion (such as "
"), reported by hamidh on the pyparsing wiki - thanks! - Fixed minor bug in makeHTMLTags and makeXMLTags, which did not accept whitespace in closing tags. Download pyparsing 1.4.8 at http://sourceforge.net/projects/pyparsing/. The pyparsing Wiki is at http://pyparsing.wikispaces.com -- Paul ======================================== Pyparsing is a pure-Python class library for quickly developing recursive-descent parsers. Parser grammars are assembled directly in the calling Python code, using classes such as Literal, Word, OneOrMore, Optional, etc., combined with operators '+', '|', and '^' for And, MatchFirst, and Or. No separate code-generation or external files are required. Pyparsing can be used in many cases in place of regular expressions, with shorter learning curve and greater readability and maintainability. Pyparsing comes with a number of parsing examples, including: - "Hello, World!" (English, Korean, Greek, and Spanish(new)) - chemical formulas - configuration file parser - web page URL extractor - 5-function arithmetic expression parser - subset of CORBA IDL - chess portable game notation - simple SQL parser - Mozilla calendar file parser - EBNF parser/compiler - Python value string parser (lists, dicts, tuples, with nesting) (safe alternative to eval) - HTML tag stripper - S-expression parser - macro substitution preprocessor From brainsludge at gmail.com Tue Oct 23 21:59:20 2007 From: brainsludge at gmail.com (Brainsludge) Date: Tue, 23 Oct 2007 18:59:20 -0700 Subject: Pythonw.exe exits prematurely In-Reply-To: <1193178936.407815.146200@z24g2000prh.googlegroups.com> References: <1193176910.507794.136960@y27g2000pre.googlegroups.com> <1193178936.407815.146200@z24g2000prh.googlegroups.com> Message-ID: <1193191160.156352.9570@i13g2000prf.googlegroups.com> The script has been running console-free for about an hour now without bailing. Looks like it was the stdout buffer. Thanks! Brian On Oct 23, 4:43 pm, Matimus wrote: > > I am running WinXP SP2 with Python 2.5.1 and encountered the following > > issue: > > > I wrote a script that logs into my mail server, and checks for new > > messages every 20 seconds. When a new message is found, it displays a > > Windows tool tip and prints a line to console indicating a new > > message. > > > When I run the script with python.exe (console), the script runs fine > > and checks for new messages in perpetuity (as it should). However, > > when I run the script with pythonw.exe (no console), the script > > prematurely exits after 10 or 15 minutes. For those 15 minutes, it > > works as it should, displaying tool tips when new messages arrive. > > Furthermore, when it exits prematurely, it appears to be exiting > > gracefully (I have an exit routine that logs out of the mail server > > and cleans up). > > > Does anyone know why this might be the case? The lines printed to > > console are purely for diagnostic purposes. Otherwise, the two > > processes should be identical. > > You say it exits gracefully, I'm not sure I know what you mean. My > guess is that you are writing to stdout, and when the buffer fills up > and tries to dump the program exits with an exception (but returns > 0). > > I've run into something similar before, you can reproduce it with > this: > [code] > import sys > > f2 = open("bo.err", "w") > sys.stderr = f2 > for i in range(10000): > print i > [/code] > > Run with pythonw then look at "bo.err" to see the exception. > > You can either stop printing to stdout and send the stuff somewhere > else (maybe use the logging module), or you can assign stdout and > stderr to nul. > > [code] > import sys > import os > > nul = open(sys.devnull,'w') > sys.stdout = nul > sys.stderr = nul > > # The rest of your code > [/code] > > Matt From steve at holdenweb.com Wed Oct 3 22:22:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 03 Oct 2007 22:22:57 -0400 Subject: module confusion In-Reply-To: References: <1191294190.265530.189700@o80g2000hse.googlegroups.com> <1191300108.593779.318300@y42g2000hsy.googlegroups.com> <874ph8sdhx.fsf@benfinney.id.au> Message-ID: Lawrence D'Oliveiro wrote: > In message <874ph8sdhx.fsf at benfinney.id.au>, Ben Finney wrote: > >> Lawrence D'Oliveiro writes: >> >>> On my Gentoo system: >>> >>> >>> import os >>> >>> os.path >>> >>> >>> It's just a variable that happens to point to the posixpath module. >> There's no "pointing" going on. It's another name bound to the same >> object, of equal status to the 'posixpath' name. >> >> Python doesn't have pointers, and even "variable" is a misleading term >> in Python. Best to stick to "name" and "bound to". > > In Python, all names _are_ variables. They are not "bound" to objects. The > value of os.path is a pointer. It's implemented as a pointer, it has all > the semantics of a pointer. > > Honestly, why do people react to the word "pointer" as though computers have > to wear underwear to conceal something shameful going on in their nether > regions? Because they have been told by their church that all God-fearing names do what names have always done in programming languages, which is to describe areas of memory of a particular size, type and locality. You and I know that the semantics of Python names are precisely those of (to use an Algol 68 term, unless I am mistaken) automatically dereferenced pointers to objects of arbitrary type. I actually think that's one of the neatest things about Python, and I believe it's no accident that both Tim Peters and I were Icon enthusiasts. But the rest of the world clings to its illusions. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From plumbandtree at gmail.com Mon Oct 29 02:03:55 2007 From: plumbandtree at gmail.com (plumb and tree) Date: Sun, 28 Oct 2007 23:03:55 -0700 Subject: Solaris 10 + Sun Studio 12 Pyrhon 2.4.4 64-bit build problem Message-ID: <1193637835.936397.307160@e9g2000prf.googlegroups.com> I've been trying for days to build 64 bit python with Solaris 10 + Sun Studio 12. Can anyone helpl please. This is how I tried to do build: # ./configure --prefix=/opt/python2.4 --without-gcc --enable-shared checking MACHDEP... sunos5 checking EXTRAPLATDIR... checking for --without-gcc... yes checking for --with-cxx=... no checking for c++... /opt/SUNWspro/bin/CC checking for C++ compiler default output file name... a.out checking whether the C++ compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for gcc... cc checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... no checking whether cc accepts -g... yes checking for cc option to accept ANSI C... none needed checking how to run the C preprocessor... /opt/SUNWspro/bin/CC configure: error: C preprocessor "/opt/SUNWspro/bin/CC" fails sanity check See `config.log' for more details. (sorry for the long log file but I'm not sure which part are important) config.log: This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by python configure 2.4, which was generated by GNU Autoconf 2.59. Invocation command line was $ ./configure --prefix=/opt/python2.4 --without-gcc --enable-shared ## --------- ## ## Platform. ## ## --------- ## hostname = zone2 uname -m = sun4u uname -r = 5.10 uname -s = SunOS uname -v = Generic_118833-36 /usr/bin/uname -p = sparc /bin/uname -X = System = SunOS Node = zone2 Release = 5.10 KernelID = Generic_118833-36 Machine = sun4u BusType = Serial = Users = OEM# = 0 Origin# = 1 NumCPU = 1 /bin/arch = sun4 /usr/bin/arch -k = sun4u /usr/convex/getsysinfo = unknown hostinfo = unknown /bin/machine = unknown /usr/bin/oslevel = unknown /bin/universe = unknown PATH: /usr/local/bin PATH: /usr/xpg4/bin PATH: /usr/sfw/bin PATH: /opt/SUNWspro/bin PATH: /usr/local/mysql/bin PATH: /usr/ccs/bin PATH: /usr/local/bin PATH: /usr/xpg4/bin PATH: /usr/sfw/bin PATH: /opt/SUNWspro/bin PATH: /usr/local/mysql/bin PATH: /usr/ccs/bin PATH: /usr/local/bin PATH: /usr/xpg4/bin PATH: /usr/sfw/bin PATH: /opt/SUNWspro/bin PATH: /usr/local/mysql/bin PATH: /usr/ccs/bin PATH: /usr/sbin PATH: /usr/bin PATH: /usr/openwin/bin PATH: /usr/sfw/bin PATH: /usr/openwin/bin PATH: /usr/sfw/bin PATH: /usr/openwin/bin PATH: /usr/sfw/bin ## ----------- ## ## Core tests. ## ## ----------- ## configure:1510: checking MACHDEP configure:1655: result: sunos5 configure:1661: checking EXTRAPLATDIR configure:1676: result: configure:1697: checking for --without-gcc configure:1746: result: yes configure:1752: checking for --with-cxx= configure:1773: result: no configure:1792: checking for c++ configure:1818: result: /opt/SUNWspro/bin/CC configure:1858: checking for C++ compiler default output file name configure:1861: /opt/SUNWspro/bin/CC -L/opt/SUNWmlib/lib -lrt -lm conftest.cc >&5 configure:1864: $? = 0 configure:1910: result: a.out configure:1915: checking whether the C++ compiler works configure:1921: ./a.out configure:1924: $? = 0 configure:1941: result: yes configure:1948: checking whether we are cross compiling configure:1950: result: no configure:1953: checking for suffix of executables configure:1955: /opt/SUNWspro/bin/CC -o conftest -L/opt/SUNWmlib/lib -lrt -lm conftest.cc >&5 configure:1958: $? = 0 configure:1983: result: configure:2057: checking for gcc configure:2083: result: cc configure:2327: checking for C compiler version configure:2330: cc -V &5 cc: Sun C 5.9 SunOS_sparc Patch 124867-01 2007/07/12 usage: cc [ options] files. Use 'cc -flags' for details configure:2333: $? = 1 configure:2356: checking for C compiler default output file name configure:2359: cc -O2 -L/opt/SUNWmlib/lib -lrt -lm conftest.c >&5 configure:2362: $? = 0 configure:2408: result: a.out configure:2413: checking whether the C compiler works configure:2419: ./a.out configure:2422: $? = 0 configure:2439: result: yes configure:2446: checking whether we are cross compiling configure:2448: result: no configure:2451: checking for suffix of executables configure:2453: cc -o conftest -O2 -L/opt/SUNWmlib/lib -lrt -lm conftest.c >&5 configure:2456: $? = 0 configure:2481: result: configure:2487: checking for suffix of object files configure:2508: cc -c -O2 conftest.c >&5 configure:2511: $? = 0 configure:2533: result: o configure:2537: checking whether we are using the GNU C compiler configure:2561: cc -c -O2 conftest.c >&5 "conftest.c", line 15: undefined symbol: choke "conftest.c", line 15: syntax error before or at: me cc: acomp failed for conftest.c configure:2567: $? = 2 configure: failed program was: | /* confdefs.h. */ | | #define _GNU_SOURCE 1 | #define _NETBSD_SOURCE 1 | #define __BSD_VISIBLE 1 | #define _BSD_TYPES 1 | #define _XOPEN_SOURCE 500 | #define _POSIX_C_SOURCE 200112L | /* end confdefs.h. */ | | int | main () | { | #ifndef __GNUC__ | choke me | #endif | | ; | return 0; | } configure:2593: result: no configure:2599: checking whether cc accepts -g configure:2620: cc -c -g conftest.c >&5 configure:2626: $? = 0 configure:2630: test -z || test ! -s conftest.err configure:2633: $? = 0 configure:2636: test -s conftest.o configure:2639: $? = 0 configure:2650: result: yes configure:2667: checking for cc option to accept ANSI C configure:2737: cc -c -O2 conftest.c >&5 "conftest.c", line 53: warning: statement not reached configure:2743: $? = 0 configure:2747: test -z || test ! -s conftest.err configure:2750: $? = 0 configure:2753: test -s conftest.o configure:2756: $? = 0 configure:2774: result: none needed configure:2792: cc -c -O2 conftest.c >&5 "conftest.c", line 2: warning: old-style declaration or incorrect type for: choke "conftest.c", line 2: syntax error before or at: me "conftest.c", line 3: warning: old-style declaration or incorrect type for: me cc: acomp failed for conftest.c configure:2798: $? = 2 configure: failed program was: | #ifndef __cplusplus | choke me | #endif configure:2939: checking how to run the C preprocessor configure:3057: result: /opt/SUNWspro/bin/CC configure:3081: /opt/SUNWspro/bin/CC conftest.c "conftest.c", line 15: Error: Syntax is not defined. "conftest.c", line 15: Error: "," expected instead of "end of file". "conftest.c", line 15: Error: Use ";" to terminate declarations. 3 Error(s) detected. configure:3087: $? = 3 configure: failed program was: | /* confdefs.h. */ | | #define _GNU_SOURCE 1 | #define _NETBSD_SOURCE 1 | #define __BSD_VISIBLE 1 | #define _BSD_TYPES 1 | #define _XOPEN_SOURCE 500 | #define _POSIX_C_SOURCE 200112L | /* end confdefs.h. */ | #ifdef __STDC__ | # include | #else | # include | #endif | Syntax error configure:3081: /opt/SUNWspro/bin/CC conftest.c "conftest.c", line 15: Error: Syntax is not defined. "conftest.c", line 15: Error: "," expected instead of "end of file". "conftest.c", line 15: Error: Use ";" to terminate declarations. 3 Error(s) detected. configure:3087: $? = 3 configure: failed program was: | /* confdefs.h. */ | | #define _GNU_SOURCE 1 | #define _NETBSD_SOURCE 1 | #define __BSD_VISIBLE 1 | #define _BSD_TYPES 1 | #define _XOPEN_SOURCE 500 | #define _POSIX_C_SOURCE 200112L | /* end confdefs.h. */ | #ifdef __STDC__ | # include | #else | # include | #endif | Syntax error configure:3156: error: C preprocessor "/opt/SUNWspro/bin/CC" fails sanity check See `config.log' for more details. ## ---------------- ## ## Cache variables. ## ## ---------------- ## ac_cv_c_compiler_gnu=no ac_cv_env_CC_set=set ac_cv_env_CC_value=/opt/SUNWspro/bin/cc ac_cv_env_CFLAGS_set=set ac_cv_env_CFLAGS_value=-O2 ac_cv_env_CPPFLAGS_set=set ac_cv_env_CPPFLAGS_value= ac_cv_env_CPP_set=set ac_cv_env_CPP_value=/opt/SUNWspro/bin/CC ac_cv_env_LDFLAGS_set=set ac_cv_env_LDFLAGS_value='-L/opt/SUNWmlib/lib -lrt -lm' ac_cv_env_build_alias_set= ac_cv_env_build_alias_value= ac_cv_env_host_alias_set= ac_cv_env_host_alias_value= ac_cv_env_target_alias_set= ac_cv_env_target_alias_value= ac_cv_exeext= ac_cv_objext=o ac_cv_prog_CPP=/opt/SUNWspro/bin/CC ac_cv_prog_CXX=/opt/SUNWspro/bin/CC ac_cv_prog_ac_ct_CC=cc ac_cv_prog_cc_g=yes ac_cv_prog_cc_stdc= ## ----------------- ## ## Output variables. ## ## ----------------- ## AR='' BASECFLAGS='-# -xc99=all,lib -m64 -H -Xc -c -errtags=yes' BLDLIBRARY='' BLDSHARED='' BUILDEXEEXT='' CC='cc' CCSHARED='' CFLAGS='-O2' CFLAGSFORSHARED='' CONFIGURE_MACOSX_DEPLOYMENT_TARGET='' CONFIG_ARGS=''--prefix=/opt/python2.4' '--without-gcc' '--enable- shared' 'CC=/opt/SUNWspro/bin/cc' 'CFLAGS=-O2' 'CPPFLAGS=' 'CPP=/opt/ SUNWspro/bin/CC' 'LDFLAGS=-L/opt/SUNWmlib/lib -lrt -lm'' CPP='/opt/SUNWspro/bin/CC' CPPFLAGS='' CXX='/opt/SUNWspro/bin/CC' DEFS='' DLINCLDIR='' DLLLIBRARY='' DYNLOADFILE='' ECHO_C='' ECHO_N='-n' ECHO_T='' EGREP='' EXEEXT='' EXPORT_MACOSX_DEPLOYMENT_TARGET='#' EXTRAMACHDEPPATH='' EXTRAPLATDIR='' FRAMEWORKALTINSTALLFIRST='' FRAMEWORKALTINSTALLLAST='' FRAMEWORKINSTALLFIRST='' FRAMEWORKINSTALLLAST='' FRAMEWORKUNIXTOOLSPREFIX='/opt/python2.4' HAVE_GETHOSTBYNAME='' HAVE_GETHOSTBYNAME_R='' HAVE_GETHOSTBYNAME_R_3_ARG='' HAVE_GETHOSTBYNAME_R_5_ARG='' HAVE_GETHOSTBYNAME_R_6_ARG='' INSTALL_DATA='' INSTALL_PROGRAM='' INSTALL_SCRIPT='' INSTSONAME='' LDFLAGS='-L/opt/SUNWmlib/lib -lrt -lm' LDLAST='' LDLIBRARY='' LDLIBRARYDIR='' LDSHARED='' LIBC='' LIBM='' LIBOBJS='' LIBRARY='' LIBS='' LIBTOOL_CRUFT='' LINKCC='' LINKFORSHARED='' LN='' LTLIBOBJS='' MACHDEP='sunos5' MACHDEP_OBJS='' MAINOBJ='python.o' OBJEXT='o' OPT='' OTHER_LIBTOOL_OPT='' PACKAGE_BUGREPORT='http://www.python.org/python-bugs' PACKAGE_NAME='python' PACKAGE_STRING='python 2.4' PACKAGE_TARNAME='python' PACKAGE_VERSION='2.4' PATH_SEPARATOR=':' PYTHONFRAMEWORK='' PYTHONFRAMEWORKDIR='no-framework' PYTHONFRAMEWORKINSTALLDIR='' PYTHONFRAMEWORKPREFIX='' RANLIB='' RUNSHARED='' SGI_ABI='' SHELL='/bin/bash' SHLIBS='' SIGNAL_OBJS='' SO='' SOVERSION='1.0' SRCDIRS='' THREADHEADERS='' THREADOBJ='' TRUE='' UNICODE_OBJS='' UNIVERSALSDK='' USE_SIGNAL_MODULE='' USE_THREAD_MODULE='' VERSION='2.4' ac_ct_CC='cc' ac_ct_RANLIB='' bindir='${exec_prefix}/bin' build_alias='' datadir='${prefix}/share' exec_prefix='NONE' host_alias='' includedir='${prefix}/include' infodir='${prefix}/info' libdir='${exec_prefix}/lib' libexecdir='${exec_prefix}/libexec' localstatedir='${prefix}/var' mandir='${prefix}/man' oldincludedir='/usr/include' prefix='/opt/python2.4' program_transform_name='s,x,x,' sbindir='${exec_prefix}/sbin' sharedstatedir='${prefix}/com' sysconfdir='${prefix}/etc' target_alias='' ## ----------- ## ## confdefs.h. ## ## ----------- ## #define _BSD_TYPES 1 #define _GNU_SOURCE 1 #define _NETBSD_SOURCE 1 #define _POSIX_C_SOURCE 200112L #define _XOPEN_SOURCE 500 #define __BSD_VISIBLE 1 configure: exit 1 -------end of config.log------------------------------------------------------------------------ thanks, dg From cadet.bramble at gmail.com Tue Oct 2 16:39:51 2007 From: cadet.bramble at gmail.com (bramble) Date: Tue, 02 Oct 2007 20:39:51 -0000 Subject: gui toolkits: the real story? (Tkinter, PyGTK, etc.) In-Reply-To: References: <1191287053.541506.88530@d55g2000hsg.googlegroups.com> <1191292451.096937.63000@50g2000hsm.googlegroups.com> <1191294265.611162.57730@g4g2000hsf.googlegroups.com> Message-ID: <1191357591.426416.256160@n39g2000hsh.googlegroups.com> On Oct 2, 7:33 am, Carsten Haese wrote: > On Tue, 2007-10-02 at 03:04 +0000, bramble wrote: > > But Py3k is all about breaking compatibility > > That's a complete distortion of Python 3.0's mission. Python 3.0 breaks > backwards compatibility only where there exist good reasons to do so. As > Guido put it in a recent Python-3000 post, "Python 3000 is boldly > choosing to be backwards compatible, except in cases where a real > benefit can be obtained by being incompatible." > > So, unless you can make a case that a real benefit can be obtained by > removing Tkinter, it'll stay. Well, it of course wouldn't break backward compatibility by simply removing it from the standard library and providing it as an optional extra set of modules. From paul at boddie.org.uk Mon Oct 22 06:31:38 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 22 Oct 2007 03:31:38 -0700 Subject: using "request" variable in python web program In-Reply-To: <1193042095.275835.245920@i13g2000prf.googlegroups.com> References: <1192918912.870199.297540@v29g2000prd.googlegroups.com> <1192924876.257468.27810@v29g2000prd.googlegroups.com> <1192996769.692284.163300@v23g2000prn.googlegroups.com> <1192997247.369705.326060@q5g2000prf.googlegroups.com> <1193042095.275835.245920@i13g2000prf.googlegroups.com> Message-ID: <1193049098.776008.50630@q3g2000prf.googlegroups.com> On 22 Okt, 10:34, sami wrote: > > See the library reference for information on how to get the value of > > form/request parameters from the CGI environment: > > >http://docs.python.org/lib/node561.html > > > Paul > > Thanks again Paul - now I can see that the "request" object is a > string of name/value pairs that occurs after a "?" in a url e.g. > url.com/index.cgi?name=sami&lang=python - is that correct? Googling > for this information is useless since the word "request" is so common > on the www The string after "?" in a URL is actually the "query string" and is typically exposed as the QUERY_STRING environment variable in CGI. See here for more specific details: http://www.w3.org/CGI/ http://cgi-spec.golux.com/ What the cgi module provides is some conveniences for automatically decoding the query string - perhaps not *so* difficult, you might think, even taking the decoding of encoded values into account (such as things like "%20" that you find in URLs) - but the cgi module also provides facilities to decode request parameters that are supplied in the body of a request (such as those provided in POST requests), and that can be a more difficult exercise. Paul From panguohualove at sina.com Sun Oct 14 10:22:21 2007 From: panguohualove at sina.com (panguohua) Date: Sun, 14 Oct 2007 07:22:21 -0700 Subject: a good website for softwares,sports,movies and music ,sex etc. Message-ID: <1192371741.192335.264770@t8g2000prg.googlegroups.com> www.space666.com good!!!!!!!!!!!!! From kibleur.christophe at gmail.com Fri Oct 5 18:09:55 2007 From: kibleur.christophe at gmail.com (Tool69) Date: Fri, 05 Oct 2007 15:09:55 -0700 Subject: Python Magazine: Issue 1 Free! In-Reply-To: <4706ad5e$0$30618$426a74cc@news.free.fr> References: <13gcjeqbhmh152c@corp.supernews.com> <13gcogrm9uloj4b@corp.supernews.com> <47069e40$0$16410$426a74cc@news.free.fr> <4706a7a9$0$12477$426a34cc@news.free.fr> <4706ad5e$0$30618$426a74cc@news.free.fr> Message-ID: <1191622195.830959.155510@50g2000hsm.googlegroups.com> Thanks for it, what tools did you use to build the mag : Scribus ? From stargaming at gmail.com Mon Oct 1 10:05:42 2007 From: stargaming at gmail.com (Stargaming) Date: 01 Oct 2007 14:05:42 GMT Subject: Select as dictionary... References: <1191245527.228745.17100@r29g2000hsg.googlegroups.com> Message-ID: <4700feb6$0$11466$9b622d9e@news.freenet.de> On Mon, 01 Oct 2007 09:57:46 -0400, J. Clifford Dyer wrote: > On Mon, Oct 01, 2007 at 06:32:07AM -0700, Besturk.Net Admin wrote > regarding Select as dictionary...: >> >> aia.execute("SELECT id, w from list") links=aia.fetchall() >> print links >> >> and result >> [(1, 5), (2,5).......] (2 million result) >> >> I want to see this result directly as a dictionary: >> >> {1: 5, 2: 5 .....} >> >> How do i select in this format ? >> > Try this: > > aia.execute("SELECT id, w from list") > links=aia.fetchall() > linkdict = dict() > for k,v in links: > linkdict[k] = v > print linkdict Besides using the already pointed out DB adapters, you can easily transform a list of items into a dictionary with the `dict` constructor:: >>> links = [(1, 5), (2, 5), (3, 10)] >>> dict(links) {1: 5, 2: 5, 3: 10} Stargaming From no.reply at here.com Wed Oct 3 05:52:52 2007 From: no.reply at here.com (Anonymous) Date: Wed, 03 Oct 2007 10:52:52 +0100 Subject: Building VTK-5.0.3-1 with Python bindings (VS 8.0) Message-ID: I am having problems with CMake. I currently have the ff errors (paths not set - and I am not sure what to set them to): TK_INCLUDE_PATH TK_INTERNAL_PATH TK_XLIB_PATH (I don't know why this is reqd, since I'm running W2k) Has anyone done this before or now how to fix these errors ? From steve at REMOVE-THIS-cybersource.com.au Thu Oct 4 05:37:59 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 04 Oct 2007 09:37:59 -0000 Subject: Using fractions instead of floats References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> <1191254961.729631.256760@22g2000hsm.googlegroups.com> Message-ID: <13g9d3nagotcab6@corp.supernews.com> On Mon, 01 Oct 2007 09:09:21 -0700, Arnaud Delobelle wrote: > As pointed out by others, implementations of rationals in Python abound. > Whereas there is a canonical representation of floats and ints (and even > longints) in the machine, it is not the case for rationals. Moreover > most programming tasks do not need rationals, so why burden the language > with them? If one needs them, there are perfectly adequate modules to > import (even though I, like many others I suspect, have my own > implementation in pure Python). Finally, arithmetic would become very > confusing if there were three distinct numeric types; it already causes > enough confusion with two! Or, to put it another way: As pointed out by others, implementations of sets in Python abound. Whereas there is a canonical representation of floats and ints in the machine, it is not the case for sets. Moreover most programming tasks do not need sets, so why burden the language with them? If one needs them, there are perfectly adequate modules to import (even though I, like many others I suspect, have my own implementation in pure Python). Finally, programming would become very confusing if there were three distinct sequence types; it already causes enough confusion with two! -- Steven. From andreas.tawn at ubisoft.com Wed Oct 3 05:28:44 2007 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 3 Oct 2007 11:28:44 +0200 Subject: generating range of numbers Message-ID: <8AEDA5E3386EA742B8C24C95FF0C7580013D105B@PDC-MAIL3.ubisoft.org> >i just want to generate numbers in the form like: > >1,2,4,8,16,32.....to a maximum of 1024 >using a range function >>> a = [2**x for x in range(11)] >>> a [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] Cheers, Andreas Tawn Lead Technical Artist Ubisoft Reflections -- http://mail.python.org/mailman/listinfo/python-list From steve at REMOVE-THIS-cybersource.com.au Thu Oct 25 00:47:51 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 25 Oct 2007 04:47:51 -0000 Subject: How to best send email to a low volume list? References: <1193244896.747562.291580@y27g2000pre.googlegroups.com> <1193246253.4017.34.camel@skinner.madoff.com> Message-ID: <13i07vnbbosmi49@corp.supernews.com> On Wed, 24 Oct 2007 23:08:14 -0500, Shane Geiger wrote: > A mailing list manager is really overkill for what he is trying to do > *IF* he is not maintaining a discussion list. It's not overkill at all. Mailman is easy to install (at least on a Red Hat based Linux system, your mileage may vary elsewhere) and easy to use *and* for bonus marks it's written in Python. > A "newsletter" list > doesn't sound like a discussion list, especially since he wants to hide > the email addresses of the other people. There's more to running a mailing list than just sending emails. How do you handle archives, the invariable complaints of missing newsletters, requests for subscriptions, unsubscriptions, and temporary "I'll be on holiday for a month, don't email me until I return" requests? And even if it is not a discussion list, people expect to be able to write back to the author/editor of the newsletter. -- Steven. From mail at timgolden.me.uk Tue Oct 9 04:24:53 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 09 Oct 2007 09:24:53 +0100 Subject: How to create a file on users XP desktop In-Reply-To: <470A489D.5020507@timgolden.me.uk> References: <1191727914.018474.172950@g4g2000hsf.googlegroups.com> <1191735169.441525.106060@o80g2000hse.googlegroups.com> <4708CAF4.7020206@bigfoot.com> <47090D86.5080805@tim.thechases.com> <1191853183.871616.227350@k79g2000hse.googlegroups.com> <1191854927.113225.67880@o80g2000hse.googlegroups.com> <470A489D.5020507@timgolden.me.uk> Message-ID: <470B3AD5.1020002@timgolden.me.uk> >> On Oct 8, 9:19 am, goldtech wrote: >>> How did you learn Win32com? >>> >>> Other than the O'Reilly book, I've never found a lot of >>> documentation. >>> >>> Trying to browse COM in PythonWin is tough - there's tons of stuff in >>> there. I've never been able to find the Win32com classes, methods, >>> usage examples when I browse COM in PythonWin. >>> >>> For example where is, shell.SHGetFolderPath and shellcon.CSIDL_DESKTOP >>> officially documented? Tim Golden wrote: > FWIW, the pywin32 distribution itself also comes with a local > .chm file. But aside from that, there have been several abortive > attempts -- including by Mike & myself! -- to get some kind of > online help going for pywin32, but nothing's really gained traction, > and we've all got more interesting things to be doing... To show willing :) I've added a howto on this subject to my occasionally-updated list of Python win32 howto-s: http://timgolden.me.uk/python/win32_how_do_i/get-the-desktop-folder.html and a bonus, also from the shell area: http://timgolden.me.uk/python/win32_how_do_i/browse-for-a-folder.html I usually manage to do a few of these at one go once I gather momentum, so hopefully I'll add a few more in today or tomorrow. TJG From michael at jedimindworks.com Tue Oct 2 17:29:37 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 2 Oct 2007 14:29:37 -0700 Subject: Using ImageGrab (PIL) to capture screen of remote computer In-Reply-To: References: Message-ID: <0E1E6A57-9966-45F8-B113-003F8DC59AE6@jedimindworks.com> On Oct 2, 2007, at 2:33 AM, jorma kala wrote: > Is it possible to use ImageGrab of the Python Imaging Library to > capture the screen of a remote computer? > > I'm running my python program on a computer that is connected > directly via a ethernet crossover cable to another computer. > Can I somehow get ImageGrab to grab the display of the remote > computer by specifying the IP address ? No. Unless you're using something like VNC to duplicate the remote computer's screen locally... In which case you're still capturing the screen of the local machine. hth, Michael --- Let the wookie win. -------------- next part -------------- An HTML attachment was scrubbed... URL: From f.guerrieri at gmail.com Mon Oct 15 10:51:31 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Mon, 15 Oct 2007 16:51:31 +0200 Subject: Newbi Q: Recursively reverse lists but NOT strings? In-Reply-To: <13h6te7sk7iun42@corp.supernews.com> References: <53396d9e0710141406p6182bdat789fe1706225f345@mail.gmail.com> <471308FA.3070705@islandtraining.com> <53396d9e0710150238v2ccd3df7y42f89e776c31e524@mail.gmail.com> <13h6nlmd8aku2ea@corp.supernews.com> <13h6te7sk7iun42@corp.supernews.com> Message-ID: <79b79e730710150751x78102471y3b8fc84bee7d4857@mail.gmail.com> On 10/15/07, Steven D'Aprano wrote: > On Mon, 15 Oct 2007 14:47:30 +0200, Francesco Guerrieri wrote: > > >> def myreversed(sequence): > >> if isinstance(sequence, basestring): > >> return type(sequence)().join(reversed(sequence)) > >> else: > >> return type(sequence)(reversed(sequence)) > >> > >> (in fact, that's so simple I wonder why the built-in reversed() doesn't > >> do that). > > > > simple: > > In the face of ambiguity, refuse the temptation to guess. > > What ambiguity? What guess? The above is completely unambiguous: it > returns a sequence of the same type as the input. It doesn't support > xrange objects, but that's not really a great loss. I could say that it depends on the xrange object.. but the truth is that I answered too quickly. Your suggestion was not ambiguous. Sorry :-) francesco From kay.schluehr at gmx.net Fri Oct 5 04:09:19 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 05 Oct 2007 01:09:19 -0700 Subject: Cross platform way of finding number of processors on a machine? In-Reply-To: References: <1191554907.422787.197740@y42g2000hsy.googlegroups.com> <66d0a6e10710042102m5e7bf9a9i9c6e7ff5c796c608@mail.gmail.com> Message-ID: <1191571759.756054.319730@o80g2000hse.googlegroups.com> On 5 Okt., 09:58, Tim Golden wrote: > Nicholas Bastin wrote: > > On 10/4/07, John wrote: > >> Is there a way to find the number of processors on a machine (on linux/ > >> windows/macos/cygwin) using python code (using the same code/cross > >> platform code)? > > > There's no single call that will give you the same info on every > > platform, but you can obviously write this yourself and switch based > > on os.uname()[0] in most cases. > > Second that point about not getting one cross-platform > answer. Under Windows, WMI is often the way to go for > these things: > > http://msdn2.microsoft.com/en-us/library/aa394373.aspx > > but, as Nicholas noted: > > """ > Windows Server 2003, Windows XP, and Windows 2000: > This property is not available. > """ > > since it's presumably not available in anything earlier either, > that leaves you with Vista or the early-adopter editions of the > next Windows Server product. > > TJG Remarkable. I've a two years old Windows XP dual core notebook and when I'm asking Python I get the correct answer: >>> import os >>> os.environ['NUMBER_OF_PROCESSORS'] 2 However this feature might not be guaranteed by Microsoft for arbitrary computers using their OS? Kay From jcd at sdf.lonestar.org Tue Oct 9 00:55:45 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 09 Oct 2007 00:55:45 -0400 Subject: pytz has so many timezones! In-Reply-To: <66d0a6e10710081827m47655a65p2a9b77165777180d@mail.gmail.com> References: <1191828739.635927.86590@57g2000hsv.googlegroups.com> <1191865263.572366.270820@y42g2000hsy.googlegroups.com> <1191874352.380018.216090@k79g2000hse.googlegroups.com> <1191891827.863258.23620@y42g2000hsy.googlegroups.com> <66d0a6e10710081827m47655a65p2a9b77165777180d@mail.gmail.com> Message-ID: <470B09D1.1070804@sdf.lonestar.org> Nicholas Bastin wrote: > > There is no central authority which defines global time zones. The > functional definition of a time zone is merely a geographical area of > the earth that has adopted the same local time rules. > In fact, even the authorities who do define time zones don't always have the final say. In Xinjiang province in Western China, the official time zone is the same as Beijing, even though Xinjiang is about as far west of Beijing as Nevada is from DC, so the sun comes up around "noon" and sets around "midnight." So many people set their clocks to unofficial Xinjiang time, three hours offset from Beijing. In offering a "Xinjiang" timezone set to the unofficial time, you might win some customers who see you as being on their side. Xinjiang is a muslim country, so you might also score points with muslims elsewhere in the world who see their minority Uighur brethren as oppressed by the authorities of Beijing. On the other hand, you might annoy the authorities in Beijing. Which is just to say that choice of time zone is not just a geographic issue. There are political, diplomatic issues to weigh as well. Cheers, Cliff From cesar.ortiz at gmail.com Fri Oct 26 11:25:16 2007 From: cesar.ortiz at gmail.com (cesar.ortiz) Date: Fri, 26 Oct 2007 08:25:16 -0700 Subject: distutils error dealing with rpms? Message-ID: <1193412316.160431.261530@57g2000hsv.googlegroups.com> Hi all, I am trying to generate an distribution with distutils, using in the setup() invocation the parameters 'packages' and 'data_files'. If I use bdist, the tar.gz contains all the files, but I I use bdist_rpm the data_files are not included in the rpm. has anyone face this before? I am using redhad, with rpm 4.4.2 and python 2.4. Thank you, C?sar From paul.hankin at gmail.com Wed Oct 10 08:23:06 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 10 Oct 2007 05:23:06 -0700 Subject: function wrappers In-Reply-To: References: Message-ID: <1192018986.314664.325600@d55g2000hsg.googlegroups.com> On Oct 10, 11:39 am, Ramon Crehuet wrote: > Dear all, > I have a Fortran programming background and I have some difficulties in > understading how function wrappers work. I have delved into the subject > because of the new decorators, but I understand the decorator syntax. My > ignorance is more profound... Here is an example without decorators: Functions are first-class values: this means they can be passed around, used in expressions, and returned from other functions in just the same way that ints, floats and other more obvious types. All a decorator is a function that takes the function you give it, and returns a new function. In your 'require_int' example, it returns the nested function 'wrapper'. The clever bit is that 'wrapper' remembers the argument to the decorator - func - (with value p1 in your example), and can call it later. Think of the 'def' statement as constructing an object which happens to be a function. It has a dictionary which is used for variable lookup so that it can remember 'func'. The def statement also binds this function object to a name: the name of the function. You can see some of the gory details if you go: def f(): print 42 dir(f) ... list of attributes of the function object. -- Paul Hankin From bj_666 at gmx.net Tue Oct 30 03:53:17 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Oct 2007 07:53:17 GMT Subject: Built-in functions and keyword arguments References: <20071029173742.8162.554468338.divmod.quotient.29276@ohm> Message-ID: <5oo67dFliu6sU1@mid.uni-berlin.de> On Tue, 30 Oct 2007 07:28:07 +0200, Hendrik van Rooyen wrote: > yes - the point I am trying to make is that the intention of the OP > was to use an assignment as an argument, and you can't do that, > as the interpreter thinks its a keyword. Hence the gotcha. Then you must have misunderstand his intention. He wanted to give the optional third argument of `getattr()` as keyword argument. Ciao, Marc 'BlackJack' Rintsch From whamil1 at entergy.com Tue Oct 9 11:33:18 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Tue, 9 Oct 2007 10:33:18 -0500 Subject: List loops In-Reply-To: Message-ID: <588D53831C701746A2DF46E365C018CE01D2CB76@LITEXETSP001.etrsouth.corp.entergy.com> > From: Tommy Grav > > Hi everyone, > > I have a list of objects where I have want to do two loops. > I want to loop over the list and inside this loop, work on all > the elements of the list after the one being handled in the outer > loop. I can of course do this with indexes: > > >>> alist = range(3) > >>> for i in xrange(len(alist)): > ... for j in xrange(i+1,len(alist)): > ... print i,j,alist[i],alist[j] > ... > 0 1 0 1 > 0 2 0 2 > 1 2 1 2 > >>> > > > Is there a way to do this without using indexes? > You have to use indices because you are printing the indices. Given that, the following loop does what it looks like you are trying to do. >>> alist = range(3) >>> for index, i in enumerate(alist): for jndex, j in enumerate(alist[index:]): print index, jndex, i, j 0 0 0 0 0 1 0 1 0 2 0 2 1 0 1 1 1 1 1 2 2 0 2 2 >>> -- -Bill Hamilton From bma+lists at subvert.org.uk Thu Oct 25 08:50:19 2007 From: bma+lists at subvert.org.uk (Benjamin M. A'Lee) Date: Thu, 25 Oct 2007 13:50:19 +0100 Subject: How to best send email to a low volume list? In-Reply-To: <13i07vnbbosmi49@corp.supernews.com> References: <1193244896.747562.291580@y27g2000pre.googlegroups.com> <1193246253.4017.34.camel@skinner.madoff.com> <13i07vnbbosmi49@corp.supernews.com> Message-ID: <20071025125019.GB1471@gilmour.subvert.org.uk> On Thu, Oct 25, 2007 at 04:47:51AM -0000, Steven D'Aprano wrote: > On Wed, 24 Oct 2007 23:08:14 -0500, Shane Geiger wrote: > > > A mailing list manager is really overkill for what he is trying to do > > *IF* he is not maintaining a discussion list. > > It's not overkill at all. Mailman is easy to install (at least on a Red > Hat based Linux system, your mileage may vary elsewhere) and easy to use > *and* for bonus marks it's written in Python. There's very little that Mailman is not overkill for. Running as a daemon and managing its own queue is completely unneccessary; that's what the MTA is for. Enemies of Carlotta is also written in Python, except it's written sanely. http://liw.iki.fi/liw/eoc/ or 'enemies-of-carlotta' in Debian. Alternatively, SmartList is written as a set of procmail filters; available from http://procmail.org/ or 'smartlist' in Debian. > > A "newsletter" list > > doesn't sound like a discussion list, especially since he wants to hide > > the email addresses of the other people. > > There's more to running a mailing list than just sending emails. How do > you handle archives, the invariable complaints of missing newsletters, > requests for subscriptions, unsubscriptions, and temporary "I'll be on > holiday for a month, don't email me until I return" requests? And even if > it is not a discussion list, people expect to be able to write back to > the author/editor of the newsletter. Being able to reply to the author/editor is something that has been possible via email for 25+ years. You don't need a mailing list manager for it. -- Benjamin A'Lee :: bma at subvert.org.uk http://subvert.org.uk/~bma/ "It is forbidden to kill; therefore all murderers are punished unless they kill in large numbers and to the sound of trumpets." - Voltaire -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 194 bytes Desc: not available URL: From python at rcn.com Tue Oct 23 17:17:14 2007 From: python at rcn.com (Raymond Hettinger) Date: Tue, 23 Oct 2007 14:17:14 -0700 Subject: Set operations on object attributes question In-Reply-To: <1193161534.824430.299330@k35g2000prh.googlegroups.com> References: <1193147226.862501.97240@v23g2000prn.googlegroups.com> <1193153970.762375.262430@k35g2000prh.googlegroups.com> <1193161534.824430.299330@k35g2000prh.googlegroups.com> Message-ID: <1193174234.825443.205280@v29g2000prd.googlegroups.com> [Duane] > Since what I _really_ wanted from this was the intersection of the > objects (based on attribute 2), I was looking for a set-based > solution, > kinda like a decorate - - undecorate pattern. Perhaps > the problem does not fall into that category. Decorating and undecorating do not apply to your example. If all the input were decorated with new equality and hash methods, then the intersection step would return just a single element, not the two that you specified. Compare this with ints and floats which already have cross-type equality and hash functions. Running, set([1]).intersection([1.0]), would you expect set([1.0]) or set([1, 1.0])? Your example specified the latter behavior which has the unexpected result where the set intersection returns more elements than exist in either input. Raymond From beard.mike at gmail.com Mon Oct 1 09:45:52 2007 From: beard.mike at gmail.com (MikeBeard) Date: Mon, 01 Oct 2007 13:45:52 -0000 Subject: C Source Code Generator For Test Cases In-Reply-To: <1191001738.456766.176050@n39g2000hsh.googlegroups.com> References: <1191001738.456766.176050@n39g2000hsh.googlegroups.com> Message-ID: <1191246352.203798.200650@n39g2000hsh.googlegroups.com> On Sep 28, 1:48 pm, gamename wrote: > Hi, > > Can anyone recommend a good method of using python to generate c > source code? I have tables of test cases to use as input to a > process which would generate the test's source code. The Cheetah tool > looks interesting. Has anyone used it? Any other suggestions? > > TIA, > -T You might want to look at COG (http://www.nedbatchelder.com/code/ cog/). It might be helpful to you. I really enjoy using it and keep finding things to use it with. Good luck. Mike From duncan.booth at invalid.invalid Thu Oct 4 16:18:37 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Oct 2007 20:18:37 GMT Subject: What does the syntax [::-1] really mean? References: <1191510669.307178.257500@57g2000hsv.googlegroups.com> Message-ID: Casey wrote: > From this, I would expect that x[::-1] would be identical to x[n:0:-1] > (n and 0 being the "end" values, with the order switched due to the > negative step value). But the clause that "(but never including j)" > means that x[n:0:-1] excludes the 1st element of x, x[0]. A quick > test in ipython confirms that "abc"[3:0:-1] => "cb", not "cba". > Changing the "end" value to x[n:-1:-1] results in an empty string. > > So my question is: "what exactly is [::-1] shorthand for"? Or is it a > special case, in which case why isn't it defined as such in the > library? You made a mistake thinking that the first omitted value maps to 'n': in fact it maps to -1. the invariant that you are looking for is that for all non-negative a, b: x[a:b:1] reversed is x[-len(x)+b-1:-len(x)+a-1:-1] x[::1] is equivalent to x[0:len(x):1] therefore x[::-1] is the same as: x[-len(x)+len(x)-1:-len(x)+0-1:-1] which is just: x[-1:-len(x)-1:-1] From _karlo_ at mosor.net Wed Oct 10 20:17:07 2007 From: _karlo_ at mosor.net (Karlo Lozovina) Date: Thu, 11 Oct 2007 02:17:07 +0200 Subject: Keeping track of subclasses and instances? Message-ID: Hi, what's the best way to keep track of user-made subclasses, and instances of those subclasses? I just need a pointer in a right direction... thanks. -- Karlo Lozovina -- Mosor From kyosohma at gmail.com Mon Oct 29 09:04:41 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 29 Oct 2007 13:04:41 -0000 Subject: IEC - cannot find button In-Reply-To: <1193637535.413630.252960@22g2000hsm.googlegroups.com> References: <1193637535.413630.252960@22g2000hsm.googlegroups.com> Message-ID: <1193663081.249282.106150@50g2000hsm.googlegroups.com> On Oct 29, 12:58 am, daniel_no... at msn.com wrote: > I'm brand new to Python--and programming in general. I'm trying to use > IEC to control Internet Explorer. I've navigated to a page, and now > I'm trying to click a button. The button appears to be called 'PDF > Preview' but I honestly do not know whether that's the name or the > caption. Here is my code: > > from win32com.client import Dispatch > import IEC > > . > . > . > > ie = IEC.IEController(window_num = 1) > ie.Navigate(URL_part_1 + x + URL_part_2) > ie.ClickButton(name='PDF Preview') > > (I've also tried replacing name w/ caption but I get a similar error > message.) I get this error message: > > Traceback (most recent call last): > File "C:\Program Files\Python25\experiment", line 14, in > ie.ClickButton(name='PDF Preview') > File "C:\Program Files\Python25\lib\IEC.py", line 126, in > ClickButton > elem = elemcoll.item(i) > File ">", line 3, in item > com_error: (-2147024891, 'Access is denied.', None, None) > > I really have no idea how to interpret this. I'm pasting the button > tag below: > > > onclick="javascript:performPdfPreview(2);"/> >