Re: File read-write mode: problem appending after reading

2006-10-16 Thread Frederic Rentsch
Tim Peters wrote:
> [Frederic Rentsch]
>   
>>   Thanks a lot for your input. I seemed to notice that  everything
>> works fine without setting the cursor as long as it stops before the end
>> of the file. Is that also a coincidence that may not work?
>> 
>
> "if you want to read following a write, or write following a read, on
> the same stream, you must perform a file-positioning operation
> (typically a seek) between them"
>   
I appreciate the clarification. Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


command text parsing and hints displaying on user input.

2006-10-16 Thread Andy
Hi guys,

I'm writing a program with a feature of accepting user input as command
text and parsing it to correct function calls...example:

"5 minutes later"/"5 min later"/"5 minute later"/"after 5 minutes"...
are being parsed as the same rule so the system will call a later
function with minutes=5 as parameter.

Of course there are many other possiblilities, "seconds"/"days", and
even "every(each) hour"/"every Monday"/"every two days"...so on...

The datetime computation can be done with the wonderful "dateutil"
package, but I'm not sure with the command text parsing part. I could
do a lot of regular expression, but it'll be great if there is already
something similar available...or even a hint that can make it easier
than hand-writing a lot of regular expression code...

Another requirment is to display useful hints when user input the
command text. Example:

user input:"5" -> hints: "5 minutes later/5 hours later/5 days
later/every 5 minutes"
user input:"fi" -> hints: "next Friday"/"first thing tommorrow"
user input:"ne" -> hints: "next day"/"next hour"/"next week"/"next
month"

Sounds too intelligent to do? Any advices on this?

Thanks guys.

Andy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send E-mail without an external SMTP server ?

2006-10-16 Thread Leo Kislov


On Oct 15, 10:25 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I just want to send a very simple email from within python.
>
> I think the standard module of smtpd in python can do this, but I
> haven't found documents about how to use it after googleing. Are there
> any examples of using smtpd ? I'm not an expert,so I need some examples
> to learn how to use it.

smtpd is for relaying mail not for sending. What you need it a dns
toolkit (search cheeseshop) to map domain name to list of incoming mail
servers, and then using stdlib smtplib try to submit the message to
them.

> Or maybe there is a better way to to this?

This won't work if you're behind a strict corporate firewall or if ISP
is blocking port 25 outgoing connections. In those cases you _have_ to
use an external mail server.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: What's up with the starship?

2006-10-16 Thread rurpy

George Sakkis wrote:
> [EMAIL PROTECTED] wrote:
> > Robert Hicks wrote:
> > > [EMAIL PROTECTED] wrote:
> > > > T. Bryan wrote:
> > > > > starship.python.net was compromised.  It looked like a rootkit may 
> > > > > have been
> > > > > installed.  The volunteer admins are in the process of reinstalling 
> > > > > the OS
> > > > > and rebuilding the system.  That process will probably take a few 
> > > > > days at
> > > > > least.
> > > >
> > > > Does anyone know more?
> > > >
> > > > What about the integrity of the python packages hosted there?
> > > > When was the site compromised?
> > > > I just installed the python 2.5 pywin module last week.
> > > > Should I be concerned?
> > > >
> > > > Is this related to the Python security problem recently announced?
> > >
> > > Did you even read about the vulnerability?
> >
> > Yes.  Do you have any answers, or do you just enjoy posting irrevelant
> > responses?
>
> I guess his response implied that what's irrelevant here is the
> vulnerability, and accordingly your worries about it.

Then perhaps he should have said that, in which case I would
have explained why he did not understand what he read.  Let me
try again...

1. A site which hosts (I think, hence the questions) a number
of high profile, popular python projects was compomised.
2. It was compromised with a root kit which by their nature,
often go undetected for a long time.
3. It is common for miscreants to attempt to introduce
backdoors into software that will be widely distributed.
4. Anyone downloading and installing such trojaned software
will also be compromised.
5. Verifying that such a thing has not happened can be very
difficult, particularly if the date and other details of the
compromise cannot be accurately determined.
6. Many organisations give image and pr a higher priority
than the safety of their customers/users and wave off security
breechs with "don't worry, everything is fine.  We're sure
nothing has been touched" when in fact they have no idea.
7. I have seen no public statements or information about
this leading me to wonder about the stuation and how it's
being handled, hence my seeking of further information.

That's what I am concerned about, ok?
I don't really care how the site was compromised and my
question about the python security vunerability was curiosity.

But, I am still completely at a loss why you, he, or anyone,
based on the information presented so far,.would conclude
that the python security problem is unrelated.
Care to enlighten me?
But more inmportantly, how about addressing my original
questions which are, even if you do not think so, pretty
important for anyone who has recently downloaded software
from or built there.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send E-mail without an external SMTP server ?

2006-10-16 Thread [EMAIL PROTECTED]
Rob Wolfe wrote:
> [EMAIL PROTECTED] wrote:
>   
>> Hi,
>>
>> I just want to send a very simple email from within python.
>>
>> I think the standard module of smtpd in python can do this, but I
>> haven't found documents about how to use it after googleing. Are there
>> any examples of using smtpd ? I'm not an expert,so I need some examples
>> to learn how to use it.
>> 
>
> See standard documentation:
>
> http://docs.python.org/lib/SMTP-example.html
>
> HTH,
> Rob
>
>   

I have read the example and copied the code and save as send.py, then I 
run it. Here is the output:
$ python send.py
From: [EMAIL PROTECTED]
To: [EMAIL PROTECTED]
Enter message, end with ^D (Unix) or ^Z (Windows):
just a test from localhost
Message length is 82
send: 'ehlo [202.127.19.74]\r\n'
reply: '250-WebMail\r\n'
reply: '250 AUTH plain\r\n'
reply: retcode (250); Msg: WebMail
AUTH plain
send: 'mail FROM:<[EMAIL PROTECTED]>\r\n'
reply: '502 negative vibes\r\n'
reply: retcode (502); Msg: negative vibes
send: 'rset\r\n'
reply: '502 negative vibes\r\n'
reply: retcode (502); Msg: negative vibes
Traceback (most recent call last):
 File "send.py", line 26, in ?
   server.sendmail(fromaddr, toaddrs, msg)
 File "/usr/lib/python2.4/smtplib.py", line 680, in sendmail
   raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (502, 'negative vibes', '[EMAIL PROTECTED]')


Do I have to setup a smtp server on my localhost ?

Thanks a lot.

xiaojf

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send E-mail without an external SMTP server ?

2006-10-16 Thread Rob Wolfe

[EMAIL PROTECTED] wrote:

> Do I have to setup a smtp server on my localhost ?

If I see correctly your smtp server is gmail.com.

HTH,
Rob

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send E-mail without an external SMTP server ?

2006-10-16 Thread Leo Kislov


On Oct 16, 12:31 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> Rob Wolfe wrote:
> > [EMAIL PROTECTED] wrote:
>
> >> Hi,
>
> >> I just want to send a very simple email from within python.
>
> >> I think the standard module of smtpd in python can do this, but I
> >> haven't found documents about how to use it after googleing. Are there
> >> any examples of using smtpd ? I'm not an expert,so I need some examples
> >> to learn how to use it.
>
> > See standard documentation:
>
> >http://docs.python.org/lib/SMTP-example.html
>
> > HTH,
> > RobI have read the example and copied the code and save as send.py, then I
> run it. Here is the output:
> $ python send.py
> From: [EMAIL PROTECTED]
> To: [EMAIL PROTECTED]
> Enter message, end with ^D (Unix) or ^Z (Windows):
> just a test from localhost
> Message length is 82
> send: 'ehlo [202.127.19.74]\r\n'
> reply: '250-WebMail\r\n'
> reply: '250 AUTH plain\r\n'
> reply: retcode (250); Msg: WebMail
> AUTH plain
> send: 'mail FROM:<[EMAIL PROTECTED]>\r\n'
> reply: '502 negative vibes\r\n'
> reply: retcode (502); Msg: negative vibes
> send: 'rset\r\n'
> reply: '502 negative vibes\r\n'
> reply: retcode (502); Msg: negative vibes
> Traceback (most recent call last):
>  File "send.py", line 26, in ?
>server.sendmail(fromaddr, toaddrs, msg)
>  File "/usr/lib/python2.4/smtplib.py", line 680, in sendmail
>raise SMTPSenderRefused(code, resp, from_addr)
> smtplib.SMTPSenderRefused: (502, 'negative vibes', '[EMAIL PROTECTED]')
>
> Do I have to setup a smtp server on my localhost ?

You need to use login method
. And by the way, the
subject of your message is very confusing, you are posting log where
you're sending email using external server.

-- 
http://mail.python.org/mailman/listinfo/python-list


Where to find pydoc?

2006-10-16 Thread Wijaya Edward

I tried to call pydoc from my Linux box.
To my realization that it doesn't contain
pydoc.
 
I thought this module should be a default module.
 
Can anybody suggest where can I find the module?
I tried:
 
$ easy_install pydoc
Searching for pydoc
Reading http://sqlobject.org/  
Reading http://peak.telecommunity.com/dist  
Reading http://www.python.org/pypi/pydoc/  
Couldn't find index page for 'pydoc' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://www.python.org/pypi/  
No local packages or download links found for pydoc
error: Could not find suitable distribution for Requirement.parse('pydoc')

 
Hope to hear from you again.
 
Regards,
Edward WIJAYA
SINGAPORE

 Institute For Infocomm Research - Disclaimer -
This email is confidential and may be privileged.  If you are not the intended 
recipient, please delete it and notify us immediately. Please do not copy or 
use it for any purpose, or disclose its contents to any other person. Thank you.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDE that uses an external editor?

2006-10-16 Thread Nick Craig-Wood
Jorge Godoy <[EMAIL PROTECTED]> wrote:
>  Eclipse: just a GUI over a subset of Emacs today.

;-)

>  One day, when it evolves, it will be something interesting...  I
>  won't give up on Emacs loading fast

I never thought I'd live to see emacs being quoted as loading fast!
It really is fast compared to Eclipse though.

  "E"ight(y) "M"egs "A"nd "C"onstantly "S"wapping

Trouble is is that Eclipse is Eight-Hundred Megs ;-)

This message written in emacs, which I love dearly and have spent the
last 10 years mastering!  I did try Eclipse but I found it too slow
and clunky and there was far too much GUI (I like my whole screen to
be the file I'm editing).

Attempting to bring this discussion back on topic: Emacs has a few
python modes also.  There is the basic python-mode which does
everything expected of a major-mode.  Syntax colouring, indentation
that sort of thing.  There is also IM-Python for code navigation, and
bycycle repair man for refactoring support.  You can run stuff at the
interactive python prompt from within emacs.

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wx.grid question (trying to use code from Grid_Example.py)

2006-10-16 Thread Nick Craig-Wood
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>  I am having trouble trying to reuse the code that was provided in the
>  wxdemo package of wxpython.

I suggest you ask this question on the wxpython mailing list which has
lots of very well informed contributors (not me - I'm just learning!).

  http://www.wxpython.org/maillist.php

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


COM and threads

2006-10-16 Thread Teja
HI all,

I have a problem in accesing COM objects in threads. To be precise,
lets assume that I have a class GenericFunctions which is defined as
follows:

import win32com.client, pythoncom, thread
ie=win32com.client.Dispatch('internetexplorer.application')
ie.Visible=1

class GenericFunctions:

   def __init__(self):
 print "In Constructor of Generic Functions"

   def MyNavigate(self,dest):
 ie.Navigate(dest)


Now there  is another file Main.py which is defined as follows:

import win32com.client, pythoncom, thread
from GenericFunctions import *
obj = GenericFunctions()

class Mainclass:
   def __init__(self);
print "In Constructor of Main class"

   def threadFunction(self,dest):
pythoncom.CoInitialize()
d=pythoncom.CoGetInterfaceAndReleaseStream(s,
pythoncom.IID_IDispatch)
my_ie=win32com.client.Dispatch(d)
obj.func(dest)  # this is gving an error.
pythoncom.CoUninitialize()

if __name__ == "__main__":

s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie)
 thread.start_new_thread(self.nav, (s,'www.google.com')

Basically, I want to access object of GenericFunctions class inside
threadFunction(). However I was able to execute
my_ie.Navigate("google.com"). But that was not I wanted. I am not
knowing where the error is
Please let me know the solution ASAP...

Teja.P

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Attribute error

2006-10-16 Thread Teja

Max Erickson wrote:
> "Teja" <[EMAIL PROTECTED]> wrote:
>
> > Hi all,
> >
> > What is attribute error? what causes that error, especially with COM
> > objects?
> >
> > To be precise :
> >
> > Attribute Error: LCAS.LabcarController.writeLogWindow()
> >
> > Here, LCAS is a COM object
> >
> > Thanks
> > Teja.P
> >
>
> LabcarController might be a function. See:
>
> http://groups.google.com/group/comp.lang.python/msg/d7341f1aedcae6d3
>
> for more detail.
>
> hope this helps,
> max


HI all,

I have a problem in accesing COM objects in threads. To be precise,
lets assume that I have a class GenericFunctions which is defined as
follows:

import win32com.client, pythoncom, thread
ie=win32com.client.Dispatch('internetexplorer.application')
ie.Visible=1

class GenericFunctions:

   def __init__(self):
 print "In Constructor of Generic Functions"

   def MyNavigate(self,dest):
 ie.Navigate(dest)


Now there  is another file Main.py which is defined as follows:

import win32com.client, pythoncom, thread
from GenericFunctions import *
obj = GenericFunctions()

class Mainclass:
   def __init__(self);
print "In Constructor of Main class"

   def threadFunction(self,dest):
pythoncom.CoInitialize()
d=pythoncom.CoGetInterfaceAndReleaseStream(s,
pythoncom.IID_IDispatch)
my_ie=win32com.client.Dispatch(d)
obj.func(dest)  # this is gving an error.
pythoncom.CoUninitialize()

if __name__ == "__main__":

s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie)
 thread.start_new_thread(self.nav, (s,'www.google.com')

Basically, I want to access object of GenericFunctions class inside
threadFunction(). However I was able to execute
my_ie.Navigate("google.com"). But that was not I wanted. I am not
knowing where the error is
Please let me know the solution ASAP...

Teja.P

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: COM error

2006-10-16 Thread Teja

Neil Cerutti wrote:
> On 2006-10-14, Teja <[EMAIL PROTECTED]> wrote:
> > What is "ValueError: argument is not a COM object" ? I get this
> > error when I try to pass a COM object to a thread.
> >
> > Any pointers
>
> Try passing it to Larry Bird, instead. He's bound to score some
> points.
>
> Seriously, the function you called expected a COM object and you
> passed it something else. Without seeing more code, it's hard to
> be any helpfuller.
>
> --
> Neil Cerutti

HI all,

I have a problem in accesing COM objects in threads. To be precise,
lets assume that I have a class GenericFunctions which is defined as
follows:

import win32com.client, pythoncom, thread
ie=win32com.client.Dispatch('internetexplorer.application')
ie.Visible=1

class GenericFunctions:

   def __init__(self):
 print "In Constructor of Generic Functions"

   def MyNavigate(self,dest):
 ie.Navigate(dest)


Now there  is another file Main.py which is defined as follows:

import win32com.client, pythoncom, thread
from GenericFunctions import *
obj = GenericFunctions()

class Mainclass:
   def __init__(self);
print "In Constructor of Main class"

   def threadFunction(self,dest):
pythoncom.CoInitialize()
d=pythoncom.CoGetInterfaceAndReleaseStream(s,
pythoncom.IID_IDispatch)
my_ie=win32com.client.Dispatch(d)
obj.func(dest)  # this is gving an error.
pythoncom.CoUninitialize()

if __name__ == "__main__":

s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie)
 thread.start_new_thread(self.nav, (s,'www.google.com')

Basically, I want to access object of GenericFunctions class inside
threadFunction(). However I was able to execute
my_ie.Navigate("google.com"). But that was not I wanted. I am not
knowing where the error is
Please let me know the solution ASAP...

Teja.P

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: COM and Threads

2006-10-16 Thread Teja

Teja wrote:
> Roger Upole wrote:
> > "Teja" <[EMAIL PROTECTED]> wrote:
> > >
> > > Roger Upole wrote:
> > >
> > >> "Teja" <[EMAIL PROTECTED]> wrote:
> > >> >
> > >> > Roger Upole wrote:
> > >> >
> > >> >> "Teja" <[EMAIL PROTECTED]> wrote:
> > >> >> >I have an application which uses COM 's Dispatch to create a COM 
> > >> >> >based
> > >> >> > object. Now I need to upgrade the application to a threaded one. But
> > >> >> > its giving an error that COM and threads wont go together. 
> > >> >> > Specifically
> > >> >> > its an attribute error at the point where COM object is invoked. Any
> > >> >> > pointers please??
> > >> >> >
> > >> >>
> > >> >> An actual traceback would help.
> > >> >> At a guess, when using COM in a thread
> > >> >> you need to call pythoncom.CoInitialize and
> > >> >> CoUninitialize yourself.
> > >> >>
> > >> >>  Roger
> > >> >
> > >> > Actually Roger, this is the scenario
> > >> >
> > >> > I create a COM object at the beginnning of the main thread. In the sub
> > >> > thread, I need to access the same instance of the COM object. If it
> > >> > were a normal object ie. not a COM obj, i was able to do it. But if it
> > >> > were a COM object, its giving an attribute error? Should I pass a COM
> > >> > object to the thread. If so How? Please let me know ASAP... Thnks
> > >> >
> > >>
> > >> To pass COM objects between threads, usually they'll need to be marshaled
> > >> using pythoncom.CoMarshalInterThreadInterfaceInStream, and unmarshaled
> > >> with pythoncom.CoGetInterfaceAndReleaseStream.
> > >>
> > >>  Roger
> > >
> > > I really appreciate your quick replyCan u please let me know how to
> > > do marshalling and unmarshalling or any good refrences to do it.
> > > Because i tried to do it. I got some errors ans so I left it...
> > >
> > > Thnks again...
> > >
> >
> > Here's a simple example using Internet Explorer.
> >
> > import win32com.client, pythoncom, thread
> > ie=win32com.client.Dispatch('internetexplorer.application')
> > ie.Visible=1
> >
> > def nav(istream, dest):
> > pythoncom.CoInitialize()
> > d=pythoncom.CoGetInterfaceAndReleaseStream(istream, 
> > pythoncom.IID_IDispatch)
> > my_ie=win32com.client.Dispatch(d)
> > my_ie.Navigate(dest)
> > pythoncom.CoUninitialize()
> >
> > s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie)
> > thread.start_new_thread(nav, (s, 'www.google.com'))
> >
> >   Roger
>
> Thnks a lot Roger, Its working gr8..Now, once the thread is started
> with start_new_thread, is there any way to terminate it upon user's
> request. I have explored and found out that there is no thread.kill().
> So wht to do now?
>
> Teja

HI all,

I have a problem in accesing COM objects in threads. To be precise,
lets assume that I have a class GenericFunctions which is defined as
follows:

import win32com.client, pythoncom, thread
ie=win32com.client.Dispatch('internetexplorer.application')
ie.Visible=1

class GenericFunctions:

   def __init__(self):
 print "In Constructor of Generic Functions"

   def MyNavigate(self,dest):
 ie.Navigate(dest)


Now there  is another file Main.py which is defined as follows:

import win32com.client, pythoncom, thread
from GenericFunctions import *
obj = GenericFunctions()

class Mainclass:
   def __init__(self);
print "In Constructor of Main class"

   def threadFunction(self,dest):
pythoncom.CoInitialize()
d=pythoncom.CoGetInterfaceAndReleaseStream(s,
pythoncom.IID_IDispatch)
my_ie=win32com.client.Dispatch(d)
obj.func(dest)  # this is gving an error.
pythoncom.CoUninitialize()

if __name__ == "__main__":

s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie)
 thread.start_new_thread(self.nav, (s,'www.google.com')

Basically, I want to access object of GenericFunctions class inside
threadFunction(). However I was able to execute
my_ie.Navigate("google.com"). But that was not I wanted. I am not
knowing where the error is
Please let me know the solution ASAP...

Teja.P

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where to find pydoc?

2006-10-16 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Wijaya Edward
wrote:

> 
> I tried to call pydoc from my Linux box.
> To my realization that it doesn't contain
> pydoc.
>  
> I thought this module should be a default module.

Yes it is part of the standard library.  What distribution are you using?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Where to find pydoc?

2006-10-16 Thread Wijaya Edward

Hi,
Thanks for the reply.
 
Red Hat Linux Enterprise:
Linux host.com 2.6.9-34.ELsmp #1 SMP Fri Feb 24 16:54:53 EST 2006 i686 i686 
i386 GNU/Linux

 
Python 2.3.4.
 
Any problem with that?
 
--- Edward



From: [EMAIL PROTECTED] on behalf of Marc 'BlackJack' Rintsch
Sent: Mon 10/16/2006 5:00 PM
To: [email protected]
Subject: Re: Where to find pydoc?



In <[EMAIL PROTECTED]>, Wijaya Edward
wrote:

>
> I tried to call pydoc from my Linux box.
> To my realization that it doesn't contain
> pydoc.
> 
> I thought this module should be a default module.

Yes it is part of the standard library.  What distribution are you using?

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list



 Institute For Infocomm Research - Disclaimer -
This email is confidential and may be privileged.  If you are not the intended 
recipient, please delete it and notify us immediately. Please do not copy or 
use it for any purpose, or disclose its contents to any other person. Thank you.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send E-mail without an external SMTP server ?

2006-10-16 Thread [EMAIL PROTECTED]
Leo Kislov wrote:
>>
>> Do I have to setup a smtp server on my localhost ?
>> 
>
> You need to use login method
> . And by the way, the
> subject of your message is very confusing, you are posting log where
> you're sending email using external server.
>
>   
Thanks.

Yes, I want to find a way to send email without an external smtp server.

According to Rob's reply, I thought this could be implemented as 
described in
the example code of "SMTP Example" on 
"http://docs.python.org/lib/SMTP-example.html";.  So I tried the code, 
but failed.

Actually I was writing a script that can submit jobs automatically on a 
remote server. I should not submit the jobs all at once, because this 
will take up all resources of the server. I just want a specified number 
of jobs to be running at one time. If one jobs is over, the script 
should submit another job. I run the script with nohup, then I logout.  
The script will take care of all jobs.

But I have to check the status of the script manually, which is very 
inefficient. So I want to be informed automatically by E-mail when all 
jobs are done.


It's not safe if I have to use login method explicitly by which I have 
to put my username and password in the script. I have also tried the 
Unix command 'mail', but without success, either. I could use 'mail' to 
send an E-mail to the user on the server, but I couldn't send an E-mail 
to an external E-mail server. I realized that it may because the port 25 
outgoing connections are blocked, so I gave up. I will have to login 
periodically to check the status of the jobs:-(

Anyway, thank you, Rob, and thank you, Leo.

xiaojf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where to find pydoc?

2006-10-16 Thread Fredrik Lundh
Wijaya Edward wrote:

> Thanks for the reply.
>  
> Red Hat Linux Enterprise:
> Linux host.com 2.6.9-34.ELsmp #1 SMP Fri Feb 24 16:54:53 EST 2006 i686 i686 
> i386 GNU/Linux
> 
> Python 2.3.4.
>  
> Any problem with that?

only that Red Hat obviously hasn't bothered to include "pydoc" in the 
distribution you're using.

look for "python-tools" or a similar package in your favourite package 
repository.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ok. This IS homework ...

2006-10-16 Thread Frederic Rentsch
spawn wrote:
> but I've been struggling with this for far too long and I'm about to
> start beating my head against the wall.
>
> My assignment seemed simple: create a program that will cacluate the
> running total of user inputs until it hits 100.  At 100 it should stop.
>  That's not the problem, in fact, that part works.  It's the adding
> that isn't working.  How can my program add 2 + 7 and come up with 14?
>
> I'm posting my code (so that you may all laugh).  If ANYONE has any
> ideas on what I'm doing wrong, I'd appreciate.
>
> ---
>
> running = True
> goal = 100
>
> # subtotal = 0
> # running_total = subtotal + guess
>
> while running:
>   guess = int(raw_input('Enter an integer that I can use to add : '))
>   subtotal = guess
>
>   while running:
>   guess = int(raw_input('I\'ll need another number : '))
>   running_total = guess + subtotal
>   print running_total
>
>   if running_total == goal:
>   print 'Congratulations!  You\'re done.'
>
>   elif running_total > goal:
>   print 'That\'s a good number, but too high.  Try again.'
>
> print 'Done'
>
> --
>
> I tried adding an additional "while" statement to capture the second
> number, but it didn't seem to solve my problem.  Help!
>
>   
Dear anonymous student,

Once upon a time programmers did things like this:

   BEGIN
 |
  -->|<-
 |   |  |
 |   catch input|
 |   |  |
 |   input type valid? - prompt for correct input --|
 |   +  |
 |input too large? + --- prompt for new input --
 |   -
 |  add to running total 
 |   |
 |  status report 
 |   |
  -- - running total >= max?
 +
report done  
 |
END

It was called a flow chart. Flow charts could be translated directly 
into machine code written in assembly languages which had labels, tests 
and jumps as the only flow-control constructs. When structured 
programming introduced for and while loops they internalized labeling 
and jumping. That was a great convenience. Flow-charting became rather 
obsolete because the one-to-one correspondence between flow chart and 
code was largely lost.
I still find flow charting useful for conceptualizing a system of 
logical states too complex for my intuition. Everybody's intuition has a 
limit. Your homework solution shows that the assignment exceeds yours. 
So my suggestion is that you use the flow chart, like this:


def homework ():

   # Local functions. (I won't do those for you.)

   def explain_rules (): 
   def check_type (r):   
   def explain_type ():
   def check_size (r):
   def explain_max_size ():
   def report_status (rt):
   def report_done ():


   # Main function

   GOAL  = 100   #BEGIN
   MAX_INPUT =  20   #  |
   running_total =   0   #  |
 #  |
   explain_rules ()  #  |
 #  | 
   while 1:  #   
-->|<-
 #  |   
|  |
  response = raw_input ('Enter a number > ') #  |   
catch input|
 #  |   
|  |
  if check_type (response) == False: #  |   input 
type valid? - prompt for correct input --|
 explain_type () #  |   
+  |
 continue#  |   
|  |
 #  |   
|  |
  if check_size (response) == False: #  |input 
too large? + --- prompt for new input --
 explain_max_size () #  |   -
 continue#  |   |
 #  |   |
  running_total += int (response)#  |  add to 
running total 
  report_st

Re: python's OOP question

2006-10-16 Thread Bruno Desthuilliers
neoedmund wrote:
(*PLEASE* stop top-posting - corrected)
> 
> Ben Finney wrote:
>> [Please don't top-post above the text to which you're replying.]
>>
>> "neoedmund" <[EMAIL PROTECTED]> writes:
>>
>>> I'm trying to achieve a higher level of "reusability". Maybe it
>>> cannot be done in python? Can anybody help me?
>> What, specifically, are you trying to achieve? What problem needs
>> solving?

> python use multiple inheritance.
> but "inheritance" means you must inherite all methods from super type.
> now i just need "some" methods from one type and "some" methods from
> other types, to build the new type.
> Do you think this way is more flexible than tranditional inheritance?

While dynamically adding attributes (and methods - which are attributes
too) is not a problem, I'd second Gregor's anwser : it might be better
to use composition/delegation here.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Cannot import a module from a variable

2006-10-16 Thread Bruno Desthuilliers
Jia Lu wrote:
> Hi all:
> 
> I try to do things below:
 import sys
 for i in sys.modules.keys():
>   import i
> Traceback (most recent call last):
>   File "", line 2, in 
> import i
> ImportError: No module named i
> 
> But it seems that import donot know what is i ? 

The import statement expects a name (a symbol), not a string.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python's OOP question

2006-10-16 Thread neoedmund

Bruno Desthuilliers wrote:
> neoedmund wrote:
> (*PLEASE* stop top-posting - corrected)
> >
> > Ben Finney wrote:
> >> [Please don't top-post above the text to which you're replying.]
> >>
> >> "neoedmund" <[EMAIL PROTECTED]> writes:
> >>
> >>> I'm trying to achieve a higher level of "reusability". Maybe it
> >>> cannot be done in python? Can anybody help me?
> >> What, specifically, are you trying to achieve? What problem needs
> >> solving?
>
> > python use multiple inheritance.
> > but "inheritance" means you must inherite all methods from super type.
> > now i just need "some" methods from one type and "some" methods from
> > other types, to build the new type.
> > Do you think this way is more flexible than tranditional inheritance?
>
> While dynamically adding attributes (and methods - which are attributes
> too) is not a problem, I'd second Gregor's anwser : it might be better
> to use composition/delegation here.
>

Could you show some code to help me know how composition/delegation can
be done here? Thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Book about database application development?

2006-10-16 Thread Bruno Desthuilliers
Wolfgang Keller wrote:
> Hello,
> 
> and thanks for your reply, but...
> 
>> Here's a start:
>>
>> http://philip.greenspun.com/sql/
> 
> ...small misunderstanding: I already know a bit of SQL,

Developping quality SQLDBMS-based applications requires more than "a
bit" of SQL knowledge.

> and I intend to avoid 
> its use as far as possible (and use e.g. Modeling or SQLAlchemy).  

I don't know Modeling, but have a bit of experience with SQLAlchemy, and
without SQL and relational model knowledge, you won't get very far.

> What I'm interested in is rather how to connect a GUI to a database, with 
> quite a bit of application logic in between. And how to do it well.

This is more a general design question than a database-related (or even
Python-related) one. The answer starts with forgetting about
"connect(ing) a GUI to a database" IMHO and experience. Might be time to
google for MVC...


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python

2006-10-16 Thread Bruno Desthuilliers
Paul Boddie wrote:
> Kay Schluehr wrote:
>> Spreading tiny function definitions all over the code
>> may be finally not such a good idea compared with a few generic methods
>> that get just called? OO might run out of fashion these days but Python
>> is not Java and Pythons OO is pretty lightweight.
> 
> I think you've successfully identified a recent trend in Python
> development: the abandonment of fairly transparent object-oriented
> techniques in favour of more opaque but supposedly more convenient
> hybrid techniques. 

Just for the record : Ruby's code-blocks (closures, really) come from
Smalltalk, which is still the OneTrueObjectLanguage(tm).


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python's OOP question

2006-10-16 Thread Kay Schluehr
neoedmund wrote:

> Could you show some code to help me know how composition/delegation can
> be done here? Thanks.

Starting with your example C2 might just derive from C1 and perform a
supercall:

class C1(object):
def v(self, o):
return "expected "+o


class C2(C1):
def v(self, o):
return "unexpected "+o
def m(self):
print super(C2,self).v("aaa")

>>> c2 = C2()
>>> c2.m()
expected aaa

But in general there is no single pattern to deal with object
composition.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python

2006-10-16 Thread Kay Schluehr
Bruno Desthuilliers wrote:

> Just for the record : Ruby's code-blocks (closures, really) come from
> Smalltalk, which is still the OneTrueObjectLanguage(tm).

IsTheOneTrueObjectLanguage(tm)ReallyCamelCased?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sufficiently pythonic code for testing type of function

2006-10-16 Thread Bruno Desthuilliers
Fredrik Lundh wrote:
> Scott David Daniels wrote:
> 
>> Nope.  idempotent: f(f(x)) = f(x)
>> That is, after doing it once, repeating it won't hurt.
> 
> http://en.wikipedia.org/wiki/Idempotence_%28computer_science%29
> 
> 
> 
Thank you (Scott and Fredrik) for the correction.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send E-mail without an external SMTP server ?

2006-10-16 Thread Leo Kislov


On Oct 16, 2:04 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> It's not safe if I have to use login method explicitly by which I have
> to put my username and password in the script. I have also tried the
> Unix command 'mail', but without success, either. I could use 'mail' to
> send an E-mail to the user on the server, but I couldn't send an E-mail
> to an external E-mail server. I realized that it may because the port 25
> outgoing connections are blocked, so I gave up. I will have to login
> periodically to check the status of the jobs:-(

Using username password is safe as long as you trust system admin, you
just need to make your script readable only to you. Or even better put
the username and password in a separate file. There is also a way to
limit damage in case you don't trust admin, you just need to get auth
token. Start smtp session and set debug level(True), use login method
and see the token:

send: 'AUTH PLAIN \r\n'
reply: '235 2.7.0 Accepted\r\n'
reply: retcode (235); Msg: 2.7.0 Accepted

Then put the token in a file readable only to you, and from now on
instead of login() method use docmd('AUTH PLAIN',"). If the token is stolen, the thief can only send mail from your
account but won't be able to login with password.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Book about database application development?

2006-10-16 Thread Paul Rubin
Wolfgang Keller <[EMAIL PROTECTED]> writes:
> > http://philip.greenspun.com/sql/
> 
> ...small misunderstanding: I already know a bit of SQL, and I intend to avoid 
> its use as far as possible (and use e.g. Modeling or SQLAlchemy).  

I'm not sure what you mean, that book isn't just an intro to SQL, it
discusses how to tune for performance, etc.  It has quite a bit of
practical advice that you can tell came from hard-won experience by
the author.  On the other hand, it's somewhat out of date by now and
it's Oracle-centered.  Anyway it's online, you might spend a minute
looking at it to see if it's useful to you.  It had sounded like the
type of thing you're asking for.

> What I'm interested in is rather how to connect a GUI to a database, with 
> quite a bit of application logic in between. And how to do it well.

Erm, I can't really tell what you're asking for here; the application
simply makes database queries as needed.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: What's up with the starship?

2006-10-16 Thread micahel
[EMAIL PROTECTED] wrote:
> Then perhaps he should have said that, in which case I would
> have explained why he did not understand what he read.  Let me
> try again...

Well, let's have some answers then.

> 1. A site which hosts (I think, hence the questions) a number
> of high profile, popular python projects was compomised.

Yes.  However, it doesn't *seem* as if the machine was deliberately
targeted, and I think it's unlikely the attackers were interested in
trojanning software.  But of course the machine was rooted, so it's
pretty hard to be sure of these things.

> 2. It was compromised with a root kit which by their nature,
> often go undetected for a long time.

As far as I can tell, the machine was compromised on 2006-09-02.

Irritatingly we didn't find out until just after logrotate had deleted
the logs for around the time of the attack.

It wasn't a very subtle rootkit -- installing a version of netstat with
different command line options, for example...

> 5. Verifying that such a thing has not happened can be very
> difficult, particularly if the date and other details of the
> compromise cannot be accurately determined.

I guess you should find out from the author of whatever you downloaded
what the checksums should have been for what you downloaded and check
that against what you downloaded.

If you don't still have the downloaded files, I can tell you what the
md5's of the files in the back up are.

> 6. Many organisations give image and pr a higher priority
> than the safety of their customers/users and wave off security
> breechs with "don't worry, everything is fine.  We're sure
> nothing has been touched" when in fact they have no idea.

There is no organization behind python.net.

I am a volunteer.  I help run python.net in my spare time.

> 7. I have seen no public statements or information about
> this leading me to wonder about the stuation and how it's
> being handled, hence my seeking of further information.

I'm sorry, I'm busy trying to get the server going again.

> But, I am still completely at a loss why you, he, or anyone,
> based on the information presented so far,.would conclude
> that the python security problem is unrelated.

Why would it be?  For all it's position in the community, there aren't
actually many python web apps running on python.net, certainly not as
root...

Cheers,
mwh

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: run subprocess in separate window

2006-10-16 Thread [EMAIL PROTECTED]

Radek a écrit :

> Hi,
>
> I am trying to create GUI launcher of several applications using Python
> and Tkinter.
>
> Currently when using subprocess.Popen("mycommand") all output goes to
> the stdout of my launcher.
>
> For some command line applications I need to launch them so that their
> output goes into the separate "terminal" window.
>
> How can I make it?
>
> Thanks,
>
> Radek

Hello, have a look at the subprocess module, it might help you get to
what you want.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where can I find good python code?

2006-10-16 Thread kdart
I think the following is a package with a lot of good code. But then,
I'm biased. ;-)

http://code.google.com/p/pynms/


On Oct 13, 9:08 am, "js " <[EMAIL PROTECTED]> wrote:
>  Hi,
>
> I've learned basics of Python and want to go to the next step.
> So I'm looking for good python examples
> I steal good techniques from.
>
> I found Python distribution itself contains some examples in Demo directory.
> I spent some time to read them and
> I think they're good but seemed not so practical to me.
> 
> Any recommendations?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ok. This IS homework ...

2006-10-16 Thread Nick Craig-Wood
Frederic Rentsch <[EMAIL PROTECTED]> wrote:
>  It was called a flow chart. Flow charts could be translated directly 
>  into machine code written in assembly languages which had labels, tests 
>  and jumps as the only flow-control constructs. When structured 
>  programming introduced for and while loops they internalized labeling 
>  and jumping. That was a great convenience. Flow-charting became rather 
>  obsolete because the one-to-one correspondence between flow chart and 
>  code was largely lost.

The trouble with flow charts is that they aren't appropriate maps for
the modern computing language territory.

I was born and bred on flow charts and I admit they were useful back
in the days when I wrote 1000s of lines of assembler code a week.

Now-a-days a much better map for the the territory is pseudo-code.
Python is pretty much executable pseudo-code anway!

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


EXCITING OPPORTUNITY FOR EXPERIENCED APPLICATION DEVELOPERS (PYTHON)

2006-10-16 Thread Azri
EXCITING OPPORTUNITY FOR EXPERIENCED APPLICATION DEVELOPERS (PYTHON)

Azri Solutions Pvt Limited ( http://www.azri.de/en/) provides a
challenging work environment, an open work culture & competitive
remuneration : the right ingredients to facilitate superlative
performance.Vacancies for Experienced Application Developers (PYTHON)
are currently open. Azri is an extremely flexible & sustainable
networked enterprise with presence in Germany, the U.S.A. & India. Our
team has intense hands-on experience in designing, deploying and
managing high-volume Service-Oriented Architectures (SOA) including
RDBMS-backed Webservices. In most cases, we leverage tried and tested
open-source software.

Join our highly motivated and dedicated team to embark upon a
challenging and rewarding career where you get to make decisions,
create great products and in the process, have some fun! We believe in
the concept of continuous learning, taking on responsibilities and
providing growth opportunities for every team member. Our environment
encourages innovation. Ideas are welcome and every individual is
empowered to think, share and take ownership oftheir ideas and
creations.

MAIL YOUR RESUME TO [EMAIL PROTECTED]

JOB DESCRIPTION :

· General : Should have developed applications using Open Source
systems.
· Scripting : TCL, PHP, Perl, Python, Ruby.
· Languages : C, C++ development experience is an added advantage.
· OS : Linux / Unix, Windows. (Must have Linux / Unix experience).
· Frameworks : Should have used Open Source languages like PHP /
Perl/Ruby / TCL and frameworks like Drupal / Mojave / Rails / OpenACS.

DESIRED PROFILE :

· Should enjoy programming.
· Experience : One to four years' programming experience.
· Knowledge of Linux, Shell scripting, Web application development,
Quality software development.
· Excellent conceptual, analytical and programming skills.
· Should have Application Design experience.
· Familiarity with Open Source Application Development.
· Familiarity with Open Source Web Application Frameworks.
· Participation in open source communities is an added advantage.

SOFTSKILLS :

 · Good communication and interpersonal skills.
· Team player.

LOCATION : HYDERABAD

MAIL YOUR RESUME TO [EMAIL PROTECTED]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: classroom constraint satisfaction problem

2006-10-16 Thread [EMAIL PROTECTED]

Steven Bethard a écrit :

> I'm trying to solve a constraint-satisfaction problem, and I'm having
> some troubles framing my problem in such a way that it can be
> efficiently solved.
>
> Basically, I want to build groups of two teachers and four students such
> that [1]:
>
> * Students are assigned to exactly one group
> * Teachers are assigned to approximately the same number of groups
> * Students are not in groups with their homeroom teachers
> * Students in each group are from four different homerooms
>
> So given teachers A, B, C, D, E and F and their corresponding students
> A1, A2, ... F3, F4, here's a good grouping:
>
> A, B:   C1, D1, E1, F1
> B, C:   A1, D2, E2, F2
> C, D:   A2, B1, E3, F3
> D, E:   A3, B2, C2, F4
> E, F:   A4, B3, C3, D3
> F, A:   B4, C4, D4, E4
>
>
> My current solution is to create a constraint satisfaction problem using
> python-constraint (http://labix.org/python-constraint) where there are

Last time I looked at it, it seemed to not use (by default) its Arc8
routine that prunes domains between each variable instantiation by the
backtracker. Did you enable it ? (it should have a crucial performance
impact).

You could also try the logilab constraint package
(http://www.logilab.org/projects/constraint) and see how it fares with
your problem (it 'only' provides the AC3 domain pruning algorithm but
at least uses it by default).

Cheers,
Aurélien.

> variables for:
>
> * each student  domain: group names
> * each group name   domain: all pairs of teachers
>
> This works for simple problems, but because most of my constraints have
> to iterate over all students and/or all groups, this takes way too long
> on my real dataset (which has 300+ students).  I thought about trying to
> reframe the problem so that there are variables for:
>
> * each group name   domain: pairs of teachers X 4-tuples of students
>
> but that seems like it would be generating something like 15^2*300^4
> items for the domain, which is clearly also going to be way too big.
>
>
> Any suggestions on how to speed things up?  I've posted my current code_
> and the tests_ in case anyone has the time to look at them.
>
> .. _code: http://ucsu.colorado.edu/~bethard/py/constraint/student_groups.py
> .. _tests:
> http://ucsu.colorado.edu/~bethard/py/constraint/test_student_groups.py
>
>
> Thanks!
>
> Steve
>
>
> [1] There are actually two other constraints that I omitted:
>
> * Some teachers cannot be placed in the same group, e.g. I might know
> that A cannot work with B or that E cannot work with F.
>
> * If you create a graph out of the teacher pairs from all the groups,
> the graph should not be disconnected.  That is, the following grouping
> is bad because the teachers are disconnected:
>
> A, B: ...
> C, D: ...
> A, B: ...
>
> while this grouping would be okay:
> 
> A, B: ...
> B, C: ...
> C, D: ...

-- 
http://mail.python.org/mailman/listinfo/python-list


New Software Development Articles Directory

2006-10-16 Thread editormt
A new links directory of articles related to software development is
"under construction" on http://www.softdevarticles.com/

Please feel free use it in future research and to contribute with your
articles on python.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDE that uses an external editor?

2006-10-16 Thread Jorge Godoy
Nick Craig-Wood <[EMAIL PROTECTED]> writes:

> Attempting to bring this discussion back on topic: Emacs has a few
> python modes also.  There is the basic python-mode which does
> everything expected of a major-mode.  Syntax colouring, indentation
> that sort of thing.  There is also IM-Python for code navigation, and
> bycycle repair man for refactoring support.  You can run stuff at the
> interactive python prompt from within emacs.

Besides, even though PyDev's indentation got a little better it isn't as smart
as Emacs'.  Being a language where indentation matters, I find Emacs much more
productive and this only feature is a major problem to "migrate" from Emacs to
Eclipse. 

But, who knows when Eclipse gets better it will have the power needed to
implement the same set of indentation rules...

-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Book about database application development?

2006-10-16 Thread Wolfgang Keller
>> What I'm interested in is rather how to connect a GUI to a database, with
>> quite a bit of application logic in between. And how to do it well.
> 
> You've described Dabo perfectly. Have you looked into it yet? It's
> written by a couple of database application developers.

Yes, thanks, I know about Dabo. As I know about Kiwi, Thyme, GNUe, TinyERP 
and so on...

But I would still like to learn how to do things myself if I need to.

Sincerely,

Wolfgang Keller

-- 
My email-address is correct.
Do NOT remove ".nospam" to reply.

-- 
http://mail.python.org/mailman/listinfo/python-list


Convert StringIO to string

2006-10-16 Thread Jonathan Bowlas
Hi listers,

I've written this little script to generate some html but I cannot get it to
convert to a string so I can perform a replace() on the >, <
characters that get returned.

from StringIO import StringIO

def generator_file(rsspath,titleintro,tickeropt): 
scripter=StringIO()
scripter.write('\n')
scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath,
titleintro, tickeropt))
scripter.write('\n')
return scripter.getvalue()

I tried adding this:

scripter = scripter.replace("<", "<")
scripter = scripter.replace(">", ">")

But obviously replace() isn't an attribute of StringIO so I guess I need to
convert it to a string first, can someone please advise how I can do this?

Cheers

Jon


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: EXCITING OPPORTUNITY FOR EXPERIENCED APPLICATION DEVELOPERS (PYTHON)

2006-10-16 Thread beliavsky
If the company is so good, why does it hire recruiters like you?

It is rude to SHOUT your subject in all caps.

Your subject conveys nothing more than "Python job offered".

You should have mentioned in the subject that the job is in Hyderabad,
because even most readers of this group looking for jobs are probably
unwilling to relocate there, and thus they could skip the rest of the
message.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert StringIO to string

2006-10-16 Thread skryskalla
Jonathan Bowlas wrote:
> But obviously replace() isn't an attribute of StringIO so I guess I need to
> convert it to a string first, can someone please advise how I can do this?

StringIO objects are file-like objects, so you need to use read or
readlines to get the string data out of it (just like a regular file).
Before reading remember to seek back to the beginning to get all of the
data ("Be kind, rewind!"):

>>> import StringIO
>>> s = StringIO.StringIO()
>>> s.write("hello world\n")
>>> s.seek(0)
>>> s.read()
'hello world\n'

>>> s = StringIO.StringIO()
>>> s.write("hello world\n")
>>> s.read()
''

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python's OOP question

2006-10-16 Thread Bruno Desthuilliers
neoedmund wrote:
> Bruno Desthuilliers wrote:
>> neoedmund wrote:
>> (*PLEASE* stop top-posting - corrected)
>>> Ben Finney wrote:
 [Please don't top-post above the text to which you're replying.]

 "neoedmund" <[EMAIL PROTECTED]> writes:

> I'm trying to achieve a higher level of "reusability". Maybe it
> cannot be done in python? Can anybody help me?
 What, specifically, are you trying to achieve? What problem needs
 solving?
>>> python use multiple inheritance.
>>> but "inheritance" means you must inherite all methods from super type.
>>> now i just need "some" methods from one type and "some" methods from
>>> other types, to build the new type.
>>> Do you think this way is more flexible than tranditional inheritance?
>>>
>> While dynamically adding attributes (and methods - which are attributes
>> too) is not a problem, I'd second Gregor's anwser : it might be better
>> to use composition/delegation here.
>> 
> Could you show some code to help me know how composition/delegation can
> be done here? Thanks.

About composition/delegation, there's no "one-size-fits-all" answer, but
the main idea is to use the magic '__getattr__(self, name)' method.

Now back to your specific case : after a better reading of your original
question, straight composition/delegation wouldn't work here - at least
not without modifications to both C1 and C2 (sorry, should have read
better the first time).

Given the context (ie : "create a new type with methods from type X and
methods from type Y"), a very simple solution could be:

class C3(object):
m = C2.m.im_func
v = C1.v.im_func

FWIW, if you have full control over C1, C2 and C3, you could also just
'externalize' the functions definitions:

def v1(self, o):
return "expected "+o

def v2(self, o):
return "unexpected "+o

def m2(self):
""" requires that 'self' has a v(self, somestring) method """
print self.v("aaa")

class C1(object):
v = v1

class C2(object):
v = v2
m = m2

class C3(object):
v = v1
m = m2


The problem (with the whole approach, whatever the choosen technical
solution) is that if one of theses methods depends on another one (or on
any other attribute) that is not defined in your new class, you're in
trouble. This is not such a big deal in the above example, but might
become much more brittle in real life.

Now we can look at the problem from a different perspective. You wrote:
"""
but "inheritance" means you must inherite all methods from super type.
now i just need "some" methods from one type and "some" methods from
other types, to build the new type.
"""

What is your problem with having the other extra methods too ?

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list

RE: Convert StringIO to string

2006-10-16 Thread Jonathan Bowlas
Ahh thanks, I'll give that a try.

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
[EMAIL PROTECTED]
Sent: 16 October 2006 14:00
To: [email protected]
Subject: Re: Convert StringIO to string

Jonathan Bowlas wrote:
> But obviously replace() isn't an attribute of StringIO so I guess I need
to
> convert it to a string first, can someone please advise how I can do this?

StringIO objects are file-like objects, so you need to use read or
readlines to get the string data out of it (just like a regular file).
Before reading remember to seek back to the beginning to get all of the
data ("Be kind, rewind!"):

>>> import StringIO
>>> s = StringIO.StringIO()
>>> s.write("hello world\n")
>>> s.seek(0)
>>> s.read()
'hello world\n'

>>> s = StringIO.StringIO()
>>> s.write("hello world\n")
>>> s.read()
''

-- 
http://mail.python.org/mailman/listinfo/python-list



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert StringIO to string

2006-10-16 Thread paul
Jonathan Bowlas schrieb:
> Hi listers,
> 
> I've written this little script to generate some html but I cannot get it to
> convert to a string so I can perform a replace() on the >, <
> characters that get returned.
> 
> from StringIO import StringIO
> 
> def generator_file(rsspath,titleintro,tickeropt): 
>   scripter=StringIO()
>   scripter.write('\n')
>   scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath,
> titleintro, tickeropt))
>   scripter.write('\n')
>   return scripter.getvalue()
> 
> I tried adding this:
> 
> scripter = scripter.replace("<", "<")
> scripter = scripter.replace(">", ">")
I'm not sure why you are using a StringIO instance here, but the
standard library has all you need:

from StringIO import StringIO
from xml.sax.saxutils import escape, unescape

def generator_file(rsspath, titleintro, tickeropts):
  #unescape your strings first
  rsspath, titleintro, tickeropts = map(unescape, [rsspath, titleintro,
tickeropts])
  scripter=StringIO()
  scripter.write('\n')
  scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath, titleintro,
tickeropt))
  scripter.write('\n')
  return scripter.getvalue()

I'm still curious what all this StringIO stuff is for ;)

cheers
 Paul



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert StringIO to string

2006-10-16 Thread Brian Quinlan
Jonathan Bowlas wrote:
> Ahh thanks, I'll give that a try.
> 
> -Original Message-
> From: [EMAIL PROTECTED]
> [mailto:[EMAIL PROTECTED] On Behalf Of
> [EMAIL PROTECTED]
> Sent: 16 October 2006 14:00
> To: [email protected]
> Subject: Re: Convert StringIO to string
> 
> Jonathan Bowlas wrote:
>> But obviously replace() isn't an attribute of StringIO so I guess I need
> to
>> convert it to a string first, can someone please advise how I can do this?
> 
> StringIO objects are file-like objects, so you need to use read or
> readlines to get the string data out of it (just like a regular file).
> Before reading remember to seek back to the beginning to get all of the
> data ("Be kind, rewind!"):
> 
 import StringIO
 s = StringIO.StringIO()
 s.write("hello world\n")
 s.seek(0)
 s.read()
> 'hello world\n'

Or, instead of seak/read, just do

 >>> s.getvalue()

Cheers,
Brian


-- 
http://mail.python.org/mailman/listinfo/python-list


comparing Unicode and string

2006-10-16 Thread [EMAIL PROTECTED]
Hello,

here is something that surprises me.

  #coding: iso-8859-1
  s1=u"Frau Müller machte große Augen"
  s2="Frau Müller machte große Augen"
  if s1 == s2:
  pass

Running this code produces a UnicodeDecodeError:

Traceback (most recent call last):
  File "tmp.py", line 4, in ?
if s1 == s2:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 6:
ordinal not in range(128)

I would have expected that "s1 == s2" gives True... or maybe False...
but raising an error here is unnecessary. I guess that the comparison
operator decides to convert s2 to a Unicode but forgets that I said
#coding: iso-8859-1 at the beginning of the file.

TIA for any comments.

Luc Saffre

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert StringIO to string

2006-10-16 Thread Rob Williscroft
Jonathan Bowlas wrote in
news:[EMAIL PROTECTED] in
comp.lang.python: 

> Hi listers,
> 
> I've written this little script to generate some html but I cannot get
> it to convert to a string so I can perform a replace() on the >,
> < characters that get returned.
> 
> from StringIO import StringIO
> 
> def generator_file(rsspath,titleintro,tickeropt): 
>  scripter=StringIO()
>  scripter.write('\n')
>  scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath,
> titleintro, tickeropt))
>  scripter.write('\n')
>  return scripter.getvalue()
> 
> I tried adding this:
> 
> scripter = scripter.replace("<", "<")
> scripter = scripter.replace(">", ">")
> 
> But obviously replace() isn't an attribute of StringIO so I guess I
> need to convert it to a string first, can someone please advise how I
> can do this? 
> 

How strange, you are already "converting" to a string in the return
line (the call to the getvalue() method), so:

scripter = scripter.getvalue().replace("<", "<")
scripter = scripter.replace(">", ">")
return scripter

should do what you want.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wx.grid question (trying to use code from Grid_Example.py)

2006-10-16 Thread paul
[EMAIL PROTECTED] schrieb:
> To extend and revise my remarks my error is
> 
>  File "C:\Python24\Lib\site-packages\boa-constructor\test of
> snake\csoundgrid.py", line 8, in create_grid
> win = Grid_MegaExample.MegaTable(self, data, colnames, pugins)
> NameError: global name 'self' is not defined
> Script terminated.
This has nothing to do with wx, you just don't use "self" if you're
_calling_ a method. So:

def create_grid():
win = Grid_MegaExample.MegaTable(data, colnames, pugins)
win.Show(True)

should get you to the next error ;)

cheers
 paul

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Convert StringIO to string

2006-10-16 Thread Jonathan Bowlas








Ok, I think I'm explaining
this badly because I've used getvalue() in the script I originally submitted to
the list, see below:

 

from StringIO import
StringIO

 

def
generator_file(rsspath,titleintro,tickeropt): 

  scripter=StringIO()

  scripter.write('\n')

  scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath, titleintro, tickeropt))

  scripter.write('\n')   return scripter.getvalue()     The problem is this script returns the following:     And I want to replace the < and > characters for < or > so it actually renders correctly in a browser so I'm returned this:  

new rss_ticker(www.bbc.co.uk, True, True)   So what am I doing wrong?   J   -- http://mail.python.org/mailman/listinfo/python-list


Re: comparing Unicode and string


[EMAIL PROTECTED] wrote:
> Hello,
>
> here is something that surprises me.
>
>   #coding: iso-8859-1
>   s1=u"Frau Müller machte große Augen"
>   s2="Frau Müller machte große Augen"
>   if s1 == s2:
>   pass
>
> Running this code produces a UnicodeDecodeError:
>
> Traceback (most recent call last):
>   File "tmp.py", line 4, in ?
> if s1 == s2:
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 6:
> ordinal not in range(128)
>
> I would have expected that "s1 == s2" gives True... or maybe False...
> but raising an error here is unnecessary. I guess that the comparison
> operator decides to convert s2 to a Unicode but forgets that I said
> #coding: iso-8859-1 at the beginning of the file.

The #coding declaration is not effective at runtime. It's
there strictly to guide the compiler in how to compile
byte strings.

The default encoding at run time is ascii unless
it's been set to something else, which is why the
error message specifies ascii.

John Roth

> 
> TIA for any comments.
> 
> Luc Saffre

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Output from subprocess.Popen()

Clodoaldo Pinto Neto <[EMAIL PROTECTED]> wrote:
>Fredrik Lundh wrote:
>> this works for me:
>>
>>  >>> f = subprocess.Popen("set | grep IFS", shell=True,
>> stdout=subprocess.PIPE)
>>  >>> f.stdout.readlines()
>> ["IFS=$' \\t\\n'\n"]
>>
>> what does the above return on your machine?
>
 f = subprocess.Popen("set | grep IFS", shell=True, stdout=subprocess.PIPE)
 f.stdout.readlines()
>["BASH_EXECUTION_STRING='set | grep IFS'\n", "IFS=' \t\n"]
>
>I'm on FC5

OK, there's something going on here:
$ set | grep IFS
IFS=$' \t\n'
$ python
Python 2.4.1 (#2, May  5 2005, 11:32:06)
[GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> f = subprocess.Popen("set | grep IFS", shell=True, stdout=subprocess.PIPE)
>>> f.stdout.readlines()
["IFS=' \t\n"]
>>>

(Hmph, I don't have any other non-Windows boxes with >=2.4 to hand.)

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: A Universe Set

> - the wildcard object, which compares equal to everything else

class MatchAny(object):
def __cmp__(self,other):
return 0

wild = MatchAny()

print wild == 1000
print 1000 == wild
print wild == (1,2,3)
print wild == 'abck'
print wild == wild

print wild != 1000
print 1000 != wild
print wild != (1,2,3)
print wild != 'abck'
print wild != wild


Prints:
True
True
True
True
True
False
False
False
False
False 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web Hosting


Sir Psycho wrote:
> Hi,
>
> With web hosting, does the ISP you chose have to support the framework
> you work with as well?
>
> Im looking at making a site in Python, however, Im lost as to what ISPs
> actually support.

We support any and every thing Python and we are a not-for-profit
cooperative. Check us out:

http://www.HCOOP.net
irc://irc.freenode.org/#hcoop

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Universe Set

"Jorgen Grahn" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Yes. But note that being able to write it yourself is one thing, having it
> in the Standard Library and known to anyone is another.
>

Perhaps you could compile the submissions in this thread into an entry in 
the Python Cookbook.  Probably the next best thing to being in the stdlib, 
and it might even make it into the next print edition (earning you a free 
copy!).

-- Paul


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: comparing Unicode and string

On 2006-10-16, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hello,
>
> here is something that surprises me.
>
>   #coding: iso-8859-1

I think that's supposed to be:

# -*- coding: iso-8859-1 -*-

The special comment changes only the encoding of unicode
literals. In particular, it doesn't change the default encoding
of str literals.

>   s1=u"Frau Müller machte große Augen"
>   s2="Frau Müller machte große Augen"
>   if s1 == s2:
>   pass

On my machine, the ü and ß in s2 are being stored in the code
points of my terminal's encoding, cp437. Unforunately cp437 code
points from 127-255 are not the same as those in iso-8859-1.

To fix this, I have to do the following:

>>> s1 == s2.decode('cp437')
True

> Running this code produces a UnicodeDecodeError:
>
> Traceback (most recent call last):
>   File "tmp.py", line 4, in ?
> if s1 == s2:
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 6:
> ordinal not in range(128)
>
> I would have expected that "s1 == s2" gives True... or maybe
> False... but raising an error here is unnecessary. I guess that
> the comparison operator decides to convert s2 to a Unicode but
> forgets that I said #coding: iso-8859-1 at the beginning of the
> file.

It's trying to interpret s2 as ascii, and failing, since 129 and
225 code points are out of range.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Universe Set


>> - the wildcard object, which compares equal to everything else

Paul> class MatchAny(object):
Paul> def __cmp__(self,other):
Paul> return 0

Paul> wild = MatchAny()

...

You're at the mercy of the comparison machinery implemented by individual
classes.  Executing this script (using any of Python 2.3 through what's
currently in the SVN repository):

import datetime

class MatchAny(object):
def __cmp__(self,other):
return 0

wild = MatchAny()

print wild == datetime.datetime.now()
print datetime.datetime.now() == wild
print wild != datetime.datetime.now()
print datetime.datetime.now() != wild

yields

False
False
True
True

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


Strange Behavior

class Foo:
def __init__(self, name, data=[]):
self.name = name
self.data = data

def addData(self, val):
self.data.append(val)


f = Foo('a')
f.addData(1)
f.addData(2)

f2 = Foo('b')

print f.name, f.data
print f2.name, f2.data


OUTPUT
---
a [1, 2]
b [1, 2]


why would f and f2 contain the same data??

however, if I do this instead

f = Foo('a')
f.addData(1)
f.addData(2)

f2 = Foo('b', [])

print f.name, f.data
print f2.name, f2.data


OUTPUT
---
a [1, 2]
b []


Any ideas?  is this a bug?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange Behavior

abcd wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

> class Foo:
> def __init__(self, name, data=[]):

http://docs.python.org/ref/function.html#l2h-619

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


How to increase buffer size of a file ?

Hello !

How to increase buffer size of a file ?
I want to use more buffer, but I don't want to replace every file object 
with my class.

It have a contant in a module ?

Thanks for your help:
dd

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange Behavior

Rob Williscroft wrote:
> http://docs.python.org/ref/function.html#l2h-619


thanks.  weird that it works that way since they even state "This is
generally not what was intended."

oh well.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send E-mail without an external SMTP server ?

On 2006-10-16, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Yes, I want to find a way to send email without an external smtp server.

If you're not going to use an SMTP server, what sort of server
do you want to use?

-- 
Grant Edwards   grante Yow!  Let me do my TRIBUTE
  at   to FISHNET STOCKINGS...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange Behavior

On Mon, 16 Oct 2006 07:26:05 -0700, abcd wrote:

> class Foo:
> def __init__(self, name, data=[]):

The binding of the name "data" to the empty list happens at compile time,
not runtime.

> self.name = name
> self.data = data
> 
> def addData(self, val):
> self.data.append(val)

Every time you call addData on an instance, it appends to the same list.
So all instances created with Foo(name) share the same list in data.

Think of it like this:

some_list = []
x = Foo("fred", some_list)
y = Foo("wilma", some_list)

Isn't it obvious now that both instances share the same list? That x.data
and y.data don't just have the same value, but are the same object? The
same thing happens when you set the default.


> f = Foo('a')
> f.addData(1)
> f.addData(2)
> 
> f2 = Foo('b', [])

And in this case, you've passed a DIFFERENT empty list as an argument.


The normal Python way for handling this situation is to not use mutable
objects as defaults unless you want this behaviour. Instead, use None as
the default value:

class Foo:
def __init__(self, name, data=None):
self.name = name
if data is None: self.data = []
else: self.data = data


> Any ideas?  is this a bug?

Well, it's a bug in your code :)

It isn't a bug in Python. At worst, it is a "gotcha", but it is a
deliberate design decision, and quite useful. For example, this is good
for caching complicated calculations:

def function(x, _cache={}):
# _cache is initialised to an empty dictionary at compile time
if _cache.has_key(x):
return _cache[x]
else:
# complicated and time consuming calculation happens
_cache[x] = result
return result




-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange Behavior

Steven D'Aprano <[EMAIL PROTECTED]> writes:
> It isn't a bug in Python. At worst, it is a "gotcha", but it is a
> deliberate design decision, and quite useful. For example, this is good
> for caching complicated calculations:
> 
> def function(x, _cache={}):
> # _cache is initialised to an empty dictionary at compile time
> if _cache.has_key(x):
> return _cache[x]

The above can be done explicitly:

 def function(x):
 if function._cache.has_key(x):
 return function._cache[x]
 ...
 # function gets an initially-empty cache
 function._cache = {}

So the existing behavior, while not a bug (since it's documented), may
well be a wart.
-- 
http://mail.python.org/mailman/listinfo/python-list


set operations on dictionaries?

A suggestion:In effect, sets are dictionaries without values. (Even thought their implementation is different)My suggestion would be to generalise set operations (such as union, intersection, etc.) to work for dictionaries just as they work on sets.>>> Set([1,2,3]) - Set([3,4])Set([1, 2])>>> {1: 10, 2: 20, 3: 30} - {3: 30, 4: 40}should give{1: 10, 2:20}instead of"TypeError: unsupported operand type(s) for -: 'dict' and 'dict'"Similarly, union ( | ) and intersetion ( & ) should also be very useful for dictionaries.It should be quite obvious what should happen when the values stored for the relevant keys are identical. It is less obvious (and needs some though) what should  happen when the keys are the same in the
 two operands,  but the values are different.E.g. Should{1: 10, 2: 20} | {2: 25, 3:30}give an error message (because the values for the key 2 don't match), or should this value conflict be somehow resolved automatically?Similarly, should intersection and differenc eliminate keys only when the keys match, or not.I think this would be useful. Would this be worth implementing? Would it be difficult to implement?-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Strange Behavior

On 2006-10-16, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> Well, it's a bug in your code :)
>
> It isn't a bug in Python. At worst, it is a "gotcha", but it is
> a deliberate design decision, and quite useful. For example,
> this is good for caching complicated calculations:

I'd say the feature is "usable" rather than "useful", like
bitfields in C.

-- 
Neil Cerutti
Next Sunday Mrs. Vinson will be soloist for the morning service.
The pastor will then speak on "It's a Terrible Experience."
--Church Bulletin Blooper 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Universe Set

On 10/16/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> You're at the mercy of the comparison machinery implemented by individual
> classes.

Plus, if you put a wildcard object into a set (or use it as a
dictionary key) you'll confuse yourself horribly.

I know I did. ;-)

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


jython and toString

Hello,

For one java class (Hello) i use another (HelloPrinter) to build the
string representation of the first one. When i've tried to use this
from within jython,  HelloPrinter.toString(hello) call gives results
like Object.toString() of hello has being called. The example below
shows this behaviour.
Could somebody explain this?


// Hello.java
package jythontest;
public class Hello {
private String name;
public Hello(String name)
{
this.name = name;
}
public String sayHello()
{
return "Hello, "+name;
}
}

// HelloPrinter.java
package jythontest;
public class HelloPrinter {
public static String toString(Hello h)
{
return h.sayHello();
}

public static String toMyString(Hello h)
{
return h.sayHello();
}
}



#  calljava.py
from jythontest import *
h = Hello("theName")
print h
print HelloPrinter.toString(h)
print HelloPrinter.toMyString(h)

OUTPUT:
[EMAIL PROTECTED]   // GOOD
[EMAIL PROTECTED]   // WRONG
Hello, theName // GOOD


Jython 2.1 on java (JIT: null)

java version "1.5.0_03"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_03-b07)
Java HotSpot(TM) Server VM (build 1.5.0_03-b07, mixed mode)

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Convert StringIO to string

Your suggestion didn't seem to make any difference at all, it still returns



Any other ideas?

Jon


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Rob
Williscroft
Sent: 16 October 2006 14:37
To: [email protected]
Subject: Re: Convert StringIO to string

Jonathan Bowlas wrote in
news:[EMAIL PROTECTED] in
comp.lang.python: 

> Hi listers,
> 
> I've written this little script to generate some html but I cannot get 
> it to convert to a string so I can perform a replace() on the >, 
> < characters that get returned.
> 
> from StringIO import StringIO
> 
> def generator_file(rsspath,titleintro,tickeropt): 
>  scripter=StringIO()
>  scripter.write('\n')
>  scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath, 
> titleintro, tickeropt))
>  scripter.write('\n')
>  return scripter.getvalue()
> 
> I tried adding this:
> 
> scripter = scripter.replace("<", "<") scripter = 
> scripter.replace(">", ">")
> 
> But obviously replace() isn't an attribute of StringIO so I guess I 
> need to convert it to a string first, can someone please advise how I 
> can do this?
> 

How strange, you are already "converting" to a string in the return line
(the call to the getvalue() method), so:

scripter = scripter.getvalue().replace("<", "<")
scripter = scripter.replace(">", ">")
return scripter

should do what you want.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to increase buffer size of a file ?

durumdara wrote:

> How to increase buffer size of a file ?
> I want to use more buffer, but I don't want to replace every file object 
> with my class.

the open() file factory takes the buffer size as an optional third 
argument.  see the documentation for details.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web Hosting

Sir Psycho wrote:
> Hi,
> 
> With web hosting, does the ISP you chose have to support the framework
> you work with as well?

It at least has to support a reasonable way to deploy an application
using the said framework - now what this implies depends on the choosen
framework.

> Im looking at making a site in Python, however, Im lost as to what ISPs
> actually support. Some ISPs say they support Python so does that mean
> if I wanted to use TurboGears It would just work anyway?
> 
> If an ISP just mentions Python support, does it mean CGI only
> scripting?

It really depends on the ISP. You have to check on case by case basis.

> I always assumed a framework was just a set of libraries you import
> into your project and things just start working...like a jar file in
> Java.

Things may get a bit more complicated when it comes to web applications.
FWIW, I'm not sure you can deploy any web applications in Java without a
(distinct, long-running process) application server... In the very worst
case, Python has at least CGI support (now why would anyone go for an
ISP that doesn't provide a better Python support is another question !-).




-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange Behavior

Steven D'Aprano wrote:

> It isn't a bug in Python. At worst, it is a "gotcha", but it is a
> deliberate design decision, and quite useful. For example, this is good
> for caching complicated calculations:

it's also used to pass in *objects* instead of names into an inner scope.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: jython and toString


ivansh wrote:

> Hello,
>
> For one java class (Hello) i use another (HelloPrinter) to build the
> string representation of the first one. When i've tried to use this
> from within jython,  HelloPrinter.toString(hello) call gives results
> like Object.toString() of hello has being called. The example below
> shows this behaviour.
> Could somebody explain this?
>
>
> // Hello.java
> package jythontest;
> public class Hello {
>   private String name;
>   public Hello(String name)
>   {
>   this.name = name;
>   }
>   public String sayHello()
>   {
>   return "Hello, "+name;
>   }
> }
>
> // HelloPrinter.java
> package jythontest;
> public class HelloPrinter {
>   public static String toString(Hello h)
>   {
>   return h.sayHello();
>   }
>
>   public static String toMyString(Hello h)
>   {
>   return h.sayHello();
>   }
> }
>
>
>
> #  calljava.py
> from jythontest import *
> h = Hello("theName")
> print h
> print HelloPrinter.toString(h)
> print HelloPrinter.toMyString(h)
>
> OUTPUT:
> [EMAIL PROTECTED]   // GOOD
> [EMAIL PROTECTED]   // WRONG
> Hello, theName // GOOD
>
>
> Jython 2.1 on java (JIT: null)
>
> java version "1.5.0_03"
> Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_03-b07)
> Java HotSpot(TM) Server VM (build 1.5.0_03-b07, mixed mode)


I'm guessing your toString(Hello h) is never being called because
there's another toString(something) behind the scenes that's being
preferred. I could be well wrong, but I'm guessing toString isn't meant
to be static, and when you create an object in Java they inherit from
object which defines a default toString. It might be a temporary object
of type HelloPrinter is created in the call to "print
HelloPrinter.toString(h)", and the method you end up calling is the
toString for that temporary (not your static one). This would
especially make sense if there's a version of toString which takes an
object, and returns its toString result...

I'm basing this purely on the fact PrintHello.toMyString() works... so
take with a pinch of salt.

Jon.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert StringIO to string

Jonathan Bowlas wrote:

> Ok, I think I'm explaining this badly because I've used getvalue() in 
> the script I originally submitted to the list, see below:
> 
> from StringIO import StringIO
> 
> def generator_file(rsspath,titleintro,tickeropt):
> 
>   scripter=StringIO()
> 
>   scripter.write('\n')
> 
>   scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath, 
> titleintro, tickeropt))
> 
>   scripter.write('\n')
> 
>   return scripter.getvalue()
> 
> The problem is this script returns the following:
> 
> 

no, it doesn't.  it returns " So what am I doing wrong?

coding under the influence of confusion?

can you post the code that calls generator_file() and the code that 
writes the return value to the browser?



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: set operations on dictionaries?


It should be quite obvious what should happen when the values stored for
the relevant keys are identical. It is less obvious (and needs some
though) what should happen when the keys are the same in the two
operands, but the values are different.

I think you answered you own proposal in the negative.  Precisely because
the result of this example

{1: 10, 2: 20} | {2: 25, 3:30}

is ill-defined, Python shouldn't implement set operations on dictionaries.

"In the face of ambiguity, refuse the temptation to guess."

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange Behavior

abcd wrote:

> Rob Williscroft wrote:
>> http://docs.python.org/ref/function.html#l2h-619
> 
> 
> thanks.  weird that it works that way since they even state "This is
> generally not what was intended."

The "not intended" refers to the programmer making the mistake of creating a
shared instance - which usually isn't intended, as you yourself are an
example of.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Output from subprocess.Popen()

Now we have 3 different outputs from 3 people to the command:
>>> f = subprocess.Popen("set | grep IFS", shell=True,
 stdout=subprocess.PIPE)
>>> f.stdout.readlines()

>From me on FC5:
["BASH_EXECUTION_STRING='set | grep IFS'\n", "IFS=' \t\n"]

>From Fredrik Lundh on unknown OS:
["IFS=$' \\t\\n'\n"]

>From Sion Arrowsmith on Debian 1:3.3.5-12:
["IFS=' \t\n"]

I found this problem while developing a CGI shell:
http://code.google.com/p/cgpy-shell/

Although the cgi-shell is working quite well, this issue is a show
stopper for that project. I need a stable/reliable output from Popen().
It looks like each bash or sh version outputs things differently, with
different escaping.

It is not a problem if there is only one or more than one line in the
returned list as i will always get the last one. The problem is the
escaping.

-- 
http://mail.python.org/mailman/listinfo/python-list


dynamic module loading via __import__, nonetype?

Hi all,

I'm trying to create a setup which allows a program to request an object
using strings and get an object of that type. It appears to be mostly
working but i have difficulties if i attempt to load a module at runtime
and then request an object of that type.

Essentially, my code works as follows:

I have a registry class which has a method to register a class. It
inserts an entry into a dictionary using a tuple of two strings (read
from attributes of the class) that points to the class. It also has a
method which will create an object of that class type which takes two
strings as an argument.

Every class i want to use this technique inherits from a class which
uses a custom metaclass. The custom metaclass' __init__ function
registers them with the registry class.

The registry class has another method which allows you to specify a path
to place your plugins in. In reality it merely appends this string to
sys.path. The registry "create" function has a little extra smarts in
that if it can't find the class already in the dictionary, it will
attempt to load the appropriate module. It does this by using __import__
and uses the two strings supplied with a dot in between as the module name.

If i manually import a module, this method works a treat, however if i
attempt to dynamically load a module at runtime the create method fails
with the following error:

TypeError: 'NoneType' object is not callable

I can see that the module is getting imported as i have set print
statements in the custom metaclass to let me know when it is registering
a new class. I can only conclude then that there is some difference
between using the import statement and the __import__ function.

I don't want to clutter the mailing list so i haven't attached any code,
but i certainly can supply it assuming the answer isn't something
obvious i've missed. Am i going about this completely the wrong way? Is
there already an established approach for an auto-registering,
dynamically loading plugin setup? Any help greatly appreciated.

I'm not subscribed to the list, so please cc me in any replies.

Thanks,

John Allman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Book about database application development?

Paul Rubin wrote:
> http://philip.greenspun.com/sql/

There was a time (some time in the mid 90s) when I thought that Philip
Greenspun had a Clue. Then I realised just how wrong he was (he started
off reasonably right, he just didn't keep up when the world moved on).
The highlight of this process was seeing him booed during a conference
keynote speech -- by angry librarians and museum curators  (he deserved
it too).

I can't imagine any topic, except possibly dog grooming, where I'd
listen to his advice.

-- 
http://mail.python.org/mailman/listinfo/python-list


Problem: Python search path - module order

Hello!

I have a shared hosting account at GrokThis.net and have a problem with
the module order of the Python search path.

I'd like to use django's svn trunk instead of the
"Django-0.95-py2.4.egg" provided in site-packages.

The problem is that the "django egg" gets preference over the "django
svn trunk" module I manually added to PYTHONPATH...

Instead of being prepended to the top of sys.path, the "django svn
trunk" module gets inserted AFTER the eggs that are in
"/usr/lib/python2.4/site-packages".

I use ~/.bash_profile to set:

export PYTHONPATH="$HOME/local/lib/python:$HOME/django_src"


where "django_src" is the location of django's svn trunk directory

sys.path contains:


/usr/lib/python2.4/site-packages/flup-0.5-py2.4.egg
/usr/lib/python2.4/site-packages/setuptools-0.6c1-py2.4.egg
/usr/lib/python2.4/site-packages/Django-0.95-py2.4.egg
/usr/lib/python2.4/site-packages/Myghty-1.0.2-py2.4.egg
/usr/lib/python2.4/site-packages/PasteScript-0.9.7-py2.4.egg
/usr/lib/python2.4/site-packages/PasteDeploy-0.9.6-py2.4.egg
/usr/lib/python2.4/site-packages/Paste-0.9.7-py2.4.egg
/usr/lib/python2.4/site-packages/Routes-1.4-py2.4.egg
/usr/lib/python2.4/site-packages/Cheetah-1.0-py2.4-linux-x86_64.egg
/home/shared/username/local/lib/python
/home/shared/username/django_src
/usr/lib/python24.zip
/usr/lib/python2.4
/usr/lib/python2.4/plat-linux2
/usr/lib/python2.4/lib-tk
/usr/lib/python2.4/lib-dynload
/usr/local/lib/python2.4/site-packages
/usr/lib/python2.4/site-packages
/usr/lib/python2.4/site-packages/PIL



importing django form the Python console renders:

>>> import django
>>> django.VERSION
(0, 95, 'post-magic-removal')
>>>


Is there a way to give the "django svn trunk" module preference over
the "django egg" (i.e. to have the "django svn trunk" inserted BEFORE
the eggs listed)??

Does anyone know a solution to this problem? Any help would be greatly
appreciated!

Best regards,
Aznach

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange Behavior

On Mon, 2006-10-16 at 10:51, Steven D'Aprano wrote:
> On Mon, 16 Oct 2006 07:26:05 -0700, abcd wrote:
> 
> > class Foo:
> > def __init__(self, name, data=[]):
> 
> The binding of the name "data" to the empty list happens at compile time,
> not runtime.

I think this statement needs to be clarified. The binding of "data" to
the empty list *does* happen at runtime, not at compile time. However,
the binding happens only once, when the "def" statement is executed, as
opposed to every time the __init__ function is called.

-Carsten


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange Behavior

Carsten Haese wrote:

> I think this statement needs to be clarified. The binding of "data" to
> the empty list *does* happen at runtime, not at compile time. However,
> the binding happens only once, when the "def" statement is executed, as
> opposed to every time the __init__ function is called.

to be precise, it happens every time the "def" statement is executed.



-- 
http://mail.python.org/mailman/listinfo/python-list


SAPI and Python

Ok - I've done a lot of searching with google for info on 
what I'm about to ask, and haven't found enough to accomplish
what I'm after - so if anyone has the answers (or even
just ideas on how to proceed) I'd love the help.

I'm fairly new to Python, but not to OO programming.  I've
written a simple wx application that uses an SpSharedRecognizer
for voice recognition, and currently sendKeys to send control
applications.  The basic ideas came from Inigo Surguy's 
web page describing voice recognition in Python.

The problems:

1.  The application is specifically tailored to World of Warcraft, 
and it will not be useful to the folks who might otherwise use it
if I can't share the audio in with Teamspeak and/or Ventrillo.  I
currently have Push-to-Talk implemented by clearing the wordsrule
when it's not listening and setting it when it is.  That, as far
as I can tell, will not allow another app to grab the audio in 
device.

My first notion of an idea on how to accomplish this came from the
following code at http://msdn.microsoft.com/library/default.asp?
url=/library/en-us/SAPI51sr/html/VB_ISpeechRecognizer_AudioInput.asp

It looks there like they are releasing the audio-in.  However, setting
the AudioInput property to None in Python results in an exceptions with
a type mismatch.

Question:  Do you think clearing the AudioInput property will actually
release the audio-in?  And, what is the correct way to do it in Python?

2.  sendKeys works - but it has the problem of causing McAfee to perk
up and raise a warning on the python interpreter.  I can tell it to allow
the script to run, but it only works until the next time I close and 
restart the application. 

Question:  Is sendEvent a better way to do this?  And is there a nice
web site with sample python code about it?

Thanks from a python newbie for any insights you folks have.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: What's up with the starship?


[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] wrote:

--snip--

> As far as I can tell, the machine was compromised on 2006-09-02.

So it was compromised for over a month.

> Irritatingly we didn't find out until just after logrotate had deleted
> the logs for around the time of the attack.

Murphy strikes again. :-(

> It wasn't a very subtle rootkit -- installing a version of netstat with
> different command line options, for example...
>
> > 5. Verifying that such a thing has not happened can be very
> > difficult, particularly if the date and other details of the
> > compromise cannot be accurately determined.
>
> I guess you should find out from the author of whatever you downloaded
> what the checksums should have been for what you downloaded and check
> that against what you downloaded.
>
> If you don't still have the downloaded files, I can tell you what the
> md5's of the files in the back up are.

I don't think that would help in the case of Pywin32 since the
Sourceforge dates for build 210 are 9/22.
I emailed Mark Hammond but have not heard anything back yet.

> > 6. Many organisations give image and pr a higher priority
> > than the safety of their customers/users and wave off security
> > breechs with "don't worry, everything is fine.  We're sure
> > nothing has been touched" when in fact they have no idea.
>
> There is no organization behind python.net.
>
> I am a volunteer.  I help run python.net in my spare time.

Organizations do not have to be formal or official to exhibit
similar behavior.

> > 7. I have seen no public statements or information about
> > this leading me to wonder about the stuation and how it's
> > being handled, hence my seeking of further information.
>
> I'm sorry, I'm busy trying to get the server going again.

I understand, and appreciate your (and the other people
involved) efforts.  I know it must be a royal pain in the
ass.  But I am still responsible for the code I (and my
clients) run so I had to ask.

> > But, I am still completely at a loss why you, he, or anyone,
> > based on the information presented so far,.would conclude
> > that the python security problem is unrelated.
>
> Why would it be?  For all it's position in the community, there aren't
> actually many python web apps running on python.net, certainly not as
> root...

That's what one would hope but to assume that without better
information (such as you just provided) would be foolish.

Thanks again for taking the time to answer my questions.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: What's up with the starship?


[EMAIL PROTECTED] wrote:

> > > 5. Verifying that such a thing has not happened can be very
> > > difficult, particularly if the date and other details of the
> > > compromise cannot be accurately determined.
> >
> > I guess you should find out from the author of whatever you downloaded
> > what the checksums should have been for what you downloaded and check
> > that against what you downloaded.
> >
> > If you don't still have the downloaded files, I can tell you what the
> > md5's of the files in the back up are.
>
> I don't think that would help in the case of Pywin32 since the
> Sourceforge dates for build 210 are 9/22.
> I emailed Mark Hammond but have not heard anything back yet.

In the case of pywin32, are you at all sure that you actually
downloaded anything from starship.python.net?  AFAICT all the files are
now hosted on sf, and there doesn't seem to be any vaguely new files in
the backup of /home/www.

Cheers,
mwh

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: What's up with the starship?

[EMAIL PROTECTED] wrote:

> But, I am still completely at a loss why you, he, or anyone,
> based on the information presented so far,.would conclude
> that the python security problem is unrelated.

Because he's read the security advisory, perhaps, and understands what 
it says?



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: What's up with the starship?


[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] wrote:
>
> > I don't think that would help in the case of Pywin32 since the
> > Sourceforge dates for build 210 are 9/22.
> > I emailed Mark Hammond but have not heard anything back yet.
>
> In the case of pywin32, are you at all sure that you actually
> downloaded anything from starship.python.net?  AFAICT all the files are
> now hosted on sf, and there doesn't seem to be any vaguely new files in
> the backup of /home/www.

The files I downloaded were from sourceforge.  I don't know if
starship.python.net hosts the source files or plays any role in
building the disrtribution package.  It may be that is all done
elsewhere.  But given starship.python.net's historical association
with Pywin32, I am not going to just assume that.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-list Digest, Vol 37, Issue 292

thanks,do not sentonother message it's enougth


---
For super low premiums, click here http://www.webmail.co.za/dd.pwm

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: What's up with the starship?


Fredrik Lundh wrote:
> [EMAIL PROTECTED] wrote:
>
> > But, I am still completely at a loss why you, he, or anyone,
> > based on the information presented so far,.would conclude
> > that the python security problem is unrelated.
>
> Because he's read the security advisory, perhaps, and understands what
> it says?

Then perhaps you or he could explain it to us less intelligent
people in very simple terms?

-- 
http://mail.python.org/mailman/listinfo/python-list


urllib.urlopen: Errno socket error

Hi,

I'm just trying to read from a webpage with urllib but I'm getting
IOErrors. This is my code:

import urllib
sock = urllib.urlopen("http://www.google.com/";)

and this is the error:

Traceback (most recent call last):
  File "", line 1, in 
sock = urllib.urlopen("http://www.google.com/";)
  File "C:\Python25\lib\urllib.py", line 82, in urlopen
return opener.open(url)
  File "C:\Python25\lib\urllib.py", line 190, in open
return getattr(self, name)(url)
  File "C:\Python25\lib\urllib.py", line 325, in open_http
h.endheaders()
  File "C:\Python25\lib\httplib.py", line 856, in endheaders
self._send_output()
  File "C:\Python25\lib\httplib.py", line 728, in _send_output
self.send(msg)
  File "C:\Python25\lib\httplib.py", line 695, in send
self.connect()
  File "C:\Python25\lib\httplib.py", line 679, in connect
raise socket.error, msg
IOError: [Errno socket error] (10060, 'Operation timed out')

I'm behind my company's firewall. Would that cause a problem? If it
does, How do I get around it?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: set operations on dictionaries?

              It should be quite obvious what should happen when the values stored forthe relevant keys are identical. It is less obvious (and needs somethough) what should happen when the keys are the same in the twooperands, but the values are different.I think you answered you own proposal in the negative.  Precisely becausethe result of this example{1: 10, 2: 20} | {2: 25, 3:30}is ill-defined, Python shouldn't implement set operations
 on dictionaries."In the face of ambiguity, refuse the temptation to guess."I understand this point but this is just an argument for saying that it should throw an exception when the values don't match. It is not an argument for not doing the logical thing when they do. In fact in many situations it can be reasonably expected that the values will be the same. If not, give an error. There is no danger in that. The programmer should know whether this is a reasonable expectation in any givn case.(As it is at the moment, you get an error even if they match...)-- 
http://mail.python.org/mailman/listinfo/python-list

Re: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python

Kay Schluehr wrote:
> Bruno Desthuilliers wrote:
> 
>> Just for the record : Ruby's code-blocks (closures, really) come from
>> Smalltalk, which is still the OneTrueObjectLanguage(tm).
> 
> IsTheOneTrueObjectLanguage(tm)ReallyCamelCased?
> 
ThatsAGoodQuestion.

DoYouMeanIsTheIdentifierTheOneTrueObjectLanguage(tm)CamelCasedOrIsTheObjectObjectBoundToIdentifierTheOneTrueObjectLanguage(tm)CamelCasedOrYetSomethingElse?

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Need a strange sort method...

I have a list and I need to do a custom sort on it...

for example:
a = [1,2,3,4,5,6,7,8,9,10] #Although not necessarily in order

def cmp(i,j):  #to be defined in this thread.

a.sort(cmp)

print a
[1,4,7,10,  2,5,8, 3,6,9]

So withouth making this into an IQ test.
Its more like
1 4 7 10
2 5 8
3 6 9

Read that top to bottom from column 1 to column 4.
When you get to the bottom of a column move to the next column.
Get it?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web Hosting

> With web hosting, does the ISP you chose have to support the framework
> you work with as well?
>
> Im looking at making a site in Python, however, Im lost as to what ISPs
> actually support. Some ISPs say they support Python so does that mean
> if I wanted to use TurboGears It would just work anyway?
>

Check out http://webfaction.com...  They have a one-click TurboGears
installation procedure (as well as some other frameworks) but you can
also install your own custom frameworks if they don't support it
directly.

HTH,

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: set operations on dictionaries?

> I understand this point but this is just an argument for
> saying that it should throw an exception when the values don't
> match. It is not an argument for not doing the logical thing
> when they do. In fact in many situations it can be reasonably
> expected that the values will be the same. If not, give an
> error. There is no danger in that. The programmer should know
> whether this is a reasonable expectation in any givn case. (As
> it is at the moment, you get an error even if they match...)

Well, the operation as you describe it is easy enough to implement:

 >>> d1 = {1:42, 2:43, 3:44}
 >>> d2 = {1:42, 2:55, 5:66}
 >>> dict((k,v) for k,v in d1.items() if k in d2)
{1: 42, 2: 43}
 >>> dict((k,v) for k,v in d1.items() if k in d2 and d2[k] == v)
{1: 42}

depending on whether you want to enforce the matching of the 
values as well.

Sure, it's not a native operator, but given the ambiguity of the 
definition (do you or don't you include the values in the 
comparison?), it's best to leave it as a function rather than 
trying to shoehorn it into the __sub__ operator.

-tkc



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: What's up with the starship?

[EMAIL PROTECTED] wrote:

> Then perhaps you or he could explain it to us less intelligent
> people in very simple terms?

the security advisory explains that the cause of the problem is a bug
in the source code used to implement repr() for 32-bit Unicode strings, 
on all Python versions from 2.2 and onwards.

Python 2.2 was released in 2001.



-- 
http://mail.python.org/mailman/listinfo/python-list


Alphabetical sorts


I have several applications where I want to sort lists in alphabetical order. 
Most examples of sorting usually sort on the ord() order of the character set 
as 
an approximation.  But that is not always what you want.

The solution of converting everything to lowercase or uppercase is closer, but 
it would be nice if capitalized words come before lowercase words of the same 
spellings.  And I suspect ord() order may not be correct for some character 
sets.

So I'm wandering what others have done and weather there is something in the 
standard library I haven't found for doing this.

Below is my current way of doing it, but I think it can probably be improved 
quite a bit.

This partial solution also allows ignoring leading characters such as spaces, 
tabs, and underscores by specifying what not to ignore.  So '__ABC__' will be 
next to 'ABC'.  But this aspect isn't my main concern.

Maybe some sort of alphabetical order string could be easily referenced for 
various alphabets instead of having to create them manually?

Also it would be nice if strings with multiple words were ordered correctly.


Cheers,
   _Ron



def stripto(s, goodchrs):
 """ Removes leading and trailing characters from string s
 which are not in the string goodchrs.
 """
 badchrs = set(s)
 for c in goodchrs:
 if c in badchrs:
 badchrs.remove(c)
 badchrs = ''.join(badchrs)
 return s.strip(badchrs)


def alpha_sorted(seq):
 """ Sort a list of strings in 123AaBbCc... order.
 """
 order = ( '0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNn'
   'OoPpQqRrSsTtUuVvWwXxYyZz' )
 def chr_index(value, sortorder):
 """ Make a sortable numeric list
 """
 result = []
 for c in stripto(value, order):
 cindex = sortorder.find(c)
 if cindex == -1:
 cindex = len(sortorder)+ord(c)
 result.append(cindex)
 return result

 deco = [(chr_index(a, order), a) for a in seq]
 deco.sort()
 return list(x[1] for x in deco)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a strange sort method...

"SpreadTooThin" <[EMAIL PROTECTED]> writes:
> a = [1,2,3,4,5,6,7,8,9,10] #Although not necessarily in order
> 
> def cmp(i,j):  #to be defined in this thread.
> 
> a.sort(cmp)
> 
> print a
> [1,4,7,10,  2,5,8, 3,6,9]

def k(n): return (n-1) % 3, (n-1) // 3
a.sort(key=k)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a strange sort method...

On 16 Oct 2006 11:13:08 -0700, SpreadTooThin <[EMAIL PROTECTED]> wrote:
> I have a list and I need to do a custom sort on it...
>
> for example:
> a = [1,2,3,4,5,6,7,8,9,10] #Although not necessarily in order
>
> def cmp(i,j):  #to be defined in this thread.
>
> a.sort(cmp)
>
> print a
> [1,4,7,10,  2,5,8, 3,6,9]
>
> So withouth making this into an IQ test.
> Its more like
> 1 4 7 10
> 2 5 8
> 3 6 9

>>> a = [1,2,3,4,5,6,7,8,9,10]
>>> a.sort(key=lambda item: (((item-1) %3), item))
>>> a
[1, 4, 7, 10, 2, 5, 8, 3, 6, 9]

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib.urlopen: Errno socket error

Hello,

Try to increase the time out : socket.settimeout(n)
and catch the timeout error when it occurs

Regards



[EMAIL PROTECTED] a écrit :

> Hi,
>
> I'm just trying to read from a webpage with urllib but I'm getting
> IOErrors. This is my code:
>
> import urllib
> sock = urllib.urlopen("http://www.google.com/";)
>
> and this is the error:
>
> Traceback (most recent call last):
>   File "", line 1, in 
> sock = urllib.urlopen("http://www.google.com/";)
>   File "C:\Python25\lib\urllib.py", line 82, in urlopen
> return opener.open(url)
>   File "C:\Python25\lib\urllib.py", line 190, in open
> return getattr(self, name)(url)
>   File "C:\Python25\lib\urllib.py", line 325, in open_http
> h.endheaders()
>   File "C:\Python25\lib\httplib.py", line 856, in endheaders
> self._send_output()
>   File "C:\Python25\lib\httplib.py", line 728, in _send_output
> self.send(msg)
>   File "C:\Python25\lib\httplib.py", line 695, in send
> self.connect()
>   File "C:\Python25\lib\httplib.py", line 679, in connect
> raise socket.error, msg
> IOError: [Errno socket error] (10060, 'Operation timed out')
>
> I'm behind my company's firewall. Would that cause a problem? If it
> does, How do I get around it?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a strange sort method...

SpreadTooThin wrote:

> I have a list and I need to do a custom sort on it...

> Its more like
> 1 4 7 10
> 2 5 8
> 3 6 9

that's trivial to do with slicing, of course.  what makes you think you 
need to do this by calling the "sort" method ?



-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >