Learn about mod_wsgi at SyPy Meetup Thursday, 1 Nov 2007
Hi everyone, For our November meeting, Google have kindly offered to host us again. Thursday, November 1, 2007 6:15-8:30PM Google Australia Level 18, Tower 1 Darling Park 201 Sussex St Sydney We will have one scheduled presentation: Graham Dumpleton will talk about mod_wsgi (http://www.modwsgi.org). Graham is the developer of mod_wsgi which is a simple to use Apache module that can host any Python application which supports the Python WSGI interface. followed by some lively discussion and for those who want to, we will continue the gathering at a local watering hole after 8:30PM. Of course if anyone else would like to give a presentation or a lightening talk please let me know asap. The room can hold 40 people. To attend this meeting you must RSVP to Alan Green (alangreen at google dot com) Regards Mark About SyPy A group of Sydney based python users who meet on the first Thursday of the month. Website: http://sypy.org Maillist: http://groups.google.com/group/sydneypython -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Python on Intel A110?
Bob Greschke [EMAIL PROTECTED] 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, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Windows Installation
TheFlyingDutchman [EMAIL PROTECTED] 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, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: win32com.client documentation?
Colin J. Williams [EMAIL PROTECTED] 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, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: win32com.client documentation?
Mark Morss [EMAIL PROTECTED] 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, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
about functions question
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;) -- http://mail.python.org/mailman/listinfo/python-list
Regular Expression question
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. Thanks for your help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Mobile Startup looking for sharp coders
On Oct 24, 2:42 pm, Vangati [EMAIL PROTECTED] wrote: Plusmo is Hiring! (snipped) Recruiting Agencies: Please do not send us unsolicited resumes. Plusmo does not consider resumes from any agencies. Lame company headhunters: Please do not send us unsolicited spamvertisments irrelevant to Python. Comp.lang.python does not consider spamvertisments from any lame companies. There, I fixed it for you. -- http://mail.python.org/mailman/listinfo/python-list
Re: about functions question
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. -- http://mail.python.org/mailman/listinfo/python-list
Re: about functions question
On Oct 25, 2:28 am, NoName [EMAIL PROTECTED] 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression question
On Thu, 25 Oct 2007 06:34:03 +, 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: about functions question
On Thu, 25 Oct 2007 06:28:16 +, NoName wrote: I try it: def b(): ... a() ... def a(): ... b() ... b() it's not work. What do you mean by not working? At the time `b()` is called, both functions are defined so it should working. Or at least it's not the problem you think it is. The code above, the dots replaced with nothing, will of course run forever until the stack limit is reached. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression question
On Oct 25, 8:49 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: needle = re.compile(r'create\s+or\s+replace\s+package(\s+body)?\s+', re.IGNORECASE) What I want here is a RE that return ONLY the line without the body keyword. Your RE return both. I know I could use it but I want to learn how to search something that is NOT in the string using RE. -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression question
looping wrote: On Oct 25, 8:49 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: needle = re.compile(r'create\s+or\s+replace\s+package(\s+body)?\s+', re.IGNORECASE) What I want here is a RE that return ONLY the line without the body keyword. Your RE return both. I know I could use it but I want to learn how to search something that is NOT in the string using RE. You want a negative lookahead assertion then: import re s = Isaac Newton ... Isaac Asimov ... Isaac Singer ... re.compile(Isaac (?!Asimov).*).findall(s) ['Isaac Newton', 'Isaac Singer'] Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: TeX pestilence (was Distributed RVS, Darcs, tech love)
On Thu, 2007-10-25 at 00:48 +0200, Wildemar Wildenburger wrote: Byung-Hee HWANG wrote: On Mon, 2007-10-22 at 12:19 -0400, Lew wrote: [something attackish] Well, you are making a personal attack, it's dangerous. I wish to see only discussions about TeX ;; On a python group? Also: Lew won't see your post, he's on c.l.java.* oh my god..;; -- Byung-Hee HWANG * مجاهدين * InZealBomb Friendship is everything. Friendship is more than talent. -- Vito Corleone, Chapter 1, page 38 -- http://mail.python.org/mailman/listinfo/python-list
Re: TeX pestilence (was Distributed RVS, Darcs, tech love)
Wildemar Wildenburger schrieb: Joachim Durchholz wrote: And yes, it sucks in major ways. Oh my God, I don't want to, but I just have to ask: Why? First of all, irregularities. http://en.wikipedia.org/wiki/TeX#The_typesetting_system: [...]almost all of TeX's syntactic properties can be changed on the fly which makes TeX input hard to parse by anything but TeX itself. Then: No locals. In particular, processing is controlled via global flags. If you need a different setting while a macro is processing, you have to remember to reset it before macro exit. Many packages just set the flags to a standard value. In other words, if you didn't know that a specific flag affects the operation of your macro, the macro may break when used with a different package that sets the flag to a different default value. (This may be one of the reasons why everybody just sticks with LaTeX.) Four stages of processing, and you have to know exactly which is responsible for what to predict the outcome of a macro. This is more a documentation problem - for several features, there's no description which stage is responsible for processing it. That can make working with a feature difficult, since you don't know which processing steps have already been done and which are still to happen. My TeX days are long gone, so I may have forgotten some of the problems, but I think these were the worst. (And, of course, I may have gotten some details mixed up, so if you're seriously interested in the good and bad sides of TeX, verify before taking anything for granted.) Note that it's just the markup language that I object to. The typesetting algorithms seem to be remarkably regular and robust. I would have very much liked to see TeX split up into a typesetting library and a language processor. Unfortunately, that was beyond my capabilities at the time I came into contact with TeX, and I never got around to revisiting the issue. However, the TeX algorithm has been extracted and made available as a Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
Solaris 64 bit compilation
Hi Holden, I am having problems compiling some custom apps. Can you send me the configure.in where you added the lines. Since then, I have hacked the configure.in and added the option --enable-solaris-64bit and regenerated the configure script. Now, good news, it all builds fine. Except I am having a few problems with extension. Or if you can show me where to add that line I WILL APPRECIATE IT. Thanks, JOEL SRIGIRI Pharmacopeia, Inc. * 609-452-3652 * [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] Scanned by IBM Email Security Management Services powered by MessageLabs. -- http://mail.python.org/mailman/listinfo/python-list
Re: python project ideas
On Oct 25, 5:09 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: hi to everyone I wondered if this might be the right place to ask for some ideas for python project for university. I'd like it to be something useful and web-based. And the project must be complete in 2-3 months by 2-3 person group. May be something useful for open source or python community ... Well, just post what you think could be appropriate ... Rewrite moodle in python?:) -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression question
On Oct 25, 9:25 am, Peter Otten [EMAIL PROTECTED] wrote: You want a negative lookahead assertion then: Now I feel dumb... I've seen the (?!...) dozen times in the doc but never figure out that it is what I'm looking for. So this one is the winner: s = re.search(r'create\s+or\s+replace\s+package\s+(?!body\s+)', txt, re.IGNORECASE) Thanks Peter and Marc. -- http://mail.python.org/mailman/listinfo/python-list
Re: python project ideas
On 10/24/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: hi to everyone I wondered if this might be the right place to ask for some ideas for python project for university. I'd like it to be something useful and web-based. And the project must be complete in 2-3 months by 2-3 person group. May be something useful for open source or python community ... Well, just post what you think could be appropriate ... Something I've been thinking about recently -- a templating tool capable of chunked output (i.e. sending the rendered output of the template as it is filled in). For example, if you have a page that has a slow database query in the middle of the template, you could emit the top half of the page as chunked HTML so that the client could start rendering the page without stalling and waiting for the SQL query to complete before the page is sent out. You'd probably write this as an extension to Mako/Cheetah (and possibly extend something like mod_python/mod_wsgi, don't know whether these support chunked output or not), but you could also write your own templating engine for this. -- Evan Klitzke [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
local variable referenced before assignment
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? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: python project ideas
Evan Klitzke wrote: but you could also write your own templating engine for this. No, please. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: python project ideas
On Oct 25, 10:05 am, Stefan Behnel [EMAIL PROTECTED] wrote: Evan Klitzke wrote: but you could also write your own templating engine for this. No, please. I'm afraid it is the inalienable right of every python programmer to write their own templating engine. After all, it takes less time to write your own than to understand some of them! -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: local variable referenced before assignment
On 2007-10-25, Pete Bartonly [EMAIL PROTECTED] 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: local variable referenced before assignment
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 -- http://mail.python.org/mailman/listinfo/python-list
Re: local variable referenced before assignment
On Oct 25, 10:02 am, Pete Bartonly [EMAIL PROTECTED] 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 Check your indentation? Seems to me that you might really have: def review(...): for ...: if (logMsg...): HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: about functions question
On Oct 25, 7:28 am, NoName [EMAIL PROTECTED] 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: about functions question
On Oct 25, 10:30 am, Arnaud Delobelle [EMAIL PROTECTED] wrote: [...] 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 This is what happens at runtime. Rereading, I thought I hadn't made it clear. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: python project ideas
Arnaud Delobelle wrote: On Oct 25, 10:05 am, Stefan Behnel [EMAIL PROTECTED] wrote: Evan Klitzke wrote: but you could also write your own templating engine for this. No, please. I'm afraid it is the inalienable right of every python programmer to write their own templating engine. Oh, definitely. But there is no reason to encourage someone to do so. After all, it takes less time to write your own than to understand some of them! 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. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: python project ideas
On Oct 25, 6:12 am, Stefan Behnel [EMAIL PROTECTED] 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 :) -- http://mail.python.org/mailman/listinfo/python-list
Re: python project ideas
On Oct 25, 5:09 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: hi to everyone I wondered if this might be the right place to ask for some ideas for python project for university. I'd like it to be something useful and web-based. And the project must be complete in 2-3 months by 2-3 person group. May be something useful for open source or python community ... Well, just post what you think could be appropriate ... Is their anything left over from the last Google summer of code Python suggestions? - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross-platform GUI development
On 10/24/07, bramble [EMAIL PROTECTED] wrote: On Oct 23, 2:59 pm, Chris Mellon [EMAIL PROTECTED] wrote: On 10/23/07, maco [EMAIL PROTECTED] wrote: On Oct 13, 12:34 am, Michael L Torrie [EMAIL PROTECTED] wrote: 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. In the end, GTK+ is themable, and it's a free software project, so if the MS Windows port has warts, anyone can come along and polish it up for that platform. There's been plenty to say about this in the past, so I will be brief: Being able to use the native theme API is necessary but not sufficient for native look and feel. Gtk doesn't even try for anything other than a cursory attempt at look, and as far as I know doesn't have any real interest in doing so. I don't have any problem than that, but I don't like people misrepresenting what you get from using Gtk. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding idle timeout capabilities to asyncore
On Thu, 25 Oct 2007 04:46:12 -, Josiah Carlson [EMAIL PROTECTED] 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Test for a unicode string
* goldtech (Wed, 24 Oct 2007 12:09:24 -0700) I have a regular expression test in a script. When a unicode character get tested in the regex it gives an error: As Martin pointed out: you are *not* using unicode... Question: Is there a way to test a string for unicode chars (ie. test if a string will throw the error cited above). There is but this is not your problem and if it was it wouldn't be the right solution. Read http://www.amk.ca/python/howto/unicode. You should at least have a minimal understanding of unicode before trying to use unicode. Thanks, still using Python 2.1 Best way to get yourself into trouble. Thorsten -- http://mail.python.org/mailman/listinfo/python-list
Parallel insert to postgresql with thread
Hi.. I use the threading module for the fast operation. But i have some problems.. This is my code sample: = conn = psycopg2.connect(user='postgres',password='postgres',database='postgres') cursor = conn.cursor() class paralel(Thread): def __init__ (self, veriler, sayii): Thread.__init__(self) def run(self): save(a, b, c) def save(a,b,c): cursor.execute(INSERT INTO keywords (keyword) VALUES ('%s') % a) conn.commit() cursor.execute(SELECT CURRVAL('keywords_keyword_id_seq')) idd=cursor.fetchall() return idd[0][0] def start(hiz): datas=[] for a in datas: current = paralel(a, sayii) current.start() == And it gives me different errors to try parallel insert. My querys work in normal operation but in paralel don't work. How can i insert data to postgresql the same moment ? errors: no results to fetch cursor already closed -- http://mail.python.org/mailman/listinfo/python-list
Re: Parallel insert to postgresql with thread
Abandoned wrote: Hi.. I use the threading module for the fast operation. But i have some problems.. This is my code sample: = conn = psycopg2.connect(user='postgres',password='postgres',database='postgres') cursor = conn.cursor() class paralel(Thread): def __init__ (self, veriler, sayii): Thread.__init__(self) def run(self): save(a, b, c) def save(a,b,c): cursor.execute(INSERT INTO keywords (keyword) VALUES ('%s') % a) conn.commit() cursor.execute(SELECT CURRVAL('keywords_keyword_id_seq')) idd=cursor.fetchall() return idd[0][0] def start(hiz): datas=[] for a in datas: current = paralel(a, sayii) current.start() == And it gives me different errors to try parallel insert. My querys work in normal operation but in paralel don't work. How can i insert data to postgresql the same moment ? errors: no results to fetch cursor already closed 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. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Parallel insert to postgresql with thread
On Thu, 25 Oct 2007 04:00:44 -0700, Abandoned [EMAIL PROTECTED] wrote: Hi.. I use the threading module for the fast operation. For fast operation, avoid the threading module. Here's a code sample: conn = connect(...) cursor = conn.cursor() cursor.executemany(INSERT INTO keywords (keyword) VALUES (%s), datas) Note that I also corrected your use of %, which was unnecessarily complex and insecure. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: about functions question
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 module print qq() NameError: name 'qq' is not defined Or onli possible: def main(): print qq() def qq(): return 'hello' main() -- http://mail.python.org/mailman/listinfo/python-list
Re: Parallel insert to postgresql with thread
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 [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: about functions question
NoName wrote: sorry! Yes it's work. What about 2 question? Can i put function after main block? print qq() def qq(): return 'hello' You can't call a thing before it is defined. Traceback (most recent call last): File C:\Python25\projects\indexer\test.py, line 1, in module print qq() NameError: name 'qq' is not defined Or onli possible: def main(): print qq() def qq(): return 'hello' main() Yes. That's the way to go. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: New to Vim and Vim-Python
On Oct 24, 7:25 pm, Daniel Folkes [EMAIL PROTECTED] 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 [EMAIL PROTECTED] You asked at the right time :-) See: http://www.builderau.com.au/program/python/soa/Extending-Vim-with-Python/0,264084,339283181,00.htm -- http://mail.python.org/mailman/listinfo/python-list
Re: local variable referenced before assignment
On 25/10/2007, A.T.Hofkamp [EMAIL PROTECTED] wrote: On 2007-10-25, Pete Bartonly [EMAIL PROTECTED] wrote: 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: Or just if logMsg: do_something() :) -- http://mail.python.org/mailman/listinfo/python-list
Re: local variable referenced before assignment
On 2007-10-25, Tim Williams [EMAIL PROTECTED] wrote: On 25/10/2007, A.T.Hofkamp [EMAIL PROTECTED] wrote: On 2007-10-25, Pete Bartonly [EMAIL PROTECTED] wrote: 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: Or just if logMsg: do_something() :) That is not the same. If logMsg is 0, False, or empty string, the second variant would be False and not True. Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: python project ideas
On Oct 25, 12:09 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: hi to everyone I wondered if this might be the right place to ask for some ideas for python project for university. I'd like it to be something useful and web-based. And the project must be complete in 2-3 months by 2-3 person group. May be something useful for open source or python community ... Well, just post what you think could be appropriate ... Write a good, clean web-based music library/jukebox. This is something I've been thinking of doing for a while, but I welcome someone to beat me to the punch. There are a few such things out there already--the most active is probably Jinzora, but I find it to be bloated and slow, with a horribly cluttered interface. And I think there are some other projects out there, but most of them are abandoned. A simple, attractive interface would be good, with a built- in flash player, and UTF-8 support throughout. (and though this is a relatively minor detail, for god's sake if a file has both ID3v1 and ID3v2 tags, use the ID3v2 tags by default. Jinzora doesn't didn't do this last I tried and it was quite obnoxious). -- http://mail.python.org/mailman/listinfo/python-list
Re: How to best send email to a low volume list?
On Thu, Oct 25, 2007 at 04:47:51AM -, 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 :: [EMAIL PROTECTED] 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 pgpSq6A1MKB2z.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: about functions question
NoName a écrit : sorry! Yes it's work. What about 2 question? Can i put function after main block? print qq() def qq(): return 'hello' Where's your main block here ? Traceback (most recent call last): File C:\Python25\projects\indexer\test.py, line 1, in module print qq() NameError: name 'qq' is not defined Indeed. When the code is loaded in the interpreter (that is, when passed as a script or when imported as a module), all top-level statements are executed sequentially. This creates all the function and class objects and populate the module's namespace accordingly. Or onli possible: def main(): print qq() def qq(): return 'hello' main() The canonical case for small scripts is to have first all functions and globals defined, then the main code protected by a guard, ie: import something SOME_CONST = 42 def do_something(): pass def try_something_else(): pass if __name__ == '__main__': print SOME_CONST if not do_something(): try_somethin_else() For bigger apps, you usually define all functions and classes in modules, so the 'main' script doesn't define much - just do the needed imports, and call the appropriate function or class. -- http://mail.python.org/mailman/listinfo/python-list
Help wanted for opensource project
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. -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross-platform GUI development
On Oct 25, 6:32 am, Chris Mellon [EMAIL PROTECTED] wrote: On 10/24/07, bramble [EMAIL PROTECTED] wrote: In the end, GTK+ is themable, and it's a free software project, so if the MS Windows port has warts, anyone can come along and polish it up for that platform. There's been plenty to say about this in the past, so I will be brief: Being able to use the native theme API is necessary but not sufficient for native look and feel. Gtk doesn't even try for anything other than a cursory attempt at look, and as far as I know doesn't have any real interest in doing so. I don't have any problem than that, but I don't like people misrepresenting what you get from using Gtk. Sorry, I didn't mean to misrepresent GTK+. I clumsily jammed 2 ideas into one sentence: one, that theming can mitigate some issues with differences in LF (look and feel), and two, that it's free software, so contributors can try and make the LF more native if it's really that big a deal. One reason I'm not crazy about wx because I don't like the idea of adding yet another API layer into the mix. Wx seems quite large, and if issues arise, debugging a GUI that calls another GUI does not seem like a fun way to spend your time. Anyhow, my opinion is, pick one good enough native GNU/Linux GUI toolkit that the community can somewhat standardize on (and GTK+/PyGTK seems to fit that bill pretty well), write your apps in that so they run really well on GNU/Linux distros, and *then* get your apps running on secondary OS's as-needed. -- http://mail.python.org/mailman/listinfo/python-list
Re: delineating by comma where commas inside quotation marks don't count
On 10/24/07, Dan Bishop [EMAIL PROTECTED] wrote: On Oct 24, 8:56 pm, Junior [EMAIL PROTECTED] 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 ct2: 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/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression
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() -- http://mail.python.org/mailman/listinfo/python-list
Re: Parallel insert to postgresql with thread
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 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. Fortunately, in his case, that's not necessarily true. If they do all their work with the same connection then, yes, but there are other problems with that as mention wrt thread safety and psycopg2. 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). Erik Jones Software Developer | Emma® [EMAIL PROTECTED] 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 -- http://mail.python.org/mailman/listinfo/python-list
Delete all not allowed characters..
Hi.. I want to delete all now allowed characters in my text. I use this function: def clear(s1=): if s1: allowed = [u'+',u'0',u'1',u'2',u'3',u'4',u'5',u'6',u'7',u'8',u'9',u' ', u'Ş', u'ş', u'Ö', u'ö', u'Ü', u'ü', u'Ç', u'ç', u'İ', u'ı', u'Ğ', u'ğ', 'A', 'C', 'B', 'E', 'D', 'G', 'F', 'I', 'H', 'K', 'J', 'M', 'L', 'O', 'N', 'Q', 'P', 'S', 'R', 'U', 'T', 'W', 'V', 'Y', 'X', 'Z', 'a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'j', 'm', 'l', 'o', 'n', 'q', 'p', 's', 'r', 'u', 't', 'w', 'v', 'y', 'x', 'z'] s1 = .join(ch for ch in s1 if ch in allowed) return s1 And my problem this function replace the character to but i want to for example: input: Exam%^^ple output: Exam ple I want to this output but in my code output Example How can i do quickly because the text is very long.. -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
In article [EMAIL PROTECTED], [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: def factorial(i): fact=1.0 for n in xrange(i): fact=n*fact return fact Simple minded indeed. factorial(3) 0.0 Whoops, should have xrange(i)+1 there. Or, better, xrange(2,n+1). Save a multiplication. Just trying to show the OP the scheme for iteration here. -- -- Lou Pecora -- http://mail.python.org/mailman/listinfo/python-list
Re: about functions question
On 2007-10-25, Bruno Desthuilliers [EMAIL PROTECTED] 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. 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. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Bypassing __getattribute__ for attribute access
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. 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. 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: X().y Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 3, in __my_getattribute__ AttributeError X().get_y() Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 3, in __my_getattribute__ AttributeError So it looks as if 'attribute' here means any key in self.__dict__, 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). 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. 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. 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__, self ).__getattribute__( name ) def __init__( klass, name, bases, dict ): super( XType, klass ).__init__( name, bases, dict ) setattr( klass, '__getattribute__', klass.__my_getattribute__ ) Of course this is imperfect as a user can simply bypass the __getattribute__ call too and access __dict__ directly, 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? (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.) Thanks. Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: python project ideas
On Thu, 25 Oct 2007 04:09:00 +, [EMAIL PROTECTED] wrote: hi to everyone I wondered if this might be the right place to ask for some ideas for python project for university. I'd like it to be something useful and web-based. And the project must be complete in 2-3 months by 2-3 person group. May be something useful for open source or python community ... Well, just post what you think could be appropriate ... How about a linux GUI for truecrypt ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Parallel insert to postgresql with thread
On Thu, 25 Oct 2007 09:46:54 -0500, Erik Jones [EMAIL PROTECTED] wrote: [snip] Fortunately, in his case, that's not necessarily true. If they do all their work with the same connection then, yes, but there are other problems with that as mention wrt thread safety and psycopg2. 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). PostgreSQL won't serialize inserts to the same table with a sequence column? Wow. :) Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
An efficient, pythonic way to calculate result sets
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: (a, b, c, d, e) (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 (a, b, a, c), 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. -- http://mail.python.org/mailman/listinfo/python-list
Re: [0..9] list (range) syntax
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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete all not allowed characters..
On Oct 25, 10:52 am, Abandoned [EMAIL PROTECTED] wrote: Hi.. I want to delete all now allowed characters in my text. I use this function: def clear(s1=): if s1: allowed = [u'+',u'0',u'1',u'2',u'3',u'4',u'5',u'6',u'7',u'8',u'9',u' ', u'Þ', u'þ', u'Ö', u'ö', u'Ü', u'ü', u'Ç', u'ç', u'Ý', u'ý', u'Ð', u'ð', 'A', 'C', 'B', 'E', 'D', 'G', 'F', 'I', 'H', 'K', 'J', 'M', 'L', 'O', 'N', 'Q', 'P', 'S', 'R', 'U', 'T', 'W', 'V', 'Y', 'X', 'Z', 'a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'j', 'm', 'l', 'o', 'n', 'q', 'p', 's', 'r', 'u', 't', 'w', 'v', 'y', 'x', 'z'] s1 = .join(ch for ch in s1 if ch in allowed) return s1 And my problem this function replace the character to but i want to for example: input: Exam%^^ple output: Exam ple I want to this output but in my code output Example How can i do quickly because the text is very long.. Something like: import re def clear( s, allowed=[], case_sensitive=True): flags = '' if not case_sensitive: flags = '(?i)' return re.sub( flags + '[^%s]' % ''.join( allowed ), ' ', s ) And call: clear( '123abcdefgABCdefg321', [ 'a', 'b', 'c' ] ) clear( '123abcdefgABCdefg321', [ 'a', 'b', 'c' ], False ) And so forth. Or just use re directly! (This implementation is imperfect in that it's possible to hack the regular expression, and it may break with mismatched '[]' characters, but the idea is there.) Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: python project ideas
Hi Menkaur, I work in a university as well. I am looking for some help in developing an apache graphical log analyzer using gluon http:// mdp.cti.depaul.edu/ I am about to release a pre-configured virtual appliance with it and a graphical log analyzer would be very handy. Massimo On Oct 24, 2007, at 11:09 PM, [EMAIL PROTECTED] wrote: hi to everyone I wondered if this might be the right place to ask for some ideas for python project for university. I'd like it to be something useful and web-based. And the project must be complete in 2-3 months by 2-3 person group. May be something useful for open source or python community ... Well, just post what you think could be appropriate ... -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: New to Vim and Vim-Python
On Oct 24, 12:25 pm, Daniel Folkes [EMAIL PROTECTED] 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 [EMAIL PROTECTED] 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 silent F9 :new Bar r!c:/Python25/python c:/Python25/scripts/ pyflakes #CR You could use your favorite syntax checker like Pychecker or Pylint instead of Pyflakes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete all not allowed characters..
On Thu, 25 Oct 2007 07:52:36 -0700, Abandoned wrote: Hi.. I want to delete all now allowed characters in my text. I use this function: def clear(s1=): if s1: allowed = [u'+',u'0',u'1',u'2',u'3',u'4',u'5',u'6',u'7',u'8',u'9',u' ', u'Ş', u'ş', u'Ö', u'ö', u'Ü', u'ü', u'Ç', u'ç', u'İ', u'ı', u'Ğ', u'ğ', 'A', 'C', 'B', 'E', 'D', 'G', 'F', 'I', 'H', 'K', 'J', 'M', 'L', 'O', 'N', 'Q', 'P', 'S', 'R', 'U', 'T', 'W', 'V', 'Y', 'X', 'Z', 'a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'j', 'm', 'l', 'o', 'n', 'q', 'p', 's', 'r', 'u', 't', 'w', 'v', 'y', 'x', 'z'] s1 = .join(ch for ch in s1 if ch in allowed) return s1 And my problem this function replace the character to but i want to for example: input: Exam%^^ple output: Exam ple I want to this output but in my code output Example How can i do quickly because the text is very long.. the list comprehension does not allow else, but it can be used in a similar form: s2 = for ch in s1: s2 += ch if ch in allowed else (maybe this could be written more nicely) -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete all not allowed characters..
I want to delete all now allowed characters in my text. I use this function: def clear(s1=): if s1: allowed = [u'+',u'0',u'1',u'2',u'3',u'4',u'5',u'6',u'7',u'8',u'9',u' ', u'Ş', u'ş', u'Ö', u'ö', u'Ü', u'ü', u'Ç', u'ç', u'İ', u'ı', u'Ğ', u'ğ', 'A', 'C', 'B', 'E', 'D', 'G', 'F', 'I', 'H', 'K', 'J', 'M', 'L', 'O', 'N', 'Q', 'P', 'S', 'R', 'U', 'T', 'W', 'V', 'Y', 'X', 'Z', 'a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'j', 'm', 'l', 'o', 'n', 'q', 'p', 's', 'r', 'u', 't', 'w', 'v', 'y', 'x', 'z'] s1 = .join(ch for ch in s1 if ch in allowed) return s1 And my problem this function replace the character to but i want to for example: input: Exam%^^ple output: Exam ple I want to this output but in my code output Example How can i do quickly because the text is very long.. Any reason your alphabet is oddly entered? You can speed it up by using a set. You can also tweak your join to choose a space if the letter isn't one of your allowed letters: import string allowed = set( string.letters + string.digits + ' +' + u'ŞşÖöÜüÇçİıĞğ') def clear(s): return .join( letter in allowed and letter or for letter in s) In Python 2.5, there's a ternary operator syntax something like the following (which I can't test, as I'm not at a PC with 2.5 installed) def clear(s): return .join( letter if letter in allowed else for letter in s) which some find more readable...I don't particularly care for either syntax. The latter is 2.5-specific and makes more sense, but still isn't as readable as I would have liked; while the former works versions of python back to at least 2.2 which I still have access to, and is a well documented idiom/hack. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: local variable referenced before assignment
A.T.Hofkamp wrote: On 2007-10-25, Pete Bartonly [EMAIL PROTECTED] 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: local variable referenced before assignment
A.T.Hofkamp wrote: On 2007-10-25, Pete Bartonly [EMAIL PROTECTED] wrote: Quick question, probably quite a simple matter. Take the follow start of a method: With respect to compactness and style, you can move your multi-assignment statement in the for loop, as in [snip] Btw, thanks for the tips on style too! Pete -- http://mail.python.org/mailman/listinfo/python-list
Re: local variable referenced before assignment
Peter Otten wrote: 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. I am! See my other reply just now. Here it the code again, directly cut and pasted from emacs: for item in filesNeedingReview: (tightestOwner, logMsg) = item if (logMsg != None): for logInfo in logMsg.changed_paths: if (not tightestOwner in emailListForReviewers): emailListForReviewers.append(tightestOwner) This triggers the error when review() is called with an empty sequence. Please remember to copy and paste both code and traceback next time. Sorry 'bout that. The traceback I forgot is: Traceback (most recent call last): File checkCode.py, line 599, in ? analyseFiles(tempDir) File checkCode.py, line 445, in analyseFiles analyseFilesInARepos(startDir, f) File checkCode.py, line 587, in analyseFilesInARepos makeReport(projName, filesNeedingReview, filesFailedReview) File checkCode.py, line 419, in makeReport for logInfo in logMsg.changed_paths: UnboundLocalError: local variable 'logMsg' referenced before assignment Pete -- http://mail.python.org/mailman/listinfo/python-list
bug: subprocess.Popen() hangs
This is a bug in python 2.4 under Linux 2.6. I occasionally see subprocess.Popen() fail to return, and I have finally figured out roughly what's going on. It involves the GC and stderr. 1. os.fork() 2. Parent blocks reading from errpipe_read (subprocess.py:982) 3. In child, a GC occurs before the exec. 4. The GC attempts to free a file descriptor, calling file_dealloc. 5. That function gets an error closing the descriptor (close failed: [Errno 9] Bad file descriptor\n, is the string I extracted via gdb). 6. It attempts to write the error to stderr and blocks. Since it never execs or writes to errpipe_write, both child and parent are hung. Here is the pstack output on the child: #0 0x006587a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2 #1 0x0072f11b in __write_nocancel () from /lib/tls/libc.so.6 #2 0x006d409f in _IO_new_file_write () from /lib/tls/libc.so.6 #3 0x006d42ec in _IO_new_file_xsputn () from /lib/tls/libc.so.6 #4 0x006afce9 in buffered_vfprintf () from /lib/tls/libc.so.6 #5 0x006afe8b in vfprintf () from /lib/tls/libc.so.6 #6 0x080dd4af in mywrite () #7 0x080dd505 in PySys_WriteStderr () #8 0x08064cd0 in file_dealloc () #9 0x08079c88 in dict_dealloc () #10 0x0808931d in subtype_dealloc () #11 0x08079af3 in PyDict_Clear () #12 0x0807bb6a in dict_tp_clear () #13 0x080e0ead in collect () #14 0x080e1912 in _PyObject_GC_New () #15 0x0805e50b in PyInstance_NewRaw () #16 0x0805e5d7 in PyInstance_New () #17 0x0805bdc0 in PyObject_Call () #18 0x080aecef in PyEval_CallObjectWithKeywords () #19 0x080ca975 in PyErr_NormalizeException () #20 0x080b492c in PyEval_EvalFrame () #21 0x080b5eb2 in PyEval_EvalCodeEx () #22 0x080b3c83 in PyEval_EvalFrame () #23 0x080b5734 in PyEval_EvalFrame () #24 0x080b5eb2 in PyEval_EvalCodeEx () #25 0x080fce92 in function_call () #26 0x0805bdc0 in PyObject_Call () #27 0x080641e5 in instancemethod_call () #28 0x0805bdc0 in PyObject_Call () #29 0x0808ffce in slot_tp_init () #30 0x08088b3a in type_call () #31 0x0805bdc0 in PyObject_Call () #32 0x080b0f05 in PyEval_EvalFrame () #33 0x080b5eb2 in PyEval_EvalCodeEx () #34 0x080fce92 in function_call () #35 0x0805bdc0 in PyObject_Call () #36 0x080641e5 in instancemethod_call () #37 0x0805bdc0 in PyObject_Call () #38 0x0808ffce in slot_tp_init () #39 0x08088b3a in type_call () #40 0x0805bdc0 in PyObject_Call () #41 0x080b0f05 in PyEval_EvalFrame () #42 0x080b5734 in PyEval_EvalFrame () #43 0x080b5eb2 in PyEval_EvalCodeEx () #44 0x080fce92 in function_call () #45 0x0805bdc0 in PyObject_Call () #46 0x080641e5 in instancemethod_call () #47 0x0805bdc0 in PyObject_Call () #48 0x0808ffce in slot_tp_init () #49 0x08088b3a in type_call () #50 0x0805bdc0 in PyObject_Call () #51 0x080b0f05 in PyEval_EvalFrame () #52 0x080b5eb2 in PyEval_EvalCodeEx () #53 0x080fce92 in function_call () #54 0x0805bdc0 in PyObject_Call () #55 0x080b075f in PyEval_EvalFrame () #56 0x080b5734 in PyEval_EvalFrame () #57 0x080b5734 in PyEval_EvalFrame () #58 0x080b5734 in PyEval_EvalFrame () #59 0x080b5eb2 in PyEval_EvalCodeEx () #60 0x080b3c83 in PyEval_EvalFrame () #61 0x080b5734 in PyEval_EvalFrame () #62 0x080b5734 in PyEval_EvalFrame () #63 0x080b5eb2 in PyEval_EvalCodeEx () #64 0x080b3c83 in PyEval_EvalFrame () #65 0x080b5eb2 in PyEval_EvalCodeEx () #66 0x080b3c83 in PyEval_EvalFrame () #67 0x080b5eb2 in PyEval_EvalCodeEx () #68 0x080b3c83 in PyEval_EvalFrame () #69 0x080b5734 in PyEval_EvalFrame () #70 0x080b5734 in PyEval_EvalFrame () #71 0x080b5734 in PyEval_EvalFrame () #72 0x080b5734 in PyEval_EvalFrame () #73 0x080b5734 in PyEval_EvalFrame () #74 0x080b5eb2 in PyEval_EvalCodeEx () #75 0x080fce92 in function_call () #76 0x0805bdc0 in PyObject_Call () #77 0x080b075f in PyEval_EvalFrame () #78 0x080b5eb2 in PyEval_EvalCodeEx () #79 0x080b3c83 in PyEval_EvalFrame () #80 0x080b5eb2 in PyEval_EvalCodeEx () #81 0x080b3c83 in PyEval_EvalFrame () #82 0x080b5eb2 in PyEval_EvalCodeEx () #83 0x080b3c83 in PyEval_EvalFrame () #84 0x080b5734 in PyEval_EvalFrame () #85 0x080b5734 in PyEval_EvalFrame () #86 0x080b5eb2 in PyEval_EvalCodeEx () #87 0x080b601a in PyEval_EvalCode () #88 0x080d9ff4 in PyRun_FileExFlags () #89 0x080da8d6 in PyRun_SimpleFileExFlags () #90 0x08055617 in Py_Main () #91 0x08054e3f in main () -- http://mail.python.org/mailman/listinfo/python-list
Re: about functions question
On 10/25/07, Neil Cerutti [EMAIL PROTECTED] wrote: On 2007-10-25, Bruno Desthuilliers [EMAIL PROTECTED] 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. -- http://mail.python.org/mailman/listinfo/python-list
Re: local variable referenced before assignment
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? Thanks! Argh! Mea culpa everyone! Turns out that there is a similar few lines of code later on in the code. I was confusing which was which. (I was using meta-x goto-line but then looking at the wrong but somehow, as it appeared on the same screen in emacs.) So the error was occuring at a similar line in the code, but one at whihc logMsg *wasn't* being set beforehand. Sorry all, thanks for your help, appreciate it! Pete -- http://mail.python.org/mailman/listinfo/python-list
Re: Bypassing __getattribute__ for attribute access
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__',
Re: python project ideas
Neil Wallace wrote: On Thu, 25 Oct 2007 04:09:00 +, [EMAIL PROTECTED] wrote: hi to everyone I wondered if this might be the right place to ask for some ideas for python project for university. I'd like it to be something useful and web-based. And the project must be complete in 2-3 months by 2-3 person group. May be something useful for open source or python community ... Well, just post what you think could be appropriate ... How about a linux GUI for truecrypt ? Since there is no GUI tool (that I'm aware of) I might even use it! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: python project ideas
hi to everyone I wondered if this might be the right place to ask for some ideas for python project for university. I'd like it to be something useful and web-based. And the project must be complete in 2-3 months by 2-3 person group. May be something useful for open source or python community ... Well, just post what you think could be appropriate ... Hi, have you tried this: http://wiki.python.org/moin/CodingProjectIdeas Cheers, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: building a linux executable
Paul Boddie wrote: Any suggestions, then? ;-) Not really; I've got a vaguely similar problem myself -- several Debian systems with Python 2.4 and Python 2.5. But modules I need (wxWidgets 2.8 and Twisted) aren't available as Python 2.5 packages for Debian, so I'm stuck with 2.4. Packages from unstable won't work because Twisted has a binary part that is linked against another libc. I don't really want to compile and install manually from tarballs everywhere, and building .deb packages with Python is complicated. Regards, Björn -- BOFH excuse #151: Some one needed the powerstrip, so they pulled the switch plug. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Windows Installation
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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Windows Installation
On Oct 24, 11:22 pm, Tim Roberts [EMAIL PROTECTED] wrote: TheFlyingDutchman [EMAIL PROTECTED] 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, [EMAIL PROTECTED] 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. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Windows Installation
On Oct 25, 12:36 pm, TheFlyingDutchman [EMAIL PROTECTED] wrote: On Oct 24, 11:22 pm, Tim Roberts [EMAIL PROTECTED] wrote: TheFlyingDutchman [EMAIL PROTECTED] 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, [EMAIL PROTECTED] 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 -- http://mail.python.org/mailman/listinfo/python-list
print vs sys.stdout.write, and UnicodeError
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 stdin, line 1, in module 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete all not allowed characters..
On Thu, 25 Oct 2007 17:42:36 +0200, Michal Bozon wrote: the list comprehension does not allow else, but it can be used in a similar form: s2 = for ch in s1: s2 += ch if ch in allowed else (maybe this could be written more nicely) 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: s2 = [] for ch in s1: s2.append(ch if (ch in allowed) else ) s2 = ''.join(s2) Although even that doesn't come close to the efficiency and speed of string.translate() and string.maketrans(). Try to find a way to use them. Here is one way, for ASCII characters. allowed = abcdef all = string.maketrans('', '') not_allowed = ''.join(c for c in all if c not in allowed) table = string.maketrans(not_allowed, ' '*len(not_allowed)) new_string = string.translate(old_string, table) -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Parallel insert to postgresql with thread
On Oct 25, 2007, at 10:12 AM, Jean-Paul Calderone wrote: On Thu, 25 Oct 2007 09:46:54 -0500, Erik Jones [EMAIL PROTECTED] wrote: [snip] Fortunately, in his case, that's not necessarily true. If they do all their work with the same connection then, yes, but there are other problems with that as mention wrt thread safety and psycopg2. 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). PostgreSQL won't serialize inserts to the same table with a sequence column? Wow. :) No, because sequences are separate relations that are transaction- safe, which is Postgres multi-process/session version of thread safe. To be more specific, there's really no such thing as a sequence column in Postgres. I wan't go into more detail here since this is a Python list, but if you want more info check out the Postges site and manual, the mailing lists, or respond directly to me if you just want to know how this particular bit works better. Erik Jones Software Developer | Emma® [EMAIL PROTECTED] 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete all not allowed characters..
On Thu, 25 Oct 2007 07:52:36 -0700, Abandoned wrote: Hi.. I want to delete all now allowed characters in my text. I use this function: def clear(s1=): if s1: allowed = [u'+',u'0',u'1',u'2',u'3',u'4',u'5',u'6',u'7',u'8',u'9',u' ', u'Ş', u'ş', u'Ö', u'ö', u'Ü', u'ü', u'Ç', u'ç', u'İ', u'ı', u'Ğ', u'ğ', 'A', 'C', 'B', 'E', 'D', 'G', 'F', 'I', 'H', 'K', 'J', 'M', 'L', 'O', 'N', 'Q', 'P', 'S', 'R', 'U', 'T', 'W', 'V', 'Y', 'X', 'Z', 'a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'j', 'm', 'l', 'o', 'n', 'q', 'p', 's', 'r', 'u', 't', 'w', 'v', 'y', 'x', 'z'] s1 = .join(ch for ch in s1 if ch in allowed) return s1 You don't need to make allowed a list. Make it a string, it is easier to read. allowed = u'+0123456789 ŞşÖöÜüÇçİıĞğ' \ u'ACBEDGFIHKJMLONQPSRUTWVYXZacbedgfihkjmlonqpsrutwvyxz' And my problem this function replace the character to but i want to for example: input: Exam%^^ple output: Exam ple I think the most obvious way is this: def clear(s): allowed = u'+0123456789 ŞşÖöÜüÇçİıĞğ' \ u'ACBEDGFIHKJMLONQPSRUTWVYXZacbedgfihkjmlonqpsrutwvyxz' L = [] for ch in s: if ch in allowed: L.append(ch) else: L.append( ) return ''.join(s) Perhaps a better way is to use a translation table: def clear(s): allowed = u'+0123456789 ŞşÖöÜüÇçİıĞğ' \ u'ACBEDGFIHKJMLONQPSRUTWVYXZacbedgfihkjmlonqpsrutwvyxz' not_allowed = [i for i in range(0x11) if unichr(i) not in allowed] table = dict(zip(not_allowed, u *len(not_allowed))) return s.translate(table) Even better is to pre-calculate the translation table, so it is calculated only when needed: TABLE = None def build_table(): global TABLE if TABLE is None: allowed = u'+0123456789 ŞşÖöÜüÇçİıĞğ' \ u'ACBEDGFIHKJMLONQPSRUTWVYXZacbedgfihkjmlonqpsrutwvyxz' not_allowed = \ [i for i in range(0x11) if unichr(i) not in allowed] TABLE = dict(zip(not_allowed, u *len(not_allowed))) return TABLE def clear(s): return s.translate(build_table()) The first time you call clear(), it will take a second or so to build the translation table, but then it will be very fast. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
RE: parsing the output from matlab
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: [EMAIL PROTECTED]: [EMAIL PROTECTED]: Re: parsing the output from matlab On 10/22/07, wang frank [EMAIL PROTECTED] 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('(?Pvariable\w+)\s=\s+(?Pvalue\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-- http://mail.python.org/mailman/listinfo/python-list
Re: An efficient, pythonic way to calculate result sets
On Oct 25, 10:31 am, [EMAIL PROTECTED] 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: (a, b, c, d, e) (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 (a, b, a, c), 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. -- http://mail.python.org/mailman/listinfo/python-list
Re: Bypassing __getattribute__ for attribute access
Bruno, I appreciate your attempt to answer my questions below, although I think my main point was lost amongst all your commentary and assumptions. :^) I'm not inexperienced, but I take the blame for the rambling initial post, though, which probably lead to the confusion. So let me be more direct: From reading it seems that, indeed, __getattribute__ handles calling attribute.__get__( obj, type(obj ), which does the binding of the attribute to the object. That is: thingy.attribute in turn is a call to thingy.__getattribute__( 'attribute' )1 The default body of __getattribute__ in turn fetches the associated value (by traversing the class hierarchy if necessary) and examines its type in order to determine what to return. Let's assume the ultimate value associated with the attribute (key) is v. If type(v) is a function, __getattribute__ returns v.__get__( thingy, type( thingy ) If type(v) is, say, an integer, __getattribute__ returns v unmolested. And so forth. So: class X( object ): ... a = 1 ... class b( object ): pass ... def c( self ): pass ... X.a 1 X.b class '__main__.b' X.c unbound method X.c x = X() x.a 1 x.b class '__main__.b' x.c bound method X.c of __main__.X object at 0x81b2b4c If my interpretation is correct, the X.c's __getattribute__ call knows the attribute reference is via a class, and thus returns an unbound method (though it does convert the value to a method). Likewise, x.c's __getattribute__ returns the value as a method bound to the x instance. How does __getattribute__ knows the calling context. Its first argument is the attribute name from what I can tell, not the object calling it. Is this correct so far? Moving on to __get__. Assume: class X( object ): def foo(self): print `self` x = X() Then: x.foo() Is similar (perhaps the same as) to: X.foo.__get__( x, X )() (__getattribute__ performs the transformation automatically when one references via the . operator.) And so one can do: class X( object ): ... x = 1 ... def set_x( self, x ): self.x = x ... x = X() set_x.__get__( x, X )( 5 ) x.x 5 The logical next question then is how does one best add a new method to this class so that future references to x.set_x() and X.set_x will properly resolve? It seems the answer would be to somehow add to X.__dict__ a new value, with key 'set_x', value the function set_x. From there on the . operator I assume would perform the binding to X or x as needed on-the-fly. Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: print vs sys.stdout.write, and UnicodeError
25 Oct 2007 17:37:01 GMT, Brent Lievers [EMAIL PROTECTED]: 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 stdin, line 1, in module UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128) sys.stdout.write(u'\u00e9\n'.encode(UTF-8)) é 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? you forgot to encode what you are going to print :) -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours -- http://mail.python.org/mailman/listinfo/python-list
Re: Test for a unicode string
snip... Like: if unicode string: print 'string's line #' else: process the string If I use re.UNICODE like: m = re.match(r\w+, s, re.UNICODE) then it seems to fix my problem. Trying to read as much as I can on unicode -- http://mail.python.org/mailman/listinfo/python-list
Re: does PyAntlr come with Antlr download
chewie54 wrote: I want use java2python which requires PyAntlr.I can't seem to find PyAntlr mentioned on the main website for Antlr. j2py requires antlr 2.7.7 This is what I did (for windows): - download and run 2.7.7 msi installer from http://www.antlr2.org/download.html, un-check all but python options - run python c:\antlr\277\sbin\pyantlr.py install -- View this message in context: http://www.nabble.com/does-PyAntlr--come-with-Antlr-download-tf4681566.html#a13414494 Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: print vs sys.stdout.write, and UnicodeError
Martin Marcher [EMAIL PROTECTED] wrote: 25 Oct 2007 17:37:01 GMT, Brent Lievers [EMAIL PROTECTED]: 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 stdin, line 1, in module UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128) sys.stdout.write(u'\u00e9\n'.encode(UTF-8)) ? 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? you forgot to encode what you are going to print :) Thanks. I obviously have a lot to learn about both Python and Unicode ;-) So does print do this encoding step based on the value of sys.stdout.encoding? In other words, something like: sys.stdout.write(textstr.encode(sys.stdout.encoding)) I'm just trying to understand why encode() is needed in the one case but not the other. Cheers, Brent -- http://mail.python.org/mailman/listinfo/python-list
sem_post: Invalid argument
On a server the binary (red hat) installed python2.4 and also a fresh compiled python2.5 spits sem_post: Invalid argument. What is this and how can this solved? Robert == server [~]# python2.4 sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument Python 2.4.3 (#1, Jun 6 2006, 21:10:41) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-54)] on linux2 Type help, copyright, credits or license for more information. sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument sem_post: Invalid argument server [~]# uname -a Linux server 2.4.34.1-p4-smp-bigmem-JWH #1 SMP Mon Mar 19 03:26:57 JST 2007 i686 i686 i386 GNU/Linux server [~]# -- http://mail.python.org/mailman/listinfo/python-list
Re: sem_post: Invalid argument
On Oct 25, 12:56 pm, robert [EMAIL PROTECTED] wrote: On a server the binary (red hat) installed python2.4 and also a fresh compiled python2.5 spits sem_post: Invalid argument. What is this and how can this solved? ... Python 2.4.3 (#1, Jun 6 2006, 21:10:41) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-54)] on linux2 ... server [~]# uname -a Linux server 2.4.34.1-p4-smp-bigmem-JWH #1 SMP Mon Mar 19 03:26:57 JST 2007 i686 i686 i386 GNU/Linux Are you sure you have compatible binaries? Or did you install a random RPM without checking for dependencies? -- http://mail.python.org/mailman/listinfo/python-list
Re: Bypassing __getattribute__ for attribute access
Adam Donahue wrote: class X( object ): ... def c( self ): pass ... X.c unbound method X.c x = X() x.c bound method X.c of __main__.X object at 0x81b2b4c If my interpretation is correct, the X.c's __getattribute__ call knows the attribute reference is via a class, and thus returns an unbound method (though it does convert the value to a method). No, that's wrong. It's not the __getattribute__ of X.c, it's the __getattribute__ of X itself:: type.__getattribute__(X, 'c') unbound method X.c X.c.__getattribute__('c') Traceback (most recent call last): File interactive input, line 1, in module AttributeError: 'function' object has no attribute 'c' In the former case, we use the type's __getattribute__, and we get the unbound method as expected. In the latter case, we ask the unbound method object for an attribute which it doesn't have Basically, classes define a __getattribute__ that looks something like:: def __getattribute__(self, name): value = object.__getattribute__(self, name) if hasattr(value , '__get__'): return value .__get__(None, self) return value For more information, read: http://users.rcn.com/python/download/Descriptor.htm STeVe -- http://mail.python.org/mailman/listinfo/python-list
[Windows embedding] sys.path not properly initialized (was: PyImport_ImportModule/embedding: surprising behaviors)
on Sat Mar 24 2007, Ziga Seilnacht ziga.seilnacht-AT-gmail.com 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, ... Linux working OK now Unfortunately, nothing you have written below or on the pages you reference seems to help in Windows. Here's a simple program that demonstrates: #include Python.h int main() { // uncomment to test the effect of Py_SetProgramName // Py_SetProgramName(c:\\Python25\\python.exe); Py_Initialize(); if (!PyRun_String(import sys\nimport os, Py_file_input, Py_None, Py_None)) { PyErr_Print(); } } The output is: 'import site' failed; use -v for traceback Traceback (most recent call last): File string, line 1, in module 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 string, line 1, in module 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? -- Dave Abrahams Boost Consulting http://www.boost-consulting.com -- http://mail.python.org/mailman/listinfo/python-list
threading problem..
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 :( -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Windows Installation
Bjoern Schliessmann wrote: 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). Best practice? Says who? /W -- http://mail.python.org/mailman/listinfo/python-list
Re: Bypassing __getattribute__ for attribute access
Adam Donahue a écrit : Bruno, I appreciate your attempt to answer my questions below, although I think my main point was lost amongst all your commentary and assumptions. :^) Possibly. I sometimes tend to get a bit verbose !-) I'm not inexperienced, Obviously not. but I take the blame for the rambling initial post, though, which probably lead to the confusion. So let me be more direct: From reading it seems that, indeed, __getattribute__ handles calling attribute.__get__( obj, type(obj ), which does the binding of the attribute to the object. Yes. That is: thingy.attribute in turn is a call to thingy.__getattribute__( 'attribute' )1 Yes. The default body of __getattribute__ in turn fetches the associated value (by traversing the class hierarchy if necessary) and examines its type in order to determine what to return. Yes. Let's assume the ultimate value associated with the attribute (key) is v. If type(v) is a function, If v supports the descriptor protocol (which is the case for function objects and property objects) AND v is a class attribute __getattribute__ returns v.__get__( thingy, type( thingy ) Yes. If type(v) is, say, an integer, If v doesn't support the descriptor protocol __getattribute__ returns v unmolested. Yes. And so forth. So: class X( object ): ... a = 1 You understand that 'a' is a class attribute, don't you ? ... class b( object ): pass ... def c( self ): pass ... X.a 1 X.b class '__main__.b' X.c unbound method X.c x = X() x.a 1 Returns type(x).a x.b class '__main__.b' idem x.c bound method X.c of __main__.X object at 0x81b2b4c Yes. If my interpretation is correct, the X.c's __getattribute__ call knows the attribute reference is via a class, Yes and thus returns an unbound method It returns c.__get__(None, X). Which is implemented to return an unbound method if the first arg is None. (though it does convert the value to a method). __getattribute__ doesn't convert anything here - and FWIW, doesn't care if c is a function or property or whatnot. The only thing it looks for is if c has a __get__ method. Likewise, x.c's __getattribute__ returns the value as a method bound to the x instance. Yes, because then __getattribute__ returns x.c.__get__(x, X), which, since c is a function, returns a bound method. How does __getattribute__ knows the calling context. Its first argument is the attribute name from what I can tell, not the object calling it. Really ?-) __getattribute__ is itself a function and an attribute of a class (and FWIW, it's signature is __getattribute__(self, name)). So when itself looked up, it returns a method object, which when called passes the 'target' object as first arg. You already know that Python's classes are objects (instances of type 'type'). So you should by now understand how __getattribute__ knows it's target. Got it ? Yes, right: when looking up attributes on a class, it's the class's class (IOW: the type) __getattribute__ method that is invoked !-) Is this correct so far? cf above. Moving on to __get__. Assume: class X( object ): def foo(self): print `self` x = X() Then: x.foo() Is similar (perhaps the same as) to: X.foo.__get__( x, X )() Almost but not quite. It's: x.foo() = X.foo(x) = X.foo.im_func.__get__(x, X)() It's a bit less confusing when the function is defined outside the class: def bar(self): print self X.bar = bar x = X() Now you have: x.bar() = X.bar(x) = bar.__get__(x, X)() (__getattribute__ performs the transformation automatically when one references via the . operator.) And so one can do: class X( object ): ... x = 1 Here, x is a class attribute. def set_x( self, x ): self.x = x Now this creates an instance attribute that will shadow the class attribute. ... x = X() set_x.__get__( x, X )( 5 ) x.x 5 So far, so good. The logical next question then is how does one best add a new method to this class so that future references to x.set_x() and X.set_x will properly resolve? It seems the answer would be to somehow add to X.__dict__ a new value, with key 'set_x', value the function set_x. Yes. Which is very simply done by just binding set_x to X.set_x. Just like I did above. Dynamically adding methods to classes is pretty straightforward, the tricky point is to dynamically add methods to instances, since the descriptor protocol is only triggered for class attributes. But you obviously found how to do it using func.__get__(obj, type(obj)) !-) From there on the . operator I assume would perform the binding to X or x as needed on-the-fly. Yes. NB: please some guru around correct me if I said something wrong (Alex ? Tim ? Fredrick ? If you hear me ?) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Combinatorics
none wrote: Is there some package to calculate combinatorical stuff like (n over k), i.e., n!/(k!(n - k!) ? Yes, in SciPy. Alan Isaac from scipy.misc.common import comb help(comb) Help on function comb in module scipy.misc.common: comb(N, k, exact=0) Combinations of N things taken k at a time. If exact==0, then floating point precision is used, otherwise exact long integer is computed. Notes: - Array arguments accepted only for exact=0 case. - If k N, N 0, or k 0, then a 0 is returned. -- http://mail.python.org/mailman/listinfo/python-list
Re: sem_post: Invalid argument
Jonathan Gardner wrote: On Oct 25, 12:56 pm, robert [EMAIL PROTECTED] wrote: On a server the binary (red hat) installed python2.4 and also a fresh compiled python2.5 spits sem_post: Invalid argument. What is this and how can this solved? ... Python 2.4.3 (#1, Jun 6 2006, 21:10:41) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-54)] on linux2 ... server [~]# uname -a Linux server 2.4.34.1-p4-smp-bigmem-JWH #1 SMP Mon Mar 19 03:26:57 JST 2007 i686 i686 i386 GNU/Linux Are you sure you have compatible binaries? Or did you install a random RPM without checking for dependencies? Should be compatible - but I am not sure if the kernel was recompiled on this machine. And at least the fresh ./configure'ed and compiled py2.5, which yields the same problem, should be maximum compatible. Maybe because this machine is a smp-bigmem .. Robert -- http://mail.python.org/mailman/listinfo/python-list
elementtree w/utf8
Hi, I'm getting the by-now-familiar error: return codecs.charmap_decode(input,errors,decoding_map) UnicodeEncodeError: 'ascii' codec can't encode character u'\xa9' in position 4615: ordinal not in range(128) the html file I'm working with is in utf-8, I open it with codecs, try to feed it to TidyHTMLTreeBuilder, but no luck. Here's my code: from elementtree import ElementTree as ET from elementtidy import TidyHTMLTreeBuilder fd = codecs.open(htmfile,encoding='utf-8') tidyTree = TidyHTMLTreeBuilder.TidyHTMLTreeBuilder(encoding='utf-8') tidyTree.feed(fd.read()) self.tree = tidyTree.close() fd.close() what am I doing wrong? Thanks in advance. 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Bypassing __getattribute__ for attribute access
On Thu, 2007-10-25 at 23:13 +0200, Bruno Desthuilliers wrote: snip excellent breakdown The logical next question then is how does one best add a new method to this class so that future references to x.set_x() and X.set_x will properly resolve? It seems the answer would be to somehow add to X.__dict__ a new value, with key 'set_x', value the function set_x. Yes. Which is very simply done by just binding set_x to X.set_x. Just like I did above. Dynamically adding methods to classes is pretty straightforward, the tricky point is to dynamically add methods to instances, since the descriptor protocol is only triggered for class attributes. But you obviously found how to do it using func.__get__(obj, type(obj)) !-) This is the greasy, getting your hands dirty way. I vastly prefer (and reccomend) using the new module: import new class X(object): ... pass ... def bar(self): ... print self ... x = X() x.bar = new.instancemethod(bar, x, X) x.bar() __main__.X object at 0x87dca0c From there on the . operator I assume would perform the binding to X or x as needed on-the-fly. Yes. NB: please some guru around correct me if I said something wrong (Alex ? Tim ? Fredrick ? If you hear me ?) -- http://mail.python.org/mailman/listinfo/python-list
Dual Python Installed Environments..
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 -- http://mail.python.org/mailman/listinfo/python-list