Re: How to generate only rotationally-unique permutations?

2012-05-19 Thread Arnaud Delobelle
On 19 May 2012 06:23, John O'Hagan  wrote:
> To revisit a question which I'm sure none of you remember from when I posted 
> it
> a year or so ago - there were no takers at the time - I'd like to try again 
> with
> a more concise statement of the problem:
>
> How to generate only the distinct permutations of a sequence which are not
> rotationally equivalent to any others? More precisely, to generate only the 
> most
> "left-packed" of each group of rotationally equivalent permutations, such that
> for each permutation p:

This makes me think of Lyndon words.  A Lyndon word is a word which is
the only lexicographical minimum of all its rotations.  There is a
very effective way of generating Lyndon words of length <= n.  It may
be possible to adapt it to what you want (obviously as Lyndon words
are aperiodic you'd have to generate Lyndon word of length d | n when
suitable).

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


Re: How to generate only rotationally-unique permutations?

2012-05-19 Thread Zero Piraeus
:

On 19 May 2012 01:23, John O'Hagan  wrote:
> How to generate only the distinct permutations of a sequence which are not
> rotationally equivalent to any others? More precisely, to generate only the 
> most
> "left-packed" of each group of rotationally equivalent permutations, such that
> for each permutation p:

It's late and I'm tired (and the solution below isn't a generator), but ...

itertools.permutations() generates results in lexicographic order [1],
so if you reverse-sort the sequence before processing it, when you get
a sequence back whose first item isn't the maximum, you'll know that
you've got all the sequences whose first item *is* the maximum - which
means you can bail at that point.

Wow, that's a nasty sentence. As I said, tired. Anyway - you'll get
dupes if there are non-unique items in the rest of the sequence, so
some form of filtering is required, but you could use a set to handle
that. Something like:

from itertools import permutations

def rot_uniq_perms(seq):
result = set()
seq = sorted(seq, reverse=True)
maximum = seq[0]
for x in permutations(seq):
if x[0] != maximum:
break
else:
result.add(x[::-1])
return result

No idea how this performs compared to your existing solution, but it
might be a starting point.

[1] http://docs.python.org/library/itertools.html#itertools.permutations

 -[]z.
-- 
http://mail.python.org/mailman/listinfo/python-list


ctype C library call always returns 0 with Python3

2012-05-19 Thread Johannes Bauer
Hi group,

I'm playing with ctypes and using it to do regressions on some C code
that I compile as a shared library. Python is the testing framework.

This works nicely as long as I do not need the return value (i.e.
calling works as expected and parameters are passed correctly). The
return value of all functions is always zero in my case, however.

Even the example in the standard library fails:

import ctypes
libc = ctypes.cdll.LoadLibrary("/lib64/libc-2.14.1.so")
print(libc.strchr("abcdef", ord("d")))

Always returns "0".

I'm working on a x86-64 Gentoo Linux and can reproduce this behavior
with Python 3.1.4 and Python 3.2.3.

On Python 2.7.3 and Python 2.6.6 the example works fine on my system.

Since I'd like to use Python3, I'm curious to know what changed in the
behavior and how I can get this to run. Any help is greatly appreciated.

Best regards,
Joe

-- 
>> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
 - Karl Kaos über Rüdiger Thomas in dsa 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ctype C library call always returns 0 with Python3

2012-05-19 Thread Nobody
On Sat, 19 May 2012 11:30:46 +0200, Johannes Bauer wrote:

> import ctypes
> libc = ctypes.cdll.LoadLibrary("/lib64/libc-2.14.1.so")
> print(libc.strchr("abcdef", ord("d")))

In 3.x, a string will be passed as a wchar_t*, not a char*. IOW, the
memory pointed to by the first argument to strchr() will consist mostly of
NUL bytes.

Either use a "bytes" instead of a string:

> print(libc.strchr(b"abcdef", ord("d")))
198291

or specify the argument types to force a conversion:

> libc.strchr.argtypes = [c_char_p, c_int]
> print(libc.strchr("abcdef", ord("d")))
1984755787

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


Re: ctype C library call always returns 0 with Python3

2012-05-19 Thread Colin McPhail

On 19/05/2012 10:30, Johannes Bauer wrote:

Even the example in the standard library fails:

import ctypes
libc = ctypes.cdll.LoadLibrary("/lib64/libc-2.14.1.so")
print(libc.strchr("abcdef", ord("d")))

Always returns "0".


I think there may be two problems with this code:

(1) You are using a 64-bit system but, in the absence of a function 
prototype for strchr, ctypes will be passing and returning 32-bit types. 
To add prototype information put something like:

  libc.strchr.restype = ctypes.c_char_p
  libc.strchr.argtypes = [ctypes.c_char_p, c_int]
before the call of strchr().

(2) In Python3 strings are not plain sequences of bytes by default. In 
your example try passing b"abcdef" instead of "abcdef".


-- CMcP

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


Re: Plot a function with matplotlib?

2012-05-19 Thread Vlastimil Brom
2012/5/19 Steven D'Aprano :
> I have matplotlib and iPython, and want to plot a function over an
> equally-spaced range of points.
>
> That is to say, I want to say something like this:
>
> plot(func, start, end)
>
> rather than generating the X and Y values by hand, and plotting a scatter
> graph. All the examples I've seen look something like this:
>
> from pylab import *
> import numpy as np
> t = arange(0.0, 2.0+0.01, 0.01)  # generate x-values
> s = sin(t*pi)  # and y-values
> plot(t, s)
> show()
>
>
> which is fine for what it is, but I'm looking for an interface closer to
> what my HP graphing calculator would use, i.e. something like this:
>
>
> plot(lambda x: sin(x*pi), # function or expression to plot,
>     start=0.0,
>     end=2.0,
>    )
>
> and have step size taken either from some default, or better still,
> automatically calculated so one point is calculated per pixel.
>
> Is there a way to do this in iPython or matplotlib?
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list


Hi,
would a mpmath solution be acceptable?
http://code.google.com/p/mpmath/
http://mpmath.googlecode.com/svn/trunk/doc/build/plotting.html#mpmath.plot

"""
mpmath.plot(ctx, f, xlim=[-5, 5], ylim=None, points=200, file=None,
dpi=None, singularities=[], axes=None)
Shows a simple 2D plot of a function ... or list of functions ...
over a given interval specified by xlim. ...
"""

>>> import mpmath
>>> mpmath.plot(lambda x: mpmath.sin(x*mpmath.pi), xlim=[0.0, 2.0])

hth,
  vbr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: .py to .pyc

2012-05-19 Thread Colin J. Williams

On 18/05/2012 7:20 PM, Tony the Tiger wrote:

On Sun, 13 May 2012 23:36:02 +0200, Irmen de Jong wrote:


Why do you care anyway?


Wanna hide his code...?

  /Grrr
Curiosity.  Perhaps there are stack-based processors out there which 
could use the .pyc code more directly.


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


sqlalchemy: delete() on m:n-relationship

2012-05-19 Thread Wolfgang Meiners
Hi all,

i dont understand, how sqlalchemy deletes from m:n relationships.

Maybe, someone can explain to me, how to delete in the following program:

(pyhton3, sqlalchemy 0.7.0)

=
> #!/usr/bin/env python3
> # -*- coding: utf-8 -*-
> 
> '''
> Created on 19.05.2012
> 
> @author: wolfgang
> 
> '''
> 
> from sqlalchemy import *
> 
> from sqlalchemy.orm.session import sessionmaker
> from sqlalchemy.orm import relationship, backref
> from sqlalchemy.ext.declarative import declarative_base
> 
> 
> Base = declarative_base()
> 
> class Book(Base):
> __tablename__='books'
> 
> def __init__(self, title, authors):
> # here authors is a list of items of type Autor
> self.title = title
> for author in authors:
> self.authors.append(author)
> 
> bid = Column(Integer, primary_key=True)
> title = Column(String, index=True)
> 
> authors = relationship('Author', secondary='author_book', 
>backref=backref('books', order_by='Book.title', 
> cascade='all, delete'),
>cascade='all, delete')
> 
> class Author(Base):
> __tablename__ = 'authors'
> 
> def __init__(self, name):
> self.name = name
> 
> aid = Column(Integer, primary_key=True)
> name = Column(String, index=True)
> 
> 
> # Association table between authors and books:
> author_book = Table('author_book', Base.metadata,
> Column('aid', Integer, ForeignKey('authors.aid'), 
> primary_key=True),
> Column('bid', Integer, ForeignKey('books.bid'), 
> primary_key=True))
> 
> 
> class DB:
> def __init__(self, dbname=None, echo=False):
> self.dbname = dbname if dbname else ':memory:'
> self.dbfile = 'sqlite:///{db}'.format(db=self.dbname)
> self.engine = create_engine(self.dbfile)
> Base.metadata.create_all(self.engine)
> self.Session = sessionmaker(self.engine)
> 
> def find_or_create_author(session, name):
> qauthor = session.query(Author).filter_by(name=name)
> if qauthor.count() == 0:
> session.add(Author(name=name))
> return qauthor.one()
> 
> if __name__ == '__main__':
> 
> db = DB(dbname='booksdb.sqlite', echo=True)
> session = db.Session()
> 
> # insert 4 books into db
> session.add_all([Book(title='Title a',
>   authors=[find_or_create_author(session, 
> name='Author 1'),
>find_or_create_author(session, 
> name='Author 2')]),
>  Book(title='Title b',
>   authors=[find_or_create_author(session, 
> name='Author 1'),
>find_or_create_author(session, 
> name='Author 2')]),
>  Book(title='Title c',
>   authors=[find_or_create_author(session, 
> name='Author 3'),
>find_or_create_author(session, 
> name='Author 4')]),
>  Book(title='Title d',
>   authors=[find_or_create_author(session, 
> name='Author 3'),
>find_or_create_author(session, 
> name='Author 4')])])
> 
> session.commit()
> 
> # At this point there are 4 book in db, the first 2 written by Author 1 
> and Author 2,
> # the last 2 written by Author 3 and Author 4.
> # Now, i delete books with bid == 1 and bid == 3:
> 
> book1 = session.query(Book).filter_by(bid=1).one()
> session.delete(book1)
> 
> session.query(Book).filter_by(bid=3).delete()
> 
> session.commit()
> 
> # The first query deletes to much: Title b is related to Author 1 and 
> Author 2
> # this relation has dissapeared from the db
> 
> # The last query deletes to less: There is no Title 3, but the entries 
> # of this book remain in the associationtable.
> 
> # How is this done right?
==

after i run this program, the contents of booksdb.sqlite has the
following data:

$ sqlite3 booksdb.sqlite
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from author_book;
3|3
4|3
3|4
4|4

sqlite> select * from
   ...> books natural inner join author_book
   ...> natural inner join authors;
4|Title d|3|Author 3
4|Title d|4|Author 4

which means, association between Title b and ist authors is lost,
information on Title c is still in author_book table.

Thank you for any help

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


Re: Questions on __slots__

2012-05-19 Thread Adam Tauno Williams
On Fri, 2012-05-18 at 09:53 -0700, Charles Hixson wrote: 
> Does __slots__ make access to variables more efficient?

Absolutely, yes.

> If one uses property() to create a few read-only pseudo-variables, does 
> that negate the efficiency advantages of using __slots__?
> (Somehow I feel the documentation needs a bit of improvement.)

If you are tempted to use property, setattr, etc... then do not use
__slots__.  __slots__ should really only be used for Fly Weight pattern
type work, or at least for objects with a limited scope and will not be
inherited from.


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


Re: Plot a function with matplotlib?

2012-05-19 Thread Alex van der Spek
On Sat, 19 May 2012 01:59:59 +, Steven D'Aprano wrote:

> I have matplotlib and iPython, and want to plot a function over an
> equally-spaced range of points.
> 
> That is to say, I want to say something like this:
> 
> plot(func, start, end)
> 
> rather than generating the X and Y values by hand, and plotting a
> scatter graph. All the examples I've seen look something like this:
> 
> from pylab import *
> import numpy as np
> t = arange(0.0, 2.0+0.01, 0.01)  # generate x-values s = sin(t*pi)  #
> and y-values
> plot(t, s)
> show()
> 
> 
> which is fine for what it is, but I'm looking for an interface closer to
> what my HP graphing calculator would use, i.e. something like this:
> 
> 
> plot(lambda x: sin(x*pi), # function or expression to plot,
>  start=0.0,
>  end=2.0,
> )
> 
> and have step size taken either from some default, or better still,
> automatically calculated so one point is calculated per pixel.
> 
> Is there a way to do this in iPython or matplotlib?

Not to my knowledge unless you code it yourself.

However in gnuplot (www.gnuplot.info)

gnuplot>>> set xrange[start:end]
gnuplot>>> foo(x)=mycomplicatedfunction(x)
gnuplot>>> plot foo(x)

or shorter still

gnuplot>>> plot [start:end] foo(x)

without the need to set the xrange in advance.

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


Re: cPython, IronPython, Jython, and PyPy (Oh my!)

2012-05-19 Thread Adam Tauno Williams
On Thu, 2012-05-17 at 11:13 +1000, Chris Angelico wrote: 
> On Thu, May 17, 2012 at 9:01 AM, Ethan Furman  wrote:
> > A record is an interesting critter -- it is given life either from the user
> > or from the disk-bound data;  its fields can then change, but those changes
> > are not reflected on disk until .write_record() is called;  I do this
> > because I am frequently moving data from one table to another, making
> > changes to the old record contents before creating the new record with the
> > changes -- since I do not call .write_record() on the old record those
> > changes do not get backed up to disk.
> I strongly recommend being more explicit about usage and when it gets
> written and re-read, 

You need to define a 'session' that tracks records and manages flushing.
Potentially it can hold a pool of weak references to record objects that
have been read from disk.  Record what records are 'dirty' and flush
those to disk explicitly or drop all records ('essentially rollback').
That is the only sane way to manage this.

> rather than relying on garbage collection.

+1 +1 Do *not* rely on implementation details as features.  Sooner or
later doing so will always blow-up.

> Databasing should not be tied to a language's garbage collection.
> Imagine you were to reimplement the equivalent logic in some other
> language - could you describe it clearly? If so, then that's your
> algorithm. If not, you have a problem.


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


Re: Plot a function with matplotlib?

2012-05-19 Thread Miki Tebeka
> I'm looking for an interface closer to 
> what my HP graphing calculator would use, i.e. something like this:
> 
> 
> plot(lambda x: sin(x*pi), # function or expression to plot,
>  start=0.0,
>  end=2.0,
> )
> 
> and have step size taken either from some default, or better still, 
> automatically calculated so one point is calculated per pixel.
> 
> Is there a way to do this in iPython or matplotlib?
I don't think there is, but using range and list comprehension you can write a 
little utility function that does that:

HTH
--
Miki Tebeka 
http://pythonwise.blogspot.com

def simplot(fn, start, end):
xs = range(start, end+1)
plot(xs, [fn(x) for x in xs)])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bash/shell to python

2012-05-19 Thread Michael Torrie
On 05/16/2012 08:16 PM, Rita wrote:
> I currently build a lot of interfaces/wrappers to other applications
> using bash/shell. One short coming for it is it lacks a good method
> to handle arguments so I switched to python a while ago to use
> 'argparse' module.

Actually there is a great way of parsing command line options in
bash, using the GNU "getopt" program.  See:
http://www.manpagez.com/man/1/getopt/

This command is available on all Linux systems, and most BSD systems.
There's also freegetopt, a BSD implementation for unix, MSDOS, or Windows.

> Its a great complement to subprocess module. I was wondering if there
> is a generic framework people follow to build python scripts which
> are replacing shell scripts? Is there a guide or a template to
> follow?

Besides the advice given by the other posters in this thread, here is a
very good document on some unique aspects of python that are well suited
to doing system programming or shell scripting in python:

http://www.dabeaz.com/generators/

This describes how generators can be used to replace pipes with
something that is quite efficient and very pythonic.  See the
presentation pdf first.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ctype C library call always returns 0 with Python3

2012-05-19 Thread Hans Mulder
On 19/05/12 13:20:24, Nobody wrote:
> On Sat, 19 May 2012 11:30:46 +0200, Johannes Bauer wrote:
> 
>> import ctypes
>> libc = ctypes.cdll.LoadLibrary("/lib64/libc-2.14.1.so")
>> print(libc.strchr("abcdef", ord("d")))
> 
> In 3.x, a string will be passed as a wchar_t*, not a char*. IOW, the
> memory pointed to by the first argument to strchr() will consist mostly of
> NUL bytes.
> 
> Either use a "bytes" instead of a string:
> 
>   > print(libc.strchr(b"abcdef", ord("d")))
>   198291
> 
> or specify the argument types to force a conversion:
> 
>   > libc.strchr.argtypes = [c_char_p, c_int]
>   > print(libc.strchr("abcdef", ord("d")))
>   1984755787

You'll also want to specify the return type:

>>> libc.strchr.argtypes = [c_char_p, c_int]
>>> print(libc.strchr(b"abcdef", ord("d")))
7224211
>>> libc.strchr.restype = c_char_p
>>> print(libc.strchr(b"abcdef", ord("d")))
b'def'

Hope this helps,

-- HansM

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


Re: How to generate only rotationally-unique permutations?

2012-05-19 Thread John O'Hagan
On Sat, 19 May 2012 09:15:39 +0100
Arnaud Delobelle  wrote:

> On 19 May 2012 06:23, John O'Hagan  wrote:
[...]
> >
> > How to generate only the distinct permutations of a sequence which are not
> > rotationally equivalent to any others? More precisely, to generate only the
> > most "left-packed" of each group of rotationally equivalent permutations,
> > such that for each permutation p:
> 
> This makes me think of Lyndon words.  A Lyndon word is a word which is
> the only lexicographical minimum of all its rotations.  There is a
> very effective way of generating Lyndon words of length <= n.  It may
> be possible to adapt it to what you want (obviously as Lyndon words
> are aperiodic you'd have to generate Lyndon word of length d | n when
> suitable).
> 

Thanks for your suggestion. The Lyndon word generators I found were not
quite what I was after as they didn't guarantee giving sequences with the same
elements. but your suggestion led me to necklaces:

http://en.wikipedia.org/wiki/Necklace_ (combinatorics)
 
of which Lyndon words represent a special aperiodic case. I found these
algorithms for generating necklaces:

http://www.sagenb.org/src/combinat/necklace.py

which seems to be exactly what I want. Thanks!

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


Re: Jython 2.7 alpha1 is out!

2012-05-19 Thread Guido van Rossum
Congrats Frank!

I reposted this on my G+ account and got some interesting comments.
https://plus.google.com/u/0/115212051037621986145/posts/ifyqW3JBd3a

There's got to be a way for you to make money off the Oracle connection!

(PS: It would have been nice if there was an announcement page on the
Jython website/wiki instead of having to link to a mailing list
archive page. :-)

--Guido

On Thu, May 17, 2012 at 1:56 PM, fwierzbi...@gmail.com
 wrote:
> On behalf of the Jython development team, I'm pleased to announce that
> Jython 2.7 alpha1 is available for download here:
> http://sourceforge.net/projects/jython/files/jython-dev/2.7.0a1/jython_installer-2.7a1.jar/downloaddownload.
> See the installation instructions here:
> http://wiki.python.org/jython/InstallationInstructions
>
> I'd like to thank Adconion Media Group for sponsoring my work on
> Jython 2.7. I'd also like to thank the many contributors to Jython.
>
> Jython 2.7 alpha1 implements much of the functionality introduced by
> CPython 2.6 and 2.7. There are still some missing features, in
> particular bytearray and the io system are currently incomplete.
>
> Please report any bugs here: http://bugs.jython.org/ Thanks!
>
> -Frank
> --
> http://mail.python.org/mailman/listinfo/python-announce-list
>
>        Support the Python Software Foundation:
>        http://www.python.org/psf/donations/



-- 
--Guido van Rossum (python.org/~guido)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions on __slots__

2012-05-19 Thread Charles Hixson

On 05/19/2012 06:39 AM, Adam Tauno Williams wrote:

On Fri, 2012-05-18 at 09:53 -0700, Charles Hixson wrote:
   

Does __slots__ make access to variables more efficient?
 

Absolutely, yes.

   

If one uses property() to create a few read-only pseudo-variables, does
that negate the efficiency advantages of using __slots__?
(Somehow I feel the documentation needs a bit of improvement.)
 

If you are tempted to use property, setattr, etc... then do not use
__slots__.  __slots__ should really only be used for Fly Weight pattern
type work, or at least for objects with a limited scope and will not be
inherited from.
   
Thank you.  What I really wanted was a "named list", sort of like a 
"named tuple", only modifiable, but since the only way to do it was to 
create a class, I started thinking of reasonable operations for it to 
perform (data hiding, etc.)  Sounds like I should go back to the "named 
list" idea.


--
Charles Hixson

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


Re: How to generate only rotationally-unique permutations?

2012-05-19 Thread John O'Hagan
On Sat, 19 May 2012 04:21:35 -0400
Zero Piraeus  wrote:

> :
> 
> On 19 May 2012 01:23, John O'Hagan  wrote:
> > How to generate only the distinct permutations of a sequence which are not
> > rotationally equivalent to any others? More precisely, to generate only the
> > most "left-packed" of each group of rotationally equivalent permutations,
> > such that for each permutation p:
> 
> It's late and I'm tired (and the solution below isn't a generator), but ...
> 
> itertools.permutations() generates results in lexicographic order [1],
> so if you reverse-sort the sequence before processing it, when you get
> a sequence back whose first item isn't the maximum, you'll know that
> you've got all the sequences whose first item *is* the maximum - which
> means you can bail at that point.
> 
> Wow, that's a nasty sentence. As I said, tired. Anyway - you'll get
> dupes if there are non-unique items in the rest of the sequence, so
> some form of filtering is required, but you could use a set to handle
> that. Something like:
> 
> from itertools import permutations
> 
> def rot_uniq_perms(seq):
> result = set()
> seq = sorted(seq, reverse=True)
> maximum = seq[0]
> for x in permutations(seq):
> if x[0] != maximum:
> break
> else:
> result.add(x[::-1])
> return result
> 
> No idea how this performs compared to your existing solution, but it
> might be a starting point.

Thanks for your reply, but I can't profitably use itertools.permutations, as my
sequences have repeated elements, so I was using a python implementation of the
next_permutation algorithm, which yields only distinct permutations. Your
trick of bailing when x[0] != maximum is, I think, another version of what my
attempt did, that is, remove the maximum, permute the rest, then replace it.
But the problem remains of what to do if there are several maxima.

That is obviated by a solution suggested by another reply, of using a
necklace generator.

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


Advantages of logging vs. print()

2012-05-19 Thread Giampaolo Rodolà
Hi all,
I'm currently working on 1.0.0 release of pyftpdlib module.
This new release will introduce some backward incompatible changes in
that certain APIs will no longer accept bytes but unicode.
While I'm at it, as part of this breackage I was contemplating the
possibility to rewrite my logging functions, which currently use the
print statement, and use the logging module instead.

As of right now pyftpdlib delegates the logging to 3 functions:

def log(s):
"""Log messages intended for the end user."""
print s

def logline(s):
"""Log commands and responses passing through the command channel."""
print s

def logerror(s):
"""Log traceback outputs occurring in case of errors."""
print >> sys.stderr, s


The user willing to customize logs (e.g. write them to a file) is
supposed to just overwrite these 3 functions as in:


>>> from pyftpdlib import ftpserver
>>> def log2file(s):
...open(''ftpd.log', 'a').write(s)
...
>>> ftpserver.log = ftpserver.logline = ftpserver.logerror = log2file


Now I'm asking: what benefits would imply to get rid of this approach
and use logging module instead?
>From a module vendor perspective, how exactly am I supposed to
use/provide logging in my module?
Am I supposed to do this:

import logging
logger = logging.getLogger("pyftpdlib")

...and state in my doc that "logger" is the object which is supposed
to be used in case the user wants to customize how logs behave?
Is logging substantially slower compared to print()?


Thanks in advance

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


setdefault behaviour question

2012-05-19 Thread pete McEvoy
I am confused by some of the dictionary setdefault behaviour, I think
I am probably missing the obvious here.

def someOtherFunct():
print "in someOtherFunct"
return 42

def someFunct():
myDict = {1: 2}
if myDict.has_key(1):
print "myDict has key 1"
x = myDict.setdefault(1, someOtherFunct())   # < I didn't
expect someOtherFunct to get called here
print "x", x
y = myDict.setdefault(5, someOtherFunct())
print "y", y


+

if I call someFunct() I get the following output

myDict has key 1
in someOtherFunct
x 2
in someOtherFunct
y 42


For the second use of setdefault I do expect a call as the dictionary
does not the key. Will the function, someOtherFunct, in setdefault
always be called anyway and it is just that the dictionary will not be
updated in any way?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: setdefault behaviour question

2012-05-19 Thread MRAB

On 19/05/2012 20:44, pete McEvoy wrote:

I am confused by some of the dictionary setdefault behaviour, I think
I am probably missing the obvious here.

def someOtherFunct():
 print "in someOtherFunct"
 return 42

def someFunct():
 myDict = {1: 2}
 if myDict.has_key(1):
 print "myDict has key 1"
 x = myDict.setdefault(1, someOtherFunct())   #<  I didn't
expect someOtherFunct to get called here
 print "x", x
 y = myDict.setdefault(5, someOtherFunct())
 print "y", y


+

if I call someFunct() I get the following output

myDict has key 1
in someOtherFunct
x 2
in someOtherFunct
y 42


For the second use of setdefault I do expect a call as the dictionary
does not the key. Will the function, someOtherFunct, in setdefault
always be called anyway and it is just that the dictionary will not be
updated in any way?


The answer is yes.

someOtherFunct() is called and then 1 and the result of
someOtherFunct() are passed as arguments to myDict.setdefault(...).
--
http://mail.python.org/mailman/listinfo/python-list


Re: setdefault behaviour question

2012-05-19 Thread pete McEvoy
Ah - I have checked some previous posts (sorry, should
have done this first) and I now can see that the
lazy style evaluation approach would not be good.
I can see the reasons it behaves this way.

many thanks anyway.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Plot a function with matplotlib?

2012-05-19 Thread Mark Lawrence

On 19/05/2012 02:59, Steven D'Aprano wrote:

I have matplotlib and iPython, and want to plot a function over an
equally-spaced range of points.

That is to say, I want to say something like this:

plot(func, start, end)

rather than generating the X and Y values by hand, and plotting a scatter
graph. All the examples I've seen look something like this:

from pylab import *
import numpy as np
t = arange(0.0, 2.0+0.01, 0.01)  # generate x-values
s = sin(t*pi)  # and y-values
plot(t, s)
show()


which is fine for what it is, but I'm looking for an interface closer to
what my HP graphing calculator would use, i.e. something like this:


plot(lambda x: sin(x*pi), # function or expression to plot,
  start=0.0,
  end=2.0,
 )

and have step size taken either from some default, or better still,
automatically calculated so one point is calculated per pixel.

Is there a way to do this in iPython or matplotlib?




Sorry don't know but wouldn't it make sense to ask on the matplotlib 
users mailing lst, cos like most python users the're extremely friendly?


--
Cheers.

Mark Lawrence.

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


Re: print XML

2012-05-19 Thread Karl Knechtel
What do you want the contents of the file to look like? Why are you
parsing the XML in the first place? (What do you want to happen if the
data on `sys.stdin` isn't actually valid XML?)

On Thu, May 17, 2012 at 9:52 AM, Nibin V M  wrote:
> Hello,
>
> I have the following code, which will assign  XML data to a variable! What
> is the best method to write the contents of the variable to a file?
>
> ===
> doc = minidom.parse(sys.stdin)
> ===
>
> Any help will be highly appreciated!
>
> Thank you,
> --
> Regards
>
> Nibin.
>
> http://TechsWare.in
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: setdefault behaviour question

2012-05-19 Thread Chris Angelico
On Sun, May 20, 2012 at 5:44 AM, pete McEvoy  wrote:
> I am confused by some of the dictionary setdefault behaviour, I think
> I am probably missing the obvious here.
>
> def someOtherFunct():
>    print "in someOtherFunct"
>    return 42
>
>    x = myDict.setdefault(1, someOtherFunct())   # < I didn't
> expect someOtherFunct to get called here

Python doesn't have lazy evaluation as such, but if what you want is a
dictionary that calls a function of yours whenever a value isn't
found, check out collections.defaultdict:

>>> import collections
>>> a=collections.defaultdict()
>>> def func():
print("Generating a default!")
return 42

>>> a.default_factory=func
>>> x = a[1]
Generating a default!
>>> x = a[1]

Tested in 3.2, but should work fine in 2.5 and newer.

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


Re: http://porn-extreme.2304310.n4.nabble.com/

2012-05-19 Thread jimmy970
http://porn-extreme.2304310.n4.nabble.com/

--
View this message in context: 
http://python.6.n6.nabble.com/AMPUTEE-INCEST-MIDGET-2012-tp4708963p4975250.html
Sent from the Python - python-list mailing list archive at Nabble.com.
-- 
http://mail.python.org/mailman/listinfo/python-list