IconvCodec, UTF-32 & P4 ?

2005-03-20 Thread Do Re Mi chel La Si Do
Hi !

Iconvcodec was good, for to work with UTF-32, with Python 2.3
But, which tool, for the same use, with Python 2.4  ?
Thanks for suggestions.

Michel Claveau 


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


Python limericks (was Re: Text-to-speech)

2005-03-20 Thread Brian van den Broek
Steve Holden said unto the world upon 2005-03-20 16:18:

Since it's PyCon week, I will offer a prize of $100 to the best (in my 
opinion) limerick about Python posted to this list (with a Cc: to 
[EMAIL PROTECTED]) before midday on Friday. The prize money will be my 
own, so there are no other rules. I will post my judgment when the PyCon 
nonsense has died down a little, but the winner will be read before the 
entire PyCon audience. Get to it!

regards
 Steve

Homage to the Interactive Interpreter (with apologies to all the monks 
out there):

My dear Guido dared once to combine
Out of objects, command of a line
There was nary a brace.
In their place? Some whitespace!
And cast many their Perl before swine.
(I agree that the idiom played upon in the last line is obverted, but 
but plead poetic license :-)

Best to all,
Brian vdB

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


Re: exec src in {}, {} strangeness

2005-03-20 Thread Do Re Mi chel La Si Do
Hi !


Try :

exec f in globals(),locals()
or
exec(f,globals(),locals())
or
exec f in globals(),globals()
or
exec(f,globals(),globals())



@-salutations

Michel Claveau 


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


Re: (",) Do You Want To Know For Sure You Are Going To Heaven?

2005-03-20 Thread Chris Rebert (cybercobra)
Please do STFU! You are most annoying and this is the wrong place to
post this.
If anyone else if reading this, yes, I do realize it's probably a bot.
But I need to vent some rage. Now if only his nick didn't have a "..."
in it... I would so report it to yahoo and/or counterspam it.

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


Re: For loop extended syntax

2005-03-20 Thread Kay Schluehr
George Sakkis wrote:

> > Looks very appealing, but what to do with
> >
> > [x*y-z for (x=0,y,z) in (1,2,3), (4,5), (6,7,8)] ?
> >
> > Should it raise an exception due to a pattern mismatch?
>
> I didn't have in mind to generalize the syntax even more than the
respective
> for function
> signatures, therefore this would be syntax error:
> SyntaxError: non-keyword arg after keyword arg

O.K. Allthough it has fallen out of Guidos favor one can use a lambda
to obtain the same solution:

[(lambda x,y,z=0:x*y-z)(*vec) for vec in (1,2,3), (4,5), (6,7,8)]

This inspires to examine Your list comprehension not as plain 'syntax
suggar' but in a clear operational perspective. Since (x,y,z=0) is not
a valid Python tuple we have to replace it by

lambda x,y,z=0:(x,y,z)

This acts on the list elements of the comprehension like the proposed
(x,y,z=0) whereas the valid (x,y,z) acts like

lambda x,y,z:(x,y,z)

So we have generalized tuples to lambdas. If we let lambda
x,y,z=0:(x,y,z) iterate over the list elements, why not the generalized

lambda x,y,z=0:(lambda x,a=0:(x,a),y,z) ?

Returning to Your soluion and translating back the lambda:

[x*y-z for ((x,a=0),y,z=0) in (1,2,3), (4,5), (6,7,8)]

should also be possible from an operational perspective.

Regards Kay

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


Re: Event Handeling Between Two wxPanles in A wxNotebook

2005-03-20 Thread F. GEIGER
My DataPool then is a singleton, well, actually, a Borg. See Alex Martelli's
recipe for that. If you use new style classes, then you have to look for
"Singleton" in the cookbook.

HTH
Franz GEIGER


"MyHaz" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> so you run data pool as like a sruct that contains all your global
> objects? That sounds like an iteresting way of doing things. i try to
> stay away from gloabs as much as possible but this might be a good time
> to queue up that particular tool
>
> thanks for your reply
>


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


Re: printing anomaly

2005-03-20 Thread Greg Ewing
Paul Rubin wrote:
What's the deal with this?
>>> print 3.2
3.2
>>> print [3.2]
[3.2002]
>>> 

Yes, I know that 3.2 isn't an exact binary fraction.  I'm wondering
why it's converted differently depending on whether it's in a list.
It's not. The difference is that print uses str() to convert
its arguments to strings, whereas lists always use repr()
to convert their elements to strings, regardless of whether
you use str() or repr() on the list as a whole.
A simple experiment shows the difference between str()
and repr() on floats:
Python 2.3.4 (#1, Jun 30 2004, 16:47:37)
[GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> str(3.2)
'3.2'
>>> repr(3.2)
'3.2002'
--
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pre-PEP: Dictionary accumulator methods

2005-03-20 Thread Ron
On Sun, 20 Mar 2005 15:14:22 -0800, David Eppstein
<[EMAIL PROTECTED]> wrote:

>In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] (Aahz) 
>wrote:
>
>> >I am surprised nobody suggested we put those two methods into a
>> >separate module (say dictutils or even UserDict) as functions:
>> >
>> >from dictutils import tally, listappend
>> >
>> >tally(mydict, key)
>> >listappend(mydict, key, value)
>> 
>> That seems like a reasonable compromise.
>
>The more messages I see on this thread, the more I think adding a 
>different new method for each commonly used kind of update is the wrong 
>solution.
>
>We already have methods that work pretty well and, I think, read better 
>than the new methods:
>  mydict[key] += 1
>  mydict[key].append(value)
>The problem is merely that they don't work when key is missing, so we 
>need to resort to setdefault circumlocutions instead.  A better solution 
>seems to be the one I've seen suggested here several times, of changing 
>the dict's behavior so that the setdefault is automatic whenever trying 
>to access a missing key.  If this would be in a separate module or 
>separate subclass of dict, so much the better.


I think that the setdefault behavior needs to be done on an per
application basis because whose to say what default is best?.

With a preset default mode, it then becomes possible to  inadvertently
create default values that will cause problems without knowing it.  So
then we have to remember to change the setdefault value to None or
null to avoid problems.  Ouch!

Also pythons normal behavior for retrieving objects that are not
defined is to give an error.  So having dictionaries that auto
defaults to a mode that doesn't behave that way is inconsistent with
the rest of the language.

Yet,  I'm all for the creation of specialized containers in a standard
module!  :)  Then we can have string dicts, and int dicts, and card
dicts, account dicts, etc, as well as specialized lists.  Call them
'smart containers'.  But they should not be built into the base class.

Ron

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


exec src in {}, {} strangeness

2005-03-20 Thread Stefan Seefeld
hi there,
I have trouble running some python code with 'exec':
t.py contains:
class Foo: pass
class Bar:
f = Foo
From a python shell I do:
>>> f = ''.join(open('t.py').readlines())
>>> exec f in {}, {}
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 2, in ?
  File "", line 3, in Bar
NameError: name 'Foo' is not defined
However, when I use the current global and local scope, i.e.
simply 'exec f', everything works fine. What am I missing ?
Thanks,
Stefan
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to create stuffit files on Linux?

2005-03-20 Thread Greg Ewing
Leif K-Brooks wrote:
Noah wrote:
The problem is that my users want to see .sit files.
I know it's sort of silly. Zip files are foreign and frightening to
them.
Would Stuffit open zip files renamed to .sit?
Yes! I just tried it, and it works.
--
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
--
http://mail.python.org/mailman/listinfo/python-list


RE: IORCC Crossword and Wordfind Puzzles

2005-03-20 Thread iorcc
Hello Fellowist Rubyist (and scripters of all flavor)

Here is a neat Ruby-centric 84 word crossword puzzle.  To follow will
be the word find for solution words.  Its not too hard, but a good
strong search engine and some knowledge of Ruby helps.  I found all but
10 or so words/questions online.  Some are more obscurely worded and
hints are mostly available if you read the clues carefully.

   http://iorcc.dyndns.org/2005/puzzles/crossword/2005.xword.png

Q17 of the Official IORCC FAQ

   http://iorcc.dyndns.org/faq.html

spells out the prize setup for this little 'fun' sub-event.


Cheers,

Todd Nathan
IORCC Founder/Judge
irc://irc.freenode.net/iorcc (SeaForth)
http://iorcc.dyndns.org/ 
"What you talkin about Willis?" - GC

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


Python limericks (was Re: Text-to-speech)

2005-03-20 Thread Tim Churches
Steve Holden wrote:
> Tim Churches wrote:
>> There once was a language called Python...
>>
>> (which is pretty close to having three anapaestic left feet)
>>
>> or more promisingly, rhyme-wise, but metrically rather worse :
>>
>> There once was a mathematician named van Rossum...
>>
>> Tim C
>>
> Of course this last suggestion clearly has the wrong meter for a good
> limerick. 

I did say it was metrically worse...

> Not everyone knows the ingredients of a good limerick, which
> led to the following (which has been around in various forms since God
> was a lad):
> 
> There was a young man from Japan
> Who never quite learned how to scan.
>   He got on quite fine
>   Until the last line
> And then somehow he could never quite get the number of syllables
> right,or make it rhyme.

This page on meta-limericks is worth a look:
http://www.kith.org/logos/words/lower/l.html

> So, let's accept that the first line should scan correctly, that would
> make the following first lines acceptable:
> 
> A mathematician named Guido ...
> The inventor of Python, called Guido ...
> A mathematician (van Rossum) ...
> Van Rossum, inventor of Python ...
> 
> Hopefully that will begin to get the idea across.

The Wikipaedia page on limericks is also worth reading:
http://en.wikipedia.org/wiki/Limericks

> Since it's PyCon week, I will offer a prize of $100 to the best (in my
> opinion) limerick about Python posted to this list (with a Cc: to
> [EMAIL PROTECTED]) before midday on Friday. The prize money will be my
> own, so there are no other rules. I will post my judgment when the PyCon
> nonsense has died down a little, but the winner will be read before the
> entire PyCon audience. Get to it!

My first attempt (which does not scan properly):

A Dutch mathematician most prophetic,
Did invent a language, name herpetic.
  With design quite intelligent,
  And syntax mostly elegant,
Big ideas could be made non-hypothetic.

Tim C


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


PyPI errors?

2005-03-20 Thread Daniel Yoo

Does anyone know why PyPI's doesn't like my PKG-INFO file?  Here's
what I have:

##
mumak:~/work/aho/src/python/dist/ahocorasick-0.8 dyoo$ cat PKG-INFO 
Metadata-Version: 1.0
Name: ahocorasick
Version: 0.8
Summary: Aho-Corasick automaton implementation
Home-page: http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/
Author: Danny Yoo
Author-email: [EMAIL PROTECTED]
License: GPL
Download-URL: 
http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ahocorasick-0.8.tar.gz
Description: UNKNOWN
Platform: any
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU General Public License (GPL)
Classifier: Topic :: Text Editors :: Text Processing
##


Here's the error message I'm getting when I do a submit_form from the
PyPI web interface:

##
Internal Server Error

Traceback (most recent call last):
  File "/usr/local/pypi/lib/pypi/webui.py", line 115, in run
self.inner_run()
  File "/usr/local/pypi/lib/pypi/webui.py", line 408, in inner_run
getattr(self, action)()
  File "/usr/local/pypi/lib/pypi/webui.py", line 1148, in submit_pkg_info
self.validate_metadata(data)
  File "/usr/local/pypi/lib/pypi/webui.py", line 1284, in validate_metadata
map(versionpredicate.check_provision, data['provides'])
KeyError: provides
##


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


(",) Do You Want To Know For Sure You Are Going To Heaven?

2005-03-20 Thread Ron038548
http://www.want-to-be-sure.blogspot.com << Click On Link

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


Re: Overloaded Constructors?!?

2005-03-20 Thread Paul McGuire
>>Another way is to make two factory methods that
>>create instances of the class and do the correct initialization.

>I am sorry to be so tedious, but I am still quite a
>newbie in Python... could you please provide a very
>small example of your last sentence? Looks
>quite interesting...

See the recipe at this link.  It defines a basic constructor to create
Color objects using 3 integer args for red/green/blue, and a separate
staticmethod as a factory method to create a Color using a single
integer representing an RBG value.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223611

-- Paul
(This recipe was taken from a much larger sample for basic bitmap
drawing, which you will find at
http://www.geocities.com/ptmcg/python/index.html#bmp .)

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


Re: Import mechanism to support multiple Python versions

2005-03-20 Thread Greg Ewing
Nicolas Fleury wrote:
All my code in under a single package.  Is it possible to override the 
import mechanism only for modules under that package and sub-packages so 
that?:
Yes. A package module has a __path__ attribute to which
you can add additional directories to be searched for
submodules of that package. So in your package's
__init__.py you can do something like
  if sys.version == "2.4":
subdir = "python24"
  elif sys.version == "2.3":
subdir = "python23"
  __path__.append(os.path.join(os.path.basename(__file__, subdir)))
The directory structure is then
  yourpackage/
__init__.py
python23/
  cppmymodule.pyd   (2.3 version)
python24/
  cppmymodule.pyd   (2.4 version)
but at run time it will appear as though one version or
the other of cppmymodule is a direct submodule of
yourpackage.
--
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: printing anomaly

2005-03-20 Thread Erik Max Francis
Paul Rubin wrote:
What's the deal with this?
>>> print 3.2
3.2
>>> print [3.2]
[3.2002]
>>> 

Yes, I know that 3.2 isn't an exact binary fraction.  I'm wondering
why it's converted differently depending on whether it's in a list.
repr vs. str.  The str of the sequence types prints the repr of their 
contents.

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  History is a set of lies agreed upon.
  -- Napoleon Bonaparte
--
http://mail.python.org/mailman/listinfo/python-list


Re: printing anomaly

2005-03-20 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Paul Rubin  wrote:

> What's the deal with this?
> 
> >>> print 3.2
> 3.2
> >>> print [3.2]
> [3.2002]
> >>> 
> 
> Yes, I know that 3.2 isn't an exact binary fraction.  I'm wondering
> why it's converted differently depending on whether it's in a list.

That's intersting.  It looks like it's the difference between str() and 
repr():

>>> print str(3.2)
3.2
>>> print repr(3.2)
3.2002
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: printing anomaly

2005-03-20 Thread Delaney, Timothy C (Timothy)
Paul Rubin wrote:

> What's the deal with this?
> 
> >>> print 3.2
> 3.2
> >>> print [3.2]
> [3.2002]
> >>>
> 
> Yes, I know that 3.2 isn't an exact binary fraction.  I'm wondering
> why it's converted differently depending on whether it's in a list.

`print 3.2` == `print str(3.2)`.
`print [3.2]` == `print str([3.2])`.

list.str calls repr() on all elements. Partly, this is so that:

>>> print [3.2]
>>> print ['3.2']

don't have the same output. Otherwise, how could you tell (visually) if
an element was a string or a float (or integer, or whatever)?

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


Re: Lowest hassle Python web server?

2005-03-20 Thread Gerhard Häring
kanzen wrote:
I keep telling my friends that Python rocks. Now it's time to put my
money where my mouth is. I'm about to start writing a server for a
phone based game. It needs to handle simlpe requests from some Java
code running on the phone at a fairly low transaction rate. There will
also be a simple web site allowing users to edit preferences and so
forth. I have just enough Python experience to decide that I prefer it
over Java for this job. It'll be on a Linux box that I have full
control over.
I can see from FAQs that there are several possible ways of doing web
server work in Python, e.g. Twisted or mod_python in Apache, etc. So
I'm wondering:
- Could you recommend a solution you've found to be the most
convenient?
I've tested a few, and when it finally came that I wanted and needed to 
do web application development in Python for real, I decided to use 
Snakelets.

So far, I find it a very convenient way to write web applications. It's 
also very close to how Java servlets/JSP pages work.

FWIW, the other frameworks I've tested thoroughly were Quixote and WebWare.
- Does threading cause any more of a hassle in Python than Java?
- Is there anything similar to JSP in Java?
Snakelets Ypages come close to JSP.
-- Gerhard
--
http://mail.python.org/mailman/listinfo/python-list


printing anomaly

2005-03-20 Thread Paul Rubin
What's the deal with this?

>>> print 3.2
3.2
>>> print [3.2]
[3.2002]
>>> 

Yes, I know that 3.2 isn't an exact binary fraction.  I'm wondering
why it's converted differently depending on whether it's in a list.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overloaded Constructors?!?

2005-03-20 Thread Shalabh Chaturvedi
[EMAIL PROTECTED] wrote:
 Hello NG,
   I am trying to port a useful class from wxWidgets (C++) to a pure 
Python/wxPython
implementation. In the C++ source code, a unique class is initialized with
2 different methods (???). This is what it seems to me. I have this 
declarations:

The 2 different initializations refers to completely different objects (the
first one is a wx.Window, the second one is an horizontal line). 

Does anyone know if is there a way to achieve the same thing in Python/wxPython?
Someone else has talked about overloaded constructors, but I don't have
any idea on how to implement this kind of "constructors" in Python. Does
anyone have a small example of overloaded constructors in Python?
I have no idea... Or am I missing something obvious?
If you do have to do something like this you could use keyword arguments 
with defaults. For example:

class C(object):
def __init__(self, a=None, b=None):
if None not in (a, b):
raise some error (only one of a/b should be given)
if a:
   # do something
elif b:
   # do something else
Another way to do it is to use classmethods:
class C(object):
def __init__(self):
# do initialization
def create_one(cls, a):
obj = cls()
# do something with a
return obj
create_one = classmethod(create_one)
def create_two(cls, b):
obj = cls()
# do something with b
return obj
create_two = classmethod(create_two)
Then you can use it thus:
x = C.create_one(a='value')
y = C.create_two(b='value')
Because it is a classmethod, calling C.create_one('value') calls 
create_one() with two parameters:
- C
- 'value'

i.e. the first parameter is the class, not an instance of the class.
Hope this helped.
Shalabh

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


Re: [DB-SIG] Sybase module 0.37pre2 released

2005-03-20 Thread Dave Cole
Dave Cole wrote:
The module is available here:
http://www.object-craft.com.au/projects/sybase/download/sybase-0.37pre1.tar.gz 
Ooops.  Make that:
http://www.object-craft.com.au/projects/sybase/download/sybase-0.37pre2.tar.gz
- Dave
--
http://www.object-craft.com.au
--
http://mail.python.org/mailman/listinfo/python-list


Re: FAQ 1.7.3 : How can I have modules that mutually import each other

2005-03-20 Thread John Roth
Circular import dependencies don't work well; depending
on the exact conditions they can leave you pulling your  hair
out for hours. In your example, just pull the global variable
out into a third module and have both of your major
modules import and reference it from there.
In general, you should never have circular imports at
load time. There are three general ways of handling
the issue:
1. Redesign to eliminate the circular dependencies.
2. Put the classes with the circular dependencies in
  the same module.
3. Load the backlinks at run time.
I may be old fashioned, but I put all of the import
statements at the top of the module. Putting them
into the middle of functions obscures the structure
of the code, at least to my eyes. I'd rather have them
all in one place.
I've got a Java package (Fit Library) that I'm porting
to Python that has a number of very nasty circular
import dependencies that I can't structure out easily:
they're fundamental to the functionality. I'm taking
the "load at run time" option, which works well since
the basic FIT package has a very competent dynamic
loader.
However, all of this is kind of advanced functionality.
Most applications don't require that kind of mess.
John Roth



"MackS" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Hi
I'm new to Python, I've read the FAQ but still can't get the following
simple example working:
# file main_mod.py:
global_string = 'abc'
def main():
   import auxiliary_mod
   instance = auxiliary_mod.ClassA()
   instance.fun()
   return
main()
# file auxiliary_mod.py:
class ClassA:
 def fun(self):
   import main_mod
   print 'this is ClassA.fun() and global_string is ' +
main_mod.global_string
   return
In words, the problem is: I've a main module which defines a global
variable and instantiates a class defined in a second module, and a
method of that class needs to access the global variable defined in the
main module.
When I run main_mod.py the method is executed twice:
this is ClassA.fun() and global_string is abc
this is ClassA.fun() and global_string is abc
How can I avoid this problem even in this simple example? If I move the
import main_mod statement to the outside of the definion of ClassA I
get an exception:
Traceback (most recent call last):
 File "./main_mod.py", line 4, in ?
   import auxiliary_mod
 File "/manel/ewt/test/auxiliary_mod.py", line 4, in ?
   import main_mod
 File "/manel/ewt/test/main_mod.py", line 13, in ?
   main()
 File "/manel/ewt/test/main_mod.py", line 9, in main
   instance = auxiliary_mod.ClassA()
AttributeError: 'module' object has no attribute 'ClassA'
As far as I can tell I'm following the technique suggested by Guido
himself to handle mutual imports:
"Guido van Rossum recommends avoiding all uses of from  import
..., and placing all code inside functions. Initializations of global
variables and class variables should use constants or built-in
functions only. This means everything from an imported module is
referenced as .."
[http://www.python.org/doc/faq/programming.html]
How can I get this simple example to work?
Thank you for any help in advance,
Mack
--
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous copy to multiple media

2005-03-20 Thread Diez B. Roggisch
> Well, 430 MB/s is only for USB 2.0. AFAIK, most devices (esp. storage
> devices) are still only USB 1.1 compliant, which makes this rate go down
> to a mere 40 MB/s or something close.

I think it is 430 MBit(!), so about 50MB per second. The old usb 1.1 has
12MBits. So I don't think that Claudio could observe 15MByte/s with a 1.1
bus

> 
>> 4) with 45 MByte/s I could theoretically simultaneously
>> supply three separate data streams to three USB
>> controller writing with 15 MByte/s each out to the
>> external storage media.
> 
> No, you can't. As I said in response to point 2, it doesn't matter what
> kind of bus you use, when the bus isn't meant to do real "broadcasts" or
> can actually talk to several devices simultaneously because all wires are
> duplicated a corresponding number of times, there's always overhead when
> switching between the devices.

Well, if the bus is faster, it can (and does) use multiplexing. All busses
do that, apart from crossbar switches which have n:n point2point
connectivity.
> The bus must be acquired for communication with one device (so that the
> others won't simply go blabbering over the communication), then the data
> must be streamed, then the bus released again. This process takes time,
> and AFAIK, USB is pretty expensive (compared to data transmission speed)
> here, as USB guarantees that a packet reaches the endpoint when its
> transmitted over the wire (in the sense that it won't get lost because
> someone else was also talking). Now, when more devices come into play,
> this overhead becomes significant, and takes away quite some bandwith.

USB uses a host-based bus arbitration scheme where only the controller
decides who can talk when. So there is very limited bus arbitration
overhead. But of course this also means that the host has grant each
attached device bus time every now and then, as the device itself has no
chance of signalling data availability itself. So - that adds again some
overhead :)

In the end, I'm not sure what throughoutput is actually possible. As I said
to Claudio in a private mail: Apart from multithreaded writing to the bus
and _hoping_ that things speed up one can't do much - at least not in
python, and not without deep driver fiddling or even writing drivers
oneself.
-- 
Regards,

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


Re:[perl-python] a program to delete duplicate files

2005-03-20 Thread Xah Lee
Sorry i've been busy...

Here's the Perl code. I have yet to clean up the code and make it
compatible with the cleaned spec above. The code as it is performs the
same algorithm as the spec, just doesn't print the output as such. In a
few days, i'll post a clean version, and also a Python version, as well
a sample directory for testing purposes. (The Perl code has gone thru
many testings and is considered correct.)

The Perl code comes in 3 files as it is:

Combo114.pm
Genpair114.pm
del_dup.pl

The main program is del_dup.pl. Run it on the command line as by the
spec. If you want to actually delete the dup files, uncomment the
"unlink" line at the bottom. Note: the module names don't have any
significance.


Note: here's also these python files ready to go for the final python
version. Possibly the final propram should be just a single file...

Combo114.py
Genpair114.py


Here're the files: del_dup.zip
-
to get the code and full detail with latest update, please see:
http://xahlee.org/perl-python/delete_dup_files.html

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html


Claudio Grondi wrote:
> >> I'll post my version in a few days.
> Have I missed something?
> Where can I see your version?
> 
> Claudio

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


Re: Overloaded Constructors?!?

2005-03-20 Thread Michael Spencer
[EMAIL PROTECTED] wrote:
 [trying to create a single Python class with the equivalent of the following 
overloaded constructors]
wxFoldWindowItem(wxWindow *wnd, int flags = wxFPB_ALIGN_WIDTH,
 int ySpacing = wxFPB_DEFAULT_YSPACING,
 int leftSpacing = wxFPB_DEFAULT_LEFTSPACING, 
 int rightSpacing = wxFPB_DEFAULT_RIGHTSPACING)

or
wxFoldWindowItem(int y, const wxColour &lineColor = *wxBLACK, 
 int ySpacing = wxFPB_DEFAULT_YSPACING,
 int leftSpacing = wxFPB_DEFAULT_LEFTLINESPACING,
 int rightSpacing = wxFPB_DEFAULT_RIGHTLINESPACING)

Several options in addition to the factory function that Kent has suggested (and 
 I'll assume he'll follow up with clarification)

# Option 1: one abstract base class holding all/most of the methods, and two 
separate subclasses reflecting the two use-cases.

class _AbstractFoldWindowItem(object):
def __init__(self, *args, **kw):
raise NotImplemetedError
def
... all the shared methods
then
class FoldWindowItem(_AbstractFoldWindowItem):
def __init__(self, wxWindow, flags = wxFPB_ALIGN_WIDTH,
 ySpacing = wxFPB_DEFAULT_YSPACING,
 leftSpacing = wxFPB_DEFAULT_LEFTSPACING,
 rightSpacing = wxFPB_DEFAULT_RIGHTSPACING):
class FoldSeparator(_AbstractFoldWindowItem):
def __init__(self, y, lineColor = wx.BLACK,
 ySpacing = wx.FPB_DEFAULT_YSPACING,
 leftSpacing = wx.FPB_DEFAULT_LEFTLINESPACING,
 rightSpacing = wx.FPB_DEFAULT_RIGHTLINESPACING):
# Option 2: One class, two constructors:
class FoldWindowItem():
def __init__(self, wxWindow, flags = wxFPB_ALIGN_WIDTH,
 ySpacing = wxFPB_DEFAULT_YSPACING,
 leftSpacing = wxFPB_DEFAULT_LEFTSPACING,
 rightSpacing = wxFPB_DEFAULT_RIGHTSPACING):
"""Initializes with wxWindow"""
self._type = wx.Window
@classmethod
def FromSeparator(cls, y, lineColor = wx.BLACK,
 ySpacing = wx.FPB_DEFAULT_YSPACING,
 leftSpacing = wx.FPB_DEFAULT_LEFTLINESPACING,
 rightSpacing = wx.FPB_DEFAULT_RIGHTLINESPACING):
newobj = cls.__new__(y, lineColor = wx.BLACK,
 ySpacing = wx.FPB_DEFAULT_YSPACING,
 leftSpacing = wx.FPB_DEFAULT_LEFTLINESPACING,
 rightSpacing = wx.FPB_DEFAULT_RIGHTLINESPACING)
newobj._type = wx.SEPARATOR
# other initializatio
return newobj
This requires the user code to call the class in two ways depending on how it is 
to be used:

i.e., myFoldWindowItem = FoldWindowItem(Window)
or myFoldWindowItem = FoldWindowItem.FromSeparator(y)

# Option 3: inspect the arguments and provide the signature details in the 
docstring
class FoldWindowItem():
def __init__(self, obj, **kw):
"""Initialize with:
 wxWindow, flags = wxFPB_ALIGN_WIDTH,
 ySpacing = wxFPB_DEFAULT_YSPACING,
 leftSpacing = wxFPB_DEFAULT_LEFTSPACING,
 rightSpacing = wxFPB_DEFAULT_RIGHTSPACING)
or:
 y, lineColor = wx.BLACK,
 ySpacing = wx.FPB_DEFAULT_YSPACING,
 leftSpacing = wx.FPB_DEFAULT_LEFTLINESPACING,
 rightSpacing = wx.FPB_DEFAULT_RIGHTLINESPACING)"""
if isinstance(obj, wx.Window):
# Do one thing
elif isinstance(obj, wx.SEPARATOR):
# Do the other
HTH
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: HTML editor component?

2005-03-20 Thread Lars Heuer
Hi skol,

>>> Is there any HTML WYSIWYG editor component available for
>>> Python/wxPython? Thanks.
>>
>> There is wxMozilla: http://wxMozilla.sf.net/

> Thanks for the tip. Looks like a very elaborate component.
> Is there anything simpler? I'd need just simple HTML editing
> with formatting (bold, italic), links, and tables. 

You can use wxHTML for showing HTML and wxTextCtrl with (if I remember
right) the wxTE_RICHEDIT flag for editing.
Or the Scintilla component that should work for simple bold, italic
and link formating.
Tables might be difficult, though.

If you'll like to see wxMozilla Editor in action you may take a look
at http://www.eclass.net/

Best regards,
Lars
-- 
http://semagia.com

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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-20 Thread David Eppstein
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] (Aahz) 
wrote:

> >I am surprised nobody suggested we put those two methods into a
> >separate module (say dictutils or even UserDict) as functions:
> >
> >from dictutils import tally, listappend
> >
> >tally(mydict, key)
> >listappend(mydict, key, value)
> 
> That seems like a reasonable compromise.

The more messages I see on this thread, the more I think adding a 
different new method for each commonly used kind of update is the wrong 
solution.

We already have methods that work pretty well and, I think, read better 
than the new methods:
  mydict[key] += 1
  mydict[key].append(value)
The problem is merely that they don't work when key is missing, so we 
need to resort to setdefault circumlocutions instead.  A better solution 
seems to be the one I've seen suggested here several times, of changing 
the dict's behavior so that the setdefault is automatic whenever trying 
to access a missing key.  If this would be in a separate module or 
separate subclass of dict, so much the better.

-- 
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lowest hassle Python web server?

2005-03-20 Thread Adonis
kanzen wrote:
I keep telling my friends that Python rocks. Now it's time to put my
money where my mouth is. I'm about to start writing a server for a
phone based game. It needs to handle simlpe requests from some Java
code running on the phone at a fairly low transaction rate. There will
also be a simple web site allowing users to edit preferences and so
forth. I have just enough Python experience to decide that I prefer it
over Java for this job. It'll be on a Linux box that I have full
control over.
I can see from FAQs that there are several possible ways of doing web
server work in Python, e.g. Twisted or mod_python in Apache, etc. So
I'm wondering:
- Could you recommend a solution you've found to be the most
convenient?
- Does threading cause any more of a hassle in Python than Java?
- Is there anything similar to JSP in Java?
Thanks,
KanZen
You can look into CherryPy http://www.cherrypy.org/
Hope this helps
Adonis
--
http://mail.python.org/mailman/listinfo/python-list


Sybase module 0.37pre2 released

2005-03-20 Thread Dave Cole
WHAT IS IT:
The Sybase module provides a Python interface to the Sybase relational
database system.  It supports all of the Python Database API, version
2.0 with extensions.
NOTES:
This release contains a number of small bugfixes and patches received
from users.
I have been unable to find the source of the memory leak reported here:
http://www.object-craft.com.au/pipermail/python-sybase/2004-December/000346.html
The test program I wrote follows:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
import sys
import Sybase
db = Sybase.connect(..., auto_commit=True)
db.execute('''
if exists (select name from sysobjects where name = "sp_test_leak")
begin
drop procedure sp_test_leak
end
''')
db.execute('''
create procedure sp_test_leak
@arg int
as
select @arg
''')
for i in range(200):
for j in range(1000):
c = db.cursor()
c.callproc('sp_test_leak', {'@arg': 12345 })
sys.stdout.write('%3d\r' % i)
sys.stdout.flush()
sys.stdout.write('\n')
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If someone is able to modify this and come up with a leaking result I
am interested in working on the fix.
You can build for FreeTDS like this:
 python setup.py build_ext -D HAVE_FREETDS -U WANT_BULKCOPY
 python setup.py install
The module is available here:
http://www.object-craft.com.au/projects/sybase/download/sybase-0.37pre1.tar.gz
The module home page is here:
http://www.object-craft.com.au/projects/sybase/
CHANGES SINCE 0.36:
* Cursor state initialisation fix from Skip Montanaro.
* Callback declaration fix on Windows from Vadim Beloborodov.
* Cursor output parameters now work when parameters are passed as a
  sequence.
* Output parameters now work for FreeTDS 0.62.4.
1> create procedure sp_test_output
2> @num int, @result int output
3> as
4> select @result = @num
5> go
params = c.callproc('sp_test_output', {'@num': 12345,
   '@result': Sybase.OUTPUT(1)})
print params['@result']
* The CS_STATUS_RESULT result set is now consumed internally in the
  Cursor and does not appear in the result sets consumed by the fetch
  and nextset methods.
  The return value from the stored procedure is available in the
  .return_status member of the Cursor.  It will only contain a
  meaningful value once all of the row result sets have been consumed.
  Note that this does not work with FreeTDS 0.62.4.  The return_status
  seems to always be 0.  Research shows that the problem is probably
  in the CT emulation layer as tsql displays the correct value, but
  sqsh displays 0.
* Output hook patch from Ty Sarna has been applied.
* Applied patch from Andre Sedinin to improve error handling.
* Improved detection of SYBASE_OCS.
- Dave
--
http://www.object-craft.com.au
--
http://mail.python.org/mailman/listinfo/python-list


Re: Shell re-direction

2005-03-20 Thread Jeff Epler
buffering.

In the first case, there is either no buffering, or line buffering on
sys.stdout, so you see the lines in order.

In the second case, there is a buffer of a few hundred or thousand bytes
for stdout in the python process, and you see the two lines of python
output together (in this case, when the python process exits and flushes
all its buffers).

You can use the "flush" method on file objects to "clear out" these
buffers.

Jeff


pgpJceNYE0Rop.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: HTML editor component?

2005-03-20 Thread skol
"Lars Heuer" <[EMAIL PROTECTED]> wrote

>> Is there any HTML WYSIWYG editor component available for
>> Python/wxPython? Thanks.
>
> There is wxMozilla: http://wxMozilla.sf.net/

Thanks for the tip. Looks like a very elaborate component.
Is there anything simpler? I'd need just simple HTML editing
with formatting (bold, italic), links, and tables. 


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


Re: How to create an object instance from a string??

2005-03-20 Thread Max M
Tian wrote:
How can I create an instance of an object from a string?
For example, I have a class Dog:

class Dog:
def bark(self):
print "Arf!!!"
def Factory(class_name):
classes = {
'Dog':Dog
}
return classes[class_name]
dog = Factory('Dog')()
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Shell re-direction

2005-03-20 Thread Mike Gould
Hi all,
I have a very strange problem with the output run from commands run via 
os.system().  If the python script is run without re-direction the 
output appears as expected, but if I re-direct the output from the 
script the output gets re-ordered.

For example given the following script:
import os
print '1'
os.system('echo 2')
print '3'
$ python test.py
1
2
3
$ python test.py | cat
2
1
3
Can anyone explain what's going on here?
Thanks
Mike
--
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous copy to multiple media

2005-03-20 Thread Jacek Trzmiel

Claudio Grondi wrote:
> I am on a Widows 2000 box using the NTFS file system.
> Both up to now suggested approaches as
> - tee.exe (where I used the http://david.tribble.com/dos/tee.exe
> DOS-port with redirecting stdout to NULL) and
> - parallel copy (hoping caching does the job) are by far
> slower than the consecutive copy:
>   single copy speed 12-15 MByte/s
> which gives effectively
>   6-7 MByte/s,
>   tee.exe or twice copy in parallel
>   1-3 MByte/s.
> 
> Any other suggestions except writing an own
> optimised version of tee.exe

Try this:
  http://mastermind.com.pl/multicopy/

This is small tool I've wrote, that does use large memory buffers with
asynchronous I/O to copy file.  

Following command:
  multicopy c:\testfile d:\testfile e:\testfile f:\testfile
will copy c:\testfile to d, e and f disks.

With four separate IDE disks I can copy file at about 30MB/s, which
means 120MB/s total I/O.  You can give it a try, but I don't know if it
will work fast with USB drives.

HTH,
sc0rp.
-- 
http://mail.python.org/mailman/listinfo/python-list


I'm just an idiot when it comes logging

2005-03-20 Thread olsongt
I'm trying to be a good boy and use the logging module but it's
behaving rather counter-intuitively.  I've posted a simplified test
script below.

To summarize, I've set the basic config to only log root level messages
with >= ERROR level.  I've created another named logger that logs on
info level.  I've set it up so it just shows the message text without
"INFO:: logger:" boilerplate.

The way I see things, when I call otherLogger.info, it should propogate
the message to the root logger, but the root logger should discard it
since it is at ERROR level.

Could someone explain what I'm not getting?

-Grant

###
### logging_test.py
###

import logging

logging.basicConfig(level=logging.ERROR)

root = logging.getLogger('')

otherLogger = logging.getLogger("logger")
otherLogger.setLevel(logging.INFO)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter("%(message)s")
console.setFormatter(formatter)

otherLogger.addHandler(console)

root.info("Shouldn't print") # lower level
root.error("Should Print") #higher level

otherLogger.info("Should only print once")

root.info("Shouldn't print") # lower level

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


Re: HTML editor component?

2005-03-20 Thread Lars Heuer
Hi skol,

> Is there any HTML WYSIWYG editor component available for
> Python/wxPython? Thanks. 

There is wxMozilla: http://wxMozilla.sf.net/

Best regards,
Lars
-- 
http://semagia.com

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


Overloaded Constructors?!?

2005-03-20 Thread andrea_gavana
Hello Kent,

   thank you a lot for your answer. I was starting to think that my question
was a little bit strange to obtain an answer...

>This is a strange design. My first reaction is, why do you want to do that?
Maybe you >should split the class in two?

You are right. The problem is that this is not my code. Someone else has
written it and, since it is a useful widget to have in a wxPython GUI, I
was trying to port it to Python. I don't want to mess with things like SWIG,
because this widget (compiled in C++) is not portable through all platforms,
while pure Python code should be.
I could split the class in two, but I would like to keep the class/functions
definitions as closer as possible to the original one.

>Next, there
>> are a lot of functions that, depending on the variable _type, return
properties
>> of the wx.Window or of the line. I would like to keep the same names
for
>> classes/methods, so it would be useful to have the same class with 2
different
>> "initializations".

>One way to do this in Python is to have a single constructor that looks
at the type / >number of arguments to figure out what it is supposed to
do.

I am trying to figure it out using something like:

def __init__(self, parent, **kw):

and processing the keyword args, but it does not satisfy me very much...

>Another way is to make two factory methods that
>create instances of the class and do the correct initialization.

I am sorry to be so tedious, but I am still quite a newbie in Python...
could you please provide a very small example of your last sentence? Looks
quite interesting...

Thank you a lot.

Andrea.



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


Re: Lowest hassle Python web server?

2005-03-20 Thread Peter Hansen
kanzen wrote:
- Does threading cause any more of a hassle in Python than Java?
What hassles have you had?  I thought threads in Java
were pretty straightforward.  In any case, in Python
they are generally very easy to use, provided you have
a basic knowledge of thread safety issues and/or provided
you restrict all interaction between threads to use
the Queue module.
- Is there anything similar to JSP in Java?
Snakelets?  Google will find it for you.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: getting text from WinXP console

2005-03-20 Thread Peter Hansen
Chris Rebert (cybercobra) wrote:
You want the function raw_input().
Have you read the tutorial? I should have been covered there.
I'm pretty sure he's looking for a means of capturing
the entire contents of a console window, not just
letting the user enter some textual input.
To the OP: this is an OS-specific question, not a
Python question, and although you have a good chance
of getting an answer from someone here, your
chances are even higher if you ask in some Windows
newsgroup or mailing list.  (But let us know when you
find the answer, in any case, for the archives.)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


HTML editor component?

2005-03-20 Thread skol
Is there any HTML WYSIWYG editor component available for
Python/wxPython? Thanks. 


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


Re: simultaneous copy to multiple media

2005-03-20 Thread Heiko Wundram
Am Sonntag, 20. März 2005 23:16 schrieb Claudio Grondi:
> 2) if I understand it right, an USB controller is connected to
> to the PCI bus and there can be many separate USB
> controller on one PC

Yes, there may be more than one USB-controller in a PC, but this doesn't 
matter, they are all connected to the same bus (the PCI bus). This is a 
parallel bus, but also a bus which can only serve a single endpoint at a 
time. The frequency is normally 66 Mhz, so you get a theoretical 66*32 Mb/s 
over the PCI bus.

But, this is only theoretical usage. Consider the EIDE-controller trying to 
write data into DMA memory which it has read from disk. It has to do the 
following to communicate with memory:

1) signal the DMA chip (which is also a device on the PCI bus) that it has 
data. This implies grabbing the PCI bus, making sure noone else is talking at 
the moment.

2) pass the data, 32 bit at a time, to the DMA chip, which places this data 
into main memory.

3) you may not grab the bus too long, as other devices might also want to 
communicate with some other device (e.g. the PIC, to signal an interrupt to 
the CPU). Thus, you have to free the bus after some time, and you have to 
forcibly give free the bus when some other device signals an interrupt. This 
also means starting transmission again after the bus has been successfully 
reacquired.

4) finally, after communication with the DMA-chip is done, signal the PIC via 
an interrupt that you wish the CPU to be signaled that it should do a 
software interrupt, so that the OS interrupt handler can be scheduled and can 
take the data from the DMA region (and do something with it).

Now, even when the bus is fast, setting it up all still takes time, so you 
never get the theoretical throughput you might wish to see.

Accessing the USB controller does the game the other way around; the OS uses 
the DMA-chip to stream the data onto the PCI bus for the controller to 
transmit.

So, overall, adding more USB controllers to your PC only adds extra throughput 
until you reach the top limit of PCI (when the controllers start stealing 
bandwith from each other).

> 3) the theoreticall speed of USB (430 MByte/s?) is much
> higher as the experienced 15 MByte/s, probably due to slow
> controller on the side of the external storage media, so
> maybe even on one USB line I will have the chance to
> use it full capacity connecting many slow devices
> (I can't imagine, that USB goes down with the speed to
> the speed of the slowest component connected, does it?)

Well, 430 MB/s is only for USB 2.0. AFAIK, most devices (esp. storage devices) 
are still only USB 1.1 compliant, which makes this rate go down to a mere 40 
MB/s or something close.

> 4) with 45 MByte/s I could theoretically simultaneously
> supply three separate data streams to three USB
> controller writing with 15 MByte/s each out to the
> external storage media.

No, you can't. As I said in response to point 2, it doesn't matter what kind 
of bus you use, when the bus isn't meant to do real "broadcasts" or can 
actually talk to several devices simultaneously because all wires are 
duplicated a corresponding number of times, there's always overhead when 
switching between the devices.

The bus must be acquired for communication with one device (so that the others 
won't simply go blabbering over the communication), then the data must be 
streamed, then the bus released again. This process takes time, and AFAIK, 
USB is pretty expensive (compared to data transmission speed) here, as USB 
guarantees that a packet reaches the endpoint when its transmitted over the 
wire (in the sense that it won't get lost because someone else was also 
talking). Now, when more devices come into play, this overhead becomes 
significant, and takes away quite some bandwith.

For example, Ethernet takes another way. Ethernet simply says: when I have 
data which is transmitted while someone else was talking, throw away the 
resulting mess (a collision, remember those cool blinking lights on hubs?). 
Someone will retransmit it if it was important.

> 5) watching the low CPU usage while writing to USB
> shows me, that CPU-time is not a problem.

No, it most certainly isn't. That's why modern computers always use a DMA-chip 
to do the heavy work of dealing with the hardware on external busses... ;)

> P.S. Your message appears in my Outlook Express
> as one having no content, but an attachment, so I can't
> read it directly.

Err, that's pretty strange. I can read my KMail written emails in pretty much 
any client that I have access to... So I guess this is a problem with Outlook 
Express not understanding MIME correctly, and not a problem on my side... ;) 
And, don't worry, I won't switch to -mode now. ;)

-- 
--- Heiko.


pgp6Uj3A40bZ4.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: For loop extended syntax

2005-03-20 Thread George Sakkis
"Heiko Wundram" <[EMAIL PROTECTED]> wrote:

> Am Sonntag, 20. März 2005 22:22 schrieb George Sakkis:
> > Once more, the 2D/3D example was just that, an example; my point was not to
> > find a specific solution to a specific problem.
>
> And my point being: it's simple enough to give a general recipe (which my
> example was) without extending Python's syntax, so why extend the syntax and
> not just use a solution derived from that recipe that's working now (and is
> backwards compatible at least to 2.3), and which is also clear in itself?
>
> I'm not saying that your syntax looks "strange" or "bad", but there are means
> to do what you want to do now, without cumbersome syntax or duplicating code,
> and as such I'm -1 on syntactic sugar (TOWTDI and all)...
>
> Don't take this the wrong way, but I think introducing syntax is the wrong
> solution to a non-existant problem with the language.

The way I see it, it's closer to applying existing syntax (from function 
signatures) in a new
context than introducing new syntax, but that's a detail. I guess it's a matter 
of personal
preference to syntactic sugar then. Still, python is rife with syntactic sugar: 
iterators, default
function arguments, *varargs, **kwdargs, [list]/(tuple)/{dict} literals, 
recently @decorators, and
more. If syntactic sugar didn't matter, we would be happy with scheme's syntax.

George


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


Re: Overloaded Constructors?!?

2005-03-20 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 Hello NG,
   I am trying to port a useful class from wxWidgets (C++) to a pure 
Python/wxPython
implementation. In the C++ source code, a unique class is initialized with
2 different methods (???). This is what it seems to me. I have this 
declarations:
class wxFoldWindowItem
{
// wxWindow constructor. This initialises the class as a wxWindow type
wxFoldWindowItem(wxWindow *wnd, int flags = wxFPB_ALIGN_WIDTH, int ySpacing
= wxFPB_DEFAULT_YSPACING,
 int leftSpacing = wxFPB_DEFAULT_LEFTSPACING, int 
rightSpacing
= wxFPB_DEFAULT_RIGHTSPACING)
: _wnd(wnd)
, _type(WINDOW)
, _flags(flags)
, _leftSpacing(leftSpacing)
, _rightSpacing(rightSpacing)
, _ySpacing(ySpacing)
, _lineWidth(0)
, _lineY(0)
{
};
// separator constructor. This initialises the class as a separator
type
wxFoldWindowItem(int y, const wxColour &lineColor = *wxBLACK, int ySpacing
= wxFPB_DEFAULT_YSPACING,
 int leftSpacing = wxFPB_DEFAULT_LEFTLINESPACING,
 int rightSpacing = wxFPB_DEFAULT_RIGHTLINESPACING)
: _wnd(0)
, _type(SEPARATOR)
, _flags(wxFPB_ALIGN_WIDTH)
, _leftSpacing(leftSpacing)
, _rightSpacing(rightSpacing)
, _ySpacing(ySpacing)
, _lineWidth(0)
, _lineY(y)
, _sepLineColour(lineColor)
{
};
The 2 different initializations refers to completely different objects (the
first one is a wx.Window, the second one is an horizontal line). 
This is a strange design. My first reaction is, why do you want to do that? Maybe you should split 
the class in two?

Next, there
are a lot of functions that, depending on the variable _type, return properties
of the wx.Window or of the line. I would like to keep the same names for
classes/methods, so it would be useful to have the same class with 2 different
"initializations".
One way to do this in Python is to have a single constructor that looks at the type / number of 
arguments to figure out what it is supposed to do. Another way is to make two factory methods that 
create instances of the class and do the correct initialization.

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


Re: simultaneous copy to multiple media

2005-03-20 Thread Diez B. Roggisch
> 
> Nope. Or yes. Here comes into play why Heiko said think of what USB stands
> for. While the devices appear to be responsive concurrently (the bus
> arbitration and multiplexing/demultiplexing is tranparent to the user), it
> still is  a serial bus, so at a given point in time you can only write to
> _one_ device. And if that device is limited in its speed, you're doomed.
> The only thing I could imagine is that if you send small bursts that don't
> make the write cache full, it _might_ be possible to switch fast between
> the devices and thus write the data faster, as the devices can try and
> write the data to disk while the others are feeded.


I had second thoughts of this, and have to admit that I don't make too much
senes here. So ignore that. 
 
> But I'm on no sure ground here with that assumption, and it certainly
> would depend on how the usb-ata-controller deals with that. You said
> yourself that you only had 15MB/sec, so it doesn't look to good.
> 
> To make this work would certainly be a deep lowlever driver hack and
> nowhere in the scope of python per se.
> 

-- 
Regards,

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


Re: Building Time Based Bins

2005-03-20 Thread alessandro -oggei- ogier
MCD wrote:
> This goes on throughout a 12hr. period. I'd like to be able to place
> the low and high values of the additional fields in a single line
> divided into 5min intervals. So it would look something like this >>
> 
> 1235 22 88
> 1240 31 94

what about a sane list comprehension madness ? 

lines = """\
1231 23 56
1232 25 79
1234 26 88
1235 22 34
1237 31 85
1239 35 94
"""

input = lines.split('\n') # this is your input

div = lambda x: (x-1)/5

l = dict([
(div(x), []) for x,y,z in [
tuple([int(x) for x in x.split()]) for x in input if x
]
])

[
l[x[0]].append(x[1]) for x in
[
[div(x), (x,y,z)] for x,y,z in
[
tuple([int(x) for x in x.split()]) for x in input if x
]
]
]

print [
[max([x[0] for x in l[j]]),
 min([x[1] for x in l[j]]),
 max([x[2] for x in l[j]])
] for j in dict([
(div(x), []) for x,y,z in [
tuple([int(x) for x in x.split()]) for x in input
if x
]
  ]).keys()
]


i think it's a bit memory hungry, though

cya,
-- 
Alessandro "oggei" Ogier <[EMAIL PROTECTED]>
gpg --keyserver pgp.mit.edu --recv-keys EEBB4D0D


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


Re: Software for Poets (Was: Re: Text-to-speech)

2005-03-20 Thread Paul Rubin
Francis Girard <[EMAIL PROTECTED]> writes:
> 4- Propose a synonym that will fit in a verse, i.e. with the right amount of 
> syllabs
> 
> 5- Suggest a missing word or expression in a verse by applying the Shannon 
> text generation principle
> ...
> First, do you think it may be a useful tool ?
> What other features you think can make it usefull for a poet ?

I'm skeptical of this notion.  You can think of writing a poem as
building up a tree structure where there's a root idea you're trying
to express, "branches" in the choices of images/comparisons/etc. that
you use to express the idea, and "leaves" that are the actual words in
the poem.  Rhyme means that a left-to-right traversal of the leaves
(i.e. reading the words) results in a pattern with a certain
structure.  You're proposing a tool that helps explore the search
space in the nodes near the bottom level of the tree, to find words
with the right characteristics.

I think the constraint of rhyme and meter is best served by widening
the search space at the upper levels of the tree and not the lower
levels.  That is, if you've got an image and you don't find rhyming
words for it with easy natural diction, a computerized search for more
and more obscure words to express that image in rhyme is the last
thing you want.  Rather, you want to discard the image and choose a
different one to express the idea.  That means seeking more images by
mentally revisiting and staying inside the emotion at the center of
poem, a much more difficult thing to do than solving the mere math
problem of finding a string of rhyming words with similar semantics to
a non-rhyming sequence that you already have.  But when you find the
right image, the words and rhythm fall into place without additional
effort.

This is why writing good poems is hard, and is also why the results of
doing it well is powerful.  I don't think it can be programmed into a
computer using any current notions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python scope is too complicated

2005-03-20 Thread Ivan Van Laningham
Hi All--

Dan Bishop wrote:
> 
> > """In Python, there are only two scopes.  The global and the local.
> > The global scope is a dictionary while the local, in the case of a
> > function is extremely fast.  There are no other scopes.
> 
> This isn't true anymore, now that generator comprehensions have been
> added to the language.
> 
> >>> x = 17
> >>> sum(x for x in xrange(101))
> 5050
> >>> x
> 17
> 

The equivalent in list comprehensions which currently allows the x to
leak out into its containing scope is going away soon.  Will that be
another scope?  Or are generator and list comprehensions only one scope?

Metta,
Ivan
--
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
-- 
http://mail.python.org/mailman/listinfo/python-list


Lowest hassle Python web server?

2005-03-20 Thread kanzen
I keep telling my friends that Python rocks. Now it's time to put my
money where my mouth is. I'm about to start writing a server for a
phone based game. It needs to handle simlpe requests from some Java
code running on the phone at a fairly low transaction rate. There will
also be a simple web site allowing users to edit preferences and so
forth. I have just enough Python experience to decide that I prefer it
over Java for this job. It'll be on a Linux box that I have full
control over.

I can see from FAQs that there are several possible ways of doing web
server work in Python, e.g. Twisted or mod_python in Apache, etc. So
I'm wondering:

- Could you recommend a solution you've found to be the most
convenient?
- Does threading cause any more of a hassle in Python than Java?
- Is there anything similar to JSP in Java?

Thanks,
KanZen

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


Re: getting text from WinXP console

2005-03-20 Thread Chris Rebert (cybercobra)
You want the function raw_input().
Have you read the tutorial? I should have been covered there.

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


Re: Software for Poets (Was: Re: Text-to-speech)

2005-03-20 Thread Charles Hartman
On Mar 20, 2005, at 4:10 PM, Francis Girard wrote:
Hello M. Hartman,
It's a very big opportunity for me to find someone that both is a poet 
and
knows something about programming.

First, please excuse my bad english ; I'm a french canadian.
My French is a great deal worse than your English; fear not.
I am dreaming to write a software to help french poets to write strict
rigourous classical poetry. Since calssical poetry is somewhat 
mathematical,
a lot of tasks can be automatised :

1- Counting the number of syllabs ("pied" in french) in a verse
2- Checking the rimes ; determining the strength of a rime
3- Checking compliance of a poem to a fixed pre-determined classical 
form (in
french, we have distique, tercet, quatrain, quintain, sixain, huitain,
dizain, triolet, vilanelle, rondeau, rondel, ballade, chant royal, 
sonnet,
etc.)

4- Propose a synonym that will fit in a verse, i.e. with the right 
amount of
syllabs

5- Suggest a missing word or expression in a verse by applying the 
Shannon
text generation principle

First, do you think it may be a useful tool ?
That is a very deep question. (See below.)
What other features you think can make it usefull for a poet ?
The first task of cutting sentences into syllabs (phonetically of 
course, not
typographically) is already done. It's been difficult to get it right 
and to
make it guess correctly with a very very high percentage.

I can very well imagine that the next task is even more difficult. I 
need to
translate text into phonems. Do you know some software that does it ? 
I guess
that voice synthetisers that translates written text into spoken text 
must
first translate the text into phonems. Right ? Do you know if there 
some way
that I can re-use some sub-modules from these projects that will 
translate
text into phonems ?
The problems are hard ones. Getting reliable syllable divisions is, all 
by itself, a heart-breaker in English; I'm not sure whether harder or 
easier in French. (See the module syllables.py in the source code to my 
Scandroid program at the site listed below.)

Rhyme is harder -- I haven't yet tried it in English -- precisely 
because text-to-phoneme is very hard.

I haven't really worked with this, that is, with the sounds of speech 
(though I'm a musician as well as a poet), mostly because it's 
difficult. The projects in my *Virtual Muse: Experiments in Computer 
Poetry"[1], for example, deal almost entirely with language as a 
typographical phenomenon. So does my Scandroid, even though the 
material it's working with is all aimed at and motivated by the 
auditory qualities of poetry.

I do imagine you're right that the text-to-speech people have worked 
out a lot of this. The trouble is that so far I haven't seen 
public-domain code for the guts of such a program, which is what you 
would need.

Interesting to think about which problems change between French and 
English and which do not.

Good luck -- keep me posted.
[1] This was published by Wesleyan Univ Press, what, nine years ago. 
Probably out of print. I do know where to get some copies.

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


Re: RotatingFileHandler and logging config file

2005-03-20 Thread Vinay Sajip
Rob Cranfill wrote:
NID (No, It Doesn't)  ;-)  but thanks anyway. To reiterate, the question 
is how to make RotatingFileHandler do a doRotate() on startup from a 
*config file*. No mention of that in what you point to.
I don't think that RotatingFileHandler *should* be configurable to do a 
doRollover() on startup. I would follow up the suggestion of using your 
own derived class. The config mechanism will allow you to instantiate 
custom handlers - you only have to take into account (as an earlier 
poster has indicated) how the evaluation of the handler class (and its 
constructor arguments) is performed.

BTW - constructor is not just for Java, but C++ too (not to mention C#).
Vinay Sajip
--
http://mail.python.org/mailman/listinfo/python-list


(",) Do You Want To Know For Sure You Are Going To Heaven?

2005-03-20 Thread Ron038548
http://www.want-to-be-sure.blogspot.com << Click On Link

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


Re: Python scope is too complicated

2005-03-20 Thread Dan Bishop
jfj wrote:
> Max wrote:
> > Yeah, I know. It's the price we pay for forsaking variable
declarations.
> > But for java programmers like me, Py's scoping is too complicated.
> > Please explain what constitutes a block/namespace, and how to refer
to
> > variables outside of it.
>
>
> Some may disagree, but for me the easiest way to understand python's
> scopes is this:
>
> """In Python, there are only two scopes.  The global and the local.
> The global scope is a dictionary while the local, in the case of a
> function is extremely fast.  There are no other scopes.

This isn't true anymore, now that generator comprehensions have been
added to the language.

>>> x = 17
>>> sum(x for x in xrange(101))
5050
>>> x
17

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


Re: simultaneous copy to multiple media

2005-03-20 Thread Diez B. Roggisch
> 2) if I understand it right, an USB controller is connected to
> to the PCI bus and there can be many separate USB
> controller on one PC

True.

> 3) the theoreticall speed of USB (430 MByte/s?) is much
> higher as the experienced 15 MByte/s, probably due to slow
> controller on the side of the external storage media, so
> maybe even on one USB line I will have the chance to
> use it full capacity connecting many slow devices
> (I can't imagine, that USB goes down with the speed to
> the speed of the slowest component connected, does it?)

Nope. Or yes. Here comes into play why Heiko said think of what USB stands
for. While the devices appear to be responsive concurrently (the bus
arbitration and multiplexing/demultiplexing is tranparent to the user), it
still is  a serial bus, so at a given point in time you can only write to
_one_ device. And if that device is limited in its speed, you're doomed.
The only thing I could imagine is that if you send small bursts that don't
make the write cache full, it _might_ be possible to switch fast between
the devices and thus write the data faster, as the devices can try and
write the data to disk while the others are feeded. 

But I'm on no sure ground here with that assumption, and it certainly would
depend on how the usb-ata-controller deals with that. You said yourself
that you only had 15MB/sec, so it doesn't look to good.

To make this work would certainly be a deep lowlever driver hack and nowhere
in the scope of python per se.

> 4) with 45 MByte/s I could theoretically simultaneously
> supply three separate data streams to three USB
> controller writing with 15 MByte/s each out to the
> external storage media.

That might be the case if you use three real separate controllers. But that
will depend on how the OS deals with these, if you really achieve the
theoretical throughoutput.

> 5) watching the low CPU usage while writing to USB
> shows me, that CPU-time is not a problem.

That is certainly true - the bottleneck are the buses.

-- 
Regards,

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


Re: Text-to-speech

2005-03-20 Thread Charles Hartman
-- or ". . . a guru named Guido / (Who monitors everything we do) /"  
and ending with something about "looking max in a Speedo," but  
fortunately it's not coming to me at the moment.

The closest I have an answer to your questions about Python and poetry  
(aside from the Scandroid) is a book called *Virtual Muse: Experiments  
in Computer Poetry* which Wesleyan published something close to ten  
years ago; I don't think it's out of print yet, but I don't keep good  
track. It was out of a casual remark there (about a very primitive  
program not even directly talked about in the boolk) that there came a  
casual remark from a reader last year which led to the Scandroid.

Charles Hartman
"The time has come for someone to put his foot down; and that foot is  
me." --Animal House

On Mar 20, 2005, at 2:10 AM, Tim Churches wrote:
Charles Hartman wrote:
Does anyone know of a cross-platform (OSX and Windows at least)  
library
for text-to-speech? I know  there's an OSX API, and probably also for
Windows. I know PyTTS exists, but it seems to talk only to the Windows
engine. I'd like to write a single Python module to handle this on  
both
platforms, but I guess I'm asking too much -- it's too hardware
dependent, I suppose. Any hints?

Charles Hartman
Professor of English, Poet in Residence
http://cherry.conncoll.edu/cohar
No, but I do wonder how many other users of Python are
poets-in-residence, or indeed, published poets?
And congratulations on the release of Scandroid Version 1.0a (written  
in
Python) on 18.iii.05 (as you elegantly record it).

All this begs the question: Have any poems been written in Python
(similar to the well-known Perl Poetry (see
http://directory.google.com/Top/Computers/Programming/Languages/Perl/ 
Poetry/
)?

Indeed, have any poems ever been written about Python - other than "The
Zen of Python" by Tim Peters? A limerick, even?
There once was a language called Python...
(which is pretty close to having three anapaestic left feet)
or more promisingly, rhyme-wise, but metrically rather worse :
There once was a mathematician named van Rossum...
Tim C
--
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-20 Thread Heiko Wundram
Am Sonntag, 20. März 2005 22:22 schrieb George Sakkis:
> Once more, the 2D/3D example was just that, an example; my point was not to
> find a specific solution to a specific problem.

And my point being: it's simple enough to give a general recipe (which my 
example was) without extending Python's syntax, so why extend the syntax and 
not just use a solution derived from that recipe that's working now (and is 
backwards compatible at least to 2.3), and which is also clear in itself?

I'm not saying that your syntax looks "strange" or "bad", but there are means 
to do what you want to do now, without cumbersome syntax or duplicating code, 
and as such I'm -1 on syntactic sugar (TOWTDI and all)...

Don't take this the wrong way, but I think introducing syntax is the wrong 
solution to a non-existant problem with the language.

-- 
--- Heiko.


pgpKzqC7Aa4ue.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Limerick (was: Re: Text-to-speech)

2005-03-20 Thread Jeremy Bowers
On Sun, 20 Mar 2005 16:18:14 -0500, Steve Holden wrote:
> Since it's PyCon week, I will offer a prize of $100 to the best (in my 
> opinion) limerick about Python posted to this list (with a Cc: to 
> [EMAIL PROTECTED]) before midday on Friday. The prize money will be my 
> own, so there are no other rules. I will post my judgment when the PyCon 
> nonsense has died down a little, but the winner will be read before the 
> entire PyCon audience. Get to it!
> 
> regards
>   Steve

Practicality beats purity,
Errors should never pass silently.
Sparse is better than dense,
Flat is better than nest,
Beautiful is better than ugly.

No cc because A: I'm not really serious and B: Tim Peters would have to
get some credit for that. :-) Probably ought to add a C: While I think
that does mostly rhyme, it is pretty loose; not much source material to
work with.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Text-to-speech

2005-03-20 Thread jamesthiele . usenet
On some flavors of Windows you can use:
import pyTTS

tts = pyTTS.Create()
tts.Speak('This is the sound of my voice.')

On Mac OS X you can use:
import os

os.system("say 'This is the sound of my voice.'")

You could write a wrapper that takes a string and checks to see which
OS you are on and executes the appropriate of the two above choices.
But you probably need something slicker, and I don't know what that
might be.

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


Re: For loop extended syntax

2005-03-20 Thread George Sakkis
"Heiko Wundram" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>
> On Sunday 20 March 2005 20:47, George Sakkis wrote:
> > Not always. Say for example that you're doing some 2D geometry stuff, and
> > later you have to extend it to 3D. In this case you may have to deal with
> > both 2D and 3D objects, and map the former to the latter when necessary.
>
> But this rather sounds like you'd want an adaptor iterator, like the
> following:
>
> >>> class AdaptPossible2D(object):
> ...   def __init__(self,data):
> ... self.data = data
> ...   def __iter__(self):
> ... for item in self.data:
> ...   if len(item) == 2:
> ... yield item+(0,)
> ...   else:
> ... yield item
> ...
> >>> for x,y,z in AdaptPossible2D([(1,2),(1,2,3),(3,4)]):
> ...   print x,y,z
> ...
> 1 2 0
> 1 2 3
> 3 4 0
>
> Using the above code makes it absolutely clear what you want, and doesn't need
> any new syntax which can be ambiguous like (x=0,y,z=0), etc. The above idiom
> also takes only constant extra space, as it doesn't duplicate the list during
> iteration.


Once more, the 2D/3D example was just that, an example; my point was not to 
find a specific solution
to a specific problem. Extending the "for .. in" syntax would be an elegant way 
to express this idea
in a more succint, familiar and generic way than a customized adaptor. As for 
the ambiguity, it is
not more ambiguous than function signatures as long as all keyword arguments go 
after all the
required ones; I'm not suggesting that (x=0,y,z=0) should be valid.

George


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


Re: Text-to-speech

2005-03-20 Thread Steve Holden
Tim Churches wrote:
Charles Hartman wrote:
Does anyone know of a cross-platform (OSX and Windows at least) library
for text-to-speech? I know  there's an OSX API, and probably also for
Windows. I know PyTTS exists, but it seems to talk only to the Windows
engine. I'd like to write a single Python module to handle this on both
platforms, but I guess I'm asking too much -- it's too hardware
dependent, I suppose. Any hints?
Charles Hartman
Professor of English, Poet in Residence
http://cherry.conncoll.edu/cohar

No, but I do wonder how many other users of Python are
poets-in-residence, or indeed, published poets?
And congratulations on the release of Scandroid Version 1.0a (written in
Python) on 18.iii.05 (as you elegantly record it).
All this begs the question: Have any poems been written in Python
(similar to the well-known Perl Poetry (see
http://directory.google.com/Top/Computers/Programming/Languages/Perl/Poetry/
)?
Indeed, have any poems ever been written about Python - other than "The
Zen of Python" by Tim Peters? A limerick, even?
There once was a language called Python...
(which is pretty close to having three anapaestic left feet)
or more promisingly, rhyme-wise, but metrically rather worse :
There once was a mathematician named van Rossum...
Tim C
Of course this last suggestion clearly has the wrong meter for a good 
limerick. Not everyone knows the ingredients of a good limerick, which 
led to the following (which has been around in various forms since God 
was a lad):

There was a young man from Japan
Who never quite learned how to scan.
  He got on quite fine
  Until the last line
And then somehow he could never quite get the number of syllables 
right,or make it rhyme.

So, let's accept that the first line should scan correctly, that would 
make the following first lines acceptable:

A mathematician named Guido ...
The inventor of Python, called Guido ...
A mathematician (van Rossum) ...
Van Rossum, inventor of Python ...
Hopefully that will begin to get the idea across.
Since it's PyCon week, I will offer a prize of $100 to the best (in my 
opinion) limerick about Python posted to this list (with a Cc: to 
[EMAIL PROTECTED]) before midday on Friday. The prize money will be my 
own, so there are no other rules. I will post my judgment when the PyCon 
nonsense has died down a little, but the winner will be read before the 
entire PyCon audience. Get to it!

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.pycon.org/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous copy to multiple media

2005-03-20 Thread Claudio Grondi
I don't know any deep details about USB, except that
I _know_ that it is a serial bus, but considering
following:

1) I can read/write 45 MByte/s from harddrive to harddrive
on the E-IDE bus (theoretically 100 MByte/s), so the
speed of the harddrive I read/write from/to is probably the
bottleneck.
2) if I understand it right, an USB controller is connected to
to the PCI bus and there can be many separate USB
controller on one PC
3) the theoreticall speed of USB (430 MByte/s?) is much
higher as the experienced 15 MByte/s, probably due to slow
controller on the side of the external storage media, so
maybe even on one USB line I will have the chance to
use it full capacity connecting many slow devices
(I can't imagine, that USB goes down with the speed to
the speed of the slowest component connected, does it?)
4) with 45 MByte/s I could theoretically simultaneously
supply three separate data streams to three USB
controller writing with 15 MByte/s each out to the
external storage media.
5) watching the low CPU usage while writing to USB
shows me, that CPU-time is not a problem.

I still see a chance of writing truly simultaneously to
several devices connected via USB.
Please let me know if I am wrong in any of the
points (1-5) or if my conclusion is based on
wrong assumptions or if I use a wrong way of
infering.

By the way: I was not thought about bus design at
university, so what I know about it is comes from
self-study :-).

Claudio
P.S. Your message appears in my Outlook Express
as one having no content, but an attachment, so I can't
read it directly.

> Is there maybe a way to use a direct DMA
> transfer to multiple target destinations
> (I copy to drives connected via USB ports) ?
Think about what USB stands for. Then reconsider whether you'll ever have
the
chance of writing truly simultaneously to several devices connected via
USB... And then, as an extra exercise, think about why it takes so long when
several different jobs are done in parallel, writing to devices connected
via
USB.
Bus design... Don't they teach anything at uni these days? ;)
-- 
--- Heiko.


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


Software for Poets (Was: Re: Text-to-speech)

2005-03-20 Thread Francis Girard
Hello M. Hartman,

It's a very big opportunity for me to find someone that both is a poet and 
knows something about programming.

First, please excuse my bad english ; I'm a french canadian.

I am dreaming to write a software to help french poets to write strict 
rigourous classical poetry. Since calssical poetry is somewhat mathematical, 
a lot of tasks can be automatised :

1- Counting the number of syllabs ("pied" in french) in a verse

2- Checking the rimes ; determining the strength of a rime

3- Checking compliance of a poem to a fixed pre-determined classical form (in 
french, we have distique, tercet, quatrain, quintain, sixain, huitain, 
dizain, triolet, vilanelle, rondeau, rondel, ballade, chant royal, sonnet, 
etc.)

4- Propose a synonym that will fit in a verse, i.e. with the right amount of 
syllabs

5- Suggest a missing word or expression in a verse by applying the Shannon 
text generation principle

First, do you think it may be a useful tool ?
What other features you think can make it usefull for a poet ?

The first task of cutting sentences into syllabs (phonetically of course, not 
typographically) is already done. It's been difficult to get it right and to 
make it guess correctly with a very very high percentage. 

I can very well imagine that the next task is even more difficult. I need to 
translate text into phonems. Do you know some software that does it ? I guess 
that voice synthetisers that translates written text into spoken text must 
first translate the text into phonems. Right ? Do you know if there some way 
that I can re-use some sub-modules from these projects that will translate 
text into phonems ?

Regards,

Francis Girard

Le dimanche 20 Mars 2005 04:40, Charles Hartman a écrit :
> Does anyone know of a cross-platform (OSX and Windows at least) library
> for text-to-speech? I know  there's an OSX API, and probably also for
> Windows. I know PyTTS exists, but it seems to talk only to the Windows
> engine. I'd like to write a single Python module to handle this on both
> platforms, but I guess I'm asking too much -- it's too hardware
> dependent, I suppose. Any hints?
>
> Charles Hartman
> Professor of English, Poet in Residence
> http://cherry.conncoll.edu/cohar
> http://villex.blogspot.com

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


Re: simultaneous copy to multiple media

2005-03-20 Thread Rolf Zwart
Swaroop C H wrote:
[...]
If you are using *nix, maybe you can use the `tee` command[1] and
redirect the file to different places.
For example,
cat  | tee file1 | tee file2 > file3
On Unixes I know, only 1 process is needed:
/dev/null
It does work!
** Rolf
I haven't tried it out but it should work.
[1]: http://unixhelp.ed.ac.uk/CGI/man-cgi?tee
HTH,
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pre-PEP: Dictionary accumulator methods

2005-03-20 Thread Aahz
In article <[EMAIL PROTECTED]>,
Michele Simionato <[EMAIL PROTECTED]> wrote:
>
>I am surprised nobody suggested we put those two methods into a
>separate module (say dictutils or even UserDict) as functions:
>
>from dictutils import tally, listappend
>
>tally(mydict, key)
>listappend(mydict, key, value)

That seems like a reasonable compromise.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code -- 
not in reams of trivial code that bores the reader to death."  --GvR
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the Keyboard output

2005-03-20 Thread Jeremy Bowers
On Sun, 20 Mar 2005 19:30:05 +, Abdul Hafiz al-Muslim wrote:

> Hi,
> I am new to Python and still learning.
> 
> I am looking for a way to change the keyboard output within Tkinter - for
> example, say I press "p" and I want to come out as "t".
> 
> Could anyone point me in the right direction?

I'm pretty certain this is not possible in the general case.

One of my persistent pet peeves with GUI toolkits is that it is not
possible to insert your own arbitrary events into the toolkit and get the
toolkit to do *exactly* what it would have done if it had received that
event. While I believe Tk has a "post event" method, it only posts user
events, I do not think you can post system events.

This would completely change the testability and programmability of all
GUI toolkits, radically improving them for agile development... but that's
another rant.

Meanwhile, you've got two options, depending on what you are trying to
do, what platform you are on, and whether you control the target system.
You could actually re-map the keyboard, which all major OSs support,
although that may be too drastic. You could register two event handlers to
the same handling function, so that both "p" and "t" go to the same place.

Finally, if you're working with a Text widget, and you want a "t" to come
out when users press "p", what you do is capture the "p" event (either by
registering "p" or ""), insert a "t" at the INSERT point, move the
INSERT event forward if you have to, and then cancel the key event by
returning "break". Basically, you are implementing the keypress handler
manually. (To fully emulate the keypress, consider if you want to emulate
the behavior where a keypress destroys the highlighted range, in which
case you need to look at SEL too.) This is a pain, and there are a lot of
cases to cover, but it can be done.

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


Re: how can I put a 1Gb file in a zipfile??

2005-03-20 Thread Jeff Epler
The limits of ZIP files according to the folks who make info-zip:
http://www.info-zip.org/pub/infozip/FAQ.html#limits

 statistic limit
number of files65,536
uncompressed size of a single file   4 GB
compressed size of a single file 4 GB
total size of archive  256 TB
maximum path/filename length64 KB 

I had no trouble creating a zip file from a 4GB file filled with '\0'
bytes:
$ python bennie.py
$ ls -ls test.zip big
  12 -rw-rw-r--  1 jepler jepler 4294967296 Mar 20 14:11 big
4084 -rw-rw-r--  1 jepler jepler4174545 Mar 20 14:14 test.zip

I'm using Python 2.3.3 on Fedora Core 2.
#
# bennie.py
def make_4gb_file(f):
f = open(f, "w")
f.seek ( 4 * 1024 * 1024 * 1024 - 1)
f.write("\0")
f.close()

import zipfile
z = zipfile.ZipFile("/tmp/test.zip", "w", zipfile.ZIP_DEFLATED)
make_4gb_file("/tmp/big")
z.write("/tmp/big")
z.close()
#


pgpZ211p2vOse.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Building Time Based Bins

2005-03-20 Thread MCD
Never mind about the summing... I learned that you can do this:

sumhi = 0
sumhi += hi

Cool!

Thanks again.

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


Re: How to pass parameter when importing a module?

2005-03-20 Thread Bo Peng

Take a look at wxPython versioning:
http://wiki.wxpython.org/index.cgi/MultiVersionInstalls
The most simple usage looks like
  import wxversion
  wxversion.select("2.4")
  import wx
  Serge. 

This is essentially my second method: using another module to set 
parameter for myModule. Since wxPython uses this method, I suppose this 
is the standard approach for this problem.

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


Re: simultaneous copy to multiple media

2005-03-20 Thread Heiko Wundram
On Sunday 20 March 2005 17:16, Claudio Grondi wrote:
> Is there maybe a way to use a direct DMA
> transfer to multiple target destinations
> (I copy to drives connected via USB ports) ?

Think about what USB stands for. Then reconsider whether you'll ever have the 
chance of writing truly simultaneously to several devices connected via 
USB... And then, as an extra exercise, think about why it takes so long when 
several different jobs are done in parallel, writing to devices connected via 
USB.

Bus design... Don't they teach anything at uni these days? ;)

-- 
--- Heiko.


pgpMCGCKFMjC0.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: For loop extended syntax

2005-03-20 Thread Heiko Wundram
On Sunday 20 March 2005 20:47, George Sakkis wrote:
> Not always. Say for example that you're doing some 2D geometry stuff, and
> later you have to extend it to 3D. In this case you may have to deal with
> both 2D and 3D objects, and map the former to the latter when necessary.

But this rather sounds like you'd want an adaptor iterator, like the 
following:

>>> class AdaptPossible2D(object):
...   def __init__(self,data):
... self.data = data
...   def __iter__(self):
... for item in self.data:
...   if len(item) == 2:
... yield item+(0,)
...   else:
... yield item
...
>>> for x,y,z in AdaptPossible2D([(1,2),(1,2,3),(3,4)]):
...   print x,y,z
...
1 2 0
1 2 3
3 4 0

Using the above code makes it absolutely clear what you want, and doesn't need 
any new syntax which can be ambiguous like (x=0,y,z=0), etc. The above idiom 
also takes only constant extra space, as it doesn't duplicate the list during 
iteration.

-- 
--- Heiko.


pgpiKidxAK8Og.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Pre-PEP: Dictionary accumulator methods

2005-03-20 Thread Mike Rovner
Reinhold Birkenfeld wrote:
I don't quite understand that. Which dict item are you extending? Don't
you need something like
dl[key].append("word")
Rigth. It was just a typo on my part. Thanks for fixing.
Mike
--
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-20 Thread George Sakkis
"Matteo Dell'Amico" <[EMAIL PROTECTED]> wrote:

> George Sakkis wrote:
> > I'm sure there must have been a past thread about this topic but I don't 
> > know how to find it:
How
> > about extending the "for  in" syntax so that X can include default 
> > arguments ? This would be
very
> > useful for list/generator comprehensions, for example being able to write 
> > something like:
> >
> > [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
> >
> > instead of the less elegant explicit loop version that has to check for the 
> > length of each
sequence.
> > What do you think ?
>
> How did you get the data in that format in the first place? It looks a
> bit strange to me. Wouldn't it be easier to fill in default values when
> you gather data as opposed to when you use it?

Not always. Say for example that you're doing some 2D geometry stuff, and later 
you have to extend
it to 3D. In this case you may have to deal with both 2D and 3D objects, and 
map the former to the
latter when necessary.

George


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


Re: wxPython vs. pyQt

2005-03-20 Thread Andrew E
John J. Lee wrote:
The key question from my point of view is: can I write commercial
sell-if-I-want-to applications using Qt? If it is GPL, then I guess
the answer is 'no'?

Yes, you can write commercial apps.  It's multi-licensed (commercial,
GPL, etc.): you get to pick the license(s) you want to use.  Read the
licenses.
PyQt's licensing follows Qt's very closely, so no real complications
there.  Note PyQt (including a Qt license for use only with PyQt) is
actually far cheaper than Qt alone (if you buy Blackadder).
ok, thanks. I've just had a quick browse of the licence notes at the 
PyQt website.

I guess I meant: "can I write commercial closed-source software *without 
paying anything for Qt" - to which I sounds like the answer is 
definitely "No" :)

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


Re: How to pass parameter when importing a module?

2005-03-20 Thread Serge Orlov
Bo Peng wrote:
> Dear list,
>
> What I would like to do is something like:
>
> In myModule.py ( a wrapper module for different versions of the
> module),
>   if lib == 'standard':
> from myModule_std import *
>   elsif lib == 'optimized'
> from myModule_op import *
>
> but I do not know how to pass variable lib to myModule.py to achieve
> the following effect:
>
>   >>> lib = 'standard'
>   >>> from myModule import * # actually import myModule_std

[snip]

Take a look at wxPython versioning:
http://wiki.wxpython.org/index.cgi/MultiVersionInstalls

The most simple usage looks like

  import wxversion
  wxversion.select("2.4")
  import wx
  Serge. 


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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-20 Thread Francis Girard
Hi,

I really do not like it. So -1 for me. Your two methods are very specialized 
whereas the dict type is very generic. Usually, when I see something like 
this in code, I can smell it's a patch to overcome some shortcomings on a 
previous design, thereby making the economy of re-designing. Simply said, 
that's bad programming.

After that patch to provide a solution for only two of the more common 
use-cases, you are nonetheless stucked with the old solution for all the 
other use-cases (what if the value type is another dictionary or some 
user-made class ?).

Here's an alternate solution which I think answers all of the problems you 
mentionned while being generic.

=== BEGIN SNAP

def update_or_another_great_name(self, key, createFunc, updtFunc):
  try:
self[key] <<<= updtFunc(self[key])
  ## This is "slow" with Python "=" since the key has to be  searched 
  ## twice But the new built-in method just has to update the value the
  ## first time the key is found. Therefore speed should be ok.
return True
  except KeyError:
self[key] = createFunc()
return false

## Now your two specialized methods can be easily written as :

## A built-in should be provided for this (if not already proposed) :
def identical(val):
  return val

def count(self, key, qty=1):
  self.update_or_another_great_name(key, identical, 
partial(operator.add, qty))
  ## partial is coming from : http://www.python.org/peps/pep-0309.html
  ## Using only built-in function (assuming "identical") as arguments makes it
  ## ok for speed (I guess).
  
def appendlist(self, key, *values):
  self.update_or_another_great_name(key, 
partial(list, values),
partial(ListType.extend, X = values))
  ## The first "partial" usage here is an abuse just to make sure that the
  ## list is not actually constructed before needed. It should work.
  ## The second usage is more uncertain as we need to bind the arguments from
  ## the right. Therefore I have to use the name of the parameter and I am not
  ## sure if there's one. As this list is very prolific, someone might have an
  ## idea on how to improve this.
  
=== END SNAP

By using only built-in constructs, this should be fast enough. Otherwise, 
optimizing these built-ins is a much more clean and sane way of thinking then 
messing the API with ad-hoc propositions.

Reviewing the problems you mention :

> The readability issues with the existing constructs are:
>
> * They are awkward to teach, create, read, and review.

The method update_or_another_great_name is easy to understand, I think. But it 
might not always be easy to use it efficiently with built-ins. But this is 
always the case. "Recipees" can be added to show how to efficiently use the 
method.

> * Their wording tends to hide the real meaning (accumulation).

Solved.

> * The meaning of setdefault() 's method name is not self-evident.

Solved.

>
> The performance issues with the existing constructs are:
>
> * They translate into many opcodes which slows them considerably.

I really don't know what will be the outcome of the solution I propose. I 
certainly do not know anything about how my Python code translates into 
opcodes.

> * The get() idiom requires two dictionary lookups of the same key.

Solved

> * The setdefault() idiom instantiates a new, empty list prior to every

Solved

> call. * That new list is often not needed and is immediately discarded.

Solved

> * The setdefault() idiom requires an attribute lookup for extend/append.

Solved

> * The setdefault() idiom makes two function calls.

Solved

And perhaps, what you say here is also true for your two special use-cases :

> For other
> uses, plain Python code suffices in terms of speed, clarity, and avoiding
> unnecessary instantiation of empty containers:
>
> if key not in d:
> d.key = {subkey:value}
> else:
> d[key][subkey] = value


Much better than adding special cases on a generic class. Special cases always 
demultiply and if we open the door 

Regards,

Francis Girard


Le samedi 19 Mars 2005 02:24, Raymond Hettinger a ÃcritÂ:
> I would like to get everyone's thoughts on two new dictionary methods:
>
> def count(self, value, qty=1):
> try:
> self[key] += qty
> except KeyError:
> self[key] = qty
>
> def appendlist(self, key, *values):
> try:
> self[key].extend(values)
> except KeyError:
> self[key] = list(values)
>
> The rationale is to replace the awkward and slow existing idioms for
> dictionary based accumulation:
>
> d[key] = d.get(key, 0) + qty
> d.setdefault(key, []).extend(values)
>
> In simplest form, those two statements would now be coded more readably as:
>
>d.count(key)
>d.appendlist(key, value)
>
> In their multi-value forms, they would now be coded as:
>

getting text from WinXP console

2005-03-20 Thread Chris Maloof
Hello,

Does anyone know how I can read the ASCII text from a console window
(from another application) in WinXP?  It doesn't sound like a major
operation, but although I can find the window via pywin32, I haven't
been able to do anything with it.  I'd really just like to get the
window text into a string.

By "console window", I mean the sort of thing that comes up when you
run "command" (although this particular one is for the game NetHack).

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


Re: how can I put a 1Gb file in a zipfile??

2005-03-20 Thread bennie
Christos TZOTZIOY Georgiou wrote:
On Sun, 20 Mar 2005 10:44:06 +0100, rumours say that Bennie <[EMAIL PROTECTED]>
might have written:

Hi,
I have a problem with ZipFile.
It works okay untily I come across a file that is greater then 1Gb.
Then it exit with the error:
OverflowError: long int too large to convert to int
How can I fix this?

AFAIR there is a 4GiB (or 2GiB) size limit applying both to files added to zip
and to the total size of the zip file.  This limit comes from the zip file
specification (32 bit offsets).

souce:
zip = zipfile.ZipFile(file, 'w')

for all in os.walk(os.getcwd()):
path = all[0]
for document in all[2]:
zipaccview.write(path + os.sep + document)
	zip.close()

Can it be that you are creating a zip file that its total size exceeds the
limit?
That is possible.
But with Winzip program it can.
How come that is with ZipFile not works
--
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-20 Thread George Sakkis
"Kay Schluehr" <[EMAIL PROTECTED]> wrote:

> George Sakkis wrote:
>
> > This would be very
> > useful for list/generator comprehensions, for example being able to
> write something like:
> >
> > [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
> >
>
> Looks very appealing, but what to do with
>
> [x*y-z for (x=0,y,z) in (1,2,3), (4,5), (6,7,8)] ?
>
> Should it raise an exception due to a pattern mismatch?

I didn't have in mind to generalize the syntax even more than the respective 
for function
signatures, therefore this would be syntax error:
SyntaxError: non-keyword arg after keyword arg

> If not how should matching rules apply here?
>
> [x*y-z for (x=0,y=0,z=0) in (1,2,3), (4,5), (6,7,8)]
>
> If in doubt write a vector class that cares about the correct padding (
> or more general and with geometric meaning: select the right hyperplane
> ) and enable to switch between different paddings. This solution is
> both flexible and reusable.
>
> Regards Kay

This was just an example; I think the proposed functionality will be helpful in 
far more cases than
dealing with geometry or vectors, so I would prefer it to be supported by the 
language itself.

Regards,
George


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


Changing the Keyboard output

2005-03-20 Thread Abdul Hafiz al-Muslim
Hi,
I am new to Python and still learning.

I am looking for a way to change the keyboard output within Tkinter - for
example, say I press "p" and I want to come out as "t".

Could anyone point me in the right direction?

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


Re: simultaneous copy to multiple media

2005-03-20 Thread Claudio Grondi
means  your message, that you think, that
the consecutive copy is the fastest possible
method if using Windows 2000?

Claudio

"Grant Edwards" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> On 2005-03-20, Claudio Grondi <[EMAIL PROTECTED]> wrote:
>
> > Is there maybe a way to use a direct DMA
> > transfer to multiple target destinations
> > (I copy to drives connected via USB ports) ?
>
> Sure, but you'll have to throw away your OS, and write a
> program that runs on the bare metal.
>
> > Can someone point me in the right direction?
>
> I think they already did.
>
> -- 
> Grant Edwards   grante Yow!  I am NOT a
nut
>   at
>visi.com


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


Re: For loop extended syntax

2005-03-20 Thread Matteo Dell'Amico
George Sakkis wrote:
I'm sure there must have been a past thread about this topic but I don't know 
how to find it: How
about extending the "for  in" syntax so that X can include default arguments 
? This would be very
useful for list/generator comprehensions, for example being able to write 
something like:
[x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
instead of the less elegant explicit loop version that has to check for the 
length of each sequence.
What do you think ?
How did you get the data in that format in the first place? It looks a 
bit strange to me. Wouldn't it be easier to fill in default values when 
you gather data as opposed to when you use it?

--
Ciao,
Matteo
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pre-PEP: Dictionary accumulator methods

2005-03-20 Thread Alexander Schmolck
Beni Cherniavsky <[EMAIL PROTECTED]> writes:

>> The relatively recent "improvement" of the dict constructor signature
>> (``dict(foo=bar,...)``) obviously makes it impossible to just extend the
>> constructor to ``dict(default=...)`` (or anything else for that matter) which
>> would seem much less ad hoc. But why not use a classmethod (e.g.
>> ``d=dict.withdefault(0)``) then?
>>
> You mean giving a dictionary a default value at creation time, right?

Yes. But creating a defaultdict type with aliased content to the original
dict would also be fine by me.

> Such a dictionary could be used very easily, as in Perl::
>
>  foreach $word ( @words ) {
>  $d{$word}++; # default of 0 assumed, simple code!
>  }
>
> .  You would like to write::
>
>  d = dict.withdefault(0)  # or something
>  for word in words:
>  d[word] += 1 # again, simple code!
>
> I agree that it's a good idea but I'm not sure the default should be specified
> at creation time.  The problem with that is that if you pass such a dictionary
> into an unsuspecting function, it will not behave like a normal dictionary.

Have you got a specific example in mind? 

Code that needlessly relies on exceptions for "normal operation" is rather
perverse IMO and I find it hard to think of other examples.

> Also, this will go awry if the default is a mutable object, like ``[]`` - you
> must create a new one at every access (or introduce a rule that the object is
> copied every time, which I dislike).

I think copying should on by default for objects that are mutable (and
explicitly selectable via ``.withdefault(bar,copy=False)``).

Python of course doesn't have an interface to query whether something is
mutable or not (maybe something that'll eventually be fixed), but hashable
might be a first approximation. If that's too dodgy, most commonly the value
will be a builtin type anyway, so copy by default with "efficient
implementation" (i.e. doing nothing) for ints, tuples etc. ought to work fine
in practice.

> And there are cases where in different points in the code operating on the
> same dictionary you need different default values.

The main problem here is that the obvious .setdefault is already taken to
misnome something else. Which I guess strengthens the point for some kind of
proxy object.

> So perhaps specifying the default at every point of use by creating a proxy is
> cleaner::
>
>  d = {}
>  for word in words:
>  d.withdefault(0)[word] += 1
> Of course, you can always create the proxy once and still pass it into an
> unsuspecting function when that is actually what you mean.

Yup (I'd presumably prefer that second option for the above code).

>
> How should a dictionary with a default value behave (wheter inherently or a
> proxy)?
>
> - ``d.__getattr__(key)`` never raises KeyError for missing keys - instead it
>returns the default value and stores the value as `d.setdefult()` does.
>This is needed for make code like::
>
>d.withdefault([])[key].append(foo)
>
>to work - there is no call of `d.__setattr__()`, so `d.__getattr__()` must
>have stored it.

I'm confused -- are you refering to __getitem__/__setitem__? Even then I don't
get what you mean: __getitem__ obviously works differently, but that would be
the whole point.

>
>- `d.__setattr__()` and `d.__delattr__()` behave normally.

s/attr/item/ and agreed.

>
> - Should ``key in d`` return True for all keys?  

No. See below.

>It is desiarable to have *some* way to know whether a key is really
>present. But if it returns False for missing keys, code that checks ``key
>in d`` will behave differently from normally equivallent code that uses
>try..except. If we use the proxy interface, we can always check on the
>original dictionary object, which removes the problem.
>
>- ``d.has_key(key)`` must do whatever we decide ``key in d`` does.
>
>  - What should ``d.get(key, [default])`` and ``d.setdefault(key, default)``
>do?  There is a conflict between the default of `d` and the explicitly 
> given
>default.  I think consistency is better and these should pretend that `key`
>is always present.  But either way, there is a subtle problem here.

.setdefault ought to trump defaultdict's default. I feel that code that
operated without raising an KeyError on normal dicts should also operate the
same way on defaultdicts were possible. I'd also suspect that if you're
effectively desiring to override .setdefault's default you're up to something
dodgy.

> - Of course `iter(d)`, `d.items()` and the like should only see the keys
>that are really present (the alternative inventing an infinite amount of
>items out of the blue is clearly bogus).
>
> If the idea that the default should be specified in every operation (creating
> a proxy) is accepted, there is a simpler and more fool-proof solution: the
> ptoxy will not support anything except `__getitem__()` and `__setitem__()` at
> al

Re: Pre-PEP: Dictionary accumulator methods - typing & initialising

2005-03-20 Thread Matteo Dell'Amico
Kay Schluehr wrote:
I think that's because you have to instantiate a different object for
each different key. Otherwise, you would instantiate just one list as
a default value for *all* default values.
Or the default value will be copied, which is not very hard either or
type(self._default)() will be called. This is all equivalent and it
does not matter ( except for performance reasons ) which way to go as
long only one is selected.
I don't like it very much... it seems too implicit to be pythonic. Also, 
it won't work with non-copyable objects, and type(42)() = 0, and getting 
0 when the default is 42 looks very strange. I prefer the explicit "give 
me a callable" approach.

If the dict has a fixed semantics by applying defaultValue() and it
returns defaults instead of exceptions whenever a key is missing i.e.
behavioural invariance the client of the dict has nothing to worry
about, hasn't he?
For idioms like d[foo].append('blah') to work properly, you'd have to 
set the default value every time you access a variable. It can be really 
strange to fill up memory only by apparently accessing values.

I suspect the proposal really makes sense only if the dict-values are
of the same type. Filling it with strings, custom objects and other
stuff and receiving 0 or [] or '' if a key is missing would be a
surprise - at least for me. Instantiating dict the way I proposed
indicates type-guards! This is the reason why I want to delay this
issue and discuss it in a broader context. But I'm also undecided.
Guidos Python-3000 musings are in danger to become vaporware. "Now is
better then never"... Therefore +0.
Having duck-typing, we can have things that have common interface but no 
common type. For instance, iterables. I can imagine a list of iterables 
of different types, and a default value of maybe [] or set([]).

--
Ciao,
Matteo
--
http://mail.python.org/mailman/listinfo/python-list


Re: Building Time Based Bins

2005-03-20 Thread MCD
John Machin wrote:
> Are you (extremely) new to computer programming? Is this school
> homework?

Lol, yes, I am relatively new to programming... and very new to python.
I have experience working with loops, if thens, and boolean operations,
but I haven't worked with lists or array's as of yet... so this is my
first forray. This isn't homework, I'm long out of school. I've been
wanting to extend my programming abilities and I chose python as the
means to acheiving that goal... so far I really like it :-)

Thank you both for the code. I ended up working with John's because
it's a bit easier for me to get through. I very much appreciate the
code... it taught me quite a few things about how python converts
string's to integers and vice versa. I didn't expect to get thorugh it,
but after looking at it a bit, I did, and was able to modify it so that
I could work with my own files. Yeah!

The only question I have is in regards to being able to sum a field in
a bin. Using sum(hi) returns only the last value... I'm uncertain how
to cumulatively add up the values as the script runs through each line.
Any pointers?

Thank you again for all your help.
Marcus

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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-20 Thread Jeremy Bowers
On Sat, 19 Mar 2005 20:07:40 -0800, Kay Schluehr wrote:
> It is bad OO design, George. I want to be a bit more become more
> specific on this and provide an example:

Having thought about this for a bit, I agree it is a powerful
counter-argument and in many other languages I'd consider this a total win.

But this is Python, and frankly, I've overridden dict more than once and
violated the Liskov substitution principle without thinking twice. (Once,
oh yes, but not twice.) Of course, all the code was under my control then.

I think the tipping point for me depends on how the interfaces in Python
are going to be implemented, which I haven't dug into. If the dict class
gets an interface definition, can I subclass from dict and "cancel" (or
some other term) the interface I inherited? 

If so, then this might still be OK, although if interfaces aren't going to
confuse newbies enough, wait 'till we try to explain that their code is
blowing up because they forgot to "cancel" their interface, and they
can't *really* pass their subclass in to something expecting a dict
interface. If you *can't* cancel or downgrade the interface, then I'd say
this argument is still good; dict should be kept minimal and this should
go in a subclass.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-20 Thread Kay Schluehr
George Sakkis wrote:

> This would be very
> useful for list/generator comprehensions, for example being able to
write something like:
>
> [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
>

Looks very appealing, but what to do with

[x*y-z for (x=0,y,z) in (1,2,3), (4,5), (6,7,8)] ?

Should it raise an exception due to a pattern mismatch?

If not how should matching rules apply here?

[x*y-z for (x=0,y=0,z=0) in (1,2,3), (4,5), (6,7,8)]

If in doubt write a vector class that cares about the correct padding (
or more general and with geometric meaning: select the right hyperplane
) and enable to switch between different paddings. This solution is
both flexible and reusable.

Regards Kay

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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-20 Thread Roose
> Another option with no storage overhead which goes part way to reducing
> the awkwardness would be to provide a decorator class accessible through
> dict. The decorator class would take a value or function to be used as
> the default, but apart from __getitem__ would simply forward all other
> methods through to the underlying dictionary.

I'm not sure I like the decorator -- I would never use that flexibility to
have more than one default.  I can't come up with any reason to ever use
that.

I think it works best as a simple subclass:

class DefaultDict(dict):

  def __init__(self, default, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.default = default

  def __getitem__(self, key):
return self.setdefault(key, copy.copy(self.default))

d = DefaultDict(0)
for x in [1, 3, 1, 2, 2, 3, 3, 3, 3]:
  d[x] += 1
pprint(d)

d = DefaultDict([])
for i, x in enumerate([1, 3, 1, 2, 2, 3, 3, 3, 3]):
  d[x].append(i)
pprint(d)

Output:

{1: 2, 2: 2, 3: 5}
{1: [0, 2], 2: [3, 4], 3: [1, 5, 6, 7, 8]}


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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-20 Thread Colin J. Williams
Paul Rubin wrote:
"El Pitonero" <[EMAIL PROTECTED]> writes:
What about no name at all for the scalar case:
a['hello'] += 1
a['bye'] -= 2

I like this despite the minor surprise that it works even when
a['hello'] is uninitialized.
+1
and if the value is a list:
a['hello']= [1, 2, 3]
a['hello']+= [4]# adding the brackets is a lot simpler than
  typing append or extend.
Any user is free to add his/her own subclass to handle defaults.
Colin W.
--
http://mail.python.org/mailman/listinfo/python-list


For loop extended syntax

2005-03-20 Thread George Sakkis
I'm sure there must have been a past thread about this topic but I don't know 
how to find it: How
about extending the "for  in" syntax so that X can include default arguments 
? This would be very
useful for list/generator comprehensions, for example being able to write 
something like:

[x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]

instead of the less elegant explicit loop version that has to check for the 
length of each sequence.
What do you think ?

George


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


Re: Pre-PEP: Dictionary accumulator methods - typing & initialising

2005-03-20 Thread Kay Schluehr
Matteo Dell'Amico wrote:
> Kay Schluehr wrote:
>
> > Why do You set
> >
> > d.defaultValue(0)
> > d.defaultValue(function=list)
> >
> > but not
> >
> > d.defaultValue(0)
> > d.defaultValue([])
> >
> > ?
>
> I think that's because you have to instantiate a different object for

> each different key. Otherwise, you would instantiate just one list as
a
> default value for *all* default values.

Or the default value will be copied, which is not very hard either or
type(self._default)() will be called. This is all equivalent and it
does not matter ( except for performance reasons ) which way to go as
long only one is selected.

[...]

> By the way, to really work, I think that Duncan's proposal should
create
> new objects when you try to access them, and to me it seems a bit
> counterintuitive.

If the dict has a fixed semantics by applying defaultValue() and it
returns defaults instead of exceptions whenever a key is missing i.e.
behavioural invariance the client of the dict has nothing to worry
about, hasn't he?


> > And why not dict(type=int), dict(type=list) instead where default
> > values are instantiated during object creation? A consistent
pythonic
> > handling of all types should be envisioned not some ad hoc
solutions
> > that go deprecated two Python releases later.
>
> I don't really understand you. What should 'type' return?
> A callable
> that returns a new default value? That's exactly what Duncan proposed

> with the "function" keyword argument.

I suspect the proposal really makes sense only if the dict-values are
of the same type. Filling it with strings, custom objects and other
stuff and receiving 0 or [] or '' if a key is missing would be a
surprise - at least for me. Instantiating dict the way I proposed
indicates type-guards! This is the reason why I want to delay this
issue and discuss it in a broader context. But I'm also undecided.
Guidos Python-3000 musings are in danger to become vaporware. "Now is
better then never"... Therefore +0.

Regards Kay

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


Re: beeping portably

2005-03-20 Thread John J. Lee
"Jim" <[EMAIL PROTECTED]> writes:

> I'd like to emit beeps.  The twists are that (1) I hope to have control
> over the frequency of the beeps and their duration and (2) I'd like the
> solution to be portable across Linux, Windows, and OS X.
[...]

PyGame?  If it's too big for you, you could always borrow code from it.


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


Re: wxPython vs. pyQt

2005-03-20 Thread John J. Lee
Andrew E <[EMAIL PROTECTED]> writes:

> Hans-Peter Jansen wrote:
> > ..
> > While in PyQt world, I found these advantages:
> >  + conceptually vastly superior
> >  + powerful api/widgets/features
> >  + fast as hell due to the efficient binding of a quite efficient lib
> >  + cool tools, that are unicode/translation aware
> >  + very efficient programming environment/unbeatable productivity
> > While this sounds like the average sales talk, I will try to backup
> > these
> > claims a bit:
>  > ..
> 
> I've been a wx user since around 1999 and overall I like it. It annoys
> me a *lot* sometimes, but as Qt was always prohibitively expensive for
> commercial development, it was the only real option.
> 
> The key question from my point of view is: can I write commercial
> sell-if-I-want-to applications using Qt? If it is GPL, then I guess
> the answer is 'no'?

Yes, you can write commercial apps.  It's multi-licensed (commercial,
GPL, etc.): you get to pick the license(s) you want to use.  Read the
licenses.

PyQt's licensing follows Qt's very closely, so no real complications
there.  Note PyQt (including a Qt license for use only with PyQt) is
actually far cheaper than Qt alone (if you buy Blackadder).


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


Re: How to pass parameter when importing a module?

2005-03-20 Thread André Roberge
Bo Peng wrote:
Dear list,
What I would like to do is something like:
In myModule.py ( a wrapper module for different versions of the module),
  if lib == 'standard':
from myModule_std import *
  elsif lib == 'optimized'
from myModule_op import *
but I do not know how to pass variable lib to myModule.py to achieve the 
following effect:

How about this:
#= constants.py
lib = whatever   #assigned somewhere else
#= myModule.py
from constants import lib
etc.
André
--
http://mail.python.org/mailman/listinfo/python-list


beeping portably

2005-03-20 Thread Jim
Hello,

I'd like to emit beeps.  The twists are that (1) I hope to have control
over the frequency of the beeps and their duration and (2) I'd like the
solution to be portable across Linux, Windows, and OS X.

I've done some searching of this group and the solutions that people
have offered in the past seem not to satisfy both points. For instance,
that I can tell, "\a" or curses.beep() doesn't give you control over
the frequency or duration.  I also looked at wxWindows but there were
warnings about the MMedia module ("status is unclear") that made me
leery.

Thanks,
Jim

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


Re: simultaneous copy to multiple media

2005-03-20 Thread Grant Edwards
On 2005-03-20, Claudio Grondi <[EMAIL PROTECTED]> wrote:

> Is there maybe a way to use a direct DMA
> transfer to multiple target destinations
> (I copy to drives connected via USB ports) ?

Sure, but you'll have to throw away your OS, and write a
program that runs on the bare metal.

> Can someone point me in the right direction?

I think they already did.

-- 
Grant Edwards   grante Yow!  I am NOT a nut
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: 2005 International Obfuscated Ruby Code Contest (IORCC)

2005-03-20 Thread Gerrit Holl
[EMAIL PROTECTED] wrote:
> IMMEDIATE RELEASE: Fri Mar 18 16:34:52 CST 2005
> LOCATION:  http://iorcc.dyndns.org/2005/press/031805.html
> ANNOUNCEMENT:  International Obfuscated Ruby Code Contest (IORCC)
>Entry Deadline, Midnight on March 31st, 2005
> 
> 
> Dear Rubyists, Perlists, Shellists, Cists and Hackers,

What is this doing on comp.lang.python?

regards,
Gerrit Holl.

-- 
Weather in Twenthe, Netherlands 20/03 16:55:
9.0ÂC   wind 4.0 m/s ENE (57 m above NAP)
-- 
In the councils of government, we must guard against the acquisition of
unwarranted influence, whether sought or unsought, by the
military-industrial complex. The potential for the disastrous rise of
misplaced power exists and will persist.
-Dwight David Eisenhower, January 17, 1961
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to pass parameter when importing a module?

2005-03-20 Thread Swaroop C H
On Sun, 20 Mar 2005 10:18:14 -0600, Bo Peng <[EMAIL PROTECTED]> wrote:
> What I would like to do is something like:
> In myModule.py ( a wrapper module for different versions of the module),
>if lib == 'standard':
>  from myModule_std import *
>elsif lib == 'optimized'
>  from myModule_op import *

Suggestion: Maybe you use builtin `__import__` to load a module ? Note
that in this way, you'll have to use the module name prefix.


-- 
Swaroop C H
Blog: http://www.swaroopch.info
Book: http://www.byteofpython.info
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Re: Hi Guys. First Time Poster

2005-03-20 Thread Gerrit Holl
Jeff Schwab wrote:
> sheldon279 wrote:

> Wow, you sold me.
> 
> Does this kinda scam really still work?

This kind of replies works to confuse spambayes.

Gerrit.

-- 
Weather in Twenthe, Netherlands 20/03 16:55:
9.0ÂC   wind 4.0 m/s ENE (57 m above NAP)
-- 
In the councils of government, we must guard against the acquisition of
unwarranted influence, whether sought or unsought, by the
military-industrial complex. The potential for the disastrous rise of
misplaced power exists and will persist.
-Dwight David Eisenhower, January 17, 1961
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >