Re: ANN: Sydebar 1.0 - A browser sidebar generator for Python documentation
Remy Blank skrev: (I apologize for the poorly formatted message. Something between my news client and the server decided, besides delaying the message for over 17 hours, to add an empty line for every line of text, which obviously messed up some headers. Here's the content again, and hopefully this message comes through unaltered.) I am pleased to announce the first release of Sydebar, a browser sidebar generator for Python documentation. For the impatient, sample outputs for all Python versions ever released can be found here: http://c-space.org/download/Sydebar/samples/ This looks great. I have been missing my chm based docs since moving to Python. This goes a long way. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Handling some isolated iso-8859-1 characters
Daniel Mahoney skrev: The interesting patch is the string that reads "=?iso-8859-1?Q?Ana=EFs?=". An HTML rendering of what this string should look would be "Anaïs". There is a mention of email headers and unicode in the end of this article: http://mxm-mad-science.blogspot.com/2008/03/python-unicode-lessons-from-school-of.html -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: New chairman
Sverker Nilsson skrev: I was talking about Guido van Rossum The one who decides, so far when people agree I have been using Python since the nineties. I cannot remember when I have had to rewrite old code because of changes in the language. At the same time I have been feeling as if I was sitting in a time machine watching other languages whoosh by at breakneck speed. Entire technologies have been developed to make programming as practical and easy as it has been in Python the entire time. So I find it hard to see exactly what it is that Guido is doing wrong? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Literate programs in Python
Mike Driscoll skrev: On May 13, 10:28 am, Paul Miller <[EMAIL PROTECTED]> wrote: Does anyone know of any (preferably largish) examples of literate programs written using Python? Alternatively, does anyone know of any literate programming tools which support Python well? (I am aware of Leo and I've been to literateprogramming.com, but any additional pointers would be much appreciated!) I think that most people in Python use doctest. Personally I find this form of literal programming to be very efficient. Like the example here: http://codespeak.net/icalendar/example.html -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematics in Python are not correct
[EMAIL PROTECTED] skrev: I have two another interesting things to discuss about, for which I'll open new posts on this group. Look for "Python doesn't recognize quote types" and "Python, are you ill?". You have a tendency to form your questions as complaints about Python being broken. You will probably get better responses if you just state that there are things you do not understand, and ask why it works that way. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Am I missing something with Python not having interfaces?
Arnaud Delobelle skrev: jmDesktop <[EMAIL PROTECTED]> writes: Studying OOP and noticed that Python does not have Interfaces. Is that correct? Is my schooling for nought on these OOP concepts if I use Python. Am I losing something if I don't use the "typical" oop constructs found in other languages (Java, C# come to mind.) I'm afraid that if I never use them I'll lose them and when I need them for something beside Python, I'll be lost. Thank you. You're not missing anything. An Interface is the Poor Man's Multiple Inheritance. But in truth, even without multiple inheritance, Python wouldn't need java-like interfaces. Interfaces are a great concept for many things, and they can cover a few soft spots in Python. There is the possibility of using the great zope.interface library http://pypi.python.org/pypi/zope.interface. Just use: "easy_install zope.interface" And you have interfaces. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Python MIDI in 2008
Maciej Blizin'ski skrev: For the last couple of days, I've been looking for a Python midi library. I'm generally interested in sending MIDI events via ALSA. It seems like everything out there is pretty old; packages are from 2003 or 2005. existing or very old software packages - http://www.mxm.dk/products/public/pythonmidi/ -- no realtime support This is old in the sense that it has been a while since I wrote it. But it is virtually bug free, so nothing much is happening. The midi standard does not change so there is no real reason to change/upgrade it. It is currently being used by the very popular "frets on fire" http://fretsonfire.sourceforge.net/documentation/source/ It does not have real time support even though I did write it with that support in mind. I just never got around to write it as I did not need it myself. I also developed it on Windows and I found it to be a bore to get real time midi working. It would probably be easier now that I am on Linux. Well I just thought I would mention that it is not dead. Merely middle aged. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Real Time Midi File Playback - Reading and Writing midi at the same time
Gilly skrev: Hi I am trying to create an application that uses some form of input to create a midi file. I would like for this to be a 'real time' process. In other words, I want to be able to begin playing the midi file before I finish writing it, and continue writing as it plays. Perhaps csound can help with this. It has a lot of midi, realtime and python stuff. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: tool to calculate color combination
Astan Chee skrev: Hi, I was just wondering if there is a tool/script in python that allows me to do color calculations; specifically, when I add them. There is the colorsys module which I have used in this class: from colorsys import rgb_to_hls, hls_to_rgb import binascii from types import StringType, TupleType, ListType, IntType, FloatType from math import modf class RGB: """ Makes it easier to work with rgb colors """ def __init__(self, color): # set color value self.color = self.any2color(color) def any2color(self, color): """ Takes a number of color formats and returns a sequence of 3 floats: (r,g,b) Some legal formats for pure blue are: '0xFF','#FF','FF', [0.0, 0.0, 1.0], [0, 0, 255], (0, 0.0, 'FF') and ('0', '0', 'f'). Mixed types are allowed in sequences. """ # it must be a hex, so convert to sequence of hex values if isinstance(color, StringType): # handle hex value if color[:2].lower() == '0x': color = color[2:] elif color[0] == '#': color = color[1:] color = (color[:2], color[2:4], color[4:]) # convert sequence to floats color_result = [] a = color_result.append for part in color: # what type is the part? if isinstance(part, StringType): # hex part if len(part) == 1: part = '0%s' % part b = binascii.a2b_hex(part) a(ord(b[0])/255.0) elif isinstance(part, IntType): # int part a(part/255.0) elif isinstance(part, FloatType): # float part a(part) return color_result def __str__(self): "Returns string representation of color (same as html_hex)" return self.html_hex() def r(self): return self.color[0] def g(self): return self.color[1] def b(self): return self.color[2] def bytes(self): """ Takes a sequence of colors in floats, and returns a sequence of int in the range 0-255 """ return map(lambda x: int(x*255), self.color) def html_hex(self): """ Returns the color in a hex string representation of the form '#FF' """ r,g,b = self.color return '#%02X%02X%02X' % (int(r*255),int(g*255),int(b*255)) def _cAdd(self, x, y): "Private method! Cirkular add x+y so value allways in 0.0-1.0 range" fractional, integer = modf(x + y) if not fractional and integer: # special case 1.0 return 1.0 return abs(fractional) # wrong result for negative values! def hls_delta(self, dh, dl, ds): """ Returns a Color object same as self, but adjusted by delta hls values """ h,l,s = rgb_to_hls(*self.color) nh = self._cAdd(h, dh) nl = l + dl if nl > 1.0: nl = 1.0 if nl < 0.0: nl = 0.0 ns = s + ds if ns > 1.0: ns = 1.0 if ns < 0.0: ns = 0.0 return RGB(hls_to_rgb(nh, nl, ns)) def change_ls(self, new_l=None, new_s=None): """ Returns a Color object same as self, but with new lightness and saturation levels """ h,l,s = rgb_to_hls(*self.color) if new_l == None: new_l = l if new_s == None: new_s = s return RGB(hls_to_rgb(h, new_l, new_s)) def spacer(self, transparent=None): """ Creates a 1x1 GIF89a of color. If no color it returns a transparent gif Should probably not be in this module? """ template = [71, 73, 70, 56, 57, 97, 1, 0, 1, 0, 128, 0, 0, 255, 255, 255, 0, 0, 0, 33, 249, 4, 1, 0, 0, 0, 0, 44, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 68, 1, 0, 59] if not transparent: template[13:16] = self.bytes() # set rgb values template[22] = 0 # remove transparency return ''.join(map(chr, template)) if __name__=='__main__': red = (255, 0, 0) green = (0.0, 1.0, 0.0) blue= (0.0, 0.0, 1.0) yellow = '#00' col = RGB(blue) print col.color print col.bytes() print col brighter = col.change_ls(0.0, 0.0) print 'brighter:',brighter #complementary = col.hls_delta(0.50, 0.0, 0.0) #print complementary -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Given a string - execute a function by the same name
[EMAIL PROTECTED] skrev: Bruno, But when I release into production I'm going to shift to #3: "Place all my functions in dictionary and lookup the function to be called". This technique will allow me to precisely control the dynamic nature of my application. Just one tiny note: What you will be doing is a variation of the factory pattern. So this search might give you some new ideas: http://www.google.dk/search?hl=en&q=python+factory+pattern -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Given a string - execute a function by the same name
[EMAIL PROTECTED] skrev: I'm parsing a simple file and given a line's keyword, would like to call the equivalently named function. There are 3 ways I can think to do this (other than a long if/elif construct): 1. eval() 2. Convert my functions to methods and use getattr( myClass, "method" ) 3. Place all my functions in dictionary and lookup the function to be called Any suggestions on the "best" way to do this? No reason to use eval. use either getattr(obj, "method")() or functions['method'] They are basically the same thing. The dict of functions is a bit safer. You don't risk calling a built in method on your object . Which you risk doing with something like: getattr(obj, 'join') -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Little novice program written in Python
hellt skrev: >> Most code is not like that so perhaps you should try something more >> "usual" like sending email, fetching webpages etc. to get a feel for the >> language. >> > em, i would say, that python (esp. with NumPy+Psyco) is very popular > in numerical processing also. I know, and I might be way of, but I would believe that even that would be more like stringing ready built modules together, calling methods etc. I have written far denser code that the above example in Python regularly. But It is like 1%-5% of my code I believe. Unlike the c family of languages where there is a lot more algorithms due to the low level coding. Memory handling, list, dicts etc. qickly becomes more like math algorithms than in Python. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Little novice program written in Python
Rogério Brito skrev: Hi, All. What I would like is to receive some criticism to my code to make it more Python'esque and, possibly, use the resources of the computer in a more efficient way (the algorithm implemented below is the Sieve of Eratosthenes): I agree with the rest here. Your code generally looks fine. But on another note, this type of code is not something you often see in Python. It is very dense with regard to algorithm. Most code is not like that so perhaps you should try something more "usual" like sending email, fetching webpages etc. to get a feel for the language. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Success stories
azrael skrev: Please give me any arguments to cut him down about his commnets like :"keep programing i python. maybe, one day, you will be able to program in VisualBasic" When I started writing in Python in the nineties there was a lot of tech-media coverage of Perl. Python was always mentioned as a rival to Perl in those articles. These days Python is mentioned in a lot of tech-articles. Perl is never mentioned as a rival in those articles. Other languages like Ruby are. Ok I am Python biased, but I don't see anything happen on the Perl front anymore. It has simply gone quiet. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: expanding a variable to a dict
John Machin skrev: > On Apr 4, 9:44 am, Max M <[EMAIL PROTECTED]> wrote: > Ummm ... excessive apostrophes plus bonus gross syntax error, dood. > Did you try running any of these snippets??? No I just wanted to quickly show different ways to do it. The dicts in the original question wasn't dicts either. So I asumed I could answer in the same vein. >> http://www.mxm.dk/ >> IT's Mad Science > > Sure is. Oh yes. That will motivate further answers. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: expanding a variable to a dict
idle skrev: > now I'd like to check them all for the existence of certain default > keys; ie, if the dicts don't contain the keys, add them in with > default values. > > so, I've got: > > for a in ['dictFoo','dictBar','dictFrotz']: > if hasattr(a,'srcdir') == False: > a['srcdir']='/usr/src' There are a few ways to do it. for a in ['dictFoo','dictBar','dictFrotz']: if not a.has_key('srcdir'): a['srcdir'] = '/usr/src' for a in ['dictFoo','dictBar','dictFrotz']: if not 'srcdir' in a: a['srcdir'] = '/usr/src' for a in ['dictFoo','dictBar','dictFrotz']: a.setdefault('srcdir') = '/usr/src' -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: speeding things up with C++
bullockbefriending bard skrev: > good point. while i bow to the genius of the folks who invented > template metaprogramming, the compiler error messages tend to be > profoundly depressing :). one way or the other, pyrex is something i > need to learn since i'm now completely enamoured with python and had > better develop an arsenal of tricks for the rare times when it's just > not fast enough. A dash of c combined integrated via ctypes is probably the easiest solution? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Xml parser
ashish skrev: > Hi All, > > I want to know weather is there any api available in python for parsing > xml(XML parser) I have had very good succes with lxml -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
Dmitry Dzhus skrev: >> Actually I'm trying to convert a string to a list of float numbers: >> str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] > > str="53,20,4,2" > map(lambda s: float(s), str.split(',')) > > Last expression returns: [53.0, 20.0, 4.0, 2.0] The lambda is not needed there, as float is a callable. map(float, str.split(',')) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Cgi File Upload without Form
[EMAIL PROTECTED] skrev: > Hello, > > what is the simplest way to upload a file (or a long string) to a > server using cgi/python? > > Since I want to upload the data programmatically, a form based > solution is not good. I am not experienced with SOAP/WSDL and I > believe that would be more difficult than necessary. The client > program I have to use does not support FTP. Try out urllib2 -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing HTML/XML documents
Stefan Behnel skrev: > [EMAIL PROTECTED] wrote: >> I need to parse real world HTML/XML documents and I found two nice python >> solution: BeautifulSoup and Tidy. > > There's also lxml, in case you want a real XML tool. > http://codespeak.net/lxml/ > http://codespeak.net/lxml/dev/parsing.html#parsers I have used both BeautiullSoup and lxml. They are both good tools. lxml is blindingly fast compared to BeautifulSoup though. A simple tool for importing contact information from 6000 xml files of 23 MBytes into Zope runs in about 30 seconds. No optimisations at all. Just inefficient xpath expressions. That is pretty good in my book. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Email attachments
Steve Holden skrev: > I'm having some trouble getting attachments right for all recipients, > and it seems like Apple's mail.app is the pickiest client at the moment. > It doesn't handle attachments that both Thunderbird and Outlook find > perfectly acceptable. > > Since the code I'm using is currently ugly and embedded, before I trim > it down for posting could anyone who's successfully generated emails > with attachments received by mail.app let me know if they had any > problems along the way? Google hasn't given me much on this, but I'm not > feeling very creative today. This method is used in one of my Plone products, and there is also a bit of imap in there. But it is probably simple enough to extract the attachment relevant parts security.declareProtected(EDIT_CONTENTS_PERMISSION, 'sendMessage') def sendMessage(self, to=None, cc=None, bcc=None, inReplyTo=None, subject=None, body='', attachments=None, mode=None, folderPath=None, uid=None, REQUEST=None): "Sends a message" site_encoding = self._site_encoding() ## # Create the message msg = Message() msg.set_payload(body, site_encoding) # # if attachment, convert to multipart # file fields are posted even if empty, so we need to remove those :-s if attachments is None: attachments = [] attachments = [a for a in attachments if a] if attachments or (mode == 'Forward'): mimeMsg = MIMEMultipart() mimeMsg.attach(msg) # If mode is Forward we get original message as attachment if mode == 'Forward' and folderPath and uid: original = self.fetchMessageFromPath(folderPath, uid) mimeMsg.attach(original) for attachment in attachments: # Add the attachment tmp = email.message_from_string(str(attachment.headers)) filename = tmp.get_param('filename', 'Attachment', 'Content-Disposition') # clean up IE paths filename = filename[max(filename.rfind('/'), filename.rfind('\\'), filename.rfind(':') )+1:] contentType = tmp['Content-Type'] attach_part = Message() attach_part.add_header('Content-Type', contentType, name=filename) attach_part.add_header('Content-Disposition', 'attachment', filename=filename) attach_part.set_payload(attachment.read()) Encoders.encode_base64(attach_part) mimeMsg.attach(attach_part) msg = mimeMsg # set headers on message from_ = self.getEmail() msg['From'] = from_ msg['Reply-To'] = from_ if to: msg['To'] = to if cc: msg['Cc'] = cc if bcc: msg['Bcc'] = bcc msg['Date'] = self.ZopeTime().rfc822() # needed by some servers if inReplyTo: msg['In-Reply-To'] = inReplyTo msg['Subject'] = Header(subject, site_encoding) ## # Send the message SMTPserver = self._mailhost() outbox = smtplib.SMTP(SMTPserver) try: cleaner = lambda adresses: [adress.strip() for adress in adresses.split(',') if adress.strip()] all_receivers = cleaner(to) + cleaner(cc) + cleaner(bcc) outbox.sendmail(from_, all_receivers, msg.as_string()) success = 1 except: success = 0 ## # append the message to the 'Sent' box if success: Sent = self.getSentboxName() connection = self.getConnection() try: connection.append(Sent, msg.as_string(), ('\\Seen',)) except: # we don't want to not send messages just because the sentbox isn't set correctly pass # # returns a portal status message if REQUEST: if success: message = 'Succes! The message was sent ' else: message = 'Error! The message could not be sent' REQUEST.RESPONSE.redirect(self.absolute_url() + '/mxmImapClient_compose?portal_status_message=%s' % message) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to push data into Ical from Python ?
has skrev: > dwhall wrote: > >> One way would be to use >> Python's tie-ins to Applescript_ and apple events (AE). As you will >> read, this support isn't as strong as it used to be. > > What gave you that impression, if you don't mind my asking? http://www.google.dk/search?q=python+icalendar -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Ensure a variable is divisible by 4
[EMAIL PROTECTED] skrev: > Nick Craig-Wood wrote: >> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: >>> I am sure this is a basic math issue, but is there a better way to >>> ensure an int variable is divisible by 4 than by doing the following; >>> >>> x = 111 >>> x = (x /4) * 4 X *= 4 ;-) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Email headers and non-ASCII characters
Christoph Haas skrev: > On Thursday 23 November 2006 16:31, Max M wrote: >> Christoph Haas skrev: >>> Hello, everyone... >>> >>> I'm trying to send an email to people with non-ASCII characters in >>> their names. A recpient's address may look like: >>> >>> "Jörg Nørgens" <[EMAIL PROTECTED]> >>> >>> My example code: >>> >>> = >>> def sendmail(sender, recipient, body, subject): >>>message = MIMEText(body) >>>message['Subject'] = Header(subject, 'iso-8859-1') >>>message['From'] = Header(sender, 'iso-8859-1') >>>message['To'] = Header(recipient, 'iso-8859-1') >>> >>>s = smtplib.SMTP() >>>s.connect() >>>s.sendmail(sender, recipient, message.as_string()) >>>s.close() >>> = >>> >>> However the Header() method encodes the whole expression in >>> ISO-8859-1: >>> >>> =?iso-8859-1?q?=22J=C3=B6rg_N=C3=B8rgens=22_=3Cjoerg=40nowhere=3E?= >>> >>> However I had expected something like: >>> >>> "=?utf-8?q?J=C3=B6rg?= =?utf-8?q?_N=C3=B8rgens?=" <[EMAIL PROTECTED]> >>> >>> Of course my mail transfer agent is not happy with the first string >> Why offcourse? > > Because my MTA doesn't care about MIME. It just transports the email. And > it expects an email address in <...> but doesn't decode =?iso...? strings. > >> But it seems that you are passing the Header object a >> utf-8 encoded string, not a latin-1 encoded. >> You are telling the header the encoding. Not asking it to encode. > > Uhm, okay. Let's see: > > u'"Jörg Nørgens" <[EMAIL PROTECTED]>'.encode('latin-1') > > => '"J\xc3\xb6rg N\xc3\xb8rgens" <[EMAIL PROTECTED]>' > > So far so good. Now run Header() on it: > > => '=?utf-8?b?IkrDtnJnIE7DuHJnZW5zIiA8am9lcmdAbm93aGVyZT4=?=' > > Still nothing like <...> in it and my MTA is unhappy again. What am I > missing? Doesn't anyone know how mail clients handle that encoding? >>> address = u'"Jörg Nørgens" <[EMAIL PROTECTED]>'.encode('latin-1') >>> address '"J\xf6rg N\xf8rgens" <[EMAIL PROTECTED]>' >>> from email.Header import Header >>> hdr = str(Header(address, 'latin-1')) >>> hdr '=?iso-8859-1?q?=22J=F6rg_N=F8rgens=22_=3Cjoerg=40nowhere=3E?=' Is this not correct? At least roundtripping works: >>> from email.Header import decode_header >>> encoded, coding = decode_header(hdr)[0] >>> encoded, coding ('"J\xf6rg N\xf8rgens" <[EMAIL PROTECTED]>', 'iso-8859-1') >>> encoded.decode(coding) u'"J\xf6rg N\xf8rgens" <[EMAIL PROTECTED]>' And parsing the address works too. >>> from email.Utils import parseaddr >>> parseaddr(encoded.decode(coding)) (u'J\xf6rg N\xf8rgens', u'[EMAIL PROTECTED]') >>> -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Email headers and non-ASCII characters
Christoph Haas skrev: > Hello, everyone... > > I'm trying to send an email to people with non-ASCII characters in their > names. A recpient's address may look like: > > "Jörg Nørgens" <[EMAIL PROTECTED]> > > My example code: > > = > def sendmail(sender, recipient, body, subject): >message = MIMEText(body) >message['Subject'] = Header(subject, 'iso-8859-1') >message['From'] = Header(sender, 'iso-8859-1') >message['To'] = Header(recipient, 'iso-8859-1') > >s = smtplib.SMTP() >s.connect() >s.sendmail(sender, recipient, message.as_string()) >s.close() > = > > However the Header() method encodes the whole expression in ISO-8859-1: > > =?iso-8859-1?q?=22J=C3=B6rg_N=C3=B8rgens=22_=3Cjoerg=40nowhere=3E?= > > However I had expected something like: > > "=?utf-8?q?J=C3=B6rg?= =?utf-8?q?_N=C3=B8rgens?=" <[EMAIL PROTECTED]> > > Of course my mail transfer agent is not happy with the first string Why offcourse? But it seems that you are passing the Header object a utf-8 encoded string, not a latin-1 encoded. You are telling the header the encoding. Not asking it to encode. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: Sarcasm and irony
bryan rasmussen skrev: > Well irony originally started out as a very specific concept of the > Ancient Greek drama, this is what we nowadays refer to as Dramatic > Irony but it is the original irony. Irony then became a literary > concept for plot elements similar to Dramatic irony in books, or a > weaker type of the Dramatic irony found in the plays of Shakespeare. > People then noticed that life was at times ironic in the literary > manner. Yes and in Rome "salary" meant getting a bag of salt. Concepts changes. > Nowadays the use of the word irony has degenerated to by > pretty much synonymous with sarcasm. As a Dane that is a Chronic Ironic, I beg to differ. In Denmark at least there is a lot of difference between irony and sarcasm. Irony is the main form of humor here, and danes takes to it easily. People being sarcastic we don't much like. But I guess that it can be hard to se the difference for someone not used to irony. I believe the reason that irony works here is that we have such a homogenous society. Somewhere like the US where the cultural differences are larger, it is probably a lot harder for irony to be taken as such and not as sarcasm. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: Sarcasm and irony
bryan rasmussen skrev: > On 10/10/06, Steve Holden <[EMAIL PROTECTED]> wrote: >> ... in America. It's well-known among Brits that Americans don't >> understand irony. They can be pretty oblique when it come to sarcasms >> too, for that matter. > > is that 'in America' meant to be an addendum to what I said, as in > this is the situation in America and not elsewhere? If so I should > probably point out that I am writing from Denmark and was thinking > specifically of a situation where a dane told me they were being > 'ironic' (when what they meant, obviously, was that they were being > ironical), when I asked what they meant by that they said "saying the > opposite of what I mean" I responded: "so, in other words, what you > mean by irony is 'sarcasm'" She responded "yes, that's what it means" Are you an american? Irony does mean that one says the opposite of what one really means. If you do it for humor its irony, if you do it for mocking it is sarcasm. So now I see... americans really *do* understand irony. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory Management in python 2.5
[EMAIL PROTECTED] skrev: > Hi, I am starting to have a look to a python program that does not free > memory (I am using python 2.4.3). As I have read about a new memory > management in python 2.5 (http://evanjones.ca/python-memory.html) I > decided to try the program with the new version. > With the new version of python the memory consumption is the same. Now > I am asking myself if python 2.5 has any improving in memory > management or maybe not yet. Thank you. In previous versions Python collected memory, but never released it again. It simply kept on to it, so it could reuse it again later. From 2.5 onwards it should release most of the unused memory. However it doesn't use less memory. The peak memory usage should be the same as before. So for one-off programs that starts up and runs once, there should not be much gain. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Making posts to an ASP.NET webform.
Bernard skrev: > Has anyone tried what I'm doing? and if you tried how have you > succeeded getting the data back after the post action? Most likely you get assigned a cookie that you then need to return. Try the cookielib which automates all this for you. -- http://mail.python.org/mailman/listinfo/python-list
Re: builtin regular expressions?
Jorgen Grahn skrev: > On Sat, 30 Sep 2006 20:01:57 +0100, Thorsten Kampe <[EMAIL PROTECTED]> wrote: >> And the simple reason why Regular Expressions are not a part of the >> core Python language is that Regular Expressions are overrated. > > It seems to me they are currently /underrated/ in the Python community. Or, > I suspect, everybody disrespects them in public but secretly use them when > they're hacking ;-) When I used to program in Perl I used regex' for lots of stuff. In python I probably use them once every half year. I sinply do not need them. Max M -- http://mail.python.org/mailman/listinfo/python-list
Re: A critique of cgi.escape
Lawrence D'Oliveiro skrev: > In message <[EMAIL PROTECTED]>, Gabriel G > wrote: > >> At Monday 25/9/2006 11:08, Jon Ribbens wrote: >> > What precisely do you think it would "break"? existing code, and existing tests. >>> I'm sorry, that's not good enough. How, precisely, would it break >>> "existing code"? Can you come up with an example, or even an >>> explanation of how it *could* break existing code? >> FWIW, a *lot* of unit tests on *my* generated html code would break... > > Why did you write your code that way? Stop feeding the troll. -- http://mail.python.org/mailman/listinfo/python-list
Re: does anybody earn a living programming in python?
walterbyrd skrev: > If so, I doubt there are many. > > I wonder why that is? Because you are ignorant? -- http://mail.python.org/mailman/listinfo/python-list
Re: A critique of cgi.escape
Jon Ribbens skrev: > In article <[EMAIL PROTECTED]>, Georg Brandl wrote: >>> I'm sorry, that's not good enough. How, precisely, would it break >>> "existing code"? Can you come up with an example, or even an >>> explanation of how it *could* break existing code? >> Is that so hard to see? If cgi.escape replaced "'" with an entity reference, >> code that expects it not to do so would break. > > Sorry, that's still not good enough. Why would any code expect such a > thing? Oh ... because you cannot see a use case for that *documented* behaviour, it must certainly be wrong? This funktion which is correct by current documentation will be broken by you change. def hasSomeWord(someword): import urllib f = urllib.open('http://www.example.com/cgi_escaped_content') content = f.read() f.close() return '"%s"' % someword in content: You might think that it is stupid code that should be changed to take escaped quotes into account. But that is really not your bussines to decide if the other behaviour is documented and correct. I find it amazing that you cannot understand this. I will stop replying in this thread now. Max M -- http://mail.python.org/mailman/listinfo/python-list
Re: A critique of cgi.escape
Jon Ribbens skrev: > In article <[EMAIL PROTECTED]>, Fredrik Lundh wrote: >>> There's nothing to say that cgi.escape should take them both into account >>> in the one function >> so what exactly are you using cgi.escape for in your code ? > > To escape characters so that they will be treated as character data > and not control characters in HTML. > >>> What precisely do you think it would "break"? >> existing code, and existing tests. > > I'm sorry, that's not good enough. How, precisely, would it break > "existing code"? Can you come up with an example, or even an > explanation of how it *could* break existing code? Some examples are: - Possibly any code that tests for string equality in a rendered html/xml page. Testing is a prefered development tool these days. - Code that generates cgi.escaped() markup and (rightfully) for some reason expects the old behaviour to be used. - 3. party code that parses/scrapes content from cgi.escaped() markup. (you could even break Java code this way :-s ) Any change in Python that has these consequences will rightfully be considered a bug. So what you are suggesting is to knowingly introduce a bug in the standard library! You are right that the html generated by cgi.escape() would (probably) have the same visual appearence in the browsers. But that is a *very* narrow definition of being bug free and not breaking stuff. If you cannot think of other examples for yourself where your change would introduce breakage, you are certainly not an experienced enough programmer to suggest changes in the standard lib! Max M -- http://mail.python.org/mailman/listinfo/python-list
Re: A critique of cgi.escape
Fredrik Lundh skrev: > Jon Ribbens wrote: >> By the way, if you could try and put across your proposed arguments as >> to why you don't favour this suggested change without the insults and >> general rudeness, it would be appreciated. > > I've already explained that, but since you're convinced that your use > case is more important than other use cases, and you don't care about > things like stability and respect for existing users of an API, nor > the cost for others to update their code and unit tests, I don't see > much need to repeat myself. Breaking things just because you think > you can simply isn't the Python way of doing things. This thread is highly entertaining but perhaps not that productive. Lawrence is right that the escape method doesn't work the way he expects it to. Rewriting a library module simply because a developer is surprised is a *very* bad idea. It would break just about every web app out there that uses the escape module and uses testing. Which is probably most of them. That could mean several man years of wasted time. It also makes the escaped html harder to read for standard cases. Frederik is right that doing so is utterly ... well let us call it "unproductive". Stupid is such a harsh word ;-) Whether someone finds the bloat miniscule and thus a small enough change to warrant the rewrite does not really matter. Lawrence is free to write a wrapper and use that instead. my_escape = lambda st: cgi.escape(st, 1) So. Lawrence is happy, and the escape works as expected. Several man years has been saved. Max M -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with email.Generator.Generator
Chris Withers wrote: > Max M wrote: >> From the docs: >> >> """ >> The payload is either a string in the case of simple message objects >> or a list of Message objects for MIME container documents (e.g. >> multipart/* and message/rfc822) >> """ > > Where'd you find that? I must have missed it in my digging :-S End of third paragraph: http://docs.python.org/lib/module-email.Message.html -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with email.Generator.Generator
Chris Withers wrote: > Chris Withers wrote: >> print msg.as_string() >> >> MIME-Version: 1.0 >> Content-Type: text/plain; charset; charset="utf-8" > ^^^ > Actually, even this isn't correct as you can see above... > >> charset = Charset('utf-8') >> msg = MIMEText('','plain',None) >> msg.set_payload(u'Some text with chars that need encoding:\xa3',charset) > Has no-one ever successfully generated a correctly formatted email with > email.MIMEText where the message includes non-ascii characters?! What is the problem with encoding the message as utf-8 before setting the payload? That has always worked for me. pl = u'Some text with chars that need encoding:\xa3'.encode('utf-8') msg.set_payload(pl ,charset) From the docs: """ The payload is either a string in the case of simple message objects or a list of Message objects for MIME container documents (e.g. multipart/* and message/rfc822) """ Message objects are always encoded strings. I don't remember seeing that it should be possible to use a unicode string as a message. The charset passed in set_payload(pl ,charset) is the charset the the string *is* encoded in. Not the charset it *should* be encoded in. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: sending emails using python
sridhar wrote: > iam having user account on an exchangeserver. > with that can i send an email using python? > > if iam using the following code iam getting error > > > fromAddress = '[EMAIL PROTECTED]' > toAddress = '[EMAIL PROTECTED]' > msg = "Subject: Hello\n\nThis is the body of the message." > import smtplib > server = smtplib.SMTP("hstmsg002",25) > server.sendmail(fromAddress, toAddress, msg) Do yourself a favor and use the email module to construct your messages with. Constructing messages by hand can lead you into so many traps. Especially if you are using international characters in you messages. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: The lib email parse problem...
叮叮当当 wrote: > this is not enough. > > when a part is mulitpart/alternative, i must find out which sub part i > need, not all the subparts. so i must know when the alternative is > ended. Have you tried the email module at all? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Two Classes In Two Files
[EMAIL PROTECTED] wrote: > I just started working with Python and ran into an annoyance. Is there > a way to avoid having to use the "from xxx import yyy" syntax from > files in the same directory? I'm sure it's been asked a million times, > but I can't seem to find the answer. Probably none that are better. 1: import one class Two(one.One) 2: put both classes in the same file. It's just the way it is. Why worry about it? > For example, I have two classes stored in separate files as such. > > File: one.py > > class One: > def methodA(self): > print "class One" > def methodB(self): > print "class One" > > > File two.py > > from one import One > > class Two(One): > def methodA(self): > print "class Two" > > if __name__ == "__main__": > x = Two() > x.methodA() > x.methodB() > > When I run the Two.py file, I get the expected output but I'd like to > eliminate the from line in two.py. > -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: A game idea.
defcon8 wrote: > I have had what I think is quite a nice game idea, but I don't really > have the experience or knowledge to go about it. Would anyone be > willing to start a game project? Ideas are a dime a dozen. Implementation is the hard part. If you want something done, you will have to do it yourself. I am not trying to be negative, but I will bet you that every competent programmer on the list has 1+ project that she would love to do, if she just had the time. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is fun (useless social thread) ;-)
bruno at modulix wrote: > Max M wrote: >> bruno at modulix wrote: >> >>>> Or did you just like what you saw and decided to learn it for fun? >>> >>> Well, I haven't be really impressed the first time - note that it was at >>> the very end of the last century, with v1.5.2. >> >> >> 1.5.2 was an excellent version. Not really that different in use than >> current version. > > Nope, "not really that different" - we were just missing list-comps, > generators, new-style classes, classmethods, staticmethods, usable > metaclasses, descriptors, @decorators sugar, extended slices, and a few > other goodies coming in 2.5 like coroutines and with: statement... I wrote "different in use". Which is not the same as saying it has not changed. The general feel of coding in Python is exactly the same to me. I believe that most of those changes you mention are rarely used by most programmers. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is fun (useless social thread) ;-)
bruno at modulix wrote: >> Or did you just like what you saw and decided to learn it for fun? > > Well, I haven't be really impressed the first time - note that it was at > the very end of the last century, with v1.5.2. 1.5.2 was an excellent version. Not really that different in use than current version. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Variable name has a typo, but code still works. Why?
mateus wrote: > print "hello world" > > I have a nested loop where the outer loop iterates over key value pairs > of a dictionary and the inner loop iterates over a list each list of > which is a mapped value from the dictionary > > def showReport(self): > for dev, sessions in self.logger.items(): > for tree in session: > self.addTestItem(self, tree) > > What I don't understand is why this executes w/o any problems when > "sessions" was spelled as plural (sessionS) while later being spelled > in the singular (session). > > Is there some type of name resolution of local variables where Python > makes assumptions? No. You are probably running your script in an ide that keeps an old variable hanging around. Try it from a command promt. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Best Python Editor
Manoj Kumar P wrote: > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. pydev on top of eclipse is a nice tool. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: John Bokma harassment
John Bokma wrote: > [EMAIL PROTECTED] wrote: > Your first question should be: Is it alright that Xah harasses 5 > newsgroups? Or maybe work on your spelling, harass is with one r, but > maybe you didn't read the subject, which wouldn't amaze me, since you > sound like you should be spending time on MySpace OMG!. I assume that the single l in alright is the courteous misspelling that should allways be in a posting, when correcting other peoples speling? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: send an email with picture/rich text format in the body
Scott David Daniels wrote: > Max M wrote: > >> 90% of users are non-technical users who use standard email readers, >> that can easily read html messages. >> >> In my experience the kind of user that receives emails with html and >> pictures often prefer it that way. >> >> So why bother with the lecture? I cannot remember when I have last >> received a relevant email that I could not read in text mode. > > > Because > (A) This _is_ a technical newsgroup with mores you are violating. *I* am? How? By disagreeing on how technology should be used? > (B) Some of us "technical users" avoid such email/news readers > precisely because they can cause tracking across the web. Yes but some times it's just simpler to send formatted text and images. I also use text only email. But I don't believe everybody else has to. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: send an email with picture/rich text format in the body
Ben Finney wrote: > "anya" <[EMAIL PROTECTED]> writes: > > >>Acctualy there is a solution: >>see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810 > > > Again, sending anything but plain text as the message body ensures > that your message is unreadable to a large number of people using a > variety of software. It's your choice whether to restrict your > audience in this way, but know that that's what you're doing. 90% of users are non-technical users who use standard email readers, that can easily read html messages. In my experience the kind of user that receives emails with html and pictures often prefer it that way. So why bother with the lecture? I cannot remember when I have last received a relevant email that I could not read in text mode. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime: the date of the day one month ago...how?
gabor wrote: > hi, > > i'm trying to get the date of the day one month ago. > > for example: > > today = 12.apr.2006 > one-month-ago = 12.mar.2006 > > so: > > one-month-ago(12.apr.2006) = 12.mar.2006 > > of course sometimes it gets more complicated, like: > > one-month-ago(31.mar.2006) > > or > > one-month-ago(1.jan.2006) > > the datetime.timedelta objects only work with hours or days or weeks, > not month (i understand why)... > > but is there a way to calculate this in python? > > i really don't want to calculate it by myself :-)) It is application specific. So how *do* you want one-month-ago(31.mar.2006) or one-month-ago(28.feb.2006) to work? No one can know but you. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Difference between 'is' and '=='
Joel Hedlund wrote: >> There's no requirement that the socket module or >> anything else return values using the same object that the >> socket.AF_UNIX constant uses. > > > Ouch. That's certainly an eyeopener. > > For me, this means several things, and I'd really like to hear people's > thoughts about them. > > It basically boils down to "don't ever use 'is' unless pushed into a > corner, and nevermind what PEP8 says about it". Identity checks are often used for checking input parameters of a function: def somefunc(val=None): if val is None: val = [] do_stuff(val) Or if None is a possible parameter you can use your own object as a marker:: _marker = [] def somefunc(val=_marker): if val is marker: val = [] do_stuff(val) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Difference between 'is' and '=='
mwql wrote: > Hey guys, this maybe a stupid question, but I can't seem to find the > result anywhere online. When is the right time to use 'is' and when > should we use '=='? "is" is like id(obj1) == id(obj2) >>> 100+1 == 101 True >>> 100+1 is 101 False They don't have the same id. (Think of id as memory adresses.) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: doctest, unittest, or if __name__='__main__'
[EMAIL PROTECTED] wrote: >>and you can kill two birds with one stone. > > > By that, do you mean you can write your tests and your > docstrings in one shot with doctest? Exactly. >>> '\n'.join(['Doctests are absolutely brilliant!'] * 100) They combine two brilliant ideas that are hard to do in practice. "Testing" and "Literate Programming" In the process it even manages to make both a lot easier. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Markov process representation
Jack Diederich wrote: > On Wed, Mar 15, 2006 at 04:50:31PM -0800, Paul Rubin wrote: > >>"kpp9c" <[EMAIL PROTECTED]> writes: >> >>>self._all_states |= set(key[i] for key in probabilities) >>>I am running: >>>Python 2.3 (#1, Sep 13 2003, 00:49:11) >> >>generator comprehensions are new in 2.4. Try: >> >> self._all_states |= set([key[i] for key in probabilities]) > > > And sets aren't a builtin in 2.3 > > try: > set() > except NameError: > import sets > set = sets.Set nitpick: try: set except NameError: from sets import Set as set -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: MS word document generator
Raja Raman Sundararajan wrote: > I was wondering if there was any library as reportlab to generate word > documents. If you are on Windows, why dont you use word for it? You can call it from Python. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Cheese Shop: some history for the new-comers
A.M. Kuchling wrote: > On Sat, 11 Mar 2006 16:50:26 +1100, > richard <[EMAIL PROTECTED]> wrote: > >>So I did what people always do in this situation, I asked Barry Warsaw to >>name. it. And he did, "Cheese Shop". I liked the name, so it was done. When >>the new pydotorg machines went live last year, so too did the name >>cheeseshop.python.org > > > Given the endless whiny complaints about the name, though, I think we > should just give up and go back to PyPI (pronounced 'Pippy'). When short obscure names are bad in programming, whay are they good in general communication. "Python Packages" is too obvious perhaps? When we start using eggs will it then be renamed to "Dairy Shop" or perhaps "Daisy" to make it obscure? Or the "Chickens Nest"? Please. If it is meant to be used and understood, both Cheeseshop and Pypi are bad names. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Hashtables in pyhton ...
Konrad Mühler wrote: > Hi, > > are there predefinded chances to use hashtables in python? How can I use > Hashtable in python? Or do I have to implement this on my own? >>> a_hash_is_a_dict = {'key':'value'} >>> a_hash_is_a_dict['key2'] = 'value 2' >>> a_hash_is_a_dict['key'] 'value' -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 -- http://mail.python.org/mailman/listinfo/python-list
Re: PyCon2006 - will the content be available for download?
John Salerno wrote: > Max M wrote: > >> abcd wrote: >> >>> well actually, the site looked promising...only problem is no talks >>> have audio, video or handouts available (at least right now). >>> >>> oh well. >>> >> >> You really need to not give up so fast. >> >> http://us.pycon.org/talks >> >> makes it possible to search those with audio (TalkFlags - audio-yes): >> >> http://us.pycon.org/zope/talks/talksRoster?year%3Alist=&day%3Alist=&track%3Alist=&title=&authors=&abstract=&flags%3Alist=audio-yes&order=Sequence >> >> >> >> Then most presentations with audio has several audio formats you can >> download. >> > > I tried it too. There don't seem to be any audios for 2006, which I > think is what the OP was interested in as well. You are right, I am wrong -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: PyCon2006 - will the content be available for download?
abcd wrote: > well actually, the site looked promising...only problem is no talks > have audio, video or handouts available (at least right now). > > oh well. > You really need to not give up so fast. http://us.pycon.org/talks makes it possible to search those with audio (TalkFlags - audio-yes): http://us.pycon.org/zope/talks/talksRoster?year%3Alist=&day%3Alist=&track%3Alist=&title=&authors=&abstract=&flags%3Alist=audio-yes&order=Sequence Then most presentations with audio has several audio formats you can download. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: PyCon2006 - will the content be available for download?
abcd wrote: > Anyone know if (and when) the talks from PyCon2006 will be available > for download. I am particularly interested in the tutorials (as they > did not have them at PyCono2005). > > Thanks. > http://www.python.org/community/pycon/ leads to http://us.pycon.org/AudioVideoRecording/HomePage -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
Brian Elmegaard wrote: > "Matt Hammond" <[EMAIL PROTECTED]> writes: > > >>y_max = max([e.x for e in y]) > > > Would there be a way to refer back to the e with maximum x, or how > could I find other attributes of it? In that case a common idiom is to "decorate" decorated = [(obj.x, obj) for obj in objects] max_decorated = max(decorated) max_obj = max_decorated[-1] Or to run through it "old style" max_obj = objects[0] for obj in objects: if obj.x > max_obj.x: max_obj = obj Readbility is about the same I think. Testing should tell you which is faster in your case. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
Brian Elmegaard wrote: > Hi, > > I am struggling to understand how to really appreciate object > orientation. I guess these are FAQ's but I have not been able to find > the answers. Maybe my problem is that my style and understanding are > influenced by matlab and fortran. > What I hoped I could do: > class Foo: > def __init__(self,self.x): > continue > y=[] > y.append(Foo(10.0)) > y.append(Foo(110.0)) > y.append(Foo(60.0)) > > ys=([y[].x]) > y_max=max(y[].x) > y_min=min(y[].x) > > yz=[y[:-1].x-y[1:].x] It is hard to tell what you are trying to do here. But here is a shot at parts of the code. class Foo: def __init__(self, x): self.x = x y = [Foo(10.0), Foo(110.0), Foo(60.0)] x_values = [o.x for o in y] y_max = max(x_values) y_min = min(x_values) Otherwise you could try and describe with words what you are getting at. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
Comparing: http://www.python.org/ http://www.perl.org/ http://www.java.org/ http://www.ruby-lang.org/en/ http://java.sun.com/ http://www.php.net/ It is pretty easy to see that http://www.python.org/ is both prettier than the rest, and has a far better structure. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
projecktzero wrote: > I think the new site is great. I really don't understand all the nit > picking that's going on from the armchair web designers. It's a nice site. It is not ugly, and its easy to navigate. *much* better than the old site, -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: groupwise send mail
[EMAIL PROTECTED] wrote: > Can someone give me an idea as to why this is not working? The > Recipients.Add line doesnt cause an error, but my recipients arent > being used. The email never gets sent because there is no recipeients. > > Thanks, > Eric > > > import win32com.client > gwApp = win32com.client.Dispatch('NovellGroupWareSession') > acct1 = gwApp.Login("NDS:\\Tree_Name","user.context", "") > oMail = acct1.MailBox.Messages.Add ("GW.Message.Mail", "Draft") > oMail.fromtext = "Python Hazmat Script" > oMail.Recipients.Add("[EMAIL PROTECTED]") > oMail.Subject.PlainText = "Script error" > oMail.BodyText.PlainText = "The Python Hazmat script failed" > oMail.send > gwApp.quit > Methods must allways have a () in Python to be called > oMail.send() > gwApp.quit() Otherwise you are just adressing the objects eg. this is perfectly ok: send = oMail.send send() or q = gwApp.quit q() -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Zope 3?? How do you start it on Windows?
kbperry wrote: > Call me crazy and stupid, but how do you start zope? I downloaded the > thing, installed it, and then nothing. I can find a stupid README.txt > that is useful. > > Can someone help?Please! Install Python 2.4 Install Zope 3 in that python by using setup.py Make a Zope instance with Python24\Scripts\mkzopeinstance.bat Start that instance by running /bin/runzope.bat -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Webmail with Python
Thomas Guettler wrote: > Hi, > > Is there an application like Squirrelmail[1] written in python? > > I want to access IMAP folder with a web-browser. > > Google shows me some dead projects. Most webmail applications > seem to be written in PHP. Is there a useable webmailer written > in python? This also requires Plone, so it might be a bit heavyweight for your needs: http://www.mxm.dk/products/public/mxmImapClient/ -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
python success story
I urged a friend from Boeing to use python on a personal project. He liked it and repeatedly urged a Boeing developer to use it. Python is on the list of approved languages at Boeing. The developer wrote a thousand line enterprise level program in Python. He reports that it would have take ten times the lines of code in another language. -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft IronPython?
EP wrote: > Luis M. González wrote: > >> Will Microsoft hurt Python? >> > I think it is naive to ignore the fact that Microsoft could hurt Python, > though there may be nothing anyone can do. > >> How? > > - create a more prevalent version of "Python" that is less Pythonic or > undermines some of the principles of the language, basically usurping First of they would need to make Python a strategic platform for corporations, so that it was used practically everywhere on Windows. Then it would have the powerbase to change the lanuage and make an incompatible version that they could control. As far as I can see C## has that role for them. So I don't see how Python should be in any danger. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Are there anybody using python as the script engine for ASP?
[EMAIL PROTECTED] wrote: > Hi everyone, I'm planning using python with asp, and wonder if some > people do use python/asp in real life projects. (I'm going to) I used to back in the days, and it was fine. A lot better than VBScript / JScript that was available then. Perhaps IronPython would be worth trying out, though a bit premature. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: MidiToText : EventDispatcher instance has no attribute 'sysex_events'
Carsten Haese wrote: > On Fri, 2005-12-30 at 09:52, tim wrote: > >>Trying to convert midi to text using MidiToText.py. >>I get the following: >> >>midi_port: 0 >>Traceback (most recent call last): >> File "MidiToText.py", line 176, in ? >>midiIn.read() >> File "C:\Python24\Lib\site-packages\midi\MidiInFile.py", line 24, in read >>p.parseMTrkChunks() >> File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 167, >>in parseMTrkChunks >>self.parseMTrkChunk() # this is where it's at! >> File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 129, >>in parseMTrkChunk >>dispatch.sysex_events(sysex_data) >>AttributeError: EventDispatcher instance has no attribute 'sysex_events' > > > Try changing "def sysex_event(self, data):" in > ...\midi\EventDispatcher.py to "def sysex_events(self, data):" Or just do a search and replace on the whole package:: search: sysex_events( replace: sysex_event( Apparently I have been inconsistent in my naming. New version at: http://www.mxm.dk/products/public/pythonmidi/download -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Midi Package: writing events non-chronologically
tim wrote: Someone using Python Midi Package from http://www.mxm.dk/products/public/ lately? I want to do the following : write some note events in a midi file then after doing that, put some controllers at the beginning of the midifile (because I want to be able to make those dependant on what notes were just written) def midctrls(): global roffset, melchan, roffset, gmt, timedisplay, out_file, midi, usednotes, n midi.reset_time() #seems to do nothing for cha in range(16): if cha==1: midi.abs_time=0 #seems to do nothing midi._relative_time = 0 #seems to do nothing, but I can imagine why midi._absolute_time = 0 #seems to do nothing midi.update_time(new_time=0, relative=0) #although I give the variable relative=0 it seems to be relative ? midi.continuous_controller(cha, 0, 122) (snip) With this code I want a controller number 0 with value 122 to be written at the beginning of my midifile. It is written at the end, how I move the writing position to the beginning? You should make a wrapper around the library that handles the midi events in a data structure. When your musical structure is then is complete, you use the midi library to write it to disk. I have attached a simple example here. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science # event classes. Only used internally by notes2midi class NoteOn: def __init__(self, time=0, pitch=64, velocity=64): self.time = time self.pitch = pitch self.velocity = velocity def __str__(self): r = [] a = r.append a('NoteOn') a('time %s' % self.time) a('pitch %s' % self.pitch) a('velocity %s' % self.velocity) return '\n'.join(r) def render(self, channel, mididevice): "Writes the event to a midi stream" mididevice.note_on(channel=channel, note=self.pitch, velocity=self.velocity) class NoteOff: def __init__(self, time=0, pitch=64, velocity=64): self.time = time self.pitch = pitch self.velocity = velocity def __str__(self): r = [] a = r.append a('NoteOff') a('time %s' % self.time) a('pitch %s' % self.pitch) a('velocity %s' % self.velocity) return '\n'.join(r) def render(self, channel, mididevice): "Writes the event to a midi stream" mididevice.note_off(channel=channel, note=self.pitch, velocity=self.velocity) def notes2midi(notes, midi): "Turns a list of notes into a midi stream" # notes have absolute time values!!! # first turn notes into events (split into note-on / note-off) events = [] for note in notes: on_event = NoteOn(note.time, note.pitch, note.velocity) events.append(on_event) off_event = NoteOff(note.time+note.duration, note.pitch, note.velocity) events.append(off_event) # sort them in order of time events.sort(lambda x,y: cmp(x.time, y.time)) # midi device writing # non optional midi framework midi.header() midi.start_of_track() midi.reset_time() absolute_time = 0 for event in events: delta_time = event.time - absolute_time absolute_time = event.time # write the data midi.update_time(delta_time) event.render(0, midi) midi.end_of_track() # non optional midi framework midi.update_time(0) midi.end_of_track() midi.eof() if __name__ == '__main__': from Pattern import Note # a short example using notes, with no limits to number of simultaneous voices # creates a list of ascending notes track = [ Note(time=24*i, pitch=64+i, velocity=127, duration=24) for i in range(16) ] ## # write the notes to the file from midi.MidiOutFile import MidiOutFile out_file = 'note-test.mid' midi = MidiOutFile(out_file) notes2midi(track, midi) -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
Yves Glodt wrote: > bruno at modulix wrote: > >> Yves Glodt wrote: >> >>> Hello, >>> >>> if I do this: >>> >>> for row in sqlsth: >>> pkcolumns.append(row[0].strip()) >>> etc >>> >>> >>> without a prior: >>> >>> pkcolumns = []; >>> >>> >>> I get this error on first iteration: >>> UnboundLocalError: local variable 'pkcolums' referenced before >>> assignment >>> >>> >>> I guess that's normal as it's the way python works...?!? Well you could do something like this. (Untested and unrecommended) self.__dict__.setdefault('pkcolumns', []).append(row[0].strip()) Personally I find pkcolumns = [] pkcolumns .append(row[0].strip()) to be nicer ;-) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending email in utf-8?
morphex wrote: > That works, kinda. I get strange characters now like this > > """ > Date: Mon, 7 Nov 2005 11:38:29 -0700 (MST) > Message-Id: <[EMAIL PROTECTED]> > To: [EMAIL PROTECTED], [EMAIL PROTECTED] > From: [EMAIL PROTECTED] > Subject: Order confirmation > Content-Type: text/plain; charset="utf-8" > X-Bogosity: No, tests=bogofilter, spamicity=0.00, version=0.92.8 > > Thank you for your order, it is copied here for your convenience, and > we will process it shortly. > > Name: ø > Phone: ø > Email: [EMAIL PROTECTED] > Comments: asdf > """ > > but at least it doesn't raise any errors. > This is a method I have clipped from one of my projects. It should pretty much cover everything you would want to do while sending mails. def Workgroup_mailFormAction(self, to=None, cc=None, bcc=None, inReplyTo=None, subject=None, body='', attachments=None, mfrom=None, REQUEST=None): """ Sends a message. Many of the input parameters are not currently used, but can be used for skinning the functionlity. """ site_encoding = self._site_encoding() ## # Create the message msg = Message() msg.set_payload(body, site_encoding) # # if attachment, convert to multipart # file fields are posted even if empty, so we need to remove those :-s if attachments is None: attachments = [] attachments = [a for a in attachments if a] if attachments: mimeMsg = MIMEMultipart() mimeMsg.attach(msg) for attachment in attachments: # Add the attachment tmp = email.message_from_string(str(attachment.headers)) filename = tmp.get_param('filename', 'Attachment', 'Content-Disposition') # clean up IE paths filename = filename[max(filename.rfind('/'), filename.rfind('\\'), filename.rfind(':') )+1:] contentType = tmp['Content-Type'] attach_part = Message() attach_part.add_header('Content-Type', contentType, name=filename) attach_part.add_header('Content-Disposition', 'attachment', filename=filename) attach_part.set_payload(attachment.read()) Encoders.encode_base64(attach_part) mimeMsg.attach(attach_part) msg = mimeMsg # set headers on message if to is None: to = [] if mfrom: to.append(mfrom) msg['From'] = mfrom msg['Reply-To'] = mfrom to = ','.join(to) if to: msg['To'] = to if cc is None: cc = [] cc = ','.join(cc) if cc: msg['Cc'] = cc if bcc is None: bcc = [] bcc = ','.join(bcc) if bcc: msg['Bcc'] = bcc msg['Date'] = self.ZopeTime().rfc822() # needed by some servers if inReplyTo: msg['In-Reply-To'] = inReplyTo msg['Subject'] = Header(subject, site_encoding) ## # Send the message SMTPserver = self._mailhost() success = 0 try: cleaner = lambda adresses: [adress.strip() for adress in adresses.split(',') if adress.strip()] all_receivers = cleaner(to) + cleaner(cc) + cleaner(bcc) all_receivers = list(set(all_receivers)) if all_receivers: # only send if any recipients self._mailhost().send(str(msg), mto=all_receivers, mfrom=mfrom) success = 1 except: pass -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Mike Meyer wrote: > There were studies done in the 70s that showed that programmers > produced the same number of debugged lines of code a day no matter > what language they used. So a language that lets you build the same > program with fewer lines of code will let you build the program in > less time. In my experience the LOC count is *far* less significant than the levels of indirections. Eg. how many levels of abstraction do I have to understand to follow a traceback, or to understand what a method relly does in a complex system. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: How to do *args, **kwargs properly
Lasse Vågsæther Karlsen wrote: > Max M wrote: > So what you're saying is that instead of: > > def fn(*values, **options): > > I should use: > > def fn(values, cmp=cmp): > > in this specific case? > > and then instead of: > > fn(1, 2, 3, cmp=...) > > this: > > fn([1, 2, 3], cmp=...) Precisely. Sometimes you need different interfaces for a method. In that case it is fine. But if you are just doing it instead of passing sequences, you are just (ab)using the * and ** operators. The method definition, like any python code, is made for humans not machines. The more obvious you can make the function definition, the happier anyone will be. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: How to do *args, **kwargs properly
Lasse Vågsæther Karlsen wrote: > I must be missing something but what is the proper way to do a function > using such arguments ? > - ability to take an unspecified number of "positional arguments" You should probably pass a sequence to the method instead. You can do it the other way, but it's poor coding style in most cases. > - ability to take optional named arguments that follows the first arguments Setting the default value to a value that cannot exist as an argument is the normal way. Eg. None. def fn(vals, cmp=None) > - raise appropriate errors if I use the wrong named arguments def fn(*values, cmp=None): if cmp is None: raise TypeError, "'%s' is an invalid keyword argument for this function" % key If you insist on doing it the other way: FN_LEGAL_ARGS = set( ('cmp',) ) def fn(*values, **options): for key in options.keys(): if not key in FN_LEGAL_ARGS: raise TypeError, "'%s' is an invalid keyword argument for this function" % key -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Windows installer, different versions of Python on Windows
I would like to install several copies of Python 2.4.2 on my machine, but it doesn't seem to be possible. If I allready has a version installed, the installer only gives the options to: - change python 2.4.2 - repair python 2.4.2 - remove python 2.4.2 I would like to install different versions of Zope 3, and since it is installed under a specific python version, the simplest solution would be to install several Python versions, and install a different zope3 version under each python install. Have I misunderstood something here? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Python reliability
Ville Voipio wrote: > In article <[EMAIL PROTECTED]>, Paul Rubin wrote: > >>I would say give the app the heaviest stress testing that you can >>before deploying it, checking carefully for leaks and crashes. I'd >>say that regardless of the implementation language. > > Goes without saying. But I would like to be confident (or as > confident as possible) that all bugs are mine. If I use plain > C, I think this is the case. Of course, bad memory management > in the underlying platform will wreak havoc. Python isn't perfect, but I do believe that is as good as the best of the major "standard" systems out there. You will have *far* greater chances of introducing errors yourself by coding in c, than you will encounter in Python. You can see the bugs fixed in recent versions, and see for yourself whether they would have crashed your system. That should be an indicator: http://www.python.org/2.4.2/NEWS.html -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: New project coming up...stay with Python, or go with a dot net language??? Your thoughts please!
spiffo wrote: > The Main Issue in a nutshell > > I am a corporate developer, working for a single company. Got a new project > coming up and wondering if I should stay with Python for this new, fairly > large project, are jump back on the 'safe' M$ bandwagon using a dot net > language? Hehe ... I can run my very first Python program right now in the current version of Python. I cannot even find a platform to run my .asp code from that same timeframe ... So much for 'safe'! -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Where to find python c-sources
Erik Max Francis wrote: > Tor Erik Sønvisen wrote: > >> I need to browse the socket-module source-code. I believe it's >> contained in the file socketmodule.c, but I can't locate this file... >> Where should I look? > > The source tarball, available on python.org. Are people really too lazy > to do elementary research on Google? Don't know, have you checked Google? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from unicode to int
Tor Erik Sønvisen wrote: > Hi > > Is there any simpler way to convert a unicode numeric to an int than: > > int(u'1024'.encode('ascii')) why doesn't: int(u'104') work for you? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: C#3.0 and lambdas
Steven D'Aprano wrote: > On Mon, 19 Sep 2005 10:31:48 +0200, Fredrik Lundh wrote: > > How many items should you pass in the tuple? If it takes variable > arguments, then that works, but if you always expect a fixed number, then > > def func((x, y)) > > is more explicit. > > The only problem I have is that once you unroll the tuple like that, it is > hardly necessary to pass the argument as a tuple. Why not just pass x and > y as two arguments? > > def func(x, y) why not just pass the tuple as arguments then? def func(*(x, y)) or as it would normally look: def func(*arg) That should work just as well for those cases. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary to file
Enrique Palomo Jiménez wrote: > Hi all, > > I'm writing an application who needs to handle a lot of information of > several files. > So, i think the better way is design a batch process to catch that > information in a dictionary and write it in a file. > So, after that when a user wants to retrieve something, only with an execfile > i'll have all the information avaiable. > > Creating the file with pythonic syntax will be a hard job so, > > is there some module to do that? > is there a better way? You can easily pickle a dictionary and save that to a file. http://docs.python.org/lib/module-pickle.html -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: IDE, widget library
[EMAIL PROTECTED] wrote: > I like to use Eclipse with the Pydev plugin which is quite good and is > cross-platform. I have used those on Windows for about 3 weeks now, and I must say that the switch has been allmost completely painless. I have only good things to say about it. I can see that my Java process takes up about 80 MBytes, so it is a bit of a hog. But who cares... isn't 1 GB getting to be the standard these days? I have a 1 GHz machine, and the IDE is plenty fast. It has a few idiosyncrasies that needs to be learned, but I guess that Emacs has more ... Good job on pydev! -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: brain cramp: emulating cgi.FieldStorage
Chris Curvey wrote: > I can't be the first person to want to do this, but I also can't seem > to find a solution. (Perhaps my Google skills are poor today.) How > can I emulate cgi.FieldStorage() for my unit tests so that I don't have > to put a web server in the way? > > what I'd like to do is something like > > fs = cgi.FieldStorage() > fs["foo"] = "bar" > functionToBeTested(fs) > > Any hints/leads/suggestions? Can't you just pass the FieldStorage some dummy data to parse? It looks pretty simple. class FieldStorage: def __init__(self, fp=None, headers=None, outerboundary="", environ=os.environ, keep_blank_values=0, strict_parsing=0): """Constructor. Read multipart/* until last part. Arguments, all optional: fp : file pointer; default: sys.stdin (not used when the request method is GET) headers : header dictionary-like object; default: taken from environ as per CGI spec outerboundary : terminating multipart boundary (for internal use only) environ : environment dictionary; default: os.environ keep_blank_values: flag indicating whether blank values in URL encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. """ -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PyDev 0.9.8 released
Fabio Zadrozny wrote: > Hi Max, > > I may be a little (or maybe a lot) biased for it (as I'm its > maintainer), but as I do 'eat my own dogfood', I though I might share it > with you... Enthusiasm doesn't disqualify ;-) > At my company, everybody that programs with python switched to pydev. > Most people used 'highly customized' text-editors before pydev, as the > company does not enforce one ambient for all... still, everybody changed > to pydev, coming from vi, scintilla, komodo... and we have some really > big projects (my current ambient has about 400 python modules, all > managed in pydev). Also, there are no current bug reports for any > instability in pydev. Ok. I am starting a new product for Plone tomorrow, that should take about a week to finish. I will try switching cold-turkey to pydev and see how it goes. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PyDev 0.9.8 released
Fabio Zadrozny wrote: > Hi All, > > PyDev - Python IDE (Python Development Enviroment for Eclipse) version > 0.9.8 has just been released. I read this, and thought it was time to check out both Eclipse, end the pydev plugin. I got it all installed, along with a subversion plugin for eclipse, and it actually seems like a very sweet combo. I was afraid that a Java based editor would be sluggish. But it doesn't seem so. There are a few nice features too with a file navigator, refactoring, code folding and more. So I have decided to give it a try. But before commiting to it, I just wondered what experiences other users might have when using it for production. Being that my text editing environment is my bread and butter. Is it stable/effective etc? Anybody cares to share? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Unix diff command under Window.
TonyHa wrote: > Hello, > > Does any one have using Python to write a Unix "diff" command for > Window? I generally just us the diff built into tortoiseSVN. That way it's only a rightclick away. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: mail sending using telnet in python
praba kar wrote: > Dear All, > Normally we can send mail using > telnet in linux. In the following way > Is it possible to run same thing same manner > in python? If possible kindly help me with > specimen code. Actually I gone through > telnetlib module documentation but I cann't > get solution for it. Why not just use the smtp module? It's a tad easier. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: f*cking re module
jwaixs wrote: > arg... I've lost 1.5 hours of my precious time to try letting re work > correcty. There's really not a single good re tutorial or documentation > I could found! There are only reference, and if you don't know how a > module work you won't learn it from a reference! If you want to try out re interactively you could use: \Tools\Scripts\redemo.py -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: What are the other options against Zope?
phil wrote: > Peter Hansen wrote: > Now understand, I know what very well what Python, Apache, PhP, > MySQL, IE and javascript do. I just don't know what Zope > does. > > And if the answer is going contain phrases like "brings together" > or "sits on top of", don't bother. :-) It's an object oriented database, with a structure that is similar to files and directories in an ordinary OS. But it is a lot smarter, because the files and directories are actually objects with different attributes and parameters. The methods on these objects can then be called eg. from a web browser with different parameters. But you can also use other protocols than http like dav, ftp etc. This is a very effective way to build web applications, and does not need sql-object remapping as normal web apps does. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Modules for inclusion in standard library?
Reinhold Birkenfeld wrote: > Hello, > > Do you have any other good and valued Python modules that you would think are > bug-free, mature (that includes a long release distance) and useful enough to > be granted a place in the stdlib? > > For my part, ctypes seems like a suggestion to start with. ctypes certainly. Even though it can crash Python. People using ctypes would be aware of this. Another good bet is BeautifulSoup, which is absolutely great for scraping content from webpages. http://crummy.com/software/BeautifulSoup/index.html -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Boss wants me to program
phil wrote: > You would be wise, if you choose Python to choose Tkinter or WxWindows > and learn the properties of a radio button and how to trigger events. > Writing simple GUIs is not that hard. Then after you know what is > going on behind the scenes, a BOA Constructor will not be as > mysterious or dangerous. I agree. The language is more important than the gui. It is not very hard to make good applikations in eg. Tkinter, and you will understand evey part of it. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: \r\n or \n notepad editor end line ???
[EMAIL PROTECTED] wrote: > Hello, > > I use windows notepad editor to write text. > > For example I write (in d:\myfile.txt): > Helo > World > > If I open it with python: > FName = open(d:\myfile.txt,'r') > h = FName.readlines() > print h > > I get h : ['Helo\n', 'World'] > > I thought notepad use \r\n to to end the line. > > What's wrong with it? Python tries to be clever. Open it in binary mode to avoid it: FName = open(d:\myfile.txt,'rb') -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: how to export data from ZODB to text files
ls wrote: > I'm experienced mostly in C, PHP, also with some backgrounds of CPP > and Java, but I'm totaly new in Python ... > > What do you suggest in this case? The simplest approach is to run Zope with the Data.fs file. If you have access to the zope instance you want to export from, you only need to write an external method in Zope to export the data you want. Its pretty easy that way. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: The need to put "self" in every method
Aahz wrote: > [posted & e-mailed] > Any objection to swiping this for the FAQ? (Probably with some minor > edits.) I think it is missing the most important reason, that functions can act as unbound methods. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: The need to put "self" in every method
Terry Hancock wrote: > def __add__(a,b): > return Vector((a.x+b.x), (a.y+b.y), (a.z+b.z)) > > or something like that. I still have twinges of guilt about it, > though, and I had to write a long note in the comments, apologizing > and rationalizing a lot. ;-) Assigning self to a could have made it obvious: def __add__(self, b): a = self return Vector((a.x+b.x), (a.y+b.y), (a.z+b.z)) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Markov chain with extras?
[EMAIL PROTECTED] wrote: I want to use it for music. So given list 1 (melody), list 2 (chords) could be generated by a Markov chain. Also, given the chords the melody could be generated again by a chain. I have this small module, that can be used for markov chains. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science from random import random, randint from bisect import bisect class Randomizer: "Various stochastic methods" def inverse_scale(self, rng): "Returns a list of probablitites corresponding to 1/i in range" return [1.0 / (i + 1.0) for i in range(rng)] def n_scale(self, rng, n=2.0): "Returns a list of probablitites corresponding to i/n" n_scale = [] value = 1.0 for i in range(rng): value /= n n_scale.append(value) return n_scale class Selector: "Returns random elements by probability according to their frequency" def __init__(self, frequencies, elements): self.sum = sum(frequencies) acumulated_frequencies = [] acumulated_frequency = 0 for frequency in frequencies: acumulated_frequency += frequency acumulated_frequencies.append(acumulated_frequency) self.decorated = zip(acumulated_frequencies, elements) self.decorated.sort() def get(self): "Randomly returns an element by probability" rnd = random() * self.sum index = bisect(self.decorated, (rnd, 0)) return self.decorated[index][-1] def get_range(self, n): "Randomly returns a range of elements by probability" return [self.get() for itm in xrange(n)] class MarkovIn: """ Implements a Markov chain for arbitrary objects. The objects has same rules as dictionary keys to be valid. """ def __init__(self, key_size=1): """ key_size: how many steps in the chain """ self.key_size = key_size self.in_history = [] self.chain = {} def _update_chain(self, obj): "Puts the object into the chain" # shortcuts ch = self.chain # update the chain key = tuple(self.in_history) stat = ch.setdefault(key, {}) ch[key][obj] = stat.setdefault(obj, 0) + 1 def _update_history(self, obj): "Updates the history" his = self.in_history his.append(obj) if len(his) > self.key_size: his.pop(0) def add_object(self, obj): "Adds an object to the chain" self._update_chain(obj) self._update_history(obj) def reset(self): "Resets the history" self.in_history = [] class MarkovOut: """ A Markov Chain wrapper. Generates a "random walk" from a markov chain. It is a seperate object for performance reasons. """ def __init__(self, markov): """ markov: A populated MarkovIn object """ self.markov = markov self.key_size = markov.key_size self.out_history = [] # Set up a cache of selector objects selectors = {} ch = self.markov.chain for key in ch.keys(): m = ch[key] selectors[key] = Selector(m.values(), m.keys()) self.selectors = selectors def _update_history(self, obj): "Updates the history" his = self.out_history his.append(obj) if len(his) > self.key_size: his.pop(0) def step(self): "A 'random' step from the chain, returns an object" his = self.out_history key = tuple(his) obj = self.selectors[key].get() # keep track of history self._update_history(obj) new_key = tuple(his) self.handle_step(obj) if not self.selectors.has_key(new_key): # reset history and start over self.out_history = [] self.restart() def handle_step(self, obj): "Handles a single step" self.steps.append(obj) def do_walk(self, steps=1): "returns A 'probable' walk" self.steps = [] for itm in xrange(steps): self.step() def get_walk(self): "Returns the walk" return self.steps def _reset(self): "Resets the history" self.out_history = [] def restart(self): "A hook for when a walk restarts" pass if __name__ == '__main__': f = open('input.txt') text = f.read() lines = text.split('\n') mi = MarkovIn(1) for line in lines:
Re: Merging overlapping spans/ranges
Jim Sizelove wrote: Wow! c.l.py is allmost like an AI program generator. But I guess it helps to ask questions about problems that programmers find interresting :-) The "linear" approach is pretty simple to code and understand. I am just afraid what happens when many users tries to book that 14 day conference in the calendar sometimes this year. 365 * 24 * 60 = 525,600 booleans in the array Well ok a few MBytes ain't too bad on a modern machine. It would even be possible to cut the resolution down to 15 minutes. Yielding 35,040 bools, but the solution is still O^2 with regards to size of "search window" and number of events. Bengts/Jims and Jordans solutions seems to be relatively similar. I will use one of those instead of my own code. Thanks! -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list