Re: Problem occured while sending mail

2008-09-17 Thread sui
On Sep 17, 8:04 pm, Peter Pearson <[EMAIL PROTECTED]> wrote:
> On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui <[EMAIL PROTECTED]> wrote:
> > On Sep 17, 5:04 pm, sui <[EMAIL PROTECTED]> wrote:
> >> this is my code
>
> >> import sys, os, glob, datetime, time
> >> import smtplib
> >> ## Parameters for SMTP session
> >> port=587
> >> SMTPserver=  'smtp.gmail.com'
> >> SMTPuser= '[EMAIL PROTECTED]'
> >> pw= 'fill in here'
> >> SENDER= SMTPuser
>
> >> ## Message details
> >> FROM=  SENDER
> >> TO= '[EMAIL PROTECTED]'
> >> CC=FROM
> >> ##RECEIVERS= (TO, CC)  ##proper way to send to both TO and CC
> >> RECEIVERS= (TO,)  ## ignore the CC address
>
> >> subject= 'Test 1a'
> >> message='*** Email test  *** '
>
> >> print 'Starting SMTPmailsession on %s as  %s ' %
> >> (SMTPserver,SMTPuser)
> >> session = smtplib.SMTP(SMTPserver,port)
> >> session.set_debuglevel(0)  # set debug level to 1 to see details
> >> session.ehlo(SMTPuser)  # say hello
> >> session.starttls()  # TLS needed
> >> session.ehlo(SMTPuser)  # say hello again, not sure why
> >> session.login(SMTPuser, pw)
>
> >> ##Create HEADER + MESSAGE
> >> HEADER= 'From: %s\r\n' % FROM
> >> HEADER= HEADER + 'To: %s\r\n' % TO
> >> HEADER= HEADER + 'Cc: %s\r\n' % CC
> >> HEADER= HEADER + 'Subject: %s\r\n' % subject
> >> BODY= HEADER + '\r\n' + message
> >> print BODY
>
> >> SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY)  ## send email
>
> >> session.close()
>
> >> Now when i run this .py file...as pythonmail.py
> >> i can see only statement
> >> starting smtpmail..n details
> >> then nothing on screen after few minutes or after pressing ctrl +c
> >> Traceback (most recent call last):
> >>   File "mail4.py", line 21, in 
> >> session = smtplib.SMTP(SMTPserver,port)
> >>   File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
> >> (code, msg) = self.connect(host, port)
> >>   File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect
> >> self.sock.connect(sa)
> >>   File "", line 1, in connect
> >> or may be conncetion time out
>
> >> wats the solution for this
>
> > if i dont press cntrl + c then it shows
> > Starting SMTPmailsession on smtp.gmail.com as  [EMAIL PROTECTED]
> > Traceback (most recent call last):
> >   File "mail4.py", line 21, in 
> > session = smtplib.SMTP(SMTPserver,port)
> >   File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
> > (code, msg) = self.connect(host, port)
> >   File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect
> > raise socket.error, msg
> > socket.error: (110, 'Connection timed out')
>
> > plz help me its urgent.i want to complete it as early as possible
>
> I pasted your code into a file named temp.py,
> and (perhaps superstitiously) added a backslash to this line:
>
> >> print 'Starting SMTPmailsession on %s as  %s ' %
>
> Here's what it does (long line wrapped manually):
>
> [EMAIL PROTECTED]:~$ python temp.py
> Starting SMTPmailsession on smtp.gmail.com as  [EMAIL PROTECTED]
> Traceback (most recent call last):
>   File "temp.py", line 27, in ?
> session.login(SMTPuser, pw)
>   File "/usr/lib/python2.4/smtplib.py", line 591, in login
> raise SMTPAuthenticationError(code, resp)
> smtplib.SMTPAuthenticationError: (535,  \
>'5.7.1 Username and Password not accepted. Learn more at\n'  \
>'5.7.1http://mail.google.com/support/bin/answer.py?answer='\
>'14257 a8sm34686663poa.12')
> [EMAIL PROTECTED]:~$
>
> This indicates that it got much farther than when you ran it, since
> your timeout message comes from the smtplib.SMTP call several lines
> before the session.login call.
>
> As a simple connectivity test, you might see whether you can connect
> using telnet:
>
> [EMAIL PROTECTED]:~$ telnet smtp.gmail.com 587
> Trying 72.14.253.109...
> Connected to gmail-smtp.l.google.com.
> Escape character is '^]'.
> 220 mx.google.com ESMTP m27sm34789033pof.6
> ^]c
>
> telnet> c
> Connection closed.
> [EMAIL PROTECTED]:~$
>
> --
> To email me, substitute nowhere->spamcop, invalid->net.

even i couldnt connect using telnet
msg comes host is down
--
http://mail.python.org/mailman/listinfo/python-list


member functions in a class

2008-09-17 Thread Karl Kobata
I am new to python and am wondering.  When I create a class, with 'def'
functions and if this class is instantiated say 50 times.  Does this mean
that all the 'def' functions code within the class is duplicated for each
instance?

Can someone give me a short and simple answer as to what happens in python?

 

Thanks

 

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

XML-schema 'best practice' question

2008-09-17 Thread Frank Millman
Hi all

This is not strictly a Python question, but as I am writing in Python,
and as I know there are some XML gurus on this list, I hope it is
appropriate here.

XML-schemas are used to define the structure of an xml document, and
to validate that a particular document conforms to the schema. They
can also be used to transform the document, by filling in missing
attributes with default values.

In my situation, both the creation and the processing of the xml
document are under my control. I know that this begs the question 'why
use xml in the first place', but let's not go there for the moment.

Using minixsv, validating a document with a schema works, but is quite
slow. I appreciate that lxml may be quicker, but I think that my
question is still applicable.

I am thinking of adding a check to see if a document has changed since
it was last validated, and if not, skip the validation step. However,
I then do not get the default values filled in.

I can think of two possible solutions. I just wondered if this is a
common design issue when it comes to xml and schemas, and if there is
a 'best practice' to handle it.

1. Don't use default values - create the document with all values
filled in.

2. Use python to check for missing values and fill in the defaults
when processing the document.

Or maybe the best practice is to *always* validate a document before
processing it.

How do experienced practitioners handle this situation?

Thanks for any hints.

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


Re: decorator and API

2008-09-17 Thread George Sakkis
On Sep 17, 5:56 pm, Lee Harr <[EMAIL PROTECTED]> wrote:

> I have a class with certain methods from which I want to select
> one at random, with weighting.
>
> The way I have done it is this 
>
> import random
>
> def weight(value):
> def set_weight(method):
> method.weight = value
> return method
> return set_weight
>
> class A(object):
> def actions(self):
> 'return a list of possible actions'
>
> return [getattr(self, method)
> for method in dir(self)
> if method.startswith('action_')]
>
> def action(self):
> 'Select a possible action using weighted choice'
>
> actions = self.actions()
> weights = [method.weight for method in actions]
> total = sum(weights)
>
> choice = random.randrange(total)
>
> while choice> weights[0]:
> choice -= weights[0]
> weights.pop(0)
> actions.pop(0)
>
> return actions[0]
>
> @weight(10)
> def action_1(self):
> print "A.action_1"
>
> @weight(20)
> def action_2(self):
> print "A.action_2"
>
> a = A()
> a.action()()
>
> The problem I have now is that if I subclass A and want to
> change the weighting of one of the methods, I am not sure
> how to do that.
>
> One idea I had was to override the method using the new
> weight in the decorator, and then call the original method:
>
> class B(A):
> @weight(50)
> def action_1(self):
> A.action_1(self)
>
> That works, but it feels messy.
>
> Another idea was to store the weightings as a dictionary
> on each instance, but I could not see how to update that
> from a decorator.
>
> I like the idea of having the weights in a dictionary, so I
> am looking for a better API, or a way to re-weight the
> methods using a decorator.
>
> Any suggestions appreciated.


Below is a lightweight solution that uses a descriptor. Also the
random action function has been rewritten more efficiently (using
bisect).

George

# usage ===

class A(object):

# actions don't have to follow a naming convention

@weighted_action(weight=4)
def foo(self):
print "A.foo"

@weighted_action() # default weight=1
def bar(self):
print "A.bar"


class B(A):
# explicit copy of each action with new weight
foo = A.foo.copy(weight=2)
bar = A.bar.copy(weight=4)

@weighted_action(weight=3)
def baz(self):
print "B.baz"

# equivalent to B, but update all weights at once in one statement
class B2(A):
@weighted_action(weight=3)
def baz(self):
print "B2.baz"
update_weights(B2, foo=2, bar=4)


if __name__ == '__main__':
for obj in A,B,B2:
print obj
for action in iter_weighted_actions(obj):
print '  ', action

a = A()
for i in xrange(10): take_random_action(a)
print
b = B()
for i in xrange(12): take_random_action(b)

#== implementation ===

class _WeightedActionDescriptor(object):
def __init__(self, func, weight):
self._func = func
self.weight = weight
def __get__(self, obj, objtype):
return self
def __call__(self, *args, **kwds):
return self._func(*args, **kwds)
def copy(self, weight):
return self.__class__(self._func, weight)
def __str__(self):
return 'WeightedAction(%s, weight=%s)' % (self._func,
self.weight)

def weighted_action(weight=1):
return lambda func: _WeightedActionDescriptor(func,weight)

def update_weights(obj, **name2weight):
for name,weight in name2weight.iteritems():
action = getattr(obj,name)
assert isinstance(action,_WeightedActionDescriptor)
setattr(obj, name, action.copy(weight))

def iter_weighted_actions(obj):
return (attr for attr in
(getattr(obj, name) for name in dir(obj))
if isinstance(attr, _WeightedActionDescriptor))

def take_random_action(obj):
from random import random
from bisect import bisect
actions = list(iter_weighted_actions(obj))
weights = [action.weight for action in actions]
total = float(sum(weights))
cum_norm_weights = [0.0]*len(weights)
for i in xrange(len(weights)):
cum_norm_weights[i] = cum_norm_weights[i-1] + weights[i]/total
return actions[bisect(cum_norm_weights, random())](obj)
--
http://mail.python.org/mailman/listinfo/python-list


RELEASED Python 2.6rc2 and 3.0rc1

2008-09-17 Thread Barry Warsaw

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On behalf of the Python development team and the Python community, I  
am happy to announce the second and final planned release candidate  
for Python 2.6, as well as the first release candidate for Python 3.0.


These are release candidates, so while they are not suitable for  
production environments, we strongly encourage you to download and  
test them on your software.  We expect only critical bugs to be fixed  
between now and the final releases.  Currently Python 2.6 is scheduled  
for October 1st, 2008.  Python 3.0 release candidate 2 is planned for  
October 1st, with the final release planned for October 15, 2008.


If you find things broken or incorrect, please submit bug reports at

http://bugs.python.org

For more information and downloadable distributions, see the Python  
2.6 website:


http://www.python.org/download/releases/2.6/

and the Python 3.0 web site:

http://www.python.org/download/releases/3.0/

See PEP 361 for release schedule details:

http://www.python.org/dev/peps/pep-0361/

Enjoy,
- -Barry

Barry Warsaw
[EMAIL PROTECTED]
Python 2.6/3.0 Release Manager
(on behalf of the entire python-dev team)

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (Darwin)

iQCVAwUBSNHpw3EjvBPtnXfVAQLW9wP/RBCaUvhuheIh+BjLLIHQFBQi7D3uVgqi
l0+4fhhoKGJvtWklLfSM9I1prcjH/d6tzUu4fIOjX7aM+wZSG++vkfmBoehnhyZW
AvU9Lax4mqDwhOJA2QA0WMx0obpYYVHeUl7D1g9kWzbRUkZDX9NZGMWThhEOC1qA
UA3bBYbvWiQ=
=BFNH
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to Determine Name of the Day in the Week

2008-09-17 Thread Steven D'Aprano
On Wed, 17 Sep 2008 20:34:02 -0700, Mensanator wrote:

> And technically, weeks begin on Sunday, not Monday, but business likes
> to think of Monday as day 0 of the week and it doesn't conflict with any
> prior date format.

There's no "technically" about it. It's an arbitrary starting point, and 
consequently there are different traditions to it, even in English.

Besides, I don't think many businesses think of "day 0" at all. Most 
people outside of IT start counting from 1, not 0.

In British Commonwealth countries, Sunday is the last day of the week, 
not the first, although under American influence that's changing in 
Australia at least.

In Poland, the week begins with Monday ("poniedziałek"). Tuesday, 
"wtorek", means "second day". Other Slavic countries also start with 
Monday.

Similarly, the Lithuanian calendar simple enumerates the days of the 
week, starting with Monday, "pirmadienis" ("first day").

In China, there are at least three different systems of naming the week 
days. In two of them, the week starts with Sunday, but in the third 
system, Sunday is "zhoumo" ("cycle's end") and Monday is zhouyi ("first 
of cycle").



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

Re: A unique instance of Python GUI program

2008-09-17 Thread r0g
akineko wrote:
> Again, thank you for many postings to my question.
> I have reviewed solutions provided.
> Well, I like the named Mutex solution under Windows.
> That is a clean and straight-forward approach to the challenge.
> (I cannot believe that I'm saying good thing about Windows ;-) )
> 
> Unfortunately, I'm living in Unix realm ;-)
> 
> None of solutions for Unix are appealing to me.
> But they must be "the" solution for the challenge as well-established
> software uses those solutions.
> 
> Now, I'm wondering.
> As my program is a GUI (Tkinter) software.
> Is it possible to set a known value to X11 or Tk property through
> Tkinter so that another instance of the program can check if such
> property is set?
> 
> Of course, I know this scheme has a flaw. If one instance uses another
> logical display, then such property is probably not shared.
> But for my usage, it is logically possible but not likely.
> 
> I checked my Tkinter book and found the following function.
> winfo_interps(displayof=0)
> 
> This returns a list of all Tk-based applications currently running on
> the display.
> 
> When I tried, I got the following:
 root.winfo_interps()
> ('tk #3', 'tk #2', 'tk')
> 
> But I couldn't find a way to set a specific name to the Tcl
> interpreter.
> 
> As I'm not an expert of Tcl/Tk and X11, I probably overlooked other
> functions that may do what I need.
> 
> Any comments, suggestions on this?
> Maybe this can provide a platform independent way to ensure that only
> single instance is running.
> 
> Thank you for your attention.
> 
> Best reagrds,
> Aki Niimura


I know it's a hack but couldn't you just open a specific UDP socket and
leave it dangling til your program exits, then if a new instance can't
open that same socket it can gracefully abort? If your program dies the
socket will be freed up again by the OS yes?

Just a thought.

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


Re: Problem occured while sending mail

2008-09-17 Thread sui
On Sep 17, 8:04 pm, Peter Pearson <[EMAIL PROTECTED]> wrote:
> On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui <[EMAIL PROTECTED]> wrote:
> > On Sep 17, 5:04 pm, sui <[EMAIL PROTECTED]> wrote:
> >> this is my code
>
> >> import sys, os, glob, datetime, time
> >> import smtplib
> >> ## Parameters for SMTP session
> >> port=587
> >> SMTPserver=  'smtp.gmail.com'
> >> SMTPuser= '[EMAIL PROTECTED]'
> >> pw= 'fill in here'
> >> SENDER= SMTPuser
>
> >> ## Message details
> >> FROM=  SENDER
> >> TO= '[EMAIL PROTECTED]'
> >> CC=FROM
> >> ##RECEIVERS= (TO, CC)  ##proper way to send to both TO and CC
> >> RECEIVERS= (TO,)  ## ignore the CC address
>
> >> subject= 'Test 1a'
> >> message='*** Email test  *** '
>
> >> print 'Starting SMTP mail session on %s as  %s ' %
> >> (SMTPserver,SMTPuser)
> >> session = smtplib.SMTP(SMTPserver,port)
> >> session.set_debuglevel(0)  # set debug level to 1 to see details
> >> session.ehlo(SMTPuser)  # say hello
> >> session.starttls()  # TLS needed
> >> session.ehlo(SMTPuser)  # say hello again, not sure why
> >> session.login(SMTPuser, pw)
>
> >> ##Create HEADER + MESSAGE
> >> HEADER= 'From: %s\r\n' % FROM
> >> HEADER= HEADER + 'To: %s\r\n' % TO
> >> HEADER= HEADER + 'Cc: %s\r\n' % CC
> >> HEADER= HEADER + 'Subject: %s\r\n' % subject
> >> BODY= HEADER + '\r\n' + message
> >> print BODY
>
> >> SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY)  ## send email
>
> >> session.close()
>
> >> Now when i run this .py file...as python mail.py
> >> i can see only statement
> >> starting smtp mail..n details
> >> then nothing on screen after few minutes or after pressing ctrl +c
> >> Traceback (most recent call last):
> >>   File "mail4.py", line 21, in 
> >> session = smtplib.SMTP(SMTPserver,port)
> >>   File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
> >> (code, msg) = self.connect(host, port)
> >>   File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect
> >> self.sock.connect(sa)
> >>   File "", line 1, in connect
> >> or may be conncetion time out
>
> >> wats the solution for this
>
> > if i dont press cntrl + c then it shows
> > Starting SMTP mail session on smtp.gmail.com as  [EMAIL PROTECTED]
> > Traceback (most recent call last):
> >   File "mail4.py", line 21, in 
> > session = smtplib.SMTP(SMTPserver,port)
> >   File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
> > (code, msg) = self.connect(host, port)
> >   File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect
> > raise socket.error, msg
> > socket.error: (110, 'Connection timed out')
>
> > plz help me its urgent.i want to complete it as early as possible
>
> I pasted your code into a file named temp.py,
> and (perhaps superstitiously) added a backslash to this line:
>
> >> print 'Starting SMTP mail session on %s as  %s ' %
>
> Here's what it does (long line wrapped manually):
>
> [EMAIL PROTECTED]:~$ python temp.py
> Starting SMTP mail session on smtp.gmail.com as  [EMAIL PROTECTED]
> Traceback (most recent call last):
>   File "temp.py", line 27, in ?
> session.login(SMTPuser, pw)
>   File "/usr/lib/python2.4/smtplib.py", line 591, in login
> raise SMTPAuthenticationError(code, resp)
> smtplib.SMTPAuthenticationError: (535,  \
>'5.7.1 Username and Password not accepted. Learn more at\n'  \
>'5.7.1http://mail.google.com/support/bin/answer.py?answer='\
>'14257 a8sm34686663poa.12')
> [EMAIL PROTECTED]:~$
>
> This indicates that it got much farther than when you ran it, since
> your timeout message comes from the smtplib.SMTP call several lines
> before the session.login call.
>
> As a simple connectivity test, you might see whether you can connect
> using telnet:
>
> [EMAIL PROTECTED]:~$ telnet smtp.gmail.com 587
> Trying 72.14.253.109...
> Connected to gmail-smtp.l.google.com.
> Escape character is '^]'.
> 220 mx.google.com ESMTP m27sm34789033pof.6
> ^]c
>
> telnet> c
> Connection closed.
> [EMAIL PROTECTED]:~$
>
> --
> To email me, substitute nowhere->spamcop, invalid->net.

Actually i m working at place where proxy server has been
working..so is it problem caused by that proxy server..peter thnks
for suggestion but still its not working..
--
http://mail.python.org/mailman/listinfo/python-list


Re: A unique instance of Python GUI program

2008-09-17 Thread akineko
Again, thank you for many postings to my question.
I have reviewed solutions provided.
Well, I like the named Mutex solution under Windows.
That is a clean and straight-forward approach to the challenge.
(I cannot believe that I'm saying good thing about Windows ;-) )

Unfortunately, I'm living in Unix realm ;-)

None of solutions for Unix are appealing to me.
But they must be "the" solution for the challenge as well-established
software uses those solutions.

Now, I'm wondering.
As my program is a GUI (Tkinter) software.
Is it possible to set a known value to X11 or Tk property through
Tkinter so that another instance of the program can check if such
property is set?

Of course, I know this scheme has a flaw. If one instance uses another
logical display, then such property is probably not shared.
But for my usage, it is logically possible but not likely.

I checked my Tkinter book and found the following function.
winfo_interps(displayof=0)

This returns a list of all Tk-based applications currently running on
the display.

When I tried, I got the following:
>>> root.winfo_interps()
('tk #3', 'tk #2', 'tk')

But I couldn't find a way to set a specific name to the Tcl
interpreter.

As I'm not an expert of Tcl/Tk and X11, I probably overlooked other
functions that may do what I need.

Any comments, suggestions on this?
Maybe this can provide a platform independent way to ensure that only
single instance is running.

Thank you for your attention.

Best reagrds,
Aki Niimura
--
http://mail.python.org/mailman/listinfo/python-list


cgi-python temporary output

2008-09-17 Thread avehna
Hello:

I would like to generate a temporary output in my cgi-python script where
the user could see the actual program status while the program is still
running behind the web, and know how long approximately it could take, and
then finally display the final cgi-output. I have no idea how something like
that could be done ("temporary output"). I will appreciate any suggestion
from you.

Thank you.

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

Re: decorator and API

2008-09-17 Thread Steven D'Aprano
On Thu, 18 Sep 2008 02:26:29 +0430, Lee Harr wrote:

> I have a class with certain methods from which I want to select one at
> random, with weighting.
> 
> The way I have done it is this 

[snip]


You are coupling the weights, the actions, and the object which chooses 
an action all in the one object. I find that harder to wrap my brain 
around than a more loosely coupled system. Make the chooser independent 
of the things being chosen:


def choose_with_weighting(actions, weights=None):
if weights is None:
weights = [1]*len(actions)  # equal weights
# Taken virtually unchanged from your code.
# I hope it does what you want it to do!
assert len(weights) == len(actions)
total = sum(weights)
choice = random.randrange(total)
while choice > weights[0]:
choice -= weights[0]
weights.pop(0)
actions.pop(0)
return actions[0]


Loosely couple the actions from their weightings, so you can change them 
independently. Here's a decorator that populates a dictionary with 
weights and actions:

def weight(value, storage):
def set_weight(method):
storage[method.__name__] = value
return method
return set_weight


Here's how to use it:

class A(object):
weights = {}
def __init__(self):
self.weights = self.__class__.weights.copy()
@weight(10, weights)
def action_1(self):
print "A.action_1"
@weight(20, weights)
def action_2(self):
print "A.action_2"


The class is now populated with a set of default weights, which is then 
copied to the instance. If you want to over-ride a particular weight, you 
don't need to make a subclass, you just change the instance:

obj = A()
obj.weights["action_1"] = 30

method = choose_with_weighting(obj.weights.keys(), obj.weights.values())
getattr(obj, method)() # call the method



Hope this helps,



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


Re: How to Determine Name of the Day in the Week

2008-09-17 Thread Mensanator
On Sep 17, 10:20 pm, Keo Sophon <[EMAIL PROTECTED]> wrote:
> Fredrik Lundh wrote:
> > Henry Chang wrote:
>
> >> Instead of getting integers with weekday(), Monday == 0 ... Sunday ==
> >> 6; is there a way to get the actual names, such as "Monday ...
> >> Sunday"? I would like to do this without creating a data mapping. :)
>
> > if you have a datetime or date object, you can use strftime with the
> > appropriate formatting code. see the library reference for details.
>
> > if you have the weekday number, you can use the calender module:
>
> > >>> import calendar
> > >>> calendar.day_name[0]
> > 'Monday'
>
> > (the latter also contains abbreviated day names, month names, and a
> > bunch of other potentially useful functions and mappings.)
>
> > 
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Hi,
>
> I've tried calendar.month_name[0], it displays empty string, while
> calendar.month_name[1] is "January"? Why does calendar.month_name's
> index not start with index 0 as calendar.day_name?

Because there's no month 0?

And technically, weeks begin on Sunday, not Monday, but business
likes to think of Monday as day 0 of the week and it doesn't
conflict with any prior date format.

>
> Thanks,
> Sophon

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


Re: How to Determine Name of the Day in the Week

2008-09-17 Thread Keo Sophon

Fredrik Lundh wrote:

Henry Chang wrote:

Instead of getting integers with weekday(), Monday == 0 ... Sunday == 
6; is there a way to get the actual names, such as "Monday ... 
Sunday"? I would like to do this without creating a data mapping. :)


if you have a datetime or date object, you can use strftime with the 
appropriate formatting code. see the library reference for details.


if you have the weekday number, you can use the calender module:

>>> import calendar
>>> calendar.day_name[0]
'Monday'

(the latter also contains abbreviated day names, month names, and a 
bunch of other potentially useful functions and mappings.)




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


Hi,

I've tried calendar.month_name[0], it displays empty string, while 
calendar.month_name[1] is "January"? Why does calendar.month_name's 
index not start with index 0 as calendar.day_name?


Thanks,
Sophon
--
http://mail.python.org/mailman/listinfo/python-list


Re: SMTP via GMAIL

2008-09-17 Thread Grant Edwards
On 2008-09-18, Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> In message
><[EMAIL PROTECTED]>, sui
> wrote:
>
>> Traceback (most recent call last):
>>   File "mail5.py", line 21, in 
>> session = smtplib.SMTP(SMTPserver,port)
>>   File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
>> (code, msg) = self.connect(host, port)
>>   File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect
>> self.sock.connect(sa)
>>   File "", line 1, in connect
>> then conncetion time out.
>
> Could it be your ISP is blocking outgoing connections to port
> 25?

gmail doesn't accept mail via SMTP on port 25.

-- 
Grant

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


Do HTTPError objects always have a read method?

2008-09-17 Thread Steven D'Aprano
I understood that HTTPError objects always have a read method, so they 
can be treated as if they were a webpage. E.g. something like this 
simplified snippet:


address = 'http://www.yahoo.com/spamspamspamspamspam'
try:
conn = urllib2.urlopen(address)
except urllib2.HTTPError, e:
conn = e
print conn.read()  # Print the requested page, or the error page.



But in the source code to urllib2 (Python 2.5):


class HTTPError(URLError, addinfourl):
"""Raised when HTTP error occurs, but also acts like non-error 
return"""
__super_init = addinfourl.__init__

def __init__(self, url, code, msg, hdrs, fp):
self.code = code
self.msg = msg
self.hdrs = hdrs
self.fp = fp
self.filename = url
# The addinfourl classes depend on fp being a valid file
# object.  In some cases, the HTTPError may not have a valid
# file object.  If this happens, the simplest workaround is to
# not initialize the base classes.
if fp is not None:
self.__super_init(fp, hdrs, url)

def __str__(self):
return 'HTTP Error %s: %s' % (self.code, self.msg)



That tells me that HTTPError objects aren't guaranteed to include a file-
like interface. That makes me unhappy.

Under what circumstances do HTTPError objects not have a valid file 
object? How common is this? Does anyone have an example of a URL that 
fails in that fashion?



Thank you,



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


Re: Modifying the system menu

2008-09-17 Thread raj . indian . 08
I tested it again and found that the behaviour is a little different
from what I mentioned previously in the mailchain.
The item is working perfectly the first time around. Now if I close
the application and run it again (which was what I did earlier), if
that application system menu is already modified, it is causing this
issue.

Why would this happen? If it is that the file handle is not obtained,
it wouldnt have gone through the following check at all?
> hw = win32gui.GetSystemMenu(hwnd, False)
> if hw != None:
> win32gui.AppendMenu(hw,win32con.MF_SEPARATOR,0,'-');

Not only did it go through, it failed with an invalid menu handle
error.
--
http://mail.python.org/mailman/listinfo/python-list


Re: minimum install & pickling

2008-09-17 Thread Aaron "Castironpi" Brady
On Sep 17, 6:06 pm, greg <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
> > Even a function created from raw bytecode string can't do anything
> > without __import__ or 'open'.
>
> Not true:
>
>    for cls in (1).__class__.__bases__[0].__subclasses__():
>      if cls.__name__ == "file":
>        F = cls
>
>    F(my_naughty_path, "w").write(my_naughty_data)
>
> --
> Greg

You're right, the list is a little longer.  See above, where I renamed
the Lib/ folder.

'import site' failed; use -v for traceback
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> for cls in (1).__class__.__bases__[0].__subclasses__():
...  if cls.__name__ == "file":
...F = cls
...
>>> F
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'F' is not defined
>>>

'file' here is still defined.

>>> file

>>> del __builtins__.file
>>> file
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'file' is not defined

This one stands a chance.
--
http://mail.python.org/mailman/listinfo/python-list


Re: SMTP via GMAIL

2008-09-17 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>, sui
wrote:

> Traceback (most recent call last):
>   File "mail5.py", line 21, in 
> session = smtplib.SMTP(SMTPserver,port)
>   File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
> (code, msg) = self.connect(host, port)
>   File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect
> self.sock.connect(sa)
>   File "", line 1, in connect
> then conncetion time out.

Could it be your ISP is blocking outgoing connections to port 25?
--
http://mail.python.org/mailman/listinfo/python-list


Re: decorator and API

2008-09-17 Thread Aaron "Castironpi" Brady
On Sep 17, 6:09 pm, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:
> On Sep 17, 4:56 pm, Lee Harr <[EMAIL PROTECTED]> wrote:
>
>
>
> > I have a class with certain methods from which I want to select
> > one at random, with weighting.
(snip)
>
> > The problem I have now is that if I subclass A and want to
> > change the weighting of one of the methods, I am not sure
> > how to do that.
>
> > One idea I had was to override the method using the new
> > weight in the decorator, and then call the original method:
>
> > class B(A):
> >     @weight(50)
> >     def action_1(self):
> >         A.action_1(self)
>
> > That works, but it feels messy.
>
> > Another idea was to store the weightings as a dictionary
> > on each instance, but I could not see how to update that
> > from a decorator.
>
> > I like the idea of having the weights in a dictionary, so I
> > am looking for a better API, or a way to re-weight the
> > methods using a decorator.
>
> > Any suggestions appreciated.
>
> class A:
>    weights= WeightOb() #just a dictionary, mostly
>   [EMAIL PROTECTED]( 10 ) ...
>   [EMAIL PROTECTED]( 20 ) ...
>
> class B( A ):
>    weights= WeightOb( A.weights ) #new, refs "super-member"
>   [EMAIL PROTECTED]( 50 ) ...

Lee,

Probably overkill.   Here's a solution like above.

class WeightOb( object ):
def __init__( self, *supers ):
self.weights= {}
self.supers= supers
def set( self, weight ):
def __callset__( fun ):
self.weights[ fun.func_name ]= weight
return fun
return __callset__
def reset( self, weight, fun ):
self.weights[ fun.func_name ]= weight
return fun
#search parent 'weight' objects
#return 'child-most' weight of 'name'
def get_weight( self, name ):
if name in self.weights:
return self.weights[ name ]
else:
for x in self.supers:
try:
return x.get_weight( name )
except KeyError: #not found
pass
raise KeyError
#returns a dictionary mapping bound instances to weights
#(hence the second parameter)
def contents( self, inst ):
d= {}
for x in reversed( self.supers ):
d.update( x.contents( inst ) )
d.update( dict( [
( getattr( inst, k ), v ) for k, v in self.weights.iteritems( ) ] ) )
return d


class A( object ):
weights= WeightOb( )
@weights.set( 10 )
def action_1( self ):
print 'action_1'
@weights.set( 20 )
def action_2( self ):
print 'action_2'
#WeightOb.contents needs to know which instance to bind
#functions to.  Get weights from an instance that has them.
def getweights( self ):
return self.weights.contents( self )

class B( A ):
weights= WeightOb( A.weights )
action_2= weights.reset( 50, A.action_2 )

a= A()
b= B()
print a.weights.get_weight( 'action_1' )
print a.weights.get_weight( 'action_2' )
print b.weights.get_weight( 'action_1' )
print b.weights.get_weight( 'action_2' )
print a.getweights( )
print b.getweights( )


/Output:

10
20
10
50
{>: 20,
>: 10}
{>: 50,
>: 10}
--
http://mail.python.org/mailman/listinfo/python-list


Re: locks

2008-09-17 Thread James Matthews
You might also want to paste the output into a pastbin such as dpaste.com

On Wed, Sep 17, 2008 at 10:58 AM, <[EMAIL PROTECTED]> wrote:

>
>kalin> mailman has been locking one list out.  the web interface just
>kalin> hangs and it generates a bunch of locks. it seems that it can not
>kalin> write to a log but not sure which one. errors are like:
>...
>
> You'd probably be better off asking about Mailman problems on
> [EMAIL PROTECTED]
>
> --
> Skip Montanaro - [EMAIL PROTECTED] - http://www.webfast.com/~skip/
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://www.goldwatches.com/
--
http://mail.python.org/mailman/listinfo/python-list

Re: minimum install & pickling

2008-09-17 Thread greg

Aaron "Castironpi" Brady wrote:


Even a function created from raw bytecode string can't do anything
without __import__ or 'open'.


Not true:

  for cls in (1).__class__.__bases__[0].__subclasses__():
if cls.__name__ == "file":
  F = cls

  F(my_naughty_path, "w").write(my_naughty_data)

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


Re: decorator and API

2008-09-17 Thread Aaron "Castironpi" Brady
On Sep 17, 4:56 pm, Lee Harr <[EMAIL PROTECTED]> wrote:
> I have a class with certain methods from which I want to select
> one at random, with weighting.
>
> The way I have done it is this 
>
> import random
>
> def weight(value):
>     def set_weight(method):
>         method.weight = value
>         return method
>     return set_weight
>
> class A(object):
>     def actions(self):
>         'return a list of possible actions'
>
>         return [getattr(self, method)
>                     for method in dir(self)
>                     if method.startswith('action_')]
>
>     def action(self):
>         'Select a possible action using weighted choice'
>
>         actions = self.actions()
>         weights = [method.weight for method in actions]
>         total = sum(weights)
>
>         choice = random.randrange(total)
>
>         while choice> weights[0]:
>             choice -= weights[0]
>             weights.pop(0)
>             actions.pop(0)
>
>         return actions[0]
>
>     @weight(10)
>     def action_1(self):
>         print "A.action_1"
>
>     @weight(20)
>     def action_2(self):
>         print "A.action_2"
>
> a = A()
> a.action()()
>
> The problem I have now is that if I subclass A and want to
> change the weighting of one of the methods, I am not sure
> how to do that.
>
> One idea I had was to override the method using the new
> weight in the decorator, and then call the original method:
>
> class B(A):
>     @weight(50)
>     def action_1(self):
>         A.action_1(self)
>
> That works, but it feels messy.
>
> Another idea was to store the weightings as a dictionary
> on each instance, but I could not see how to update that
> from a decorator.
>
> I like the idea of having the weights in a dictionary, so I
> am looking for a better API, or a way to re-weight the
> methods using a decorator.
>
> Any suggestions appreciated.
>
> _
> Explore the seven wonders of the 
> worldhttp://search.msn.com/results.aspx?q=7+wonders+world&mkt=en-US&form=QBRE

What about a function, 'reweight', which wraps the original, and sets
a weight on the wrapper?

def reweight(value):
def reset_weight(method):
[EMAIL PROTECTED](method) #optional
def new_method( *ar, **kw ):
return method( *ar, **kw )
new_method.weight = value
return new_method
return reset_weight

Call like this:

class B(A):
action_1= reweight( 50 )( A.action_1 )

You could pass them both in to reweight with two parameters:

class B(A):
action_1= reweight( 50, A.action_1 )

It's about the same.  Variable-signature functions have limits.

Otherwise, you can keep dictionaries by name, and checking membership
in them in superclasses that have them by hand.  Then you'd need a
consistent name for the dictionary.  That option looks like this
(unproduced):

class A:
   __weights__= {}
   @weight( __weights__, 10 ) ...
   @weight( __weights__, 20 ) ...

class B( A ):
   __weights__= {} #new instance so you don't change the original
   @weight( __weights__, 50 ) ...

B.__weight__ could be an object that knows what it's overriding
(unproduced):

class A:
   weights= WeightOb() #just a dictionary, mostly
   @weights( 10 ) ...
   @weights( 20 ) ...

class B( A ):
   weights= WeightOb( A.weights ) #new, refs "super-member"
   @weights( 50 ) ...

If either of the last two options look promising, I think I can
produce the WeightOb class.  It has a '__call__' method.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ssl server

2008-09-17 Thread Michael Palmer
On Sep 17, 1:33 pm, Seb <[EMAIL PROTECTED]> wrote:
> I'm making a ssl server, but I'm not sure how I can verify the
> clients. What do I actually need to place in _verify to actually
> verify that the client cert is signed by me?
>
>  50 class SSLTCPServer(TCPServer):
>  51 keyFile = "sslcert/server.key"
>  52 certFile = "sslcert/server.crt"
>  53 def __init__(self, server_address, RequestHandlerClass):
>  54 ctx = SSL.Context(SSL.SSLv23_METHOD)
>  55 ctx.use_privatekey_file(self.keyFile)
>  56 ctx.use_certificate_file(self.certFile)
>  57 ctx.set_verify(SSL.VERIFY_PEER |
> SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE,
> self._verify)
>  58 ctx.set_verify_depth(10)
>  59 ctx.set_session_id('DFS')
>  60
>  61 self.server_address = server_address
>  62 self.RequestHandlerClass = RequestHandlerClass
>  63 self.socket = socket.socket(self.address_family,
> self.socket_type)
>  64 self.socket = SSL.Connection(ctx, self.socket)
>  65 self.socket.bind(self.server_address)
>  66 self.socket.listen(self.request_queue_size)
>  67
>  68 def _verify(self, conn, cert, errno, depth, retcode):
>  69 return not cert.has_expired() and
> cert.get_issuer().organizationName == 'DFS'

If I were you, I would just just hide behind apache, nginx oder
another server that does ssl. just have that server proxy locally to
your python server over http, and firewall the python server port.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PYPI, some troubles

2008-09-17 Thread Martin v. Löwis
> 1. when I commit a new release to PYPI, I can use stored data (by my
> browser: Name, package summary, keywords etc), but in the last line
> (classification) I had to chose all those lines from the very
> beginning, moreover, if I click at one of them without pressing "CTRL"
> all my choices drops & I have to type it from the very beginning (I
> use Mozilla Firefox 3.0 but I don't think it's the matter).

Then I recommend not to use the browser to commit the new releases.
Instead, arrange for your setup.py to contain all the relevant data,
and use

  python setup.py register

to add the new release.

> 2. Another issue: I have attached my source code (openopt0.19.tar.bz2
> file), now I can see it in "files for openopt 0.19" section (http://
> pypi.python.org/pypi) but easy_install can't find the package:

Try calling the file openopt-0.19.tar.bz2. If that doesn't help, contact
the setuptools mailing lists.

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python GUI development using XULRunner

2008-09-17 Thread Todd Whiteman

[EMAIL PROTECTED] wrote:

On Sep 17, 1:21 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote:

Don Spaulding wrote:

On Sep 16, 8:29 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote:

I've put together a tutorial that shows off how to build a GUI
application using XULRunner (same architectural components as Firefox
uses) that can be used in conjunction with the Python programming language.
The tutorial covers how to build a Python/XULRunner GUI 
application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul...

I get to the "Running" step and run into "Couldn't load XPCOM."
Does this work on x86_64?  Or have I made a rookie mistake?

Hi Don,

A good question. Mozilla only provide 32-bit XulRunner applications by
default, you you'll need to install the necessary 32-bit compatability
libraries on your Linux machine, i.e. for Ubuntu it's something like:
sudo apt-get install ia32-libs ia32-libs-gtk

Then you should be able to run the example. You can check the
dependencies using something the following commands, there should be no
missing dependencies:
$ cd pyxpcom_gui_app/xulrunner
$ LD_LIBRARY_PATH=. ldd ./xulrunner-bin

It is possible to use a 64-bit version, but you'll need to compile this
yourself (or find somewhere that provides these x86_64 versions). Note
that the PythonExt project does not offer Python bindings for x86_64
either (it's on my todo list), you can compile the PythonExt part
yourself as well if you need a 64-bit version.

Cheers,
Todd


Interesting, I'm running Ubuntu Intrepid here, and have both ia32-libs
and ia32-libs-gtk installed.

ldd shows that I'm missing the following libs, even though the proper
packages are installed, and the files show up in /usr/lib.

libxcb-render-util.so.0 => not found
libxcb-render.so.0 => not found

There's also /usr/lib/libxcb-render.so.0.0.0 and the same for render-
util, so I wonder if that could be part of the problem?


Don


Hi Don,

I'm thinking there may be additional 32-bit packages necessary then (I'm 
not sure which package).


Not sure about Ubuntu 8.10 (it's still alpha). I'm using a Ubuntu 8.04 
x86_64 machine and my dependencies list the following for the latest 
32-bit build of XulRunner:


$ LD_LIBRARY_PATH=. ldd ./xulrunner-bin | grep libxcb
libxcb-xlib.so.0 => /usr/lib32/libxcb-xlib.so.0 (0xf6493000)
libxcb.so.1 => /usr/lib32/libxcb.so.1 (0xf647b000)

Cheers,
Todd
--
http://mail.python.org/mailman/listinfo/python-list


decorator and API

2008-09-17 Thread Lee Harr

I have a class with certain methods from which I want to select
one at random, with weighting.

The way I have done it is this 



import random

def weight(value):
def set_weight(method):
method.weight = value
return method
return set_weight

class A(object):
def actions(self):
'return a list of possible actions'

return [getattr(self, method)
for method in dir(self)
if method.startswith('action_')]

def action(self):
'Select a possible action using weighted choice'

actions = self.actions()
weights = [method.weight for method in actions]
total = sum(weights)

choice = random.randrange(total)

while choice> weights[0]:
choice -= weights[0]
weights.pop(0)
actions.pop(0)

return actions[0]


@weight(10)
def action_1(self):
print "A.action_1"

@weight(20)
def action_2(self):
print "A.action_2"


a = A()
a.action()()




The problem I have now is that if I subclass A and want to
change the weighting of one of the methods, I am not sure
how to do that.

One idea I had was to override the method using the new
weight in the decorator, and then call the original method:

class B(A):
@weight(50)
def action_1(self):
A.action_1(self)


That works, but it feels messy.


Another idea was to store the weightings as a dictionary
on each instance, but I could not see how to update that
from a decorator.

I like the idea of having the weights in a dictionary, so I
am looking for a better API, or a way to re-weight the
methods using a decorator.

Any suggestions appreciated.

_
Explore the seven wonders of the world
http://search.msn.com/results.aspx?q=7+wonders+world&mkt=en-US&form=QBRE
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Linear Programming on Ubuntu

2008-09-17 Thread Martin Manns
On Tue, 16 Sep 2008 19:25:58 -0700 (PDT)
Fett <[EMAIL PROTECTED]> wrote:

> # SciPy -- http://www.scipy.org - supposedly has this, but as I said,
> I can't find any mention of it anywhere but on the site you linked.

I found OpenOpt on the site:
http://scipy.org/scipy/scikits/wiki/MILP

I downloaded the svn version and installed it on my Debian box.
There were some error messages while installing. However, the example
seems to work anyways. I am using the solver glpk from the
package python-glpk.

I hope that this works on your Ubuntu system as well.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python GUI development using XULRunner

2008-09-17 Thread Fred Pacquier
Todd Whiteman <[EMAIL PROTECTED]> said :

> I've put together a tutorial that shows off how to build a GUI 
> application using XULRunner (same architectural components as Firefox 
> uses) that can be used in conjunction with the Python programming
> language. 
> The tutorial covers how to build a Python/XULRunner GUI application:
> http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulru
> nner_about.html 
> The details in this tutorial covers the initial setup to full 
> packaging/deployment, mostly targeting a Windows/Linux platform
> (MacOSX is possible with a few deviations, I have tried to cover these
> deviations where applicable).
> Feedback is welcome.

Thanks for making good on your promise. I'm leaving for a trip but have it 
bookmarked for later use :-)
--
http://mail.python.org/mailman/listinfo/python-list


Configuration Parsers

2008-09-17 Thread Ron Brennan
Hello,

I am trying to parse a shared config file which doesn't contail section
headers.  Is there a way I can still use ConfigParser()?  If not what is a
widely used parser available?

Thanks,
Ron
--
http://mail.python.org/mailman/listinfo/python-list

Re: ssl server

2008-09-17 Thread Giampaolo Rodola'
On 17 Set, 19:33, Seb <[EMAIL PROTECTED]> wrote:
> I'm making a ssl server, but I'm not sure how I can verify the
> clients. What do I actually need to place in _verify to actually
> verify that the client cert is signed by me?
>
>  50 class SSLTCPServer(TCPServer):
>  51         keyFile = "sslcert/server.key"
>  52         certFile = "sslcert/server.crt"
>  53         def __init__(self, server_address, RequestHandlerClass):
>  54                 ctx = SSL.Context(SSL.SSLv23_METHOD)
>  55                 ctx.use_privatekey_file(self.keyFile)
>  56                 ctx.use_certificate_file(self.certFile)
>  57                 ctx.set_verify(SSL.VERIFY_PEER |
> SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE,
> self._verify)
>  58                 ctx.set_verify_depth(10)
>  59                 ctx.set_session_id('DFS')
>  60
>  61                 self.server_address = server_address
>  62                 self.RequestHandlerClass = RequestHandlerClass
>  63                 self.socket = socket.socket(self.address_family,
> self.socket_type)
>  64                 self.socket = SSL.Connection(ctx, self.socket)
>  65                 self.socket.bind(self.server_address)
>  66                 self.socket.listen(self.request_queue_size)
>  67
>  68         def _verify(self, conn, cert, errno, depth, retcode):
>  69                 return not cert.has_expired() and
> cert.get_issuer().organizationName == 'DFS'

What library are you using? PyOpenSSL?
In that case I think you'll have more luck by posting on their mailing
list.


--- Giampaolo
http://code.google.com/p/pyftpdlib/
--
http://mail.python.org/mailman/listinfo/python-list


Re: minimum install & pickling

2008-09-17 Thread Aaron "Castironpi" Brady
On Sep 17, 4:43 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 17 Sep, 07:26, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]>
> wrote:
>
> > Sometimes questions come up on here about unpickling safely and
> > executing foreign code.  I was thinking a minimum install that didn't
> > even have access to modules like 'os' could be safe.   (Potentially.)
> > I have time to entertain this a little, though all the devs are busy.
> > I can bring it up again in a few months if it's a better time.
>
> One alternative might be to provide "safe" versions of the underlying
> functions in modules like "os". Previously, I did wonder why people
> didn't link Python against a bunch of alternative libraries which
> would provide implementations of things like "open", "chdir" and so
> on, but then I was made aware of fakeroot and fakechroot which do more
> or less this for any program (in conjunction with chroot) in order to
> restrict the behaviour of those programs, without any need to
> statically link the programs first.
>
> [...]
>
> > A lot of modules would have to go.    IPC modules:
> > subprocess, socket, signal, popen2, asyncore, asynchat.  ctypes, mmap,
> > platform.popen, glob, shutil, dircache, and many more.
>
> Potentially, these could remain, but you'd want to provide "fake"
> versions of the underlying functions, potentially implementing your
> own preferred flavour of access control. So, with a call to the
> "socket" function, the wrapped version might first consult some kind
> of behaviour policy set by the user in order to get permission to open
> a connection to a remote host.
>
> There's a discussion of rexec and related solutions on the Wiki:
>
> http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_...)
>
> Paul

These solutions have at least the same bugs that the bare bones
solution in the corresponding framework has.  Malicious code has fewer
options, but constructive code does too.  If you're running foreign
code, what do you want it to do?  What does it want to do?  The more
options it needs, the more code you have to trust.

The only way a Python script can return a value is with sys.exit, and
only an integer at that.  It is going to have output; maybe there's a
way to place a maximum limit on its consumption.  It's going to have
input, so that the output is relative to something.  You just make
copies to prevent it from destroying data.  Maybe command-line
parameters are enough.  IIRC if I recall correctly, Win32 has a way to
examine how much time a process has owned so far, and a way to
terminate it, which could be in Python's future.

PyPy sandbox says:  "The C code generated by PyPy is not
segfaultable."  I find that to be a bold claim (whether it's true or
not).

I'm imagining in the general case, you want the foreign code to make
changes to objects in your particular context, such as exec x in
vars.  In that case, x can still be productive without any libraries,
just less productive.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python GUI development using XULRunner

2008-09-17 Thread Don Spaulding
Oh, and Google's single sign-on sucks eggs  :-|
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python GUI development using XULRunner

2008-09-17 Thread support
On Sep 17, 1:21 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote:
> Don Spaulding wrote:
> > On Sep 16, 8:29 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote:
> >> I've put together a tutorial that shows off how to build a GUI
> >> application using XULRunner (same architectural components as Firefox
> >> uses) that can be used in conjunction with the Python programming language.
>
> >> The tutorial covers how to build a Python/XULRunner GUI 
> >> application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul...
>
> > I get to the "Running" step and run into "Couldn't load XPCOM."
>
> > Does this work on x86_64?  Or have I made a rookie mistake?
>
> Hi Don,
>
> A good question. Mozilla only provide 32-bit XulRunner applications by
> default, you you'll need to install the necessary 32-bit compatability
> libraries on your Linux machine, i.e. for Ubuntu it's something like:
> sudo apt-get install ia32-libs ia32-libs-gtk
>
> Then you should be able to run the example. You can check the
> dependencies using something the following commands, there should be no
> missing dependencies:
> $ cd pyxpcom_gui_app/xulrunner
> $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin
>
> It is possible to use a 64-bit version, but you'll need to compile this
> yourself (or find somewhere that provides these x86_64 versions). Note
> that the PythonExt project does not offer Python bindings for x86_64
> either (it's on my todo list), you can compile the PythonExt part
> yourself as well if you need a 64-bit version.
>
> Cheers,
> Todd

Interesting, I'm running Ubuntu Intrepid here, and have both ia32-libs
and ia32-libs-gtk installed.

ldd shows that I'm missing the following libs, even though the proper
packages are installed, and the files show up in /usr/lib.

libxcb-render-util.so.0 => not found
libxcb-render.so.0 => not found

There's also /usr/lib/libxcb-render.so.0.0.0 and the same for render-
util, so I wonder if that could be part of the problem?


Don

/me never knew how to get out of DLL hell on Windows either  ;-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Open Office

2008-09-17 Thread Terry Reedy

Hartmut Goebel wrote:

Terry Reedy schrieb:

One way to learn the meaning of some of the numerous attributes and 
values is to create a file with the wanted features with OOo, save, 
unzip, and examine the xml to see which tags are used for which features.


The API docs are a bit hidden on the webpage. Here is the link:



I wrote my comment *after* looking at the above, which I found easily 
enough.  After 7 pages of (helpful) explanatory text, there follow 88 
pages with hundreds of entries like this:


5.13.30 style.RubyProperties
Requires the following attributes: No attribute is required.
Allows the following attributes: rubyalign, rubyposition.
These elements contain style.RubyProperties: style.DefaultStyle, 
style.Style.

The following elements occur in style.RubyProperties: No element is allowed.

which are translated to a more readable form from the Relax-NG schema 
(formal specs) in the standard.  But I have no idea what a Ruby property 
is in this context.  It would be much like reading the grammar entries 
in the Python Reference without the explanatory text that follows.



Additionally teh ODF sepcs may help:



v1.0 is the adopted international (ISO/IEC) standard.
I did not notice whether odfpy supports the 1.1 extensitons, but since 
it does appear that OOo now uses them, I will presume so.


This does help.  It has more explanatory material.
"5.4 Ruby
A ruby is additional text that is displayed above or below some base 
text. The purpose of ruby is to annotate the base text or provide 
information about its pronunciation.


tjr

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


PYPI, some troubles

2008-09-17 Thread dmitrey
hi all,

1. when I commit a new release to PYPI, I can use stored data (by my
browser: Name, package summary, keywords etc), but in the last line
(classification) I had to chose all those lines from the very
beginning, moreover, if I click at one of them without pressing "CTRL"
all my choices drops & I have to type it from the very beginning (I
use Mozilla Firefox 3.0 but I don't think it's the matter).

2. Another issue: I have attached my source code (openopt0.19.tar.bz2
file), now I can see it in "files for openopt 0.19" section (http://
pypi.python.org/pypi) but easy_install can't find the package:

# easy_install openopt
Searching for openopt
Reading http://pypi.python.org/simple/openopt/
Couldn't find index page for 'openopt' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
Reading http://pypi.python.org/simple/OpenOpt/
Reading http://scipy.org/scipy/scikits/wiki/OpenOpt
No local packages or download links found for openopt
error: Could not find suitable distribution for
Requirement.parse('openopt')

Does anyone know what shoul I do?
Thank you in advance,
Dmitrey
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generating test data from an XML Schema

2008-09-17 Thread Stefan Behnel
Mark Thomas wrote:
> On Sep 17, 5:29 am, Jonathan Fine <[EMAIL PROTECTED]> wrote:
>> I want to generate test data from an XML schema.  I've had a quick look
>> at existing tools (such as minixsv and amara) but from what I've seen
>> they don't seem to help.
> ...
>> A tool that provides a nice Python interface to navigating the schema
>> would probably be quite helpful.
>>
>> Has anyone seen anything that might help generate test data from a schema?
> 
> I'm unaware of anything in Python, but Eclipse can generate sample
> documents from a schema:
> http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.xmleditor.doc.user/topics/tcrexxsd.html
> 
> As can XML IDEs such as Stylus Studio and XML Spy.

There's also a Java tool called the "XML instance generator" by Sun that
supports XML Schema and RelaxNG. It's a bit tricky to find as most links to it
are broken by now.

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


open Invitation to Join with DeveloperWiki Knowledge base

2008-09-17 Thread Randika
Dear Developers,IT Professionals,

"We are building a online encyclopedia for developers" and we need
your contribution to make it even better. So here is our invitation
for those who happy to contribute as editors, readers for the project.

If you have written a tutorial/article/code snippet and would like to
share it with others, you can publish it on DeveloperWiki and also you
can Edit/Update any existing articles too.

Please visit DeveloperWiki web site here
http://DeveloperWiki.org

Official discussion group.
http://groups.google.com/group/DeveloperWikiUserGroup

Thanks
 --DeveloperWiki Team

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


Re: translating ascii to binary

2008-09-17 Thread Tino Wildenhain

hi,

Canned wrote:

Steven D'Aprano schreef:
Your "ascii_to_bin" method tries to do too much in one method. You should 
split the functionality into small, self-contained pieces, then combine 
them. And frankly, once you got to the part where you started popping and 
inserting, my brain melted. You are making an easy job too hard! *smiles*



It's a bad habit, I can't help it. From now on, I'll follow your advice
to split the functionality into small, self-contained pieces. That
popping and inserting is just a workaround for another workaround.


just got an interesting idea for the core of the converter,
maybe you like it:

def int_to_bin(v):
i=1
d=1
a=0
while i>> int_to_bin(5)
101
>>> print "%08d" % int_to_bin(5)
0101

I think the formatting bit is a tad nicer then '0' * (8-len(...)))

Cheers
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list

Getting/Setting HTTP Headers

2008-09-17 Thread jakecjacobson
I need to write a feed parser that takes a url for any Atom or RSS
feed and transform it into an Atom feed.  I done the transformation
part but I want to support conditional HTTP requests.  I have not been
able to find any examples that show:

1.  How to read the Last_Modified or ETag header value from the
requester
2.  How to set the corresponding HTTP header value, either a 302 not
modified or the new Last_Modified date and/or ETag values
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python GUI development using XULRunner

2008-09-17 Thread Todd Whiteman

Don Spaulding wrote:

On Sep 16, 8:29 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote:

I've put together a tutorial that shows off how to build a GUI
application using XULRunner (same architectural components as Firefox
uses) that can be used in conjunction with the Python programming language.

The tutorial covers how to build a Python/XULRunner GUI 
application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul...


I get to the "Running" step and run into "Couldn't load XPCOM."

Does this work on x86_64?  Or have I made a rookie mistake?


Hi Don,

A good question. Mozilla only provide 32-bit XulRunner applications by 
default, you you'll need to install the necessary 32-bit compatability 
libraries on your Linux machine, i.e. for Ubuntu it's something like:

sudo apt-get install ia32-libs ia32-libs-gtk

Then you should be able to run the example. You can check the 
dependencies using something the following commands, there should be no 
missing dependencies:

$ cd pyxpcom_gui_app/xulrunner
$ LD_LIBRARY_PATH=. ldd ./xulrunner-bin

It is possible to use a 64-bit version, but you'll need to compile this 
yourself (or find somewhere that provides these x86_64 versions). Note 
that the PythonExt project does not offer Python bindings for x86_64 
either (it's on my todo list), you can compile the PythonExt part 
yourself as well if you need a 64-bit version.


Cheers,
Todd
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Label 'justify' Problem

2008-09-17 Thread Guilherme Polo
On Wed, Sep 17, 2008 at 2:18 PM, Dude <[EMAIL PROTECTED]> wrote:
> Hi All,
> I am fairly new to Python programming.  I am working on a small
> Tkinter project and I think I am missing something, maybe you can
> help.  The two lines below is all I have related to the Label widget:
>
> lblServer = Tkinter.Label(serverFrame, text='Server:', fg='black',
> justify='left', relief='groove')
>
> lblServer.place_configure(width=200, bordermode='inside')
>
>
> No matter what I change the 'justify' to whether it's 'lef', 'right',
> or 'center', it always seems to be in the center.

The "justify" option comes into play only when you have a multi-line
label, which is not the case. If you want it left/right aligned then
use pack (instead of place, not really recommended but I don't know
what you are doing) and specify the anchor option with an appropriate
value ('e' or 'w') for what you want.

>
> I am also writing the keys from the Label widget to a file because
> this has me so baffled.  That is below.
>
> Thank in advance for any help or direction you can give me.
>
> Steve P
>
> -- lblServer keys -
> activebackground : SystemButtonFace
> activeforeground : SystemButtonText
> anchor : center
> background : SystemButtonFace
> bd : 2
> bg : SystemButtonFace
> bitmap :
> borderwidth : 2
> compound : none
> cursor :
> disabledforeground : SystemDisabledText
> fg : black
> font : {MS Sans Serif} 8
> foreground : black
> height : 0
> highlightbackground : SystemButtonFace
> highlightcolor : SystemWindowFrame
> highlightthickness : 0
> image :
> justify : left
> padx : 1
> pady : 1
> relief : groove
> state : normal
> takefocus : 0
> text : NNTP Server:
> textvariable :
> underline : -1
> width : 0
> wraplength : 0
> -- lblServer keys END -
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


Re: locks

2008-09-17 Thread skip

kalin> mailman has been locking one list out.  the web interface just
kalin> hangs and it generates a bunch of locks. it seems that it can not
kalin> write to a log but not sure which one. errors are like:
...

You'd probably be better off asking about Mailman problems on
[EMAIL PROTECTED]

-- 
Skip Montanaro - [EMAIL PROTECTED] - http://www.webfast.com/~skip/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting .py files to batch files.

2008-09-17 Thread r0g
Grant Edwards wrote:
> On 2008-09-17, r0g <[EMAIL PROTECTED]> wrote:
> 
>> [EMAIL PROTECTED]:~/Desktop/py$ ls
>> kickstart.py  kickstart.py~  kicktest.py  kicktest.py~
>> [EMAIL PROTECTED]:~/Desktop/py$ kickstart.py
>> bash: kickstart.py: command not found
>>
>> Any ideas why this might be?
> 
> Yes.
> 
>> A path thing?
> 
> Yes.
> 
> Linux systems generally don't have the current directory in the
> PATH that's searched for executbles (it's regarded as a rather
> serious security problem if you do).
> 
> Try doing this:
> 
>  ./kickstart.py
> 

Brilliant! :D  Thanks v.much for that, turns out the very same thing had
been driving me nuts a few days earlier when I was trying to run an
installer I had downloaded, bit of an Izzard Printer moment LOL -
http://www.youtube.com/watch?v=2wHEqDepAXo

Thanks again!

Roger.

http://www.technicalbloke.com
http://movingtoubuntu.technicalbloke.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: ka-ping yee tokenizer.py

2008-09-17 Thread Karl Kobata
Aaran,
 
Thanks for your input.  Your examples gave me other alternatives for what I
wanted to do and it seems to work.
 
Thanks all for your help.
 
 
On Sep 16, 2:48 pm, "Karl Kobata" http://mail.python.org/mailman/listinfo/python-list> > wrote:
> Hi Fredrik,
> 
> This is exactly what I need.  Thank you.
> I would like to do one additional function.  I am not using the tokenizer
to
> parse python code.  It happens to work very well for my application.
> However, I would like either or both of the following variance:
> 1) I would like to add 2 other characters as comment designation
> 2) write a module that can readline, modify the line as required, and
> finally, this module can be used as the argument for the tokenizer.
> 
> Def modifyLine( fileHandle ):
>   # readline and modify this string if required
> ...
> 
> For token in tokenize.generate_tokens( modifyLine( myFileHandle ) ):
> Print token
> 
> Anxiously looking forward to your thoughts.
> karl
> 
> -Original Message-
> From: python-list-bounces+kkobata=syncira at python.org
 
> 
> [mailto:python-list-bounces+kkobata=syncira at python.org
 ] On Behalf Of
> Fredrik Lundh
> Sent: Monday, September 15, 2008 2:04 PM
> To: python-l... at python.org
 
> Subject: Re: ka-ping yee tokenizer.py
> 
> Karl Kobata wrote:
> 
> > I have enjoyed using ka-ping yee's tokenizer.py.  I would like to
> > replace the readline parameter input with my own and pass a list of
> > strings to the tokenizer.  I understand it must be a callable object and
> > iteratable but it is obvious with errors I am getting, that this is not
> > the only functions required.
> 
> not sure I can decipher your detailed requirements, but to use Python's
> standard "tokenize" module (written by ping) on a list, you can simple
> do as follows:
> 
>  import tokenize
> 
>  program = [ ... program given as list ... ]
> 
>  for token in tokenize.generate_tokens(iter(program).next):
>  print token
> 
> another approach is to turn the list back into a string, and wrap that
> in a StringIO object:
> 
>  import tokenize
>  import StringIO
> 
>  program = [ ... program given as list ... ]
> 
>  program_buffer = StringIO.StringIO("".join(program))
> 
>  for token in tokenize.generate_tokens(program_buffer.readline):
>  print token
> 
> 
> 
> --http://mail.python.org/mailman/listinfo/python-list
> 
> 
 
This is an interesting construction:
 
>>> a= [ 'a', 'b', 'c' ]
>>> def moditer( mod, nextfun ):
... while 1:
... yield mod( nextfun( ) )
...
>>> list( moditer( ord, iter( a ).next ) )
[97, 98, 99]
 
Here's my point:
 
>>> a= [ 'print a', 'print b', 'print c' ]
>>> tokenize.generate_tokens( iter( a ).next )

>>> tokenize.generate_tokens( moditer( lambda s: s+ '#', iter( a ).next
).next )
 
It adds a '#' to the end of every line, then tokenizes.

 

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

Re: ANN: Python GUI development using XULRunner

2008-09-17 Thread Don Spaulding
On Sep 16, 8:29 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote:
> I've put together a tutorial that shows off how to build a GUI
> application using XULRunner (same architectural components as Firefox
> uses) that can be used in conjunction with the Python programming language.
>
> The tutorial covers how to build a Python/XULRunner GUI 
> application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul...
>
> The details in this tutorial covers the initial setup to full
> packaging/deployment, mostly targeting a Windows/Linux platform (MacOSX
> is possible with a few deviations, I have tried to cover these
> deviations where applicable).
>
> Feedback is welcome.
>
> Cheers,
> Todd

I get to the "Running" step and run into "Couldn't load XPCOM."

Does this work on x86_64?  Or have I made a rookie mistake?

xulapp1$ ls
app  docs  installer  pyxpcom_gui_app
xulapp1$ cd pyxpcom_gui_app/
pyxpcom_gui_app$ ls
application.ini  components  extensions  pyxpcom_gui_app
chrome   defaultspylib   xulrunner
pyxpcom_gui_app$ ./pyxpcom_gui_app
Couldn't load XPCOM.
--
http://mail.python.org/mailman/listinfo/python-list


locks

2008-09-17 Thread kalin m

hi all...

mailman has been locking one list out.
the web interface just hangs and it generates a bunch of locks. it seems 
that it can not write to a log but not sure which one. errors are like:


ep 17 05:09:12 2008 (18481) musiclist.lock lifetime has expired, breaking
Sep 17 05:09:12 2008 (18481)   File "/var/mailman/bin/qrunner", line 
270, in ?

Sep 17 05:09:12 2008 (18481) main()
Sep 17 05:09:12 2008 (18481)   File "/var/mailman/bin/qrunner", line 
230, in main

Sep 17 05:09:12 2008 (18481) qrunner.run()
Sep 17 05:09:12 2008 (18481)   File 
"/var/mailman/Mailman/Queue/Runner.py", line 70, in run

Sep 17 05:09:12 2008 (18481) filecnt = self._oneloop()
Sep 17 05:09:12 2008 (18481)   File 
"/var/mailman/Mailman/Queue/Runner.py", line 111, in _oneloop

Sep 17 05:09:12 2008 (18481) self._onefile(msg, msgdata)
Sep 17 05:09:12 2008 (18481)   File 
"/var/mailman/Mailman/Queue/Runner.py", line 167, in _onefile
Sep 17 05:09:12 2008 (18481) keepqueued = self._dispose(mlist, msg, 
msgdata)
Sep 17 05:09:12 2008 (18481)   File 
"/var/mailman/Mailman/Queue/IncomingRunner.py", line 115, in _dispose
Sep 17 05:09:12 2008 (18481) 
mlist.Lock(timeout=mm_cfg.LIST_LOCK_TIMEOUT)
Sep 17 05:09:12 2008 (18481)   File "/var/mailman/Mailman/MailList.py", 
line 159, in Lock

Sep 17 05:09:12 2008 (18481) self.__lock.lock(timeout)
Sep 17 05:09:12 2008 (18481)   File "/var/mailman/Mailman/LockFile.py", 
line 306, in lock

Sep 17 05:09:12 2008 (18481) important=True)
Sep 17 05:09:12 2008 (18481)   File "/var/mailman/Mailman/LockFile.py", 
line 416, in __writelog

Sep 17 05:09:12 2008 (18481) traceback.print_stack(file=logf)
Sep 17 10:17:05 2008 (19547) musiclist.lock lifetime has expired, breaking
Sep 17 10:17:06 2008 (19547)   File "/var/mailman/cron/checkdbs", line 
178, in ?

Sep 17 10:17:06 2008 (19547) main()
Sep 17 10:17:06 2008 (19547)   File "/var/mailman/cron/checkdbs", line 
84, in main

Sep 17 10:17:06 2008 (19547) mlist = MailList.MailList(name)
Sep 17 10:17:06 2008 (19547)   File "/var/mailman/Mailman/MailList.py", 
line 126, in __init__

Sep 17 10:17:06 2008 (19547) self.Lock()
Sep 17 10:17:06 2008 (19547)   File "/var/mailman/Mailman/MailList.py", 
line 159, in Lock

Sep 17 10:17:06 2008 (19547) self.__lock.lock(timeout)
Sep 17 10:17:06 2008 (19547)   File "/var/mailman/Mailman/LockFile.py", 
line 306, in lock

Sep 17 10:17:06 2008 (19547) important=True)
Sep 17 10:17:06 2008 (19547)   File "/var/mailman/Mailman/LockFile.py", 
line 416, in __writelog

Sep 17 10:17:06 2008 (19547) traceback.print_stack(file=logf)


all other lists appear to be working fine

thanks


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


Re: File Reading related query

2008-09-17 Thread r0g
Fredrik Lundh wrote:
> Usman Ajmal wrote:
> 
>> Is there any function for reading a file while ignoring *\n* occuring
>> in the file?
> 
> can you be a bit more precise?  are we talking about text files or
> binary files?  how do you want to treat any newlines that actually
> appear in the file?
> 
> 
> 

Hi Usan,

I've always just done...

for each in open('filename.txt', 'r'):
  each = each.rstrip()

You could wrap this as a generator if you really want it to be a one
liner, personally it's never seemed worth it to me.

Regards,


Roger Heathcote

http://www.technicalbloke.com
http://movingtoubuntu.technicalbloke.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: translating ascii to binary

2008-09-17 Thread Canned
Steven D'Aprano schreef:
> Your "ascii_to_bin" method tries to do too much in one method. You should 
> split the functionality into small, self-contained pieces, then combine 
> them. And frankly, once you got to the part where you started popping and 
> inserting, my brain melted. You are making an easy job too hard! *smiles*
> 
It's a bad habit, I can't help it. From now on, I'll follow your advice
to split the functionality into small, self-contained pieces. That
popping and inserting is just a workaround for another workaround.

> Try this instead:
> 
> class Converterab:
> '''
> Ascii-binary converter.
> '''
> def __init__(self, string):
> self.string = string
> def bin(self, n):
> """Return the binary representation of a positive integer n."""
> bindump = []
> while n > 0:
> bindump.append(str(n & 1))
> n = n >> 1
> bindump.reverse()
> if bindump:
> return ''.join(bindump)
> else:
> return '0'
> def char_to_bin(self, c):
> """Return the binary representation of a character c."""
> bits = self.bin(ord(c))
> zeroes = "0" * (8-len(bits))
> return zeroes+bits
> def ascii_to_bin(self):
> results = []
> for c in self.string:
> results.append(self.char_to_bin(c))
> return ''.join(results)
> 

I've spend 3 days to find out what did I do wrong, but you did it in
just half an hour/more. You're my hero.
--
http://mail.python.org/mailman/listinfo/python-list


ssl server

2008-09-17 Thread Seb
I'm making a ssl server, but I'm not sure how I can verify the
clients. What do I actually need to place in _verify to actually
verify that the client cert is signed by me?

 50 class SSLTCPServer(TCPServer):
 51 keyFile = "sslcert/server.key"
 52 certFile = "sslcert/server.crt"
 53 def __init__(self, server_address, RequestHandlerClass):
 54 ctx = SSL.Context(SSL.SSLv23_METHOD)
 55 ctx.use_privatekey_file(self.keyFile)
 56 ctx.use_certificate_file(self.certFile)
 57 ctx.set_verify(SSL.VERIFY_PEER |
SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE,
self._verify)
 58 ctx.set_verify_depth(10)
 59 ctx.set_session_id('DFS')
 60
 61 self.server_address = server_address
 62 self.RequestHandlerClass = RequestHandlerClass
 63 self.socket = socket.socket(self.address_family,
self.socket_type)
 64 self.socket = SSL.Connection(ctx, self.socket)
 65 self.socket.bind(self.server_address)
 66 self.socket.listen(self.request_queue_size)
 67
 68 def _verify(self, conn, cert, errno, depth, retcode):
 69 return not cert.has_expired() and
cert.get_issuer().organizationName == 'DFS'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python GUI for animation

2008-09-17 Thread r0g
Sean DiZazzo wrote:
> On Sep 15, 11:29 pm, Virgil Stokes <[EMAIL PROTECTED]> wrote:
>> I have been using Python for a short time and I find it a very flexible
>> language, and easy to learn and use. I have also worked some with PyGame

> Then again, you mention sliders, knobs, etc.  I don't think Tkinter
> has alot of widgets built in.  The other choice would be wxPython.
> It's got lots of built in widgets, and it looks pretty good.  If you
> go this route, run the demo application to see what you have to work
> with.
> 
> http://wxpython.org/
> 
> Good luck.
> 
> ~Sean

Yes, I'd say wxPython is the way to go, mainly because of the numerous
and excellent examples and example program.

Also, gui stuff can be lengthy and verbose to code by hand and if you're
using wxPython you can also use wxGlade, a python version of the popular
Glade gui builder.

Good luck :]


Roger Heathcote.

http://www.technicalbloke.com
http://movingtoubuntu.technicalbloke.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Tkinter Label 'justify' Problem

2008-09-17 Thread Dude
Hi All,
I am fairly new to Python programming.  I am working on a small
Tkinter project and I think I am missing something, maybe you can
help.  The two lines below is all I have related to the Label widget:

lblServer = Tkinter.Label(serverFrame, text='Server:', fg='black',
justify='left', relief='groove')

lblServer.place_configure(width=200, bordermode='inside')


No matter what I change the 'justify' to whether it's 'lef', 'right',
or 'center', it always seems to be in the center.

I am also writing the keys from the Label widget to a file because
this has me so baffled.  That is below.

Thank in advance for any help or direction you can give me.

Steve P

-- lblServer keys -
activebackground : SystemButtonFace
activeforeground : SystemButtonText
anchor : center
background : SystemButtonFace
bd : 2
bg : SystemButtonFace
bitmap :
borderwidth : 2
compound : none
cursor :
disabledforeground : SystemDisabledText
fg : black
font : {MS Sans Serif} 8
foreground : black
height : 0
highlightbackground : SystemButtonFace
highlightcolor : SystemWindowFrame
highlightthickness : 0
image :
justify : left
padx : 1
pady : 1
relief : groove
state : normal
takefocus : 0
text : NNTP Server:
textvariable :
underline : -1
width : 0
wraplength : 0
-- lblServer keys END -
--
http://mail.python.org/mailman/listinfo/python-list


Re: Client server implementation

2008-09-17 Thread r0g
Babloo wrote:
> On Sep 16, 7:38 am, Benjamin <[EMAIL PROTECTED]> wrote:
>> On Sep 15, 5:15 am, Babloo <[EMAIL PROTECTED]> wrote:
>>
>>> Hi everyone,
>>>   i wanted to implement a client- server connection
>>> and transfer a file over the network. i was able to implement a normal
>>> set up where in i was able to send chat messages and small chunks of
>>> data.
>>> I want to implement the file transfer with out using the FTP library
>>> available in python .
>>>   So can anyone suggest a piece of code by which i can
>>> do that.
>> I don't know what you really want, but look at 
>> Twisted.http://twistedmatrix.com
>>
>>
>>
>>> Thanks
>>> Pruthvi
>>
> I am beginner at using python language.
> I mean i am implementing that in a  windows based machine and wanted
> to transfer files over the LAN. I have written down two files as
> client.py and server.py . I ran these files at two different Computers
> in the LAN and  I was able to send small chunks of messages( like
> chat).
> 
> I was successful in establishing connection and sending small
> messages. But now i want to transfer a complete file with out using
> the ftplib(FTP LIBRARY) in python.
> 
> 
> The files look like this.i hope this would help.
> 
> __
> # Server program
> 
> from socket import *
> 
> # Set the socket parameters
> host = "117.105.224.94"
> port = 21567
> buf = 1024
> addr = (host,port)
> 
> # Create socket and bind to address
> UDPSock = socket(AF_INET,SOCK_DGRAM)
> UDPSock.bind(addr)
> 
> # Receive messages
> while 1:
>data,addr = UDPSock.recvfrom(buf)
>if not data:
>print "Client has exited!"
>break
>else:
>print "\nReceived message '", data,"'"
> 
> # Close socket
> UDPSock.close()
> __
> 
> # Client program
> 
> from socket import *
> 
> # Set the socket parameters
> host = "117.105.224.94"
> port = 21567
> buf = 1024
> addr = (host,port)
> 
> # Create socket
> UDPSock = socket(AF_INET,SOCK_DGRAM)
> 
> def_msg = "===Enter message to send to server===";
> print "\n",def_msg
> 
> # Send messages
> while (1):
>   data = raw_input('>> ')
>   if not data:
>   break
>   else:
>   if(UDPSock.sendto(data,addr)):
>   print "Sending message '",data,"'."
> 
> # Close socket
> UDPSock.close()
> 
> _
> 


You're really not far away then, you basically need to come up with a
simple protocol that can transmit

1) The file name
2) The file length
3) The file data itself

You could also transmit the files metadata: datestamps, permissions etc
if you wanted to make it better. Also, there might be security issues to
consider too if you're running this on anything other than your own home
network.

So anyway, for a simple solution howabout you send:

filename + "\n"
filesize + "\n" (make sure you use str() to send this as text)

Then loop through your filedata
  send a chunk
  wait for an OK back from the other side
  loop

At the receiving end as the chunks arrive:

Get the filename
Open a file for writing
Get the filesize
Setup a loop to receive the file data
  Send OK
  Get chunk from socket
  Write data to file
  Break (stop) if filesize reached
  Loop
Close file

This, of course has no error correction and will probably die if you
have any packet loss on your network, a more robust solution would be to
use TCP sockets rather than UDP sockets.

Hope this helps :-)


Roger Heathcote

http://www.technicalbloke.com
http://movingtoubuntu.technicalbloke.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: translating ascii to binary

2008-09-17 Thread Steven D'Aprano
On Wed, 17 Sep 2008 18:02:15 +0200, Canned wrote:

> Hi,
> I'm trying to write a class that can convert ascii to binary and vice
> versa. I write my class based on this function I've found on internet

[...]

> That works perfectly, but when I try to implement it in my own class it
> gives me alot of headache, also because I'm totally new to the language.
> It work only with one character at a time, and if I give a string it
> just give some weird result.


[snip code]

Your "ascii_to_bin" method tries to do too much in one method. You should 
split the functionality into small, self-contained pieces, then combine 
them. And frankly, once you got to the part where you started popping and 
inserting, my brain melted. You are making an easy job too hard! *smiles*

Try this instead:

class Converterab:
'''
Ascii-binary converter.
'''
def __init__(self, string):
self.string = string
def bin(self, n):
"""Return the binary representation of a positive integer n."""
bindump = []
while n > 0:
bindump.append(str(n & 1))
n = n >> 1
bindump.reverse()
if bindump:
return ''.join(bindump)
else:
return '0'
def char_to_bin(self, c):
"""Return the binary representation of a character c."""
bits = self.bin(ord(c))
zeroes = "0" * (8-len(bits))
return zeroes+bits
def ascii_to_bin(self):
results = []
for c in self.string:
results.append(self.char_to_bin(c))
return ''.join(results)



-- 
Steven

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


Re: Converting .py files to batch files.

2008-09-17 Thread Grant Edwards
On 2008-09-17, r0g <[EMAIL PROTECTED]> wrote:

> [EMAIL PROTECTED]:~/Desktop/py$ ls
> kickstart.py  kickstart.py~  kicktest.py  kicktest.py~
> [EMAIL PROTECTED]:~/Desktop/py$ kickstart.py
> bash: kickstart.py: command not found
>
> Any ideas why this might be?

Yes.

> A path thing?

Yes.

Linux systems generally don't have the current directory in the
PATH that's searched for executbles (it's regarded as a rather
serious security problem if you do).

Try doing this:

 ./kickstart.py

-- 
Grant Edwards   grante Yow! Look into my eyes and
  at   try to forget that you have
   visi.coma Macy's charge card!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting .py files to batch files.

2008-09-17 Thread r0g
Michael Palmer wrote:
> On Sep 15, 3:04 pm, Matias Surdi <[EMAIL PROTECTED]> wrote:
>> aditya shukla escribió:
>>
>>> How can we convert .py files to batch files? is there any library for this?
>>> Aditya
>>> 
> On Linux, you would instead insert the shebang line that points to
> your python interpreter, such as
> 
> #!/usr/bin/python
> 
> at the top and also set the executable bit, but I suppose if you use
> Linux at all you know that.

Doh! I'm new to Linux and so I didn't know that, thanks!
One small snag though, it doesn't work on my system :-(
I did both steps, the shebang and the execute bit but nada...

[EMAIL PROTECTED]:~/Desktop/py$ ls
kickstart.py  kickstart.py~  kicktest.py  kicktest.py~
[EMAIL PROTECTED]:~/Desktop/py$ kickstart.py
bash: kickstart.py: command not found

Any ideas why this might be? A path thing? I'm on Ubuntu 8.04 / Py2.5

Thanks,

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


Re: python-mode problem, doesnt load whole module?

2008-09-17 Thread Fredrik Lundh

cnb wrote:


a = parsing.unserialize("C:/users/saftarn/desktop/twok.txt")

Traceback (most recent call last):



  File "C:\Python25\lib\pickle.py", line 1126, in find_class
klass = getattr(mod, name)


when reporting a traceback, please include the error message that 
follows after the stack trace.




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


Re: translating ascii to binary

2008-09-17 Thread Fredrik Lundh

Lie wrote:


Any advice about this matter would be very appreciated.
Thanks in advance.


It'd be easier to make a one-char version of ascii2bin then make the
string version based on the one-char version.


And it'd be a lot easier to read your posts if you trimmed away at least 
some of the original message before posting.  If you cannot do that for 
some technical reason, I recommend using top-posting instead.




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


python-mode problem, doesnt load whole module?

2008-09-17 Thread cnb
>>> a = parsing.unserialize("C:/users/saftarn/desktop/twok.txt")
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\Progs\NetflixRecSys\parsing.py", line 91, in
unserialize
return pickle.load(open(filename, 'r'))
  File "C:\Python25\lib\pickle.py", line 1370, in load
return Unpickler(file).load()
  File "C:\Python25\lib\pickle.py", line 858, in load
dispatch[key](self)
  File "C:\Python25\lib\pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
  File "C:\Python25\lib\pickle.py", line 1126, in find_class
klass = getattr(mod, name)


if i use the python-gui-editor-repl it works though...

so isn't emacs loading modules properly? this shouldnt have to do with
emacs itself though, right?
--
http://mail.python.org/mailman/listinfo/python-list


Re: translating ascii to binary

2008-09-17 Thread Lie
On Sep 17, 11:02 pm, Canned <[EMAIL PROTECTED]> wrote:
> Hi,
> I'm trying to write a class that can convert ascii to binary and vice
> versa. I write my class based on this function I've found on internet
>
>
>
>
>
> > def ascii_to_bin(char):
> > ascii = ord(char)
> > bin = []
>
> > while (ascii > 0):
> > if (ascii & 1) == 1:
> > bin.append("1")
> > else:
> > bin.append("0")
> > ascii = ascii >> 1
>
> > bin.reverse()
> > binary = "".join(bin)
> > zerofix = (8 - len(binary)) * '0'
>
> > return zerofix + binary
>
> > some_string = 'Time to go now, Rummy?'
>
> > binary = []
> > for char in some_string:
> > binary.append(ascii_to_bin(char))
>
> > print binary
> > print " ".join(binary)
>
> That works perfectly, but when I try to implement it in my own class it
> gives me alot of headache, also because I'm totally new to the language.
> It work only with one character at a time, and if I give a string it
> just give some weird result.
>
>
>
>
>
> > if len(sys.argv) < 2:
> >         print 'usage:', os.path.basename(sys.argv[0]), 'text'
> >         sys.exit()
>
> > class Converterab:
> >         '''
> >         Ascii-binary converter.
> >         '''
> >         def __init__(self, string):
> >                 self.string = string
>
> >         def ascii_to_bin(self):
> >                 bindump = []
> >                 for char in self.string:
> >                         bin = ord(char)
> >                         while bin > 0:
> >                                 if (bin & 1) == 1:
> >                                         bindump.append("1")
> >                                 else:
> >                                         bindump.append("0")
> >                                 bin = bin >> 1
> >                 bindump.reverse()
> >                 print bindump   # Debug tool, delete this
>
> >                 '''
> >                 Zero fix in bindump
> >                 '''
> >                 bindump.insert(0, "0")
> >                 count = 0
> >                 pos = 0
> >                 for dg in bindump:
> >                         count += 1
> >                         pos += 1
> >                         if count == 8:
> >                                 bindump.insert(pos, "0")
> >                                 count = 0
> >                 bindump.pop()
> >                 print bindump   # Debug tool, delete this, the best result 
> > so far
>
> >                 '''
> >                 Reversing array per byte
> >                 '''
> >                 final = []
> >                 pos -= pos      # Set pos to 0 again
> >                 while len(bindump) != 0:
> >                         print count     # Debug tool, delete this, this is 
> > weird, start at 1, I expected 0
> >                         count += 1
> >                         if count > 8:
> >                                 pos += 8
> >                                 count -= count
> >                         final.insert(pos, bindump.pop())
> >                         print final     # Debug tool, delete this
> >                 '''
> >                 for ar in bindump:
> >                         count += 1
> >                         if (count < 8):
> >                                 final.insert(pos, bindump.pop())
> >                         elif (count >= 8):
> >                                 pos = count
> >                                 final.insert(pos, bindump.pop())
> >                         else:
> >                                 final.insert(pos, bindump.pop())
> >                 '''
> >                 final.insert(0, final.pop())
>
> >                 binary = "".join(final)
> >                 return binary
>
> > result = Converterab(sys.argv[1])
>
> > print "Char : ", result.ascii_to_bin()
>
> The problem start at "Reversing array per byte". That block should
> reversing the array from 'bindump' and copy it to 'final' per 8 items,
> e.g. a = ['0', '1', '0', '1', '0', '1', '0', '1', '2', '1', '2', '1',
> '2', '1', '2', '1', '3', '2', '3', '2', '3', '2', '3', '2']
> b = ['3', '2', '3', '2', '3', '2', '3', '2', '2', '1', '2', '1', '2',
> '1', '2', '1', '0', '1', '0', '1', '0', '1', '0', '1']
>
> Any advice about this matter would be very appreciated.
> Thanks in advance.

It'd be easier to make a one-char version of ascii2bin then make the
string version based on the one-char version.
--
http://mail.python.org/mailman/listinfo/python-list


translating ascii to binary

2008-09-17 Thread Canned
Hi,
I'm trying to write a class that can convert ascii to binary and vice
versa. I write my class based on this function I've found on internet
> def ascii_to_bin(char):
> ascii = ord(char)
> bin = []
> 
> while (ascii > 0):
> if (ascii & 1) == 1:
> bin.append("1")
> else:
> bin.append("0")
> ascii = ascii >> 1
> 
> bin.reverse()
> binary = "".join(bin)
> zerofix = (8 - len(binary)) * '0'
> 
> return zerofix + binary
> 
> 
> 
> some_string = 'Time to go now, Rummy?'
> 
> binary = []
> for char in some_string:
> binary.append(ascii_to_bin(char))
> 
> print binary
> print " ".join(binary)

That works perfectly, but when I try to implement it in my own class it
gives me alot of headache, also because I'm totally new to the language.
It work only with one character at a time, and if I give a string it
just give some weird result.

> if len(sys.argv) < 2:
> print 'usage:', os.path.basename(sys.argv[0]), 'text'
> sys.exit()
> 
> class Converterab:
> '''
> Ascii-binary converter.
> '''
> def __init__(self, string):
> self.string = string
> 
> def ascii_to_bin(self):
> bindump = []
> for char in self.string:
> bin = ord(char)
> while bin > 0:
> if (bin & 1) == 1:
> bindump.append("1")
> else:
> bindump.append("0")
> bin = bin >> 1
> bindump.reverse()
> print bindump   # Debug tool, delete this
> 
> '''
> Zero fix in bindump
> '''
> bindump.insert(0, "0")
> count = 0
> pos = 0
> for dg in bindump:
> count += 1
> pos += 1
> if count == 8:
> bindump.insert(pos, "0")
> count = 0
> bindump.pop()
> print bindump   # Debug tool, delete this, the best result so 
> far
> 
> '''
> Reversing array per byte
> '''
> final = []
> pos -= pos  # Set pos to 0 again
> while len(bindump) != 0:
> print count # Debug tool, delete this, this is 
> weird, start at 1, I expected 0
> count += 1
> if count > 8:
> pos += 8
> count -= count
> final.insert(pos, bindump.pop())
> print final # Debug tool, delete this
> '''
> for ar in bindump:
> count += 1
> if (count < 8):
> final.insert(pos, bindump.pop())
> elif (count >= 8):
> pos = count
> final.insert(pos, bindump.pop())
> else:
> final.insert(pos, bindump.pop())
> '''
> final.insert(0, final.pop())
> 
> binary = "".join(final)
> return binary
> 
> result = Converterab(sys.argv[1])
> 
> print "Char : ", result.ascii_to_bin()

The problem start at "Reversing array per byte". That block should
reversing the array from 'bindump' and copy it to 'final' per 8 items,
e.g. a = ['0', '1', '0', '1', '0', '1', '0', '1', '2', '1', '2', '1',
'2', '1', '2', '1', '3', '2', '3', '2', '3', '2', '3', '2']
b = ['3', '2', '3', '2', '3', '2', '3', '2', '2', '1', '2', '1', '2',
'1', '2', '1', '0', '1', '0', '1', '0', '1', '0', '1']

Any advice about this matter would be very appreciated.
Thanks in advance.

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


Re: append on lists

2008-09-17 Thread Lie
On Sep 16, 3:20 pm, Armin <[EMAIL PROTECTED]> wrote:
> John Machin wrote:
> > On Sep 16, 6:45 am, Armin <[EMAIL PROTECTED]> wrote:
>
> >> Yes, but this is very unconvenient.
> >> If d should reference the list a extended with a single list element
> >> you need at least two lines
>
> >> a.append(7)
> >> d=a
>
> >> and not more intuitive d = a.append(7)
>
> > Methods/functions which return a value other than the formal None and
> > also mutate their environment are "a snare and a delusion". Don't wish
> > for them.
>
>    c = [9,10]
>    [1,2,3,4,7].append(c) -> Is this a valid expression?
>

Yes, that is a valid expression, however, the list you're appending to
is immediately discarded.

>    The 'value' of that expression is None.
>
>    However ... that's the way of the implementation of the append method.
>    It's a little bit confusing to me ...

actually, you could implement your own myList which returns a value on
append method:

class MyList(list):
def append(self, item):
list.append(self, item)
return self
# or
# return self[:]
# if you want it to return a copy

But I recommend against that.

> --Armin
>
> Thanks to all !
>
>
>
>
>
> > Inconvenient? How often do you want to mutate a list and then set up
> > another reference to it?- Hide quoted text -
>
> - Show quoted text -

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


python regex character group matches...group...gotcha

2008-09-17 Thread christopher taylor
My apologies to the respondents - I failed to screen my test cases
before kicking them out to the global python-list. but yes, the 'X'
character in my test case was a mistake on my part. I'll give group()
a shot.

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


Re: python regex character group matches

2008-09-17 Thread Fredrik Lundh

Steven D'Aprano wrote:


Assuming that you want to find runs of \u escapes, simply use
non-capturing parentheses:

pat = re.compile(u"(?:\\\u[0-9A-F]{4})")


Doesn't work for me:


pat = re.compile(u"(?:\\\u[0-9A-F]{4})")


it helps if you cut and paste the right line...  here's a better version:

pat = re.compile(r"(?:\\u[0-9A-F]{4})+")



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


Re: python regex character group matches

2008-09-17 Thread Steven D'Aprano
On Wed, 17 Sep 2008 09:27:47 -0400, christopher taylor wrote:

> hello python-list!
> 
> the other day, i was trying to match unicode character sequences that
> looked like this:
> 
> \\uAD0X...

It is not clear what this is supposed to be. Is that matching a literal 
pair of backslashes, or a single escaped backslash, or a single unicode 
character with codepoint AD0X, or what?

If I read it *literally*, then you're trying to match:

backslash backslash lowercase-u uppercase-A uppercase-D zero uppercase-X

Is that what you intended to match?


> my issue, is that the pattern i used was returning:
> 
> [ '\\uAD0X', '\\u1BF3', ... ]

Unless you are using Python 3, I see that you aren't actually dealing 
with Unicode strings, you're using byte strings. Is that deliberate?


> when i expected:
> 
> [ '\\uAD0X\\u1BF3', ]

I make that to be a string of length 12. Is that what you are expecting?

>>> len('\\uAD0X\\u1BF3')
12


> the code looks something like this:
> 
> pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE) 
> #print pat.findall(txt_line)
> results = pat.finditer(txt_line)

First point: I don't think the UNICODE flag does what you think it does. 
It redefines the meaning of special escape sequences \b etc. Since you 
aren't using any special escape sequences, I'm going to guess that you 
think it turns your search string into Unicode. It doesn't. (Apologies in 
advance if I guessed wrong.) I don't think you need either the UNICODE or 
LOCALE flag for this search: they don't seem to have any effect.

Secondly: you will generally save yourself a lot of trouble when writing 
regexes to use raw strings, because backslashes in the regex engine clash 
with backslashes in Python strings. But there's a gotcha: backslash 
escapes behave differently in ordinary strings and the re engine.

In an ordinary string, the sequence backslash-char is treated as a 
literal backslash-char if it isn't a special escape. So:

>>> len('\t')  # special escape
1
>>> len('\u')  # not a special escape
2

But that's not the case in the re engine! As the Fine Manual says:

The special sequences consist of "\" and a character from 
the list below. If the ordinary character is not on the 
list, then the resulting RE will match the second character. 
For example, \$ matches the character "$".

http://docs.python.org/lib/re-syntax.html

So all of these match the same thing:
re.compile('\\u')
re.compile(r'\u')
re.compile('u')

To match a literal backslash-u, you need to escape the backslash before 
the engine joins it to the u: r'\\u'.

Putting it all together again:

pat = re.compile(r"(\\u[0-9A-F]{4})+") 

will probably do what you want, assuming I have guessed what you want 
correctly!



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


Re: Problem occured while sending mail

2008-09-17 Thread Peter Pearson
On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui <[EMAIL PROTECTED]> wrote:
> On Sep 17, 5:04 pm, sui <[EMAIL PROTECTED]> wrote:
>> this is my code
>>
>> import sys, os, glob, datetime, time
>> import smtplib
>> ## Parameters for SMTP session
>> port=587
>> SMTPserver=  'smtp.gmail.com'
>> SMTPuser= '[EMAIL PROTECTED]'
>> pw= 'fill in here'
>> SENDER= SMTPuser
>>
>> ## Message details
>> FROM=  SENDER
>> TO= '[EMAIL PROTECTED]'
>> CC=FROM
>> ##RECEIVERS= (TO, CC)  ##proper way to send to both TO and CC
>> RECEIVERS= (TO,)  ## ignore the CC address
>>
>> subject= 'Test 1a'
>> message='*** Email test  *** '
>>
>> print 'Starting SMTP mail session on %s as  %s ' %
>> (SMTPserver,SMTPuser)
>> session = smtplib.SMTP(SMTPserver,port)
>> session.set_debuglevel(0)  # set debug level to 1 to see details
>> session.ehlo(SMTPuser)  # say hello
>> session.starttls()  # TLS needed
>> session.ehlo(SMTPuser)  # say hello again, not sure why
>> session.login(SMTPuser, pw)
>>
>> ##Create HEADER + MESSAGE
>> HEADER= 'From: %s\r\n' % FROM
>> HEADER= HEADER + 'To: %s\r\n' % TO
>> HEADER= HEADER + 'Cc: %s\r\n' % CC
>> HEADER= HEADER + 'Subject: %s\r\n' % subject
>> BODY= HEADER + '\r\n' + message
>> print BODY
>>
>> SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY)  ## send email
>>
>> session.close()
>>
>> Now when i run this .py file...as python mail.py
>> i can see only statement
>> starting smtp mail..n details
>> then nothing on screen after few minutes or after pressing ctrl +c
>> Traceback (most recent call last):
>>   File "mail4.py", line 21, in 
>> session = smtplib.SMTP(SMTPserver,port)
>>   File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
>> (code, msg) = self.connect(host, port)
>>   File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect
>> self.sock.connect(sa)
>>   File "", line 1, in connect
>> or may be conncetion time out
>>
>> wats the solution for this
>
> if i dont press cntrl + c then it shows
> Starting SMTP mail session on smtp.gmail.com as  [EMAIL PROTECTED]
> Traceback (most recent call last):
>   File "mail4.py", line 21, in 
> session = smtplib.SMTP(SMTPserver,port)
>   File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
> (code, msg) = self.connect(host, port)
>   File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect
> raise socket.error, msg
> socket.error: (110, 'Connection timed out')
>
> plz help me its urgent.i want to complete it as early as possible

I pasted your code into a file named temp.py, 
and (perhaps superstitiously) added a backslash to this line:
>> print 'Starting SMTP mail session on %s as  %s ' %

Here's what it does (long line wrapped manually):

[EMAIL PROTECTED]:~$ python temp.py
Starting SMTP mail session on smtp.gmail.com as  [EMAIL PROTECTED]
Traceback (most recent call last):
  File "temp.py", line 27, in ?
session.login(SMTPuser, pw)
  File "/usr/lib/python2.4/smtplib.py", line 591, in login
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535,  \
   '5.7.1 Username and Password not accepted. Learn more at\n'  \
   '5.7.1 http://mail.google.com/support/bin/answer.py?answer=' \
   '14257 a8sm34686663poa.12')
[EMAIL PROTECTED]:~$

This indicates that it got much farther than when you ran it, since
your timeout message comes from the smtplib.SMTP call several lines
before the session.login call.

As a simple connectivity test, you might see whether you can connect
using telnet:

[EMAIL PROTECTED]:~$ telnet smtp.gmail.com 587
Trying 72.14.253.109...
Connected to gmail-smtp.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP m27sm34789033pof.6
^]c

telnet> c
Connection closed.
[EMAIL PROTECTED]:~$

-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python regex character group matches

2008-09-17 Thread Steven D'Aprano
On Wed, 17 Sep 2008 15:56:31 +0200, Fredrik Lundh wrote:

> Assuming that you want to find runs of \u escapes, simply use
> non-capturing parentheses:
> 
> pat = re.compile(u"(?:\\\u[0-9A-F]{4})")

Doesn't work for me:

>>> pat = re.compile(u"(?:\\\u[0-9A-F]{4})")
UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 
5-7: truncated \u escape


Assuming that the OP is searching byte strings, I came up with this:

>>> pat = re.compile('(\\\u[0-9A-F]{4})+')
>>> pat.search('abcd\\u1234\\uAA99\\u0BC4efg').group(0)
'\\u1234\\uAA99\\u0BC4'



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


Re: Python OOP advice

2008-09-17 Thread Bruno Desthuilliers

Simon Hibbs a écrit :

Great contributions, thanks both of you. I'm self-tought when it comes
to Python and OOP and I haven't yet grown an intuitive feel for how to
do things sensibly.


While part of the OO design patterns are mostly workaround for lack of 
dynamism in languages like C++ or Java, and while pattern abuse is 
certainly not good design, you'd probably learn a lot from the  GOF's 
Design Patterns book.



Simon

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


Re: Python OOP advice

2008-09-17 Thread Bruno Desthuilliers

Ben Finney a écrit :

Simon Hibbs <[EMAIL PROTECTED]> writes:


Orriginaly I thought I'd need to have a hull object which contains
component objects, but the component objects need access to members
of the hull object (e.g. the hull size) so that looks messy to
implement.


Was it as messy as this::

class ShipHull(object):
def __init__(self, size):
self.components = dict()
self.size = size

class ShipComponent(object):
def __init__(self, name, hull):
self.name = name
self.hull = hull


I have defined a base class Component with a class member variable
'hull_size' so that all components can see the hull size.


It seems to me the hull is an attribute of the component, and the size
is an attribute of the hull. Why would the hull size be a *class*
attribute?


I've then got two child classes called Fixed_Component and Percent
_Component that implement their mass, mass_percent and cost
properties appropriately for their type.


class FixedShipComponent(ShipComponent):
def _get_mass(self):
return calculation_foo(self.hull.size)
mass = property(_get_mass)

def _get_cost(self):
return calculation_bar(self.hull.size)
cost = property(_get_cost)

class PercentShipComponent(ShipComponent):
def _get_mass(self):
return calculation_spam(self.hull.size)
mass = property(_get_mass)

def _get_cost(self):
return calculation_eggs(self.hull.size)
cost = property(_get_cost)


Or use the strategy pattern (dummy example, don't have time to read your 
specs !-):


class FixedMassCostStrategy(object):
def get_mass(self, hull):
return calculation_foo(hull.size)
def get_cost(self):
return calculation_bar(hull.size)

class PercentMassCostStrategy(object):
def get_mass(self, hull):
return calculation_spam(hull.size)
def get_cost(self):
return calculation_eggs(hull.size)


class ShipComponent(object):
def __init__(self, name, hull, masscost_strategy):
self.name = name
self._hull = hull # implementation detail
self._strategy = masscost_strategy

mass = property(lambda self: self._strategy.get_mass(self._hull))
cost = property(lambda self: self._strategy.get_cost(self._hull))


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

Re: Generating test data from an XML Schema

2008-09-17 Thread Jonathan Fine

Mark Thomas wrote:


Has anyone seen anything that might help generate test data from a schema?


I'm unaware of anything in Python, but Eclipse can generate sample
documents from a schema:
http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.xmleditor.doc.user/topics/tcrexxsd.html

As can XML IDEs such as Stylus Studio and XML Spy.


Mark - thank you for this.  The problem is that I'd like to sit quite 
close to the schema and manipulate the generation of the test data. 
(This is because a straight representation won't suit my needs.)


However, if I get the chance I'll look at these tools, in case they can 
help me.  Thank you for the suggestion.


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


Re: python regex character group matches

2008-09-17 Thread Fredrik Lundh

christopher taylor wrote:


my issue, is that the pattern i used was returning:

[ '\\uAD0X', '\\u1BF3', ... ]

when i expected:

[ '\\uAD0X\\u1BF3', ]

the code looks something like this:

pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE)
#print pat.findall(txt_line)
results = pat.finditer(txt_line)

i ran the pattern through a couple of my colleagues and they were all
in agreement that my pattern should have matched correctly.


First, [0-9A-F] cannot match an "X".  Assuming that's a typo, your next 
problem is a precedence issue: (X)+ means "one or more (X)", not "one or 
more X inside parens".  In other words, that pattern matches one or more 
X's and captures the last one.


Assuming that you want to find runs of \u escapes, simply use 
non-capturing parentheses:


   pat = re.compile(u"(?:\\\u[0-9A-F]{4})")

and use group(0) instead of group(1) to get the match.



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


Re: Python and Open Office

2008-09-17 Thread Hartmut Goebel

Terry Reedy schrieb:

One way to learn the meaning of some of the numerous attributes and 
values is to create a file with the wanted features with OOo, save, 
unzip, and examine the xml to see which tags are used for which features.


The API docs are a bit hidden on the webpage. Here is the link:


Additionally teh ODF sepcs may help:


Regards
H. Goebel
--
http://mail.python.org/mailman/listinfo/python-list


Re: python regex character group matches

2008-09-17 Thread Marc 'BlackJack' Rintsch
On Wed, 17 Sep 2008 09:27:47 -0400, christopher taylor wrote:

> the other day, i was trying to match unicode character sequences that
> looked like this:
> 
> \\uAD0X...
>
> my issue, is that the pattern i used was returning:
> 
> [ '\\uAD0X', '\\u1BF3', ... ]
> 
> when i expected:
> 
> [ '\\uAD0X\\u1BF3', ]
> 
> the code looks something like this:
> 
> pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE) #print
> pat.findall(txt_line)
> results = pat.finditer(txt_line)
>  
> i ran the pattern through a couple of my colleagues and they were all in
> agreement that my pattern should have matched correctly.

Correctly for what input?  And the examples above are not matching (no 
pun intended) the regular expression.  `pat` doesn't match '\\uAD0X' 
because there's no 'X' in the character class.  BTW: Are you sure you 
need or want the `re.UNICODE` flag?

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


python regex character group matches

2008-09-17 Thread christopher taylor
hello python-list!

the other day, i was trying to match unicode character sequences that
looked like this:

\\uAD0X...

my issue, is that the pattern i used was returning:

[ '\\uAD0X', '\\u1BF3', ... ]

when i expected:

[ '\\uAD0X\\u1BF3', ]

the code looks something like this:

pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE)
#print pat.findall(txt_line)
results = pat.finditer(txt_line)

i ran the pattern through a couple of my colleagues and they were all
in agreement that my pattern should have matched correctly.

is this a simple case of a messed up regex or am i not using the regex
api correctly?

cheers,

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


Re: Python OOP advice

2008-09-17 Thread Simon Hibbs
Great contributions, thanks both of you. I'm self-tought when it comes
to Python and OOP and I haven't yet grown an intuitive feel for how to
do things sensibly.

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


Re: Python OOP advice

2008-09-17 Thread Paul McGuire
On Sep 17, 6:50 am, Simon Hibbs <[EMAIL PROTECTED]> wrote:
> I'm rewriting a design application for a science fiction game. in it
> you design your own starships. Each component has a mass and cost, but
> the mass can either be fixed or it can be expressed as a percentage of
> the tonnage of the overall ship.
>
> Orriginaly I thought I'd need to have a hull object which contains
> component objects, but the component objects need access to members of
> the hull object (e.g. the hull size) so that looks messy to implement.
>

I would not put this kind of intelligence into the components.

I think the issue here is that your Ship container is not really just
a generic container of ship components, but an assembly with some
specific requirements (must have 1 and only 1 hull, must have 1 or
more engines, etc.) and structure.  I would create a class called
ShipDesign that had specific members for those components that have
special logic attached to them, and then more generic list members for
collection-ish components.

Since the hull is such a significant constraint, I would make it an
initialization argument.  I would also put some kind of property on
hull representing its "capacity" (oh I see, you have something call
hull_size).

One way to generalize the fixed-cost vs. percentage-cost components
would be to have all components implement a compute_load function that
takes the ShipDesign as an argument.  Those that are fixed-cost simply
return their fixed value, those that are percentage-cost can return
their percentage of the ShipDesign's hull.hull_size - this leaves the
door open for other variations on load, that could be based on other
properties besides the hull size.

Here's how I envision your ShipDesign class:

class ShipDesign(object):
def __init__(self, hull):
self.hull = hull
self.engines = []
self.shields = []
self.weapons = []
self.other = []

def compute_consumed_capacity(self):
load = 0
for itemlist in (self.engines, self.shields,
self.weapons, self.other)):
load += sum(item.compute_load(self)
for item in itemlist)
return load

def add_engine(self,e):
engload = e.compute_load(self)
if engload + self.compute_consumed_capacity() >
self.hull.hull_size:
raise ExceededHullCapacityException()
if len(self.engines) == MAXIMUM_ALLOWED_ENGINES:
raise ExceededMaximumConfigurationLimitException()
self.engines.append(e)

def set_hull(self, hull):
if self.compute_consumed_capacity() <= hull.hull_size:
self.hull = hull
else:
raise NewHullTooSmallException()

def is_valid(self):
if not self.engines:
raise InvalidDesignException("must have at least 1
engine")
...etc...

class GenericItem(object):
def __init__(self, name, load):
self.name = name
self.load = load
crewQuarters = GenericItem("Crew Quarters", 50)
disco = GenericItem("Discotheque", 10)
...etc...

Once you have a valid ShipDesign, you can then use it to construct
multiple Ship instances.

Here is how I would work around your "only one hull at a time"
problem.  Define several classes for different kinds of hulls:

class CheapHull(Hull):
capacity = 100
name = "EconoHull 1000"
class MediumHull(Hull):
capacity = 500
name = "Mainliner X50"
class TopOTheLineHull(Hull):
capacity = 1000
name = "LuxeMaster 5000"

and then create ship designs with a CheapHull, a MediumHull, or a
TopOTheLineHull.  In this case, the member variable of the ShipDesign
is really a class, which you would later use to construct hull
instances as part of making Ship instances from your ShipDesign.

class Ship(object):
def __init__(self, design):
self.hull = design.hull()
self.engines = design.engines[:]
...etc...

This way, each Ship will have its own Hull instance, so that you
can track instance-specific properties, such as damage percentage.

If you don't want to hard-code the hull types, then you can do
something similar with instances of a generic Hull class, which you
would then use as prototypes when constructing Ship instances.  Just
be careful that you don't accidentally have all ships sharing the same
hull instance!

-- Paul

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


Re: Generating test data from an XML Schema

2008-09-17 Thread Mark Thomas
On Sep 17, 5:29 am, Jonathan Fine <[EMAIL PROTECTED]> wrote:
> Hello
>
> I want to generate test data from an XML schema.  I've had a quick look
> at existing tools (such as minixsv and amara) but from what I've seen
> they don't seem to help.
...
> A tool that provides a nice Python interface to navigating the schema
> would probably be quite helpful.
>
> Has anyone seen anything that might help generate test data from a schema?

I'm unaware of anything in Python, but Eclipse can generate sample
documents from a schema:
http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.xmleditor.doc.user/topics/tcrexxsd.html

As can XML IDEs such as Stylus Studio and XML Spy.

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


Re: recursive using the os.walk(path) from the os module

2008-09-17 Thread Fredrik Lundh

A. Joseph wrote:


I want to search through a directory and re-arrange all the files into e.g

All .doc files go into MS WORD folder, all .pdf files goes into PDF Folder.

I`m thinking of doing something with the os.walk(path) method from os 
module, I need some ideal how the algorithm should look like, maybe 
recursive ..any deal?


os.walk traverses the directory tree, so I'm not sure why you think that 
your program needs to use recursion?  wouldn't a plain loop work?


import os, shutil

for dirpath, dirnames, filenames in os.walk(directory):
for name in filenames:
source = os.path.join(dirpath, name)
... check extension and determine target directory ...
destination = os.path.join(targetdir, name)
shutil.move(source, destination)

tweak as necessary.



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


Re: recursive using the os.walk(path) from the os module

2008-09-17 Thread Simon Brunning
2008/9/17 A. Joseph <[EMAIL PROTECTED]>:
> I want to search through a directory and re-arrange all the files into e.g
>
> All .doc files go into MS WORD folder, all .pdf files goes into PDF Folder.
>
> I`m thinking of doing something with the os.walk(path) method from os
> module, I need some ideal how the algorithm should look like, maybe
> recursive ..any deal?

This help?

http://code.activestate.com/recipes/499305/

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python OOP advice

2008-09-17 Thread Ben Finney
Simon Hibbs <[EMAIL PROTECTED]> writes:

> Orriginaly I thought I'd need to have a hull object which contains
> component objects, but the component objects need access to members
> of the hull object (e.g. the hull size) so that looks messy to
> implement.

Was it as messy as this::

class ShipHull(object):
def __init__(self, size):
self.components = dict()
self.size = size

class ShipComponent(object):
def __init__(self, name, hull):
self.name = name
self.hull = hull

> I have defined a base class Component with a class member variable
> 'hull_size' so that all components can see the hull size.

It seems to me the hull is an attribute of the component, and the size
is an attribute of the hull. Why would the hull size be a *class*
attribute?

> I've then got two child classes called Fixed_Component and Percent
> _Component that implement their mass, mass_percent and cost
> properties appropriately for their type.

class FixedShipComponent(ShipComponent):
def _get_mass(self):
return calculation_foo(self.hull.size)
mass = property(_get_mass)

def _get_cost(self):
return calculation_bar(self.hull.size)
cost = property(_get_cost)

class PercentShipComponent(ShipComponent):
def _get_mass(self):
return calculation_spam(self.hull.size)
mass = property(_get_mass)

def _get_cost(self):
return calculation_eggs(self.hull.size)
cost = property(_get_cost)

> I've also defined a Hull class which also inherits from Component
> and provides methods for access to the hull_size class variable.

I don't see why, if a ShipComponent needs to refer to its hull as
something special, that a ShipHull would subclass ShipComponent.

> Is there a way to cleanly implement a parent-child relationship
> between objects that gives child objects limited access to members
> of the parent?

Sure; have the child instance grow an attribute referencing the
parent, preferably by passing it to the initialisation function
(__init__) of the child.

-- 
 \ Rommel: “Don't move, or I'll turn the key on this can of Spam!” |
  `\   —The Goon Show, _Rommel's Treasure_ |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

recursive using the os.walk(path) from the os module

2008-09-17 Thread A. Joseph
Hi,

I want to search through a directory and re-arrange all the files into e.g

All .doc files go into MS WORD folder, all .pdf files goes into PDF Folder.

I`m thinking of doing something with the os.walk(path) method from os
module, I need some ideal how the algorithm should look like, maybe
recursive ..any deal?



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

Re: Problem occured while sending mail

2008-09-17 Thread sui
On Sep 17, 5:04 pm, sui <[EMAIL PROTECTED]> wrote:
> this is my code
>
> import sys, os, glob, datetime, time
> import smtplib
> ## Parameters for SMTP session
> port=587
> SMTPserver=  'smtp.gmail.com'
> SMTPuser= '[EMAIL PROTECTED]'
> pw= 'fill in here'
> SENDER= SMTPuser
>
> ## Message details
> FROM=  SENDER
> TO= '[EMAIL PROTECTED]'
> CC=FROM
> ##RECEIVERS= (TO, CC)  ##proper way to send to both TO and CC
> RECEIVERS= (TO,)  ## ignore the CC address
>
> subject= 'Test 1a'
> message='*** Email test  *** '
>
> print 'Starting SMTP mail session on %s as  %s ' %
> (SMTPserver,SMTPuser)
> session = smtplib.SMTP(SMTPserver,port)
> session.set_debuglevel(0)  # set debug level to 1 to see details
> session.ehlo(SMTPuser)  # say hello
> session.starttls()  # TLS needed
> session.ehlo(SMTPuser)  # say hello again, not sure why
> session.login(SMTPuser, pw)
>
> ##Create HEADER + MESSAGE
> HEADER= 'From: %s\r\n' % FROM
> HEADER= HEADER + 'To: %s\r\n' % TO
> HEADER= HEADER + 'Cc: %s\r\n' % CC
> HEADER= HEADER + 'Subject: %s\r\n' % subject
> BODY= HEADER + '\r\n' + message
> print BODY
>
> SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY)  ## send email
>
> session.close()
>
> Now when i run this .py file...as python mail.py
> i can see only statement
> starting smtp mail..n details
> then nothing on screen after few minutes or after pressing ctrl +c
> Traceback (most recent call last):
>   File "mail4.py", line 21, in 
> session = smtplib.SMTP(SMTPserver,port)
>   File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
> (code, msg) = self.connect(host, port)
>   File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect
> self.sock.connect(sa)
>   File "", line 1, in connect
> or may be conncetion time out
>
> wats the solution for this

if i dont press cntrl + c then it shows
Starting SMTP mail session on smtp.gmail.com as  [EMAIL PROTECTED]
Traceback (most recent call last):
  File "mail4.py", line 21, in 
session = smtplib.SMTP(SMTPserver,port)
  File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
  File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect
raise socket.error, msg
socket.error: (110, 'Connection timed out')

plz help me its urgent.i want to complete it as early as possible
--
http://mail.python.org/mailman/listinfo/python-list


Re: SMTP via GMAIL

2008-09-17 Thread sui
On Aug 7, 12:40 am, mmm <[EMAIL PROTECTED]> wrote:
> On Aug 5, 12:18 am, Tim Roberts <[EMAIL PROTECTED]> wrote:
>
> > >But when using smtp.gmail.com as the server I learned that any
> > >@gmail.com address in the  Cc: text block would
> > >receive mail even if I changed the code to have the RECEIVERS list to
> > >ignore the CC addresses or not include the gmail address in the CC
> > >list as below
>
> > Interesting.  If true, that is incorrect behavior.
>
> I ran some more tests and now I am pretty sure
>
>   session.sendmail(SENDER, RECEIVERS, BODY)
>
> is only sending to the RECEIVERS list, ignoring the Cc: field in the
> body (as it should)
>
> What fooled me is that I was using my own gmail account (i.e.,
> [EMAIL PROTECTED]) as a Cc: field and not putting it in the RECEIVERS
> list.  It seems Gmail creates two links (or copies?) to the message:
> (1) as it is stored in the SENT box (as it should since the message
> was sent by my gmail account) and (2) another in my INBOX because the
> mail reading software reads the Cc: field.
>
> Other smtp servers such as comcast do not create the stored SENT mail
> and hence behave different in terms of how they treat Cc: fields of
> the same account ([EMAIL PROTECTED] in this case).
>
> Most important, using another gmail account (not [EMAIL PROTECTED]) as a
> Cc: field does not create another sent message (outside of what is in
> the RECEIVERS field).
>
> Sorry for confusion, and I do appreciate the tips as I now see how
> almost anything To:, Cc:, Bcc: combination can be handled by a proper
> RECEIVERS list.
>
> Below is python code that can be used by anyone that wants to test
> what I did  (just fill in the SMTPuser and password variables) and
> then check you gmail inbox
>
> import sys, os, glob, datetime, time
> import smtplib
> ## Parameters for SMTP session
> port=587
> SMTPserver=  'smtp.gmail.com'
> SMTPuser= '[EMAIL PROTECTED]'
> pw= 'fill in here'
> SENDER= SMTPuser
>
> ## Message details
> FROM=  SENDER
> TO= '[EMAIL PROTECTED]'
> CC=FROM
> ##RECEIVERS= (TO, CC)  ##proper way to send to both TO and CC
> RECEIVERS= (TO,)  ## ignore the CC address
>
> subject= 'Test 1a'
> message='*** Email test  *** '
>
> print 'Starting SMTP mail session on %s as  %s ' %
> (SMTPserver,SMTPuser)
> session = smtplib.SMTP(SMTPserver,port)
> session.set_debuglevel(0)  # set debug level to 1 to see details
> session.ehlo(SMTPuser)  # say hello
> session.starttls()  # TLS needed
> session.ehlo(SMTPuser)  # say hello again, not sure why
> session.login(SMTPuser, pw)
>
> ##Create HEADER + MESSAGE
> HEADER= 'From: %s\r\n' % FROM
> HEADER= HEADER + 'To: %s\r\n' % TO
> HEADER= HEADER + 'Cc: %s\r\n' % CC
> HEADER= HEADER + 'Subject: %s\r\n' % subject
> BODY= HEADER + '\r\n' + message
> print BODY
>
> SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY)  ## send email
>
> session.close()

i tried to run this code...but it didnt work
it shows that message like starting smtp session
then it doesnt show anything after very long time it shows
Traceback (most recent call last):
  File "mail5.py", line 21, in 
session = smtplib.SMTP(SMTPserver,port)
  File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
  File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect
self.sock.connect(sa)
  File "", line 1, in connect
then conncetion time out.
can u tell me wats the prob ...plz tell me solun
--
http://mail.python.org/mailman/listinfo/python-list


Re: help on python SWIG C++ extension

2008-09-17 Thread RLC
Thanks a lot, Tim and Diez, Merci Beaucoup!!

I strongly suspect the error was caused by the memory operation. I
made some modifications only on PolygonMesh definition. And now I have
no annoying warnings.
PolygonMesh *new_PolygonMesh()
{
  PolygonMesh *p = new PolygonMesh;
 //  p = (PolygonMesh *)malloc(sizeof(PolygonMesh));
//   p->vertices.clear();
//   p->polygonNbVertices.clear();
//   p->polygonStartVertexIndex.clear();
//   p->polygonVerticesIndices.clear();
//   p->uvs.clear();
//   p->polygonNbUVs.clear();
//   p->polygonStartUVIndex.clear();
//   p->polygonUVsIndices.clear();
  return p;
}

void delete_PolygonMesh(PolygonMesh *p)
{
  free(p);
}

when I run below script, it works well without any warning


#!/usr/local/bin/python

import tdimport

a = tdimport.PolygonMesh()

a.appendvertex(tdimport.Vertex(0.0,0.0,0.0))
a.appendvertex(tdimport.Vertex(1.0,0.0,0.0))
a.appendvertex(tdimport.Vertex(1.0,1.0,0.0))
a.appendvertex(tdimport.Vertex(0.0,1.0,0.0))
a.appendvertex(tdimport.Vertex(0.0,0.0,1.0))
a.appendvertex(tdimport.Vertex(1.0,0.0,1.0))
a.appendvertex(tdimport.Vertex(1.0,1.0,1.0))
a.appendvertex(tdimport.Vertex(0.0,1.0,1.0))

a.appendpolygon([0,3,2,1])
a.appendpolygon([0,1,5,4])
a.appendpolygon([1,2,6,5])
a.appendpolygon([2,3,7,6])
a.appendpolygon([0,4,7,3])
a.appendpolygon([4,5,6,7])

print a.getpolygonverticesindices(0)
print a.getpolygonverticesindices(1)
print a.getpolygonverticesindices(2)
print a.getpolygonverticesindices(3)
print a.getpolygonverticesindices(4)
print a.getpolygonverticesindices(5)

del a


Thanks again. Have a good day!!!

Regards
Roger

On Sep 17, 8:16 am, Tim Roberts <[EMAIL PROTECTED]> wrote:
> RLC <[EMAIL PROTECTED]> wrote:
>
> >I am new to python SWIG. Recently I wrote a small program trying to
> >import collada files(using colladadom) into python so I could use
> >python cgkit to render them. However, during the progressing, I got
> >some problems. Every time I quit from Python, I get a segmentation
> >fault, although the main program runs well. I suspect it is because I
> >wrapped std::vector objects in C struct and I did not release the
> >memory properly.
>
> That won't cause a segmentation fault.  However, I notice that you are
> using "malloc" and "free" to allocate and free your objects.  "stl" will
> use "new" and "delete", and it's not always healthy to mix them.  If I were
> you, I'd replace this:
>
> >  Vertex *v;
> >  v = (Vertex *)malloc(sizeof(Vertex));
>
> with this, which is less typing:
>Vertex * x = new Vertex;
> --
> Tim Roberts, [EMAIL PROTECTED]
> Providenza & Boekelheide, Inc.

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


Re: shelve file space always increase!

2008-09-17 Thread Michael Palmer
On Sep 17, 6:17 am, smalltalk <[EMAIL PROTECTED]> wrote:
> >>> import shelve
> >>> sf = shelve.open('e:/abc.db')
> >>> for i in range(1):
>
> ... sf[str(i)]=i
> ...>>> sf.close()
> >>> sf = shelve.open('e:/abc.db')
> >>> sf.clear()
> >>> sf
>
> {}
> the abc.db is always 312k though i have use clear(), how can i shrink
> the space?

shelve doesn't have any way of doing that. the only option is to read
all items from your shelve and write them to a new one.
--
http://mail.python.org/mailman/listinfo/python-list


Re: shelve file space always increase!

2008-09-17 Thread skip

smalltalk> the abc.db is always 312k though i have use clear(), how can
smalltalk> i shrink the space?

You really can't without deleting the file.  Hash file implementations trade
off file size against improve key lookup performance.  Similar tradeoffs are
made in the implementation of Python's dictionary and other languages'
associative arrays.

My Google skills must be lacking this morning.  Here's the best I've been
able to come up with in the way of explanation:

http://en.wikipedia.org/wiki/Associative_array#Efficient_representations

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


Problem occured while sending mail

2008-09-17 Thread sui
this is my code

import sys, os, glob, datetime, time
import smtplib
## Parameters for SMTP session
port=587
SMTPserver=  'smtp.gmail.com'
SMTPuser= '[EMAIL PROTECTED]'
pw= 'fill in here'
SENDER= SMTPuser

## Message details
FROM=  SENDER
TO= '[EMAIL PROTECTED]'
CC=FROM
##RECEIVERS= (TO, CC)  ##proper way to send to both TO and CC
RECEIVERS= (TO,)  ## ignore the CC address

subject= 'Test 1a'
message='*** Email test  *** '

print 'Starting SMTP mail session on %s as  %s ' %
(SMTPserver,SMTPuser)
session = smtplib.SMTP(SMTPserver,port)
session.set_debuglevel(0)  # set debug level to 1 to see details
session.ehlo(SMTPuser)  # say hello
session.starttls()  # TLS needed
session.ehlo(SMTPuser)  # say hello again, not sure why
session.login(SMTPuser, pw)

##Create HEADER + MESSAGE
HEADER= 'From: %s\r\n' % FROM
HEADER= HEADER + 'To: %s\r\n' % TO
HEADER= HEADER + 'Cc: %s\r\n' % CC
HEADER= HEADER + 'Subject: %s\r\n' % subject
BODY= HEADER + '\r\n' + message
print BODY

SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY)  ## send email

session.close()

Now when i run this .py file...as python mail.py
i can see only statement
starting smtp mail..n details
then nothing on screen after few minutes or after pressing ctrl +c
Traceback (most recent call last):
  File "mail4.py", line 21, in 
session = smtplib.SMTP(SMTPserver,port)
  File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
  File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect
self.sock.connect(sa)
  File "", line 1, in connect
or may be conncetion time out

wats the solution for this
--
http://mail.python.org/mailman/listinfo/python-list


Python OOP advice

2008-09-17 Thread Simon Hibbs
I'm rewriting a design application for a science fiction game. in it
you design your own starships. Each component has a mass and cost, but
the mass can either be fixed or it can be expressed as a percentage of
the tonnage of the overall ship.

Orriginaly I thought I'd need to have a hull object which contains
component objects, but the component objects need access to members of
the hull object (e.g. the hull size) so that looks messy to implement.

I have defined a base class Component with a class member variable
'hull_size' so that all components can see the hull size. I've then
got two child classes called Fixed_Component and Percent _Component
that implement their mass, mass_percent and cost properties
appropriately for their type. I've also defined a Hull class which
also inherits from Component and provides methods for access to the
hull_size class variable.

I'm not sure where to go from here. One possibility is to have a Ship
object containing a list of components, but I'd need to have a way to
ensure there's only ever one hull object so maybe that shouldn't go in
the list?

I think the fact that the hull_size is a class member also means I
can't ever have an application that loads two designs at the same
time, because they'd share the same hull_size class variable. Is that
so, and is there a way round that? I suspect the inheritance model
will work fine at first, but is too rigid in the long run.

Is there a way to cleanly implement a parent-child relationship
between objects that gives child objects limited access to members of
the parent?

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


Re: Use of generators and efficiency

2008-09-17 Thread Tim Chase
To my great surprise, this approach was often considerably _slower_  to 
complete than the original program (up to ~40% depending on which modifiers 
were used), despite producing initial results more quickly.


You may be interested in reading through this thread

http://mail.python.org/pipermail/python-list/2008-January/473650.html

where looping vs generators were timed and you can see that 
generators clearly (and sadly) impose a speed penalty as 
demonstrated by Andrew Reedick.  I'm not sure whether the "why" 
of it was ever determined, but generators should be used with 
care if speed is more important than clarity.


-tkc



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


Re: File Reading related query

2008-09-17 Thread Usman Ajmal
Thanks Tim. That rstrip('\r\n') worked. :)

On Wed, Sep 17, 2008 at 10:45 AM, Tim Chase
<[EMAIL PROTECTED]>wrote:

> Is there any function for reading a file while ignoring *\n* occuring in
>>> the file?
>>>
>>
>> can you be a bit more precise?  are we talking about text files or binary
>> files?  how do you want to treat any newlines that actually appear in the
>> file?
>>
>
> I believe the OP is referencing this behavior:
>
>  for line in file('x.txt'):
>assert not (
>  line.endswith('\r') or
>  line.endswith('\n')), "Don't want this"
>  else:
>yay()  # we never end up reaching this
>
> which can be done with a simple generator/wrapper:
>
>  def unnewline(iterator):
>for line in iterator:
>  yield line.rstrip('\r\n')
>  for line in unnewline(file('x.txt')):
>assert not (
>  line.endswith('\r') or
>  line.endswith('\n')), "Don't want this"
>  else:
>yay()  #  we get here this time
>
> Alternatively, the content can just be modified on the fly:
>
>  for line in file('x.txt'):
>line = line.rstrip('\r\n')
>...
>
> yes, the interpretation would differ if it were a binary file, but the
> above interpretation is a pretty common case (i.e. I encounter it daily, in
> my processing of client data-feeds).
>
> -tkc
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Use of generators and efficiency

2008-09-17 Thread John O'Hagan
Hi, 

I'm writing a Python program using combinatorial algorithms to generate music. 
It originally was of this general form:


First, a combinatorial function producing a list of sub-lists, then: 

For each sub-list in the list:
Filter/modifier A, then append modified sub-list to new list,

For each sublist in new list:
Filter/modifier B, then append modified sub-list to new list, 

 ..and so on for C, D,etc.

Finally, for each sub-list in the final list, output the sub-list 
(print/play as notes).


Because some of the combinatorial operations were slow 
to produce results, I changed the program to be of the form:


A combinatorial generator producing one small list for each call, then:

Filter/modify list through A,B, etc
Output the modified list
Call the generator for next list.


To my great surprise, this approach was often considerably _slower_  to 
complete than the original program (up to ~40% depending on which modifiers 
were used), despite producing initial results more quickly.

Some possibly relevant details: each sub-list consists of a short sequence of 
small numbers representing musical notes, but there may be millions of them; 
the modifiers range from simple tests (e.g., " if len(sub-list) is not n: 
continue" ) to relatively elaborate rearrangements and transformations.

My question is, how can it be quicker to unpack and rebuild a list for each 
modifier, than than to run all modifications on each element in turn? 

Any explanations, comments or advice?

Thanks,

John O'Hagan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Linear Programming on Ubuntu

2008-09-17 Thread Harold Fellermann

> > http://wiki.python.org/moin/NumericAndScientific/Libraries
> >
> > Scroll down.
>
> Yes, many of those seem to be deprecated, without destinations to
> links, most are poorly or not documented at all. The few that are, I
> still can't get running. Of those 254, I think I have tried at least
> 10 pages worth. Still no luck.
>
> # lpsolvpy - Can't get it to compile - dependency problems.
> # Lp_solve5 - NO python binding yet. Volunteers needed for python
> bindings.
> # pycplex - You need to compile the CPX.so module. Change the required
> paths to CPLEX, Python and numpy in the Makefile, and type "make". Not
> sure what to do here.
> # GLPK (GNU Linear Programming Kit) - Hrm... might be something here,
> I missed the second link to the python bindings, looked all over the
> glpk site for anything about python.
> # SciPy -- http://www.scipy.org - supposedly has this, but as I said,
> I can't find any mention of it anywhere but on the site you linked.
> # pySimplex - (broken link)(broken link)
> # Simplex - link is broken, but nothing is mentioned
>
> I'll take a closer look at glpk's python bindings and if there is any
> documentation on them, maybe I'll have some luck. btw, I have been
> looking for something that works, I have over 5 packages on my desktop
> that I have tried to get up and running, but none of them seem to
> work. glpk makes 6.

You are right that this is an unsatisfying experience. Fortunately,
the referred  site is a wiki. Why don't you edit it and delete the
broken
links or add the package that did the job for you to the list, so that
others do not need to go through the same hassle.

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


Re: File Reading related query

2008-09-17 Thread Tim Chase

I am talking about text file which contain multiple lines e.g following
three lines are there in my textfile.txt

this is python list
where we get support
from geeks

I want

sentence = this is python list where we get support from geeks

whereas when i use simple read() i get something like this

sentence = this is python list\nwhere we get support\nfrom geeks



You mean

  sentence = myfile.read().replace('\n', ' ')

?

If you want to compact multiple spaces, such as

  this is the python__
  list where__
  __we get support

(where "_" represents a space) and you want that to become

  this is the python list where we get support

you'd have to use slightly more intelligent processing, and 
explain the behavior you'd want if more than one blank line was 
encountered.  But for a first pass:


  import re
  r = re.compile(r"\s*\n")

  sentence = r.sub(" ", myfile.read())

-tkc



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


Re: File Reading related query

2008-09-17 Thread Tim Chase
Is there any function for reading a file while ignoring *\n* occuring in 
the file?


can you be a bit more precise?  are we talking about text files or 
binary files?  how do you want to treat any newlines that actually 
appear in the file?


I believe the OP is referencing this behavior:

  for line in file('x.txt'):
assert not (
  line.endswith('\r') or
  line.endswith('\n')), "Don't want this"
  else:
yay()  # we never end up reaching this

which can be done with a simple generator/wrapper:

  def unnewline(iterator):
for line in iterator:
  yield line.rstrip('\r\n')
  for line in unnewline(file('x.txt')):
assert not (
  line.endswith('\r') or
  line.endswith('\n')), "Don't want this"
  else:
yay()  #  we get here this time

Alternatively, the content can just be modified on the fly:

  for line in file('x.txt'):
line = line.rstrip('\r\n')
...

yes, the interpretation would differ if it were a binary file, 
but the above interpretation is a pretty common case (i.e. I 
encounter it daily, in my processing of client data-feeds).


-tkc


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


Re: File Reading related query

2008-09-17 Thread Usman Ajmal
I am talking about text file which contain multiple lines e.g following
three lines are there in my textfile.txt

this is python list
where we get support
from geeks

I want

sentence = this is python list where we get support from geeks

whereas when i use simple read() i get something like this

sentence = this is python list\nwhere we get support\nfrom geeks

On Wed, Sep 17, 2008 at 10:18 AM, Fredrik Lundh <[EMAIL PROTECTED]>wrote:

> Usman Ajmal wrote:
>
>  Is there any function for reading a file while ignoring *\n* occuring in
>> the file?
>>
>
> can you be a bit more precise?  are we talking about text files or binary
> files?  how do you want to treat any newlines that actually appear in the
> file?
>
> 
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: on-the-fly translation with gettext

2008-09-17 Thread Benjamin Sigonneau
Mike Driscoll <[EMAIL PROTECTED]> writes:

> On Sep 16, 4:57 am, Benjamin Sigonneau <[EMAIL PROTECTED]>
> wrote:
>> Hi all,
>>
>> I'm a complete beginner in python and in GUI designing, yet I'm writing
>> a GUI using python and Tkinter.  I need it to be available both in french
>> and english, so I read the Fine Manual and gave a try to gettext.
>>
> [...]
>> However, I'd like to let the user show the language on-the-fly during
>> execution.  Having read the Python Library Reference, sec. 21.1.3.3
>> (seehttp://docs.python.org/lib/node740.html), I added a menu with two
>> radiobuttons and I merely set them up to call install_lang:
>
> [...]
>
>> However, there is no magic.  The language of the application remains
>> unchanged.  If it was defined to be english at startup, so will it
>> remain.  Conversely, it will stay in french if this was the language at
>> startup.
>
> Try moving another window across your application after you change
> languages and see if it gets updated. Sometimes you need to refresh
> the layout of your application to get it to work...at least, in
> wxPython you do.


I tried it, but unfortunately my problem remains.  Anyway, thanks for
the advice.


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


shelve file space always increase!

2008-09-17 Thread smalltalk
>>> import shelve
>>> sf = shelve.open('e:/abc.db')
>>> for i in range(1):
... sf[str(i)]=i
...
>>> sf.close()
>>> sf = shelve.open('e:/abc.db')
>>> sf.clear()
>>> sf
{}
the abc.db is always 312k though i have use clear(), how can i shrink
the space?
--
http://mail.python.org/mailman/listinfo/python-list


Re: File Reading related query

2008-09-17 Thread Fredrik Lundh

Usman Ajmal wrote:

Is there any function for reading a file while ignoring *\n* occuring in 
the file?


can you be a bit more precise?  are we talking about text files or 
binary files?  how do you want to treat any newlines that actually 
appear in the file?




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


Re: Build Python, Numpy and Scipy source with Visual Studio 6.0 for windows

2008-09-17 Thread Richie
On Sep 16, 7:03 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Now comes the troubled bit...I now look for similar source code for
> > Python extensions Numpy and Scipy but the source code and directories
> > are not all obvious. Looks like these are normally built via other
> > compilers. However I need to do all my builds in VS 6.0.
>
> Numpy/scipy specific questions tend to get more specific answers on the
> numpy/scipy mailing lists.  Or see gmane.comp.python.numeric.general at
> news.gmane.org

Thanks very much for your advice Terry. I've just signed up with Numpy
discussion and Scipy dev. Just taking a look at gmane now!

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


File Reading related query

2008-09-17 Thread Usman Ajmal
Hi.,
Is there any function for reading a file while ignoring *\n* occuring in the
file?
--
http://mail.python.org/mailman/listinfo/python-list

Python for the iPhone?

2008-09-17 Thread skip
Anybody tried this port of Python to the iPhone?

http://www.modmyi.com/nativeapps/python-v251/
http://iphone.natetrue.com/

Hasn't been updated since July 2007.  Maybe just a proof-of-concept?  I'm
guessing it involves jailbreaking the phone.

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


  1   2   >