Wrong directory encoding when building a windows setup from Linux

2012-01-20 Thread Benedict Verheyen
Hi,


I have a suite of scripts that I develop on Debian Linux, python version 2.7.1 
but the resulting server
where the scripts are deployed to is Windows based.
I struggled making my setup.py file include data I need for my testing suite, 
but in the
end i succeeded by making a MANIFEST.in file containing "graft data" where data
is the name of the directory containing my test data.

Building an installable for Windows is easily done via python setup.py 
bdist_wininst
So far so good; The data contains directories with non ascii characters like ø, 
é and so on.
Checking the build/lib/mypackage/data reveals that the names are still correct 
on Linux.
However, on Windows, the directory names aren't correct any more, the special 
chars
are replaced with other weird chars.
If I extract the .exe file on Windows using 7 zip, I can see that the 
directories in there are already wrong.

How can I fix this?
Is there a way to specify what encoding the directory names are using and how 
do I specify this in
the setup.py script?

Thanks,
Regards,
Benedict

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


Re: Installing Python on CentOS 6 - a big pain

2012-01-20 Thread Benedict Verheyen
On 19/01/2012 5:36, Steven D'Aprano wrote:
> On Wed, 18 Jan 2012 19:10:43 -0800, alex23 wrote:
> 

> 
> download the tar ball
> extract the contents of the file
> cd into the source directory
> run ./configure
> run make
> optionally run make test
> run sudo make altinstall
> 
> As a total n00b who'd never used make before, it took me 25 minutes 
> effort on my first attempt, including reading the entire README file 
> (twice!). Now I have the whole process down to about 30 seconds effort, 
> and six minutes elapsed time, on my laptop.
> 


My first attempt to compile it on Debian took some extra steps,
as Python didn't find the ncurses and and readline libs.
But it was still easy to figure out how to build and install (locally) all
the necessary packages.
I leave the system installed python alone, and install the python version
I built in $HOME/usr/local so I can later use this in a virtualenv.

These are part of my notes from a while back so version might not be
up to date anymore.

1. Compile zlib
tar xzvf zlib-1.2.5.tar.gz
cd zlib-1.2.5
./configure --64 --prefix=$HOME/usr/local
make
make install

2. Compile readline
tar xzvf readline-6.1.tar.gz
./configure --enable-shared --prefix=$HOME/usr/local
make
make install

3. Compile ncurses
tar xzvf  ncurses-5.7
./configure --with-shared --enable-termcap --prefix=$HOME/usr/local
make
make install

4. Install Python from source
tar xzvf Python-2.7.2.gz
cd Python-2.7.2
export LDFLAGS="-L$HOME/usr/local"
./configure --enable-shared --prefix=$HOME/usr/local
make
make install

If i need to install a new version of Python, as I happen to have done today,
I only need to do step 4. Which is maybe 5 minutes of work.

Cheers,
Benedict

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


Re: verify the return value of a function

2012-01-20 Thread Jean-Michel Pichavant

Jabba Laci wrote:

Hi,

In a unit test, I want to verify that a function returns a
cookielib.LWPCookieJar object. What is the correct way of doing that?

1) First I tried to figure out its type with type(return_value) but it
is 

2) return_value.__class__ .__name__ gives 'LWPCookieJar', which is bettter

3) isinstance(return_value, cookielib.LWPCookieJar) seems to be the
best way, however somewhere I read that using isinstance is
discouraged

Thanks,

Laszlo
  
isinstance is fine, if you could find the source where it is 
discouraged... Could be a consequence of some specific context.
However, checking types in OOP is in general a failure. Unitary tests 
are possibly an exception.


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


Re: verify the return value of a function

2012-01-20 Thread Ulrich Eckhardt

Am 19.01.2012 21:45, schrieb Jabba Laci:

In a unit test, I want to verify that a function returns a
cookielib.LWPCookieJar object. What is the correct way of doing that?

1) First I tried to figure out its type with type(return_value) but it
is


I'm not sure where the problem here is and where exactly you are seeing 
this. This might even indicate a problem with how the returned type is 
constructed.


Anyhow:

>>> x = 1
>>> type(x)

>>> type(x) is int
True

So checking for an exact type should work using type().



2) return_value.__class__ .__name__ gives 'LWPCookieJar', which is bettter


It doesn't cover namespaces though. Also, you should compare that to 
cookielib.LWPCookieJar.__name__, not 'LWPCookieJar'. What is the "LWP", btw?




3) isinstance(return_value, cookielib.LWPCookieJar) seems to be the
best way, however somewhere I read that using isinstance is
discouraged.


Never trust any such claim that doesn't give a justification. In your 
case, that would be the right thing to do, IMHO. Promising to return an 
LWPCookieJar is fulfilled when the returnvalue is of that type or a 
class derived from that, which variant 1 doesn't cover.


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


C++ and Embedded Python

2012-01-20 Thread jasonkeddie
Is there a method to allow a pointer to an object in local memory to
be shared with embedded Python within a C++ executable?

The reason I require this is I have a C++ instance of a class that has
data memers that are themeselves pointers to other object types. It is
a fairly complicated object.
In an ideal world I would just pass this pointer into an instance of
the Python interpreter. This would allow the python program access and
change some properties of this object instance, then pass it back to
the calling C++ program. I would use this same system to pass messages
between the C++ (calling program) and the embedded Python interpreter.

I have looked at using shared memory, which will work until you
require embedded pointers within your object as you cannot dynamically
allocate memory in a shared space.

Any help is much appreciated.

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


Re: verify the return value of a function

2012-01-20 Thread Mel Wilson
Jean-Michel Pichavant wrote:

> isinstance is fine, if you could find the source where it is
> discouraged... Could be a consequence of some specific context.
> However, checking types in OOP is in general a failure. Unitary tests
> are possibly an exception.

I think it's discouraged when people try to write big overloaded functions 
that check the types of the arguments to decide what they should be doing.
In diagnostics and tests like the OP's there should be no problem.

Mel.

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


Re: verify the return value of a function

2012-01-20 Thread Roy Smith
In article ,
 Jabba Laci  wrote:

> Hi,
> 
> In a unit test, I want to verify that a function returns a
> cookielib.LWPCookieJar object. What is the correct way of doing that?

jar = my_function_being_tested()
self.assertIsInstance(jar, cookielib.LWPCookieJar)

That works in 2.7.  If you're using something older than 2.7, you'll 
need to do:

self.assertTrue(isinstance(jar, cookielib.LWPCookieJar)

Alternatively, just download the 2.7 version of unittest and use that 
(it works fine with 2.6, not sure about earlier than that).
 
> 3) isinstance(return_value, cookielib.LWPCookieJar) seems to be the
> best way, however somewhere I read that using isinstance is
> discouraged

Where did you read that, and in what context?

Compared to type(), isinstance() is an improvement because it correctly 
handles subclasses.  If you want a LWPCookieJar, you should be happy to 
have somebody give you a subclass of LWPCookieJar (assuming they 
correctly implemented the interface).  Thus says the Church of Most 
Corpulent Staticness and Type Bondage.

On the other hand, there are some (adherents of the Most Holy and 
Loquacious Church of Duck Typing) who would say that testing for class 
at all is a sin, and what you want to do is test that the object being 
tested has the methods and attributes you expect.

Me, I'm somewhere in between.  I believe that pinching it and seeing 
what the quack sounds like is usually the right thing to do.  On the 
other hand, if you want to demand to see its Certificate of Duckiness, 
you have a right to do that too.
-- 
http://mail.python.org/mailman/listinfo/python-list


subprocess module and long-lived subprocesses

2012-01-20 Thread Skip Montanaro

I'm converting some os.popen calls to use subprocess.Popen.  I had
previously been ignoring stdout and stderr when using os.popen.  The primary
motivation to switch to subprocess.Popen now is that I now want to check
stderr, so would have to make code changes to use os.popen[34] anyway.
Might as well go whole hog and switch to the new API.

The library documentation doesn't talk a lot about long-lived subprocesses
other than the possibility of deadlock when using Popen.wait().  Ideally, I
would write to the subprocess's stdin, check for output on stdout and
stderr, then lather, rinse, repeat.  Is it safe to assume that if the stdout
and/or stderr pipes have nothing for me the reads on those file objects (I'm
using PIPE for all three std* files) will return immediately with an empty
string for output?  They won't block, will they?  Will a broken pipe IOError
get raised as for os.popen() or do I have to call Popen.poll() even in error
situations?

Thanks,

-- 
Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: verify the return value of a function

2012-01-20 Thread Steven D'Aprano
On Fri, 20 Jan 2012 08:53:13 -0500, Mel Wilson wrote:

> Jean-Michel Pichavant wrote:
> 
>> isinstance is fine, if you could find the source where it is
>> discouraged... Could be a consequence of some specific context.
>> However, checking types in OOP is in general a failure. Unitary tests
>> are possibly an exception.
> 
> I think it's discouraged when people try to write big overloaded
> functions that check the types of the arguments to decide what they
> should be doing.

I don't agree with that. Writing polymorphic functions using isinstance 
is a perfectly reasonable thing to do. E.g. from the standard library's 
decimal module:

class Decimal(object):
"""Floating point class for decimal arithmetic."""
# We're immutable, so use __new__ not __init__
def __new__(cls, value="0", context=None):
self = object.__new__(cls)
# From a string
# REs insist on real strings, so we can too.
if isinstance(value, str):
...
# From an integer
if isinstance(value, int):
...
# From another decimal
if isinstance(value, Decimal):
...
# From an internal working value
if isinstance(value, _WorkRep):
...
# tuple/list conversion (possibly from as_tuple())
if isinstance(value, (list,tuple)):
...
if isinstance(value, float):
...
raise TypeError("Cannot convert %r to Decimal" % value)


What should be avoided, when possible, is over-reliance on isinstance 
checks instead of protocol or interface checks. For example, don't check 
for a list if your function doesn't *need* a list but would be happy with 
a tuple or some other sequence.

Worse than isinstance is testing for an exact type:

if type(x) is list  # worse than isinstance(x, list)

although of course, there are times where you need to break the rules.



> In diagnostics and tests like the OP's there should be
> no problem.

Agreed.



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


Re: verify the return value of a function

2012-01-20 Thread Ian Kelly
On Fri, Jan 20, 2012 at 2:15 AM, Ulrich Eckhardt <
ulrich.eckha...@dominolaser.com> wrote:

> Am 19.01.2012 21:45, schrieb Jabba Laci:
>
>  In a unit test, I want to verify that a function returns a
>> cookielib.LWPCookieJar object. What is the correct way of doing that?
>>
>> 1) First I tried to figure out its type with type(return_value) but it
>> is
>>
>
> I'm not sure where the problem here is and where exactly you are seeing
> this. This might even indicate a problem with how the returned type is
> constructed.
>

This just means that LWPCookieJar is an old-style class:

>>> class Foo: pass
...
>>> type(Foo())

>>> Foo().__class__


So for type checks here the __class__ attribute should be used, not the
type function.  isinstance is better for instance checks though in either
case.

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


Re: subprocess module and long-lived subprocesses

2012-01-20 Thread Mike C. Fletcher
On 12-01-20 09:42 AM, s...@pobox.com wrote:
> I'm converting some os.popen calls to use subprocess.Popen.  I had
> previously been ignoring stdout and stderr when using os.popen.  The primary
> motivation to switch to subprocess.Popen now is that I now want to check
> stderr, so would have to make code changes to use os.popen[34] anyway.
> Might as well go whole hog and switch to the new API.
>
> The library documentation doesn't talk a lot about long-lived subprocesses
> other than the possibility of deadlock when using Popen.wait().  Ideally, I
> would write to the subprocess's stdin, check for output on stdout and
> stderr, then lather, rinse, repeat.  Is it safe to assume that if the stdout
> and/or stderr pipes have nothing for me the reads on those file objects (I'm
> using PIPE for all three std* files) will return immediately with an empty
> string for output?  They won't block, will they?  Will a broken pipe IOError
> get raised as for os.popen() or do I have to call Popen.poll() even in error
> situations?
>
> Thanks,
>
Definitely *will* block, you have to explicitly set them non-blocking to
have non-blocking behaviour:

def set_nb( fh ):
"""Set non-blocking flag on given file handle"""
if isinstance( fh, int ) or hasattr( fh, 'fileno' ):
flags = fcntl.fcntl(fh, fcntl.F_GETFL)
fcntl.fcntl(fh, fcntl.F_SETFL, flags| os.O_NONBLOCK)

on each of the 3 buffers, then you need to attempt read/write on each of
them periodically, catching the EWOULDBLOCK errors, to prevent deadlocks
where the buffers have filled up (e.g. because the subprocess is
printing out errors on stderr, or because it is generating output, or
because for some reason the process isn't reading your input fast
enough).  I think everyone winds up with their own wrapper around
subprocess after they use it for more than a short period...

HTH,
Mike

-- 

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


Changing interpolation

2012-01-20 Thread Hugo Léveillé
Another quick question this morning

Does anyone have the syntax to change keyframe interpolation of a curve
?

For exemple, I am trying to change the curve of the translate of a
camera using this and it does not do much

nuke.selectedNode().knobs()['translate'].animations()[0].changeInterpolation(
nuke.selectedNode().knobs()['translate'].animations()[0].keys() ,
nuke.CONSTANT)


-- 
  Hugo Léveillé
  TD Compositing, Vision Globale
  hu...@fastmail.net

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


Is a with on open always necessary?

2012-01-20 Thread Andrea Crotti

I normally didn't bother too much when reading from files, and for example
I always did a

content = open(filename).readlines()

But now I have the doubt that it's not a good idea, does the file 
handler stays

open until the interpreter quits?

So maybe doing a

with open(filename) as f:
 contents = f.readlines()

is always a better idea??
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is a with on open always necessary?

2012-01-20 Thread Justin Simms
As I understand it, with gives you a cleaner way of doing the following
steps:

1) pre processing
2) actual work
3) post processing, where the __enter__ and __exit__ methods are used to
take care of 1 and 3.

So with is not always necessary, but it is the preferred was to do things
like file processing, since the file object and other already have the
context manager protocol in place (which is when the object being used in
the with expression has implementations of __with__ and __exit__) .

I have just learned about it myself , so hopefully if I am not accurate
someone more experienced can provide you with more detail.

On Fri, Jan 20, 2012 at 10:44 AM, Andrea Crotti
wrote:

> I normally didn't bother too much when reading from files, and for example
> I always did a
>
> content = open(filename).readlines()
>
> But now I have the doubt that it's not a good idea, does the file handler
> stays
> open until the interpreter quits?
>
> So maybe doing a
>
> with open(filename) as f:
> contents = f.readlines()
>
> is always a better idea??
> --
> http://mail.python.org/**mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is a with on open always necessary?

2012-01-20 Thread Arnaud Delobelle
On 20 January 2012 15:44, Andrea Crotti  wrote:
> I normally didn't bother too much when reading from files, and for example
> I always did a
>
> content = open(filename).readlines()
>
> But now I have the doubt that it's not a good idea, does the file handler
> stays
> open until the interpreter quits?

IIRC it stays open until garbage collected (it's closed in the file
object's __del__ method).  When the file object is collected is an
implementation detail, although in CPython it will happen straight
away because it uses reference counting.

> So maybe doing a
>
> with open(filename) as f:
>     contents = f.readlines()

That's what I do, unless I'm in an interactive session.

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


Re: Changing interpolation

2012-01-20 Thread Chris Rebert
On Fri, Jan 20, 2012 at 7:35 AM, Hugo Léveillé  wrote:
> Another quick question this morning
>
> Does anyone have the syntax to change keyframe interpolation of a curve
> ?
>
> For exemple, I am trying to change the curve of the translate of a
> camera using this and it does not do much
>
> nuke.selectedNode().knobs()['translate'].animations()[0].changeInterpolation(
> nuke.selectedNode().knobs()['translate'].animations()[0].keys() ,
> nuke.CONSTANT)

This is in apparently in reference to
http://www.thefoundry.co.uk/products/nuke/ ?

When asking questions about 3rd-party libs, it's best to clarify up
front which one you're talking about.

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


Re: Please don't use "setuptools", the "rotten .egg" install system.

2012-01-20 Thread Michael Torrie
On 01/19/2012 10:05 AM, John Nagle wrote:
>  I can do it, I just have better things to do than system
> administration.  The fact that Python doesn't "just work" is
> part of why it's losing market share.

Yes you keep saying that.  Of course you are complaining on the wrong
list.  You should be bugging Red Hat about the Python 2.7 thing (after
all you pay them for support, right?).  Whining about it here is just silly.

>  Python sort of slips through the cracks.  Nobody is doing
> the work to make PyPy handle these problems, and Python isn't
> important enough for MySQL, etc. to support the connector for
> the language.  (They support Perl, C, Java, etc., but not
> Python.)

Supporting C is all they need to do in this case.  Python works just
fine with C libraries.  I have used python with MySQL a fair amount in
my previous job.  The DB-API interface worked quite well and I found
PostgreSQL and MySQL drivers that worked quite nicely.  I'm not sure
what you think is missing.  Maybe you are whining about Python not
shipping with the MySQL connector directly.  Again, though this is a
problem best solved at the distribution level as Python cannot possibly
ship binary MySQL libraries for every variation of OS and MySQL client
library version.

I know the propensity of people on this list is to support and defend
Python from any criticism, but in this case such defense seems justified.
-- 
http://mail.python.org/mailman/listinfo/python-list


Extending PyGTK widgets with Glade

2012-01-20 Thread Richard Carlson
I'm working on a program using PyGTK and Glade.  I create a glade XML file
using Glade Designer and then load widgets like this:

class MyDialog:
def __init__(self):
self.dialog = gtk.glade.XML(self.GLADEFILE).get_widget
("dialog.xml")

I think it would be better if I extended the Dialog class, but I can't 
figure out how to do it.  I'd like to do something like this:

class MyDialog(gtk.Dialog):
def __init__(self):
self = gtk.glade.XML(self.GLADEFILE).get_widget("example_dialog")

Can someone point me in the right direction?

Thanks,

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


ANN: python-ldap 2.4.7

2012-01-20 Thread Michael Ströder

Find a new release of python-ldap:

  http://pypi.python.org/pypi/python-ldap/2.4.4

python-ldap provides an object-oriented API to access LDAP directory
servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for
that purpose. Additionally it contains modules for other LDAP-related
stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema).

Project's web site:

  http://www.python-ldap.org/

Ciao, Michael.


Released 2.4.7 2012-12-19

Changes since 2.4.6:

Lib/
* Separate classes for request/response controls for RFC 3829
* Fixed ldap.schema.subentry.SubSchema.attribute_types() to
  also eliminate double attribute types in MAY clause of
  DIT content rule

Modules/
* Fixed memory leak (thanks to David Malcolm)


Released 2.4.6 2011-11-27

Changes since 2.4.5:

Lib/
* ldap.controls.ppolicy:
  Another fix for decoding the password policy response control
--
http://mail.python.org/mailman/listinfo/python-list


Re: C++ and Embedded Python

2012-01-20 Thread Stefan Behnel
jasonked...@hotmail.com, 20.01.2012 14:52:
> Is there a method to allow a pointer to an object in local memory to
> be shared with embedded Python within a C++ executable?
> 
> The reason I require this is I have a C++ instance of a class that has
> data memers that are themeselves pointers to other object types. It is
> a fairly complicated object.
> In an ideal world I would just pass this pointer into an instance of
> the Python interpreter. This would allow the python program access and
> change some properties of this object instance, then pass it back to
> the calling C++ program. I would use this same system to pass messages
> between the C++ (calling program) and the embedded Python interpreter.
> 
> I have looked at using shared memory, which will work until you
> require embedded pointers within your object as you cannot dynamically
> allocate memory in a shared space.

Do I understand correctly that you only have one instance of a Python
runtime, embedded in a C++ program? If that's the case, I don't see the
problem. Just create an extension type to model your API towards the C++
objects and pass data back and forth. Cython will make that easy.

I specifically do not see why you would care about shared memory here. If
both parts of the application (i.e. Python code and C++ code) are in the
same process, they will usually be able to access the same memory without
any special setup.

If I misunderstood your intention, please provide more details, including
the steps you undertook so far and a specific description of what didn't
work. You may also want to provide some hints on what kind of data you want
to exchange and what both sides will do with it.

Stefan

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


Re: Installing Python on CentOS 6 - a big pain

2012-01-20 Thread rusi
On Jan 20, 2:39 pm, Benedict Verheyen 
wrote:
> On 19/01/2012 5:36, Steven D'Aprano wrote:
>
>
>
>
>
>
>
> > On Wed, 18 Jan 2012 19:10:43 -0800, alex23 wrote:
>
> 
>
> > download the tar ball
> > extract the contents of the file
> > cd into the source directory
> > run ./configure
> > run make
> > optionally run make test
> > run sudo make altinstall
>
> > As a total n00b who'd never used make before, it took me 25 minutes
> > effort on my first attempt, including reading the entire README file
> > (twice!). Now I have the whole process down to about 30 seconds effort,
> > and six minutes elapsed time, on my laptop.
>
> 
>
> My first attempt to compile it on Debian took some extra steps,
> as Python didn't find the ncurses and and readline libs.
> But it was still easy to figure out how to build and install (locally) all
> the necessary packages.
> I leave the system installed python alone, and install the python version
> I built in $HOME/usr/local so I can later use this in a virtualenv.
>
> These are part of my notes from a while back so version might not be
> up to date anymore.
>
> 1. Compile zlib
> tar xzvf zlib-1.2.5.tar.gz
> cd zlib-1.2.5
> ./configure --64 --prefix=$HOME/usr/local
> make
> make install
>
> 2. Compile readline
> tar xzvf readline-6.1.tar.gz
> ./configure --enable-shared --prefix=$HOME/usr/local
> make
> make install

>
> 3. Compile ncurses
> tar xzvf  ncurses-5.7
> ./configure --with-shared --enable-termcap --prefix=$HOME/usr/local
> make
> make install

If you apt-get the foll
libncurses5-dev
libreadline6-dev
zlib1g-dev

the first three steps should not be necessary.

In general
apt-get build-dep python2.7
will list out (a superset of) what python2.7 needs.


>
> 4. Install Python from source
> tar xzvf Python-2.7.2.gz
> cd Python-2.7.2
> export LDFLAGS="-L$HOME/usr/local"
> ./configure --enable-shared --prefix=$HOME/usr/local
> make
> make install
>
> If i need to install a new version of Python, as I happen to have done today,
> I only need to do step 4. Which is maybe 5 minutes of work.
>
> Cheers,
> Benedict

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


Re: subprocess module and long-lived subprocesses

2012-01-20 Thread skip

(Apologies for the non-threaded reply.  My subscription to the list is
currently set to no-mail and I can't get to gmane.org, so have no clean way
to reply...)

Mike Fletcher wrote:

> Definitely *will* block, you have to explicitly set them non-blocking to
> have non-blocking behaviour:

  ...

>  I think everyone winds up with their own wrapper around subprocess
> after they use it for more than a short period...

Thanks, that saves me much head scratching.

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


can some one help me with my code. thanks

2012-01-20 Thread Tamanna Sultana

can some one help me??
> I would like to create a function that, given a bin, which is a list
> (example below), generates averages for the numbers separated by a
> string 'end'. I am expecting to have 4 averages from the above bin,
> since there are 4 sets of numbers separated by 4 'end' strings


> ['2598.95165', '2541.220308', '221068.0401', 'end', '4834.581952',
> '1056.394859', '3010.609563', '2421.437603', '4619.861889',
> '746.040504', '268.3881793', '379.3934898', '1252.527752',
> '11459.88522', '4862.167506', '506.924289', '634.6737389',
> '496.4679199', '17941.59143', '919.4998935', '7247.610974',
> '1166.053214', '47360.91508', '855.2426137', '4020.444585',
> '4469.896904', '2615.874982', '19862.92009', '2379.619573',
> '1203.268956', '4399.589212', '6838.825864', '1848.407564',
> '3527.198403', '33976.85042', '818.8722263', '634.6652078',
> '469.2685928', '4864.830004', '5103.222941', '1011.239929',
> '829.9915382', '8571.237936', '3301.953656', '14594.47385',
> '25688.83822', '4024.393045', '4163.775185', '1775.894366',
> '3682.012227', '3371.092883', '6651.509488', '7906.092773',
> '7297.133447', 'end', '4566.874299', 'end', '4255.700077',
> '1857.648393', '11289.48095', '2070.981805', '1817.505094',
> '1892.256615', '1757.0048', '59458.46328', '778.5755201', '54987.32423',
> '2245.172711', '722.2619663', '5116.616632', '3427.865861',
> '17973.07118', '14398.74281', '66313.92115', '11585.24151',
> '45294.03043', '6524.744077', '25958.80015', '593.3786209',
> '2899.040703', '85577.21342', '153576.2633', '5852.008444',
> '563.0265409', '70796.45356', '565.2123689', '6560.030116',
> '2668.934414', '418.666014', '5216.392132', '760.894589', '8072.957639',
> '346.5905371', 'end']

>
> If you can give me some lead to fix the code I wrote below that will be great:
>
def average(bin):
num=[]
total = 0.0
count=0
for number in bin:
while True:
if number!='end':
number=float(number)
total += float(number)
count+=1
avg = total/count
if number=='end':
break
num.append(avg)
return num
>
> Thnx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First python project : Tuner

2012-01-20 Thread Anssi Saari
Jérôme  writes:

> - I tried to clarify the dependencies of my program by adding 
>   "PyGObject (python-gi)."
>   I believe PyGObject is the name, but python-gi being the name of the debian
>   package (and possibly other distros' package, I didn't check), I assumed it
>   would be more helpful.

You might mention that Debian Stable (Squeeze) doesn't have a new enough
PyGObject to run your code. There's no package python-gi and the version
of python-gobject is 2.21.4+is.2.21.3-1. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Python on CentOS 6 - a big pain

2012-01-20 Thread Anssi Saari
Benedict Verheyen  writes:

> If i need to install a new version of Python, as I happen to have done today,
> I only need to do step 4. Which is maybe 5 minutes of work.

I don't really understand why you compile these common libraries (zlib,
ncurses, readline) yourself instead of using the relevant libraries
provided by your Debian system? Is it just that you didn't *know* Debian
puts parts needed for compilation in separate packages so you'd need to
install those first?

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


Re: python logging filter limitation, looks intentional?

2012-01-20 Thread Vinay Sajip
On Jan 19, 12:50 am, Terry Reedy  wrote:
>
> >> I don't want people to have to code differently for Python 3.3 and for
> >> older versions.
>
> This is not a general policy, else we would never add new features ;-)
> Do you plan to keep logging feature-frozen forever, or just for another
> release? (I actually think is a good idea to fix bugs, tests, and docs
> first.)

Logging isn't by any means feature-frozen - new features are being
added all the time, including non-trivial additions made in 2.7 and
3.2, and some more changes planned for 3.3 and already checked in. My
comment was about the specific change proposed, which if implemented
could lead to existing working third party code failing after a Python
version upgrade. The proposed change isn't a new feature, it's a
request for an existing feature to work differently.

Apart from the behavioural change, there is also a performance
implication which needs to be considered. All in all, I'm not sure
there is a lot of demand for this proposed change, and I have already
suggested a workable approach to Chris which should meet his needs
without any need for a behavioural change in the standard library.

Regards,

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


Re: can some one help me with my code. thanks

2012-01-20 Thread Vincent Vande Vyvre


  
  
Le 20/01/12 19:49, Tamanna Sultana a écrit :

  
can some one help me??

  
I would like to create a function that, given a bin, which is a list
(example below), generates averages for the numbers separated by a
string 'end'. I am expecting to have 4 averages from the above bin,
since there are 4 sets of numbers separated by 4 'end' strings

  
  


  
['2598.95165', '2541.220308', '221068.0401', 'end', '4834.581952',
'1056.394859', '3010.609563', '2421.437603', '4619.861889',
'746.040504', '268.3881793', '379.3934898', '1252.527752',
'11459.88522', '4862.167506', '506.924289', '634.6737389',
'496.4679199', '17941.59143', '919.4998935', '7247.610974',
'1166.053214', '47360.91508', '855.2426137', '4020.444585',
'4469.896904', '2615.874982', '19862.92009', '2379.619573',
'1203.268956', '4399.589212', '6838.825864', '1848.407564',
'3527.198403', '33976.85042', '818.8722263', '634.6652078',
'469.2685928', '4864.830004', '5103.222941', '1011.239929',
'829.9915382', '8571.237936', '3301.953656', '14594.47385',
'25688.83822', '4024.393045', '4163.775185', '1775.894366',
'3682.012227', '3371.092883', '6651.509488', '7906.092773',
'7297.133447', 'end', '4566.874299', 'end', '4255.700077',
'1857.648393', '11289.48095', '2070.981805', '1817.505094',
'1892.256615', '1757.0048', '59458.46328', '778.5755201', '54987.32423',
'2245.172711', '722.2619663', '5116.616632', '3427.865861',
'17973.07118', '14398.74281', '66313.92115', '11585.24151',
'45294.03043', '6524.744077', '25958.80015', '593.3786209',
'2899.040703', '85577.21342', '153576.2633', '5852.008444',
'563.0265409', '70796.45356', '565.2123689', '6560.030116',
'2668.934414', '418.666014', '5216.392132', '760.894589', '8072.957639',
'346.5905371', 'end']

  
  

  

If you can give me some lead to fix the code I wrote below that will be great:


  
  def average(bin):
num=[]
total = 0.0
count=0
for number in bin:
while True:
if number!='end':
number=float(number)
total += float(number)
count+=1
avg = total/count
if number=='end':
break
num.append(avg)
return num

  

Thnx

  

That's works:

bin =['2598.95165', '2541.220308', '221068.0401', 'end',
'4834.581952',
'1056.394859', '3010.609563', '2421.437603', '4619.861889',

'2668.934414', '418.666014', '5216.392132', '760.894589',
'8072.957639',
'346.5905371', 'end']

avg = []
sp = ",".join(bin).split(',end')
for part in sp:
    vals = part.split(',')
    sum_ = 0
    for v in vals:
    if v:
    sum_ += float(v)
    else:
    continue
    avg.append(sum_ / len(vals))

print avg

-- 
  Vincent V.V.
  Oqapy . Qarte+7 . PaQager
  


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


Re: can some one help me with my code. thanks

2012-01-20 Thread Terry Reedy

On 1/20/2012 1:49 PM, Tamanna Sultana wrote:


can some one help me??

I would like to create a function that, given a bin, which is a list
(example below), generates averages for the numbers separated by a
string 'end'. I am expecting to have 4 averages from the above bin,
since there are 4 sets of numbers separated by 4 'end' strings


[Posting your overly long set of data lines with a '>' quote at the 
beginning of each line was a nuisance. Reposted with few lines. I will 
let you compare your code to mine.]


bin = ['2598.95165', '2541.220308', '221068.0401', 'end', '4834.581952',
 '1056.394859', '3010.609563', '2421.437603', '4619.861889',
  '3682.012227', '3371.092883', '6651.509488', '7906.092773',
 '7297.133447', 'end', '4566.874299', 'end', '4255.700077',
 '1857.648393', '11289.48095', '2070.981805', '1817.505094',
 '563.0265409', '70796.45356', '565.2123689', '6560.030116',
 '2668.934414', '418.666014', '5216.392132', '760.894589', '8072.957639',
 '346.5905371', 'end']

def average(bin):
num=[]
total = 0.0
count=0
for number in bin:
if number!='end':
total += float(number)
count+=1
else:
num.append(total/count)
total = 0.0
count= 0
return num

print(average(bin))

>>>
[75402.7373526, 4485.0726684, 4566.874299, 7817.36494866]
--
Terry Jan Reedy

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


Re: python logging filter limitation, looks intentional?

2012-01-20 Thread Terry Reedy

On 1/20/2012 2:17 PM, Vinay Sajip wrote:

On Jan 19, 12:50 am, Terry Reedy  wrote:



I don't want people to have to code differently for Python 3.3 and for
older versions.


This is not a general policy, else we would never add new features ;-)
Do you plan to keep logging feature-frozen forever, or just for another
release? (I actually think is a good idea to fix bugs, tests, and docs
first.)


Logging isn't by any means feature-frozen - new features are being
added all the time, including non-trivial additions made in 2.7 and
3.2, and some more changes planned for 3.3 and already checked in. My
comment was about the specific change proposed, which if implemented
could lead to existing working third party code failing after a Python
version upgrade. The proposed change isn't a new feature, it's a
request for an existing feature to work differently.


Thank you for the clarification. I had not gotten that the request was 
for a change, which has a much higher bar to pass than feature 
additions. I was thinking of 'code differently' as in


if sys.version.split()[0] >= '3.3': 
else: 

but that is not a 'have to' as long as the workaround still works.

--
Terry Jan Reedy

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


Re: verify the return value of a function

2012-01-20 Thread Terry Reedy

On 1/20/2012 10:07 AM, Steven D'Aprano wrote:


What should be avoided, when possible, is over-reliance on isinstance
checks instead of protocol or interface checks. For example, don't check
for a list if your function doesn't *need* a list but would be happy with
a tuple or some other sequence.


In other words, do not use isinstance to artificially limit the input 
domain of a function. The generic or polymorphic nature of (builtin) 
operators and functions is a major feature of Python.


On the other hand, the output range of a function is typically much more 
limited as to type. Complete testing requires testing the specified 
output type. For instance, sorted(iterable) is documented as producing a 
sorted list, so 'type(output) is list' is an appropriate test.


--
Terry Jan Reedy

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


Weird Loop Behaviour

2012-01-20 Thread Yigit Turgut
Hi,

In the following code, I am trying to run "black" screen for 3 seconds
and respectively 2 seconds "white" screen. Black routine takes 3
seconds and white 2 seconds, 2 x black + white = 8 seconds which
should be the expected value but when I run it I get black-white-black-
white   instead of black-white-black. Couldn't figure out what is
wrong thus sharing the code as well ;

white = False
 while(end<8.00):
  end = time.time() - start
  if white:
   screen.fill((255, 255, 255))
time.sleep(2)
  else:
screen.fill((0, 0, 0))
time.sleep(3)
  white = not white
  pygame.display.update()
 pygame.quit()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Weird Loop Behaviour

2012-01-20 Thread MRAB

On 20/01/2012 20:47, Yigit Turgut wrote:

Hi,

In the following code, I am trying to run "black" screen for 3 seconds
and respectively 2 seconds "white" screen. Black routine takes 3
seconds and white 2 seconds, 2 x black + white = 8 seconds which
should be the expected value but when I run it I get black-white-black-
white   instead of black-white-black. Couldn't figure out what is
wrong thus sharing the code as well ;

white = False
while(end<8.00):
end = time.time() - start
if white:
screen.fill((255, 255, 255))
time.sleep(2)
else:
screen.fill((0, 0, 0))
time.sleep(3)
white = not white
pygame.display.update()
pygame.quit()


Could it be because you're setting 'end' after testing it?

It might be simpler as:

  while time.time() - start < 8:

Also, should it really be sleeping before updating the display? I
would've thought that it should be sleeping _after_ updating the
display.
--
http://mail.python.org/mailman/listinfo/python-list


etree/lxml/XSLT and dynamic stylesheet variables

2012-01-20 Thread Adam Tauno Williams
I'm using etree to perform XSLT transforms, such as -

from lxml import etree
source = etree.parse(self.rfile)
xslt = etree.fromstring(self._xslt)
transform = etree.XSLT(xslt)
result = transform(source)

according to the docs at
 I can pass a
dictionary of parameters to transform, such as -

result = transform(doc_root, **{'non-python-identifier': '5'})

Can I pass a dictionary-like object?  That doesn't seem to be working.
I need to perform dynamic lookup of variables for the stylesheet.

I've subclassed dictionary and overloaded [], get, has_key, and in to
perform the required lookups; these work in testing. But passing the
object to transform doesn't work.

If that isn't possible is there an alternate XSLT implementation for
python that would allow calling back for variable values?

-- 
System & Network Administrator [ LPI & NCLA ]

OpenGroupware Developer 
Adam Tauno Williams

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


Re: can some one help me with my code. thanks

2012-01-20 Thread Tim Chase

On 01/20/12 13:46, Terry Reedy wrote:

def average(bin):
  num=[]
  total = 0.0
  count=0
  for number in bin:
  if number!='end':
  total += float(number)
  count+=1
  else:
  num.append(total/count)
  total = 0.0
  count= 0
  return num


print(average(['end']))

ka-blooie! :-)

would be worth noting what should happen in the event of an empty 
bin.


-tkc



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


Re: Weird Loop Behaviour

2012-01-20 Thread Emile van Sebille

On 1/20/2012 12:47 PM Yigit Turgut said...

Hi,

In the following code, I am trying to run "black" screen for 3 seconds
and respectively 2 seconds "white" screen. Black routine takes 3
seconds and white 2 seconds, 2 x black + white = 8 seconds which
should be the expected value but when I run it I get black-white-black-
white   instead of black-white-black. Couldn't figure out what is
wrong thus sharing the code as well ;

white = False
  while(end<8.00):
   end = time.time() - start
you're setting end's value before the display happens, so while tests 
the values 0,3,5 before getting after the fourth pass 8.  Move this 
after to white = note white and I suspect you'll be OK.


HTH,

Emile





   if white:
screen.fill((255, 255, 255))
time.sleep(2)
   else:
screen.fill((0, 0, 0))
time.sleep(3)
   white = not white
   pygame.display.update()
  pygame.quit()



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


Re: can some one help me with my code. thanks

2012-01-20 Thread Terry Reedy

On 1/20/2012 2:46 PM, Terry Reedy wrote:

On 1/20/2012 1:49 PM, Tamanna Sultana wrote:


can some one help me??

I would like to create a function that, given a bin, which is a list
(example below), generates averages for the numbers separated by a
string 'end'. I am expecting to have 4 averages from the above bin,
since there are 4 sets of numbers separated by 4 'end' strings


[Posting your overly long set of data lines with a '>' quote at the
beginning of each line was a nuisance. Reposted with few lines. I will
let you compare your code to mine.]

bin = ['2598.95165', '2541.220308', '221068.0401', 'end', '4834.581952',
'1056.394859', '3010.609563', '2421.437603', '4619.861889',
'3682.012227', '3371.092883', '6651.509488', '7906.092773',
'7297.133447', 'end', '4566.874299', 'end', '4255.700077',
'1857.648393', '11289.48095', '2070.981805', '1817.505094',
'563.0265409', '70796.45356', '565.2123689', '6560.030116',
'2668.934414', '418.666014', '5216.392132', '760.894589', '8072.957639',
'346.5905371', 'end']

def average(bin):
num=[]
total = 0.0
count=0
for number in bin:
if number!='end':
total += float(number)
count+=1
else:
num.append(total/count)
total = 0.0
count= 0
return num

print(average(bin))

 >>>
[75402.7373526, 4485.0726684, 4566.874299, 7817.36494866]


U're welcome. But do notice Tim's comment. In non-toy situations, you 
have to decide how to handle empty collections (return float('nan')?), 
or whether to just let whatever happens happen.


If you control the input format, a list of lists would be easier than an 
end marker. But sometimes one is handed data and asked to process it as is.


Also note (this is a more advanced topic) that average() could be turned 
into a generator function by replacing 'num.append(total/count)' with 
'yield total/count' and removing the initialization and return of num.


--
Terry Jan Reedy

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


Re: Extending PyGTK widgets with Glade

2012-01-20 Thread Adam Tauno Williams

Quoting Richard Carlson :

I'm working on a program using PyGTK and Glade.  I create a glade XML file
using Glade Designer and then load widgets like this:
class MyDialog:
def __init__(self):
self.dialog = gtk.glade.XML(self.GLADEFILE).get_widget
("dialog.xml")
I think it would be better if I extended the Dialog class, but I can't
figure out how to do it.  I'd like to do something like this:
class MyDialog(gtk.Dialog):
def __init__(self):
self = gtk.glade.XML(self.GLADEFILE).get_widget("example_dialog")

Can someone point me in the right direction?


There is some documentation about this around somewhere; but I don't  
recall offhand.  In any case you will probably get a good answer if  
you ask on the pygtk maillist.


Content on that list is pretty good.

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


Re: Weird Loop Behaviour

2012-01-20 Thread Arnaud Delobelle
On 20 January 2012 20:47, Yigit Turgut  wrote:
> Hi,
>
> In the following code, I am trying to run "black" screen for 3 seconds
> and respectively 2 seconds "white" screen. Black routine takes 3
> seconds and white 2 seconds, 2 x black + white = 8 seconds which
> should be the expected value but when I run it I get black-white-black-
> white   instead of black-white-black. Couldn't figure out what is
> wrong thus sharing the code as well ;
>
> white = False
>     while(end<8.00):
>      end = time.time() - start
>      if white:
>       screen.fill((255, 255, 255))
>        time.sleep(2)
>      else:
>        screen.fill((0, 0, 0))
>        time.sleep(3)
>      white = not white
>      pygame.display.update()
>     pygame.quit()

This is cryptic.  You'd be better off with something like

black = 0, 0, 0
white = 255, 255, 255
for color, wait in (black, 3), (white, 2), (black, 3):
screen.fill(color)
pygame.display.update()
time.sleep(wait)
pygame.quit()

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


Re: Is a with on open always necessary?

2012-01-20 Thread Roy Smith
In article ,
 Arnaud Delobelle  wrote:

> > So maybe doing a
> >
> > with open(filename) as f:
> >     contents = f.readlines()
> 
> That's what I do, unless I'm in an interactive session.

>From the resource management point of view, there's no doubt that's the 
right thing to be doing.  That being said, I don't bother most of the 
time and I can't think of a time when I've been bitten by it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can some one help me with my code. thanks

2012-01-20 Thread Rick Johnson
On Jan 20, 12:49 pm, Tamanna Sultana 
wrote:
> > If you can give me some lead to fix the code I wrote below that will be 
> > great:

Your variable names need a bit more thought

> def average(bin):

What is a "bin"? Maybe you shoulc have called this a "lst" eh?

>     num=[]
Why would you call a list of numbers (that's plural BTW) the singular
name "num"? Not to mention that even "numbers" is the wrong
identifier. Use "averages" instead. Heck, even "buffer" would have
been a better choice that "num".

>     total = 0.0
>     count = 0
>     for number in bin:

Not every "item" in the lst is a number so we should use the generic
"item" identifier here.

>         while True:
What the hell is a loop doing here???

>             if number!='end':
>                 number=float(number)
>                 total += float(number)
>                 count+=1
>                 avg = total/count
>             if number=='end':
>                     break

This block of logic is ugly. Try this instead...

>             if number == 'end':
> break
>             number=float(number)
>             total += float(number)
>             count+=1
>             avg = total/count

...but that whole loop thing is nonsense anyway. I would reconsider
this code completely. Here is an outline:

for item in lst
if item equals "end":
compute the current average from buffers
else:
increment the running total
increment the count.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess module and long-lived subprocesses

2012-01-20 Thread Nobody
On Fri, 20 Jan 2012 08:42:16 -0600, skip wrote:

> The library documentation doesn't talk a lot about long-lived subprocesses
> other than the possibility of deadlock when using Popen.wait().  Ideally, I
> would write to the subprocess's stdin, check for output on stdout and
> stderr, then lather, rinse, repeat.  Is it safe to assume that if the stdout
> and/or stderr pipes have nothing for me the reads on those file objects (I'm
> using PIPE for all three std* files) will return immediately with an empty
> string for output?  They won't block, will they?

They will. You need to use either threads, select() or non-blocking I/O in
order to avoid deadlock. See the definitions of subprocess._communicate()
(there's one version for Windows which uses threads and another for Unix
using select()).

> Will a broken pipe IOError get raised as for os.popen()

IOError(EPIPE) will be raised if you write to the stdin pipe when there
are no readers.

> or do I have to call Popen.poll() even in error situations?

Once you're finished with the process, you should close .stdin then
consume all output from .stdout and .stderr until both report EOF, then
call .wait(). That should cover any possible child behaviour (e.g. if
the child explicitly close()s its stdin, getting EPIPE doesn't mean that
you can forget about the process or that .wait() won't deadlock).

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


Re: Is a with on open always necessary?

2012-01-20 Thread Steven D'Aprano
On Fri, 20 Jan 2012 15:44:17 +, Andrea Crotti wrote:

> I normally didn't bother too much when reading from files, and for
> example I always did a
> 
> content = open(filename).readlines()
> 
> But now I have the doubt that it's not a good idea, does the file
> handler stays open until the interpreter quits?

The file will stay open until:

1) you explicitly close it;
2) the reference to the open file goes out of scope and is garbage 
collected; or
3) the Python environment shuts down

whichever happens first.

In the case of #2, the timing is a matter of implementation detail. 
CPython and PyPy currently close the file immediately the last reference 
to it goes out of scope (but that's not a promise of the language, so it 
could change in the future); Jython and IronPython will eventually close 
the file, but it may take a long time.

Except for the quickest and dirtiest scripts, I recommend always using 
either the "with file as" idiom, or explicitly closing the file.


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


Re: Please don't use "setuptools", the "rotten .egg" install system.

2012-01-20 Thread Raffaele Ricciardi
In order to build and run Mercurial on Linux, I needed Python with 
docutils.


I've just installed Python from source and later setuptools. As a 
non-Pythonista, my impression has been that the procedure of installing 
setuptools and then using them is quite straightforward, but it's not 
advertised enough to newcomers.

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


Re: can some one help me with my code. thanks

2012-01-20 Thread Jon Clements
On Jan 20, 9:26 pm, Terry Reedy  wrote:
> On 1/20/2012 2:46 PM, Terry Reedy wrote:
>
>
>
>
>
>
>
>
>
> > On 1/20/2012 1:49 PM, Tamanna Sultana wrote:
>
> >> can some one help me??
> >>> I would like to create a function that, given a bin, which is a list
> >>> (example below), generates averages for the numbers separated by a
> >>> string 'end'. I am expecting to have 4 averages from the above bin,
> >>> since there are 4 sets of numbers separated by 4 'end' strings
>
> > [Posting your overly long set of data lines with a '>' quote at the
> > beginning of each line was a nuisance. Reposted with few lines. I will
> > let you compare your code to mine.]
>
> > bin = ['2598.95165', '2541.220308', '221068.0401', 'end', '4834.581952',
> > '1056.394859', '3010.609563', '2421.437603', '4619.861889',
> > '3682.012227', '3371.092883', '6651.509488', '7906.092773',
> > '7297.133447', 'end', '4566.874299', 'end', '4255.700077',
> > '1857.648393', '11289.48095', '2070.981805', '1817.505094',
> > '563.0265409', '70796.45356', '565.2123689', '6560.030116',
> > '2668.934414', '418.666014', '5216.392132', '760.894589', '8072.957639',
> > '346.5905371', 'end']
>
> > def average(bin):
> > num=[]
> > total = 0.0
> > count=0
> > for number in bin:
> > if number!='end':
> > total += float(number)
> > count+=1
> > else:
> > num.append(total/count)
> > total = 0.0
> > count= 0
> > return num
>
> > print(average(bin))
>
> > [75402.7373526, 4485.0726684, 4566.874299, 7817.36494866]
>
> U're welcome. But do notice Tim's comment. In non-toy situations, you
> have to decide how to handle empty collections (return float('nan')?),
> or whether to just let whatever happens happen.
>
> If you control the input format, a list of lists would be easier than an
> end marker. But sometimes one is handed data and asked to process it as is.
>
> Also note (this is a more advanced topic) that average() could be turned
> into a generator function by replacing 'num.append(total/count)' with
> 'yield total/count' and removing the initialization and return of num.
>
> --
> Terry Jan Reedy

Not directing this at you Terry, and you and Tim have made fine points
-- this just appears to me to be the best point at which to respond to
a thread.

To the OP - you have great answers, and, please note this just happens
to be the way I would do this.

I would separate the parsing of the data, and the calculation code
out. I've whipped this up rather quickly, so it might have a few flaws
but...

from itertools import groupby
def partition(iterable, sep=lambda L: L == 'end', factory=float):
for key, vals in groupby(iterable, sep):
if not key: yield map(factory, vals)

# And a pure cheat, but useful if more complex calculations are
required etc... (Plus covers NaN)
import numpy as np
print map(np.mean, partition(bin))

What you've got will work though, so wouldn't worry too much and this
is just my 2p,

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


Re: can some one help me with my code. thanks

2012-01-20 Thread Steven D'Aprano
On Fri, 20 Jan 2012 16:21:30 -0800, Rick Johnson wrote:

> On Jan 20, 12:49 pm, Tamanna Sultana  wrote:
>> > If you can give me some lead to fix the code I wrote below that will
>> > be great:
> 
> Your variable names need a bit more thought
> 
>> def average(bin):
> 
> What is a "bin"? Maybe you shoulc have called this a "lst" eh?

What's a 'lst'? It's not even a real word, and it looks like 1st.

"Bin" is a standard English world. You know, like "rubbish bin" or 
"recycling bin". It is also a standard term used in statistics as a noun, 
a verb, and adjective, e.g.:

http://stackoverflow.com/questions/5581023/r-graphing-binned-data



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


Re: LibreOffice with Python

2012-01-20 Thread Adam Tauno Williams
On Tue, 2012-01-10 at 19:04 -0500, Terry Reedy wrote:
> On 1/10/2012 5:29 PM, Ben Finney wrote:
> > LibreOffice supports scripting with several languages, including Python
> > http://help.libreoffice.org/Common/Scripting>
> So that page says. But it only tells how to attach a Python script once 
> writen, not how to write one that will do anything. Are there any links 
> for that?

+1

PyUNO, and UNO in general, needs way more press and for some of the
people who use it to do a bit of BLOGing.  Getting up over the initial
learning curve is rough;  I know it has pushed me back from a couple of
attempts.

> > Extensions can also be written in Python, using the UNO runtime API
> > http://api.libreoffice.org/>.



signature.asc
Description: This is a digitally signed message part
-- 
http://mail.python.org/mailman/listinfo/python-list


Masking a dist package with a copy in my own package

2012-01-20 Thread Sam Simmons
Hey all,

I'm using twisted in a project and have run into a class that's in version 11.1 
but not 8.2 in OSX. I was thinking to get it working for mac users I could just 
extract the 11.1 twisted package and through it under my package. e.g.

project/
  __init__.py
  twisted/
__init__.py
  ...

When running anything, it imports from the local 11.1 twisted, but zope throws 
a warning:

/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/zope/__init__.py:1:
 UserWarning: Module twisted was already imported from 
/path/to/project/twisted/__init__.pyc, but 
/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python is 
being added to sys.path
  __import__('pkg_resources').declare_namespace(__name__)

Is there an elegant way to give mac users vers 11.1 other than copying in 
package and possibly renaming it?

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


Re: can some one help me with my code. thanks

2012-01-20 Thread Chris Angelico
On Sat, Jan 21, 2012 at 1:23 PM, Steven D'Aprano
 wrote:
> On Fri, 20 Jan 2012 16:21:30 -0800, Rick Johnson wrote:
>> Your variable names need a bit more thought
>>
>>> def average(bin):
>>
>> What is a "bin"? Maybe you shoulc have called this a "lst" eh?
>
> "Bin" is a standard English world. You know, like "rubbish bin" or
> "recycling bin".

Or my first thought: stock location. Inventory software often doesn't
care whether your physical stock is organized by shelf, box,
warehouse, planet, or secret-space-on-Firefly-class-ship; just number
each location, and that's the bin number. (And no, that isn't like
"PIN number".) It's then quite logical to want various stats to be
per-bin, which would lead exactly to the OP's problem - including the
odd notation of input data, all too likely in a real-world scenario.

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


Re: etree/lxml/XSLT and dynamic stylesheet variables

2012-01-20 Thread Stefan Behnel
Adam Tauno Williams, 20.01.2012 21:38:
> I'm using etree to perform XSLT transforms, such as -
> 
> from lxml import etree
> source = etree.parse(self.rfile)
> xslt = etree.fromstring(self._xslt)
> transform = etree.XSLT(xslt)
> result = transform(source)
> 
> according to the docs at
>  I can pass a
> dictionary of parameters to transform, such as -
> 
> result = transform(doc_root, **{'non-python-identifier': '5'})
> 
> Can I pass a dictionary-like object?  That doesn't seem to be working.

Yes it does, Python copies it into a plain dict at call time.


> I need to perform dynamic lookup of variables for the stylesheet.

Different story.


> I've subclassed dictionary and overloaded [], get, has_key, and in to
> perform the required lookups; these work in testing. But passing the
> object to transform doesn't work.

You should make the lookup explicit in your XSLT code using an XPath
function. See here:

http://lxml.de/extensions.html

Stefan

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