ANNOUNCE: Python for .NET beta 5 now available

2005-03-29 Thread Brian Lloyd
Python for .NET 1.0 beta 5 is now available - you can download 
it from: 

  http://www.zope.org/Members/Brian/PythonNet/


Python for .NET is a near-seamless integration of Python with the 
.NET common language runtime. For more details, see the README:

  http://www.zope.org/Members/Brian/PythonNet/README.html


The beta 5 release features a refactoring of thread management 
support, making the runtime stable for multi-threaded applications, 
as well as several improvements and bug-fixes.

Special thanks to all who sent in thread-related scenarios and test 
cases! I have tried to incorporate as many of these as possible into 
the unit tests - if you still have problems that you suspect may be 
related to threading or interpreter lock issues, please let me know 
asap.

There is also now a mailing list for discussion, questions and 
issues related to Python for .NET at: [EMAIL PROTECTED]

To subscribe to the mailing list or read the online archives, see:

  http://mail.python.org/mailman/listinfo/pythondotnet



Brian Lloyd[EMAIL PROTECTED]
V.P. Engineering   540.361.1716  
Zope Corporation   http://www.zope.com 

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Wanted: New Python Success Stories

2005-03-29 Thread Stephan Deibel
Hi,

O'Reilly Associates is going to be printing volume III of the
Python Success Stories series in June and I'm looking for
submissions of new stories.

The stories have been quite valuable for people introducing
Python to new users and companies.

The deadline for me to receive stories for editing is May 1st and
the deadline for the final edited, approved story going to
O'Reilly is June 1st.

The existing stories are online here:

http://pythonology.org/success

There's more info about writing one here:

http://pythonology.org/successguide

The biggest hurdle is usually getting approval from the company
to write about Python.  It may require some educating about open
source to get past rules against endorsing commercial products
(which Python obviously isn't).

If you have any questions, please let me know.  

Thanks,

Stephan Deibel
Pythonology.com

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


ReleaseForge 0.6 - A SourceForge project release tool

2005-03-29 Thread [EMAIL PROTECTED]
ReleaseForge 0.6 is now available at:

http://releaseforge.sourceforge.net

New to version 0.6:

* The ability to edit existing SourceForge releases
* Some UI tweaks
* Some random bug fixes
* Some code cleanup
* Stays crispy in milk

In case you're not already familiar with ReleaseForge:

ReleaseForge is a python GUI that allows SourceForge users (project
admins and release techs) the ability to create and edit SourceForge
releases of their projects.  ReleaseForge provides an alternative (re:
much improved, more intuitive) interface than the usual SourceForge web
interface.

ReleaseForge also allows users to create new project packages and
update existing packages.

ReleaseForge is developed in Python (requires version 2.3 or greater)
using PyQt (v3.3 or greater) and contains 100% real fruit juice.  A
Windows installer is also available that includes all of the software
dependencies.

http://releaseforge.sourceforge.net

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Grouping code by indentation - feature or ******?

2005-03-29 Thread Antoon Pardon
Op 2005-03-25, Terry Reedy schreef [EMAIL PROTECTED]:

 Antoon Pardon [EMAIL PROTECTED] wrote in message

 1) It makes it hard to see how many levels are dedented at the end of
   a suite, and sometime makes it difficult to see where the end
   of a suite is. If e.g. you are looking at the code spread over
   two pieces of paper, it is sometimes hard to see whether the
   suite ends at the end of the first page or not.

 One can use appropriately indented comment lines instead of closing 
 brackets for this purpose.

But then we are back at the problem of different styles.

People argue they like the python rule, because they have
difficulties with the different styles that are allowed
by the free form that is allowed in othe languages.

 2) It makes it hard to introduce some kind of new syntax constructs.

 I consider this as much a plus as a minus ;-)

I can see your point. We don't want an avalance of new constructs
and some restraint is needed but I feel python is too restraint
here.

 3) Sometimes the structure of the algorithm is not the structure
   of the code as written, people who prefer that the indentation
   reflects the structure of the algorithm instead of the structure
   of the code, are forced to indent wrongly.

 Do you have any simple examples in mind?

Essentially each time I need to use:

  if condition break.

IMO this part of the code is usualy a control for a loop and thus
of the same level as

  while condition:

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


Re: convert user input to Decimal objects using eval()?

2005-03-29 Thread Raymond Hettinger
[Julian Hernandez Gomez]
 This is maybe a silly question, but...

 is there a easy way to make eval() convert all floating
 numbers to Decimal objects and return a Decimal?

from decimal import Decimal
import re

number = re.compile(r((\b|(?=\W))(\d+(\.\d*)?|\.\d+)([eE][+-]?\d{1,3})?))
deciexpr = lambda s: number.sub(rDecimal('\1'), s)

for s in ('1.0001+0.111',
   '+21.3e-5*85-.1234/81.6',
   '1.0/7'):
print '%s\n  -- %r' % (s, eval(s))
s = deciexpr(s)
print '%s\n  -- %r\n' % (s, eval(s))




1.0001+0.111
  -- 1.
Decimal('1.0001')+Decimal('0.111')
  -- Decimal(1.)

+21.3e-5*85-.1234/81.6
  -- 0.016592745098039215
+Decimal('21.3e-5')*Decimal('85')-Decimal('.1234')/Decimal('81.6')
  -- Decimal(0.01659274509803921568627450980)

1.0/7
  -- 0.14285714285714285
Decimal('1.0')/Decimal('7')
  -- Decimal(0.1428571428571428571428571429)



Raymond Hettinger


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


Re: Looking for Stephen Turner, maintainer of informixdb

2005-03-29 Thread Michael Husmann
Carsten Haese wrote:

 Hello everybody:
 
 I have discovered that the functionality for connecting Python to an
 Informix database is currently in a frustrating state of neglect. The
 link to Kinfxdb is dead, and informixdb doesn't build on Python 2. I
 couldn't find any usable workarounds to the build problem, so I worked
 out successfully how to build informixdb using distutils.
 
 Now I'd like to share the result with the community, but the maintainer
 appears to have gone missing. My emails to [EMAIL PROTECTED] and
 [EMAIL PROTECTED] have bounced back undeliverable, so now I'm
 posting to the lists trying to locate Stephen.
 
 If anybody has any pointers for locating Stephen Turner, please let me
 know. If Stephen can't be located, I'd be willing to take over the
 project, but I'd prefer the torch be given to me rather than me just
 taking it.

Carsten,

haven't heard anything from Stephen either, but there are some extensions to
the informixdb module. I'll send the sources to you next week. So if you
like you can bundle everything in one package.

Kind greetings,
Michael
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for a 10-14 years old?

2005-03-29 Thread Duncan Booth
Joal Heagney wrote:

 Nice. I still have to download a version of pygame to try this out, but 
 the fact that you can't hide the turtle in python.turtle was bugging me 
 out with my version. (A fair bit of copy/paste in gimp, I can tell you!)

What was wrong with hiding the turtle? 'turtle.tracer(False)' usually does 
it nicely and speeds things up a lot.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling __init__ with multiple inheritance

2005-03-29 Thread Peter Otten
Axel Straschil wrote:

 Thanks to all for the very interesting postings!

You're welcome.
 
 I came to the following:
 
 For single inheritance, super is a nice tool if you will recfactoring
 the class later.

Or if you start out with a diamond inheritance graph from the beginning.
 
 For multiple inheritance, if you want to use super, you have to have
 very much knowledge of the classes you inheritance. For me, OOP is to
 not have to have the deep inner knowledge of the classes I inheritance
 from.

I failed to bring my point that you need _less_ knowledge across then.

 Also, for multiple inheritance, if think
 Mother1.__init__(self, ...)
 Mother2.__init__(self, ...)
 Mother3.__init__(self, ...)
 would be more clear to read then
 super(MyClass).__init__(Maby this will do some magic thing)

For an advantage to show up you need at least three levels of inheritance,
see my example with the Parent class.
 
 Also, I realy dislike
 __init__(self, param, **eat_some_needless_stuff)

In turn, I really like the name you gave the dictionary parameter :-)
Normalize the initializer signature to a common set of arguments. Or pass a
single parameter and take the actual information from its attributes. Or
write a custom dispatcher, that passes only parameters that correspond to
formal arguments...
 
 If I later extend my class and also add some parameters to __init__,
 what will happen to the classes using the baseclass?
 
 Also, lool at that:
 class Mother(object):
 def __init__(self, param_mother='optional', **eat):
 print 'Mother'
 class Father(object):
 def __init__(self, param_father='optional', **eat):
 print 'Father'
 class Child(Mother, Father):
 def __init__(self, **ham):
 super(Child, self).__init__(**ham)
 child = Child(param_mother=1, param_father=1)
 
 Father's init will not be called.

Change Father/Mother.__init__() to call the superclass initializer. It may
be counterintuitive, but it works.

Peter

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


Re: How to ensure Maximize button shows in Linux/Unix (Tkinter)

2005-03-29 Thread Eric Brunel
On 26 Mar 2005 08:19:07 -0800, Harlin Seritt [EMAIL PROTECTED] wrote:
Diez,
Thanks for the quick reply. I am running this under KDE. I actually
haven't tried doing so under any other wm for the moment. Any ideas how
to get it to show in KDE?
This is a tk bug; see:
http://sourceforge.net/tracker/index.php?func=detailaid=922336group_id=12997atid=112997
and:
http://sourceforge.net/tracker/index.php?func=detailaid=915350group_id=12997atid=112997
The latest tcl/tk 8.4 release may solve the problem, and a patch is provided 
for the second bug report if you don't want to upgrade.
HTH
--
python -c 'print .join([chr(154 - ord(c)) for c in 
U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)

2005-03-29 Thread Raymond Hettinger
[Jack Diederich]
   itertools to iter transition, huh?  I slipped that one in, I mentioned
   it to Raymond at PyCon and he didn't flinch.  It would be nice not to
   have to sprinkle 'import itertools as it' in code.  iter could also
   become a type wrapper instead of a function, so an iter instance could
   be a wrapper that figures out whether to call .next or __getitem__
   depending on it's argument.
   for item in iter(mylist).imap:
 print item
   or
   for item in iter.imap(mylist):
 print item

[Steven Bethard]
 Very cool idea.  I think the transition from
  itertools.XXX(iterable, *args, **kwargs)
 to
  iter.XXX(iterable, *args, **kwargs)
 ought to be pretty easy.

Just to make sure you guys can live with your proposed syntax, trying using it
for a month or so and report back on whether the experience was pleasant.  Try
dropping the following into your setup.py

def wrapiter():
import __builtin__, itertools
orig = __builtin__.iter
def iter(*args):
return orig(*args)
for name in ('__doc__', '__name__'):
setattr(iter, name, getattr(orig, name))
vars(iter).update(vars(itertools))
__builtin__.iter = iter
wrapiter()

If the experience works out, then all you're left with is the trivial matter of
convincing Guido that function attributes are a sure cure for the burden of
typing import statements.


Raymond Hettinger


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


Re: a program to delete duplicate files

2005-03-29 Thread alanwo
Why not try to use NoClone, it finds and deletes duplicate files by
true byte-by-byte comparison. Smart marker filters duplicate files to
delete. With GUI.
http://noclone.net


Xah Lee wrote:
 here's a large exercise that uses what we built before.

 suppose you have tens of thousands of files in various directories.
 Some of these files are identical, but you don't know which ones are
 identical with which. Write a program that prints out which file are
 redundant copies.

 Here's the spec.
 --
 The program is to be used on the command line. Its arguments are one
or
 more full paths of directories.

 perl del_dup.pl dir1

 prints the full paths of all files in dir1 that are duplicate.
 (including files in sub-directories) More specifically, if file A has
 duplicates, A's full path will be printed on a line, immediately
 followed the full paths of all other files that is a copy of A. These
 duplicates's full paths will be prefixed with rm  string. A empty
 line follows a group of duplicates.

 Here's a sample output.

 inPath/a.jpg
 rm inPath/b.jpg
 rm inPath/3/a.jpg
 rm inPath/hh/eu.jpg

 inPath/ou.jpg
 rm inPath/23/a.jpg
 rm inPath/hh33/eu.jpg

 order does not matter. (i.e. which file will not be rm  does not
 matter.)

 

 perl del_dup.pl dir1 dir2

 will do the same as above, except that duplicates within dir1 or dir2
 themselves not considered. That is, all files in dir1 are compared to
 all files in dir2. (including subdirectories) And, only files in dir2
 will have the rm  prefix.

 One way to understand this is to imagine lots of image files in both
 dir. One is certain that there are no duplicates within each dir
 themselves. (imagine that del_dup.pl has run on each already) Files
in
 dir1 has already been categorized into sub directories by human. So
 that when there are duplicates among dir1 and dir2, one wants the
 version in dir2 to be deleted, leaving the organization in dir1
intact.

 perl del_dup.pl dir1 dir2 dir3 ...

 does the same as above, except files in later dir will have rm 
 first. So, if there are these identical files:

 dir2/a
 dir2/b
 dir4/c
 dir4/d

 the c and d will both have rm  prefix for sure. (which one has rm

 in dir2 does not matter) Note, although dir2 doesn't compare files
 inside itself, but duplicates still may be implicitly found by
indirect
 comparison. i.e. a==c, b==c, therefore a==b, even though a and b are
 never compared.


 --

 Write a Perl or Python version of the program.

 a absolute requirement in this problem is to minimize the number of
 comparison made between files. This is a part of the spec.

 feel free to write it however you want. I'll post my version in a few
 days.

 http://www.xahlee.org/perl-python/python.html
 
  Xah
  [EMAIL PROTECTED]
  http://xahlee.org/PageTwo_dir/more.html

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


Re: static variables in functions (was: Version Number Comparison Function)

2005-03-29 Thread Bengt Richter
On 29 Mar 2005 00:29:06 -0800, El Pitonero [EMAIL PROTECTED] wrote:

Christos TZOTZIOY Georgiou wrote:

 One of the previous related threads is this (long URL):

http://groups-beta.google.com/group/comp.lang.python/messages/f7dea61a92f5e792,5ce65b041ee6e45a,dbf695317a6faa26,19284769722775d2,7599103bb19c7332,abc53bd83cf8f636,4e87b44745a69832,330c5eb638963459,e4c8d45fe5147867,5a184dac6131a61e?thread_id=84da7d3109e1ee14mode=threadnoheader=1#doc_7599103bb19c7332

Another previous message on this issue:

http://groups-beta.google.com/group/comp.lang.lisp/msg/1615d8b83cca5b20

Python's syntax surely is not clean enough for concise metaprogramming.
At any rate, I'd agree with Fernando's assessment:

Fernando wrote:
 The real problem with Python is ... Python is
 going the C++ way: piling feature upon feature, adding bells
 and whistles while ignoring or damaging its core design.

If the core design were better, many new features in Python could
have been rendered unnecessary.

Do you have specific recommendations that might benefit python 3000?
What better core design features would have eliminated what new features?
;-)

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


Re: static variables in functions (was: Version Number Comparison Function)

2005-03-29 Thread El Pitonero
Christos TZOTZIOY Georgiou wrote:

 One of the previous related threads is this (long URL):

http://groups-beta.google.com/group/comp.lang.python/messages/f7dea61a92f5e792,5ce65b041ee6e45a,dbf695317a6faa26,19284769722775d2,7599103bb19c7332,abc53bd83cf8f636,4e87b44745a69832,330c5eb638963459,e4c8d45fe5147867,5a184dac6131a61e?thread_id=84da7d3109e1ee14mode=threadnoheader=1#doc_7599103bb19c7332

Another previous message on this issue:

http://groups-beta.google.com/group/comp.lang.lisp/msg/1615d8b83cca5b20

Python's syntax surely is not clean enough for concise metaprogramming.
At any rate, I'd agree with Fernando's assessment:

Fernando wrote:
 The real problem with Python is ... Python is
 going the C++ way: piling feature upon feature, adding bells
 and whistles while ignoring or damaging its core design.

If the core design were better, many new features in Python could
have been rendered unnecessary.

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


Re: Calling __init__ with multiple inheritance

2005-03-29 Thread jfj
Peter Otten wrote:

Child()
child
father
mother
parent # -- parent only once
__main__.Child object at 0x402ad38c
D-uh?

class Parent(object):
def __init__(self):
print parent
super(Parent, self).__init__()
class Father(Parent):
def __init__(self):
print father
super(Father, self).__init__()
print D-uh
class Mother(Parent):
def __init__(self):
print mother
super(Mother, self).__init__()
print D-oh
class Child(Father, Mother):
def __init__(self):
print child
super(Child, self).__init__()
Child()

This prints
 child
 father
 mother
 parent
 D-oh
 D-uh
Therefore super is a very intelligent function indeed!
jf
--
http://mail.python.org/mailman/listinfo/python-list


Re: help with getting selection from wxChoice with out after it has changed

2005-03-29 Thread Gerrit Holl
'@'.join([..join(['fred', 'dixon']), ..join(['gmail', 'com'])]) wrote:
 From: '@'.join([..join(['fred', 'dixon']), ..join(['gmail', 'com'])]) 
 [EMAIL PROTECTED]

This is a SyntaxError.
You want to enclose the dots with '' marks as well, like this:

'@'.join(['.'.join(['fred', 'dixon']), '.'.join(['gmail', 'com'])])

regards,
Gerrit Holl.

-- 
Weather in Twenthe, Netherlands 29/03 10:55:
10.0C mist overcast wind 0.9 m/s None (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: itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)

2005-03-29 Thread Ville Vainio
 Raymond == Raymond Hettinger [EMAIL PROTECTED] writes:

Raymond If the experience works out, then all you're left with is
Raymond the trivial matter of convincing Guido that function
Raymond attributes are a sure cure for the burden of typing
Raymond import statements.

For one thing, it would make it harder to find the functions from the
docs. It's easy to find the doc for 'itertools', but iter object
methods would require browsing that infamous Chapter 2 of the
documentation...

Apart from that, I don't really see the advantage in moving away from
itertools.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Connecting to a SQL Server

2005-03-29 Thread ttmi
Ok. Understood we can interface ADO from python and connect to MS SQL.
But still not so clear where SSH comes in? Can elaborate more?

Thanks.

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


distance, angle restraint

2005-03-29 Thread HYUN-CHUL KIM



Hi, all
I put more than 10,000 points in a 
box
and then want to getone of many 
solutions that matches all angle restraints among any 3 points and all distance 
restraints between any 2 points.

How can I achieve this?
Please recommend any packages or appropriate 
methods.
Thanks in advance,

Biomatics Lab. Department of 
BiosystemsKorea Advanced Institute of Science and TechnologyYusung-Gu, 
Taejon 305-333Republic of Korea
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: help with getting selection from wxChoice with out after it has changed

2005-03-29 Thread Peter Otten
[..join(['fred','dixon'] wrote:

 I want to get the selection of several wxChoice boxes.
 But i do not want to have to catch the events for all the boxes
 I should be able to access the current selection outside of an
 event,but i am not seeing how to do this.

 #def EvtChoice(self, event):
 #print('EvtChoice: %s\n' % event.GetString())
 #self.ch.Append(A new item)
 #
 ##-changed here - from event.GetSelection()
 #if self.ch.GetSelection() == 'one':
 #print('Well done!\n')

Perhaps you are confused by the fact that GetSelection() returns an integer?
Changing the above to either

if self.ch.GetStringSelection() == 'one':
print 'Well done!'

or 

if self.ch.GetSelection() == 1:
print 'Well done, too!'

should work as you expect then.

Peter


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


passing keyword args as a parameter

2005-03-29 Thread max(01)*
hi there!
this post is somewhat a generalization of one previous question.
i was wondering if it is possible to pass an argument list as a
parameter to a function. example:
def fun_con_pc(pc1 = Ciao!, pc2 = 42):
  print pc1
  print pc2
fun_con_pc()
fun_con_pc(pc1 = Addio...)
fun_con_pc(pc2 = 666, pc1 = Addio...)
arg = 'pc2 = 666, pc1 = Addio...'
fun_con_pc(arg)

if i execute, i get:
Ciao!
42
Addio...
42
Addio...
666
pc2 = 666, pc1 = Addio...
42
**but** i want to get:
Ciao!
42
Addio...
42
Addio...
666
Addio...
666

see what i mean?
bye
macs
--
http://mail.python.org/mailman/listinfo/python-list


tkinter destroy()

2005-03-29 Thread max(01)*
hi people.
when i create a widget, such as a toplevel window, and then i destroy 
it, how can i test that it has been destroyed? the problem is that even 
after it has been destroyed, the instance still exists and has a tkinter 
name, so testing for None is not feasible:

 import Tkinter
 fin = None
 fin1 = Tkinter.Toplevel()
 fin1.destroy()
 print fin1
.1075951116
any help?
bye
macs
--
http://mail.python.org/mailman/listinfo/python-list


Re: Queue.Queue-like class without the busy-wait

2005-03-29 Thread Antoon Pardon
Op 2005-03-25, Paul Rubin schreef http:
 Antoon Pardon [EMAIL PROTECTED] writes:
 Well maybe you could use an os.pipe as a timeout lock then. When the lock is
 instantiated you put one byte in it. Aquiring the lock is implemented by
 reading one byte, releasing the lock is implemented by writing a byte.
 Aquiring the lock with a timeout would make use of select.

 Hmm, if I understand what you're saying, you'd need a separate pipe
 for every lock.  Interesting idea but I think it would burn too many
 file descriptors if you used a lot of them.  My mentioning select also
 is showing my age.  That was the way of doing short sleeps before
 usleep became widespread.

  A signal handler in the main thread could release a lock that the
  thread is waiting on.
 
 This wouldn't work. A thread would have no way knowing for what
 purpose the lock was released, because the lock was released
 by the thread holding the lock or because the signal handler
 released the lock, both would look the same for the thread
 aquiring the lock.

 Yes, you'd need a separate lock for each blocked thread.  There would
 be a list of locks waiting for timeouts and the sigalarm handler would
 release any for which a wakeup was due.  You could use a priority
 queue to maintain the timeout list, so that adding or servicing a
 timeout would be O(log n).

Well have a look at what I have written over the weekend. It uses
a seperate thread with one pipe for a wakeup mechanisme. I didn't
like using a signal handler because you never know what other
modules might have use for signals and how they might interfere.
Try it out and let me know what you think.


Not thoroughly tested:

--- tlock.py --

import threading
import os

import time

from heapq import heappush, heappop
from weakref import ref

from select import select

heapmutex = threading.Lock()
heap = []
heappipe = os.pipe()
sentinel = 365.25 * 50 * 24 * 3600  # 50 jaar
heappush(heap, (time.time() + sentinel, None, None, None))

class _Plock:
  
  def __init__(self):
self.mutex = threading.Lock()
self.broken = False

  def acquire(self):
self.mutex.acquire()

  def release(self):
self.mutex.release()

class TimeOut(Exception):
  pass


class Tlock:

  def __init__(self):
self.mutex = threading.Lock()
self.locktable = [_Plock()]

  def acquire(self, timeout=None):
self.mutex.acquire()
newlock = _Plock()
newlock.acquire()
self.locktable.append(newlock)
prevlock = self.locktable[-2]
if len(self.locktable)  2 and timeout is not None:
  heapmutex.acquire()
  heappush(heap, (time.time() + timeout, ref(prevlock), self.mutex, 
self.locktable))
  os.write(heappipe[1] , '-')
  heapmutex.release()
self.mutex.release()
prevlock.acquire()
if prevlock.broken:
  raise TimeOut, lock timed out

  def release(self):
self.mutex.acquire()
self.locktable[0].release()
del self.locktable[0]
self.locktable[0].release()
self.mutex.release()


def lock_breaker():

  heapfd = heappipe[0]
  while True:
heapmutex.acquire()
waketime, pl, mutex, table = heap[0]
timeout = waketime - time.time()
while timeout = 0.0:
  lck = pl()
  if lck is not None:
mutex.acquire()
try:
  try:
i = table.index(lck, 1)
del table[i]
lck.broken = True
lck.release()
# lck.release()
  except ValueError:
pass
finally:
  mutex.release()
  heappop(heap)
  waketime, pl, mutex, table = heap[0]
  timeout = waketime - time.time()
heapmutex.release()
rdlst, wrlst, erlst = select([heapfd],[],[],timeout)
if rdlst:
  os.read(rdlst[0],1)

breaker = threading.Thread(target = lock_breaker)
breaker.setDaemon(True)
breaker.start()

if __name__ == __main__:

  from time import sleep
  from random import randint

  T = Tlock()

  rg = 5

  def thrd(Id):

for Nr in xrange(20):
  try:
print Trying   %d (loop %d) % (Id, Nr)
T.acquire(randint(0,rg))
print Entering %d (loop %d) % (Id, Nr)
sleep(randint(0,rg))
print Leaving  %d (loop %d) % (Id, Nr)
T.release()
  except TimeOut, ErrId:
print Failed   %d (loop %d) % (Id, Nr)
  sleep(randint(0,rg))


  for i in xrange(rg):
th = threading.Thread(target=thrd, args=(i,))
th.start()
-- 
http://mail.python.org/mailman/listinfo/python-list


tksnack and socket to real time sampling and playing sound

2005-03-29 Thread didifouke
Hi,

I try to sample and playback speech using snack. My idea is to have a
socket based server that plays back the sound and a client that samples
the input from the sound card and sends it to the server using the
socket connection.

On the snack page there is a tutorial showing a socket server
implementation using tcl: http://www.speech.kth.se/snack/tutorial.html

I had problems converting that example into python.

Googling for such a solution I found one discussion back in 2001:

http://groups-beta.google.com/groups?q=tksnack+socketqt_s=Search+Groups

The difference with this solution is that it is based around python
socket and does not use the snack internal socket implementation for
the data input. If I understand that correct there is a limitation as
the socket.recv(8192) function limits the receivable data to the
specified buffer size.

Did somebody use the snack based socket implementation with python?

Is there a better way to solve this sampling and playback with another
tool than snack?

Is snack even capable of doing this? I am looking for pretty low
sampling rates, like 8kHz.

I would like to be flexible and use it under Windows and Linux as well.

TIA

Didi

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


Re: Why tuple with one item is no tuple

2005-03-29 Thread Antoon Pardon
Op 2005-03-27, Joal Heagney schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:
snip
 So python choose a non-deterministic direction. To me (2,3) + (4,5)
 equals (6,8). I don't dispute that having an operator to combine
 (2,3) and (4,5) in (2,3,4,5) is usefull, but they should never have
 used the + for that.

 (alph, bravo) + (delta, max) -- (alphdelta, bravomax)

No, that wouldn't be the result. You are still using + for
concatenation, even if only on strings. I say python should
have used something else for concatenation (string concatenation
included)

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


Re: Queue.Queue-like class without the busy-wait

2005-03-29 Thread Paul Rubin
Antoon Pardon [EMAIL PROTECTED] writes:
 Well have a look at what I have written over the weekend. It uses
 a seperate thread with one pipe for a wakeup mechanisme.

Thanks, I'll look at it.  Why don't you use usleep instead of a pipe?
I decided over the weekend that using a separate thread with usleep is
the simplest thing to do in pure Python.  If you want to use sigalarm,
that should be put in the low level C sigalarm handler so it gets
taken care separately from the Python interpreter does anything with
the signal.  Locks should also be low level primitives.

I don't know how this stuff maps onto PyPy but I sincerely hope the
looping stuff goes away.  Having a series of processing steps
connected by queues is a perfectly good way to organize a program, but
if there's even just 20 steps, then waiting for all those 50 msec
wakeups adds a whole second to the processing latency if the system
has been sleeping for a while.  The latency really only needs to be in
the microseconds on a system with efficient enough threading.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Little Q: how to print a variable's name, not its value?

2005-03-29 Thread TZOTZIOY
On 28 Mar 2005 22:06:44 -0800, rumours say that
[EMAIL PROTECTED] [EMAIL PROTECTED] might have
written:

snip complete article-- subject is enough

Read about locals() and globals() in the Python documentation.  These
provide the information you request (ie what names are bound to what
objects).
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue.Queue-like class without the busy-wait

2005-03-29 Thread Antoon Pardon
Op 2005-03-29, Paul Rubin schreef http:
 Antoon Pardon [EMAIL PROTECTED] writes:
 Well have a look at what I have written over the weekend. It uses
 a seperate thread with one pipe for a wakeup mechanisme.

 Thanks, I'll look at it.  Why don't you use usleep instead of a pipe?

Because with the pipe the sleep can be indeterminate.

The select make the thread sleep until either of the folowing
happens.

  1) A timeout, which means one of the locks has to be broken

  2) A byte was received. This means a lock was tried to be
 acquired and inserted in the heap, so the timeout may
 need to be recalculated. (acquiring a lock, sends a
 byte over the pipe)

 I decided over the weekend that using a separate thread with usleep is
 the simplest thing to do in pure Python.

I'm not going to call my solution simple, but it wastes very few
cycles. if no thread is blocked on a lock, the select will just
block until that changes. No need for some kind of polling loop.

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


Actor pattern in GUI

2005-03-29 Thread M Ali
Hi,

I am trying to grok using actor patterns in a gui as explained here by
Andrew Eland:
http://www.andreweland.org/code/gui-actor.html 

The short article explains it using java with which i am not used to
at all. But he does provide a python example using pygtk:
http://www.andreweland.org/code/gui-actor.py

Could anyone look into it and maybe explain it a bit as i don't really
get at all what's happening?

In addition I am getting these error when I try to run it:

GLib-WARNING **: giowin32.c:1654: 3 is neither a file descriptor or a
socket
GLib-CRITICAL **: g_io_add_watch_full: assertion `channel != NULL'
failed
GLib-CRITICAL **: g_io_channel_unref: assertion `channel != NULL'
failed

Any ideas?

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


Re: Calling __init__ with multiple inheritance

2005-03-29 Thread Axel Straschil
Hello!

 Also, lool at that:
 class Mother(object):
 def __init__(self, param_mother='optional', **eat):
 print 'Mother'
 class Father(object):
 def __init__(self, param_father='optional', **eat):
 print 'Father'
 class Child(Mother, Father):
 def __init__(self, **ham):
 super(Child, self).__init__(**ham)
 child = Child(param_mother=1, param_father=1)
 Father's init will not be called.
 Change Father/Mother.__init__() to call the superclass initializer. It may
 be counterintuitive, but it works.

OK, thanks, with the super(...).__init__() in Father/Mother it workes
and makes sense.

So, the last thing a *realy* don't like ist the
__init__(self, param, **ignore_the_rest) thing. 

Anyone had troubles with that, or should I cust take this as a python
way of thinking ... ;-), and getting used to that?

Thanks,
AXEL.
-- 
Aber naja, ich bin eher der Forentyp. Wolfibolfi's outing in 
http://www.informatik-forum.at/showpost.php?p=206342postcount=10
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue.Queue-like class without the busy-wait

2005-03-29 Thread Antoon Pardon
Op 2005-03-29, Antoon Pardon schreef [EMAIL PROTECTED]:
 Op 2005-03-29, Paul Rubin schreef http:
 Antoon Pardon [EMAIL PROTECTED] writes:
 Well have a look at what I have written over the weekend. It uses
 a seperate thread with one pipe for a wakeup mechanisme.

 Thanks, I'll look at it.  Why don't you use usleep instead of a pipe?

 Because with the pipe the sleep can be indeterminate.

 The select make the thread sleep until either of the folowing
 happens.

   1) A timeout, which means one of the locks has to be broken

   2) A byte was received. This means a lock was tried to be
  acquired and inserted in the heap, so the timeout may
  need to be recalculated. (acquiring a lock, sends a
  byte over the pipe)

 I decided over the weekend that using a separate thread with usleep is
 the simplest thing to do in pure Python.

 I'm not going to call my solution simple, but it wastes very few
 cycles. if no thread is blocked on a lock, the select will just
 block until that changes. No need for some kind of polling loop.


And here is a small patch for it. It corrects the acquiring and
releasing of the heapmutex.

--- tlock.py2005-03-29 14:25:09.0 +0200
+++ src/python/tlock.py 2005-03-29 14:25:43.0 +0200
@@ -67,6 +67,7 @@
 heapmutex.acquire()
 waketime, pl, mutex, table = heap[0]
 timeout = waketime - time.time()
+heapmutex.release()
 while timeout = 0.0:
   lck = pl()
   if lck is not None:
@@ -82,10 +83,11 @@
 pass
 finally:
   mutex.release()
+  heapmutex.acquire()
   heappop(heap)
   waketime, pl, mutex, table = heap[0]
   timeout = waketime - time.time()
-heapmutex.release()
+  heapmutex.release()
 rdlst, wrlst, erlst = select([heapfd],[],[],timeout)
 if rdlst:
   os.read(rdlst[0],1)
@@ -107,17 +109,17 @@
 
 for Nr in xrange(20):
   try:
-print Trying   %d (loop %d) % (Id, Nr)
+print Trying   %2d (loop %2d) % (Id, Nr)
 T.acquire(randint(0,rg))
-print Entering %d (loop %d) % (Id, Nr)
+print Entering %2d (loop %2d) % (Id, Nr)
 sleep(randint(0,rg))
-print Leaving  %d (loop %d) % (Id, Nr)
+print Leaving  %2d (loop %2d) % (Id, Nr)
 T.release()
   except TimeOut, ErrId:
-print Failed   %d (loop %d) % (Id, Nr)
+print Failed   %2d (loop %2d) % (Id, Nr)
   sleep(randint(0,rg))
 
 
-  for i in xrange(rg):
+  for i in xrange(5 * rg):
 th = threading.Thread(target=thrd, args=(i,))
 th.start()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb*ss newbie Q

2005-03-29 Thread Captain Dondo
On Mon, 28 Mar 2005 08:42:22 -0600, Larry Bates wrote:

 Others have answered your specific question, I thought I
 would add some suggestions (not tested):
 
 1) You don't need a separate set_title method.  You can
 change the title attribute at any time by just saying
 m.title=new title.  No method is required unless you
 need to do some pre/post processing.
 
 m.title=anything you want
 
 2) To get class to prepare its output, just insert a
 __str__ method like following:
 
 def __str__(self):
 return 'a href=avi://%s/%s/%s img src=%s%s/tn/%s.jpg/a' % \
(self.audience, self.title,
 self.driver, self.audience,
 self.title, self.title)
 
 
 Then you can eliminate the html method and thumb method and just write:
 
 print m
 
 3) Add extend keyword arguments for url and audience to the __init__
 method. That way you (or other users) will know that each keyword
 means when they run in Idle or other interpreter that expands
 keyword arguments on the screen as you are typing):
 
 m=Movie(title=Fate_is_the_Hunter, audience=kids, \
   driver=X=hermes.seiner.lan:xv,athena.seiner.lan:xmga, \
  default:x11;console=vesa)
 print m
 
 
 If you plan on doing a lot of this you may want to take a look
 at the htmlgen module at:
 
 http://starship.python.net/crew/friedrich/HTMLgen/html/main.html
 
 (I actually stole the idea of using the the __str__ method to
 generate the output from this module).
 
 Hope information helps.

Thanks, it does.  I am trying to write a much simplified album -
http://marginalhacks.com/Hacks/album/ . The author has taken it in a
direction that is no longer useful to me and I am desparately incompetent
in perl  Python and I like each other, except that I don't have much
experience writing it from scratch

For now I am using this tutorial as a go-by:
http://www.linuxgazette.com/issue19/python.html, but I will check out
the link you provided.

--Yan

-- 

use munged address above to email me
SpamTrap [EMAIL PROTECTED] 

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


MAC changing

2005-03-29 Thread ias0nas
Hello,

Is it possible to change the MAC address of a packet after I have
builded it?
I used impacket to build a packet that does not provide the function to
change the MAC. Is it possible to set the bytes of the packet where the
MAC is stored?
I don't want to use system calls to bring the card down and up again
with a different MAC, I need to change it in the packet

Thank you

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


Re: Queue.Queue-like class without the busy-wait

2005-03-29 Thread Antoon Pardon
Op 2005-03-29, Paul Rubin schreef http:
 Antoon Pardon [EMAIL PROTECTED] writes:
 I'm not going to call my solution simple, but it wastes very few
 cycles. if no thread is blocked on a lock, the select will just
 block until that changes. No need for some kind of polling loop.

 I think I understand.  My original idea was to use a heapq to be able
 to know exactly when the next pending timeout is due, and usleep for
 long enough to wake up at just the right time.  Then you service the
 timeout, pop the heap to find when the next timeout after that is, and
 usleep again.  No polling loops and no pipe.  But it could be that
 someone inserts a new timeout while you're sleeping, that's due before
 you're scheduled to wake up.  Your pipe scheme takes care of that,
 since any thread can write to the pipe and wake up the blocked thread
 at any time.

Right, that is the idea.

 Really, the culprit here is the weak signalling scheme in Python.
 There needs to be a way to send signals to threads, or raise
 asynchronous exceptions in them.  There's been some discussion in
 sourceforge about that, but the issues involved are complex.

Well I have raised this issue before and as far as I understand,
the big problem seems to be the various kind of behaviour you
can get depending on what platform you are working, so writing
a module so that python programs behave the same on various
platforms seems a hell of a job.

So I decided not to pester the python people for this kind
of functionality, although I would very much like to have
it.

I have been playing with the C-API and have somekind of
class that allows one thread to raise an excetion in an
other but that wouldn't be a solution here, since the
raised exception will not manifest itself while the
thread is in a C-function.

 I think the best bet for the short term is handling it at the C level,
 with sigalarm.  Another way is to have chained sigalarm handlers in
 the main thread.

Possible, but I don't have the time to investigate that
possibility now.

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


Secure scripts variables

2005-03-29 Thread Florian Lindner
Hello,
given the following situation:

I have a script which is readable and executable by a user, but not
writable.
The users executes the scripts, it reads in a value and based on this value
it computes a result and stores it in a variable.
Can the user read out the value of this variable? If yes, can he be
prevented to do so?

(It's a ordinary user on a Linux system with access to the python
interpreter.)

(Of course: He could just copy the script to a file he has write access and
modify it to print the result. It's a theoretical situation.)

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


Finding attributes in a list

2005-03-29 Thread Ben
Hi

In a list I have a number of soccer players. Each player has a
different rating for attacking, defending, midfield fitness and
goalkeeping.

I have devised a while loop that goes through this list to find the
best player at defending, attacking, midfield and goalkeeping. However
there is more than one defender per team so I therefore need it to find
the next best player.

Below is the code used to ascertain the best defender:


# STUFF TO FIND THE TOP DEFENDER
defender= 0 # The position of defender is set to the first player
in the knowledge base
topdefender = 0
c = 3 # the defensive rating of the first player in the list
d = (len(squadList)-4) # the defensive rating of the last player in the
list.

while c = d:
if squadList[c]  topdefender:
topdefender = squadList[c]
defender  = squadList[c-3] +   + squadList[c-2] # The
defender variable is assigned to the forename and surname of the player
c = c + 8 # Move to the defensive rating of the next player in the
list

print defender



any help on this would be greatly appreciated.

thank you

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


Re: [Newbie] How do I get better at Python programming?

2005-03-29 Thread Roy Smith
In article [EMAIL PROTECTED],
 Paul Rubin http://[EMAIL PROTECTED] wrote:

 Anon [EMAIL PROTECTED] writes:
  I'd like to get to the next level, but I'm not sure how.  Are there
  any suggestions for continuing to learn?  How did you guys learn?
 
 I'd say look at some more general computer science books, maybe not
 Python based.  

This is excellent advice.  Software is really about algorithms.  
Programming languages are just a way to implement those algorithms.  But, 
baby steps first.  My suggestion would be:

1) Find some problems in your daily life that you want to solve, and start 
writing Python programs to solve them (keep in mind, however, that not all 
problems in life can be solved with software).

2) Hang out on this group and ask good questions (see 
http://www.catb.org/~esr/faqs/smart-questions.html for some hints on how to 
do that).

3) After you've spent 6 months or so mastering Python, go learn another 
language.  Which one?  I don't know, there are so many good (and bad) 
choices.  Java, I guess.  Maybe C# or Visual Basic, or even C++.  The 
particular choice of which is not so important as the decision to learn 
another one.  It's not so much that it's better or worse than Python, but 
that it's different, and in experiencing the differences you will gain 
insight into what both of them have in common.

4) Here's the hard part.  Every year, for the rest of your programming 
career, learn another language.  Some languages you will learn because they 
lead to paychecks.  Some you will learn because they're cool and different 
and it's worth exploring the corners of the envelope.  Each one will teach 
you something new about programming.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with RC2

2005-03-29 Thread Anthony Baxter
On Mon, 28 Mar 2005 21:32:07 +0200, Do Re Mi chel La Si Do
[EMAIL PROTECTED] wrote:
 Hi !
 
 I have sevral problems with P4-RC2.
 
 Typical case, I have a script who run OK with P4 standard ; but, on a new
 install, with P4-RC2, I obtain :
 
 Traceback (most recent call last):
   File C:\PONX\ponx.py, line 60, in ?
 import pdebug
   File C:\PONX\pdebug.py, line 224
 for tmpArg in args[1:]:
   ^
 SyntaxError: invalid syntax

I'm assuming you mean 2.4 for P4 and 2.4.1c2 for P4-RC2. I can
see no changes that should have caused this - without seeing the
entire file, I can only assume that you've either got indentation
wrong, or you're maybe mixing tabs and spaces? That's the best I can
do without seeing the whole file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which is easier? Translating from C++ or from Java...

2005-03-29 Thread Roy Smith
[EMAIL PROTECTED] wrote:

 There is a difference between theory and practice.

You know the difference between theory and practice?  Well, in theory, 
there is no difference :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


BF interpreter in Python

2005-03-29 Thread Will McGugan
Hi,
Python is my favorite language, but I rarely get the opertunity to use 
it at work, so I find myself actively looking for problems to solve with 
it. Consequently while waiting for C++ build to finish, I wrote a 
BrainF*** interpreter.

If you are not familiar with the BF language see the following example, 
which calculates the mandlebrot set..

http://esoteric.sange.fi/brainfuck/bf-source/prog/mandelbrot.b
My BF interpreter is here..
http://www.willmcgugan.com/brainfuck.py
Release to the public domain!
I imagine somebody has already done this in Python, and I fully expect 
some Python expert to give a one line generator expression with the same 
functionality..

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


Re: Grouping code by indentation - feature or ******?

2005-03-29 Thread Roy Smith
Antoon Pardon [EMAIL PROTECTED] wrote:
 1) The stuff doesn't has to be spread over multiple pages. One
can have 2 functions, each about three quarter of a page.
The second function will then cross a page boundary.

The advice don't write a function longer than a page is as good advice 
today as it was 30 years ago, but the definition of a page has changed.  
In the old days, a page pretty much meant 66 lines, because that's what 
fit on a standard sheet of line printer paper (minus a few lines for 
headers and footers).

These days, a page pretty much means a window, which are scrollable so 
your function always starts at the top of one.  Of course, there is no 
standard for how long a window is, but...

 2) How long is a page? I have worked in differend kind of
environments where the number of lines per page could
differ from 35 to 70.

I would say 35 to 70 lines seems like a reasonable limit for how long a 
function should be :-)  The system I'm working with now is fill with 500 
line functions and 700 line functions.  Believe me, 70 lines would be a 
blessing compared to that.

The bottom line is not a rigid line count.  The goal is to be able to 
understand what the function is doing in one gulp.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing keyword args as a parameter

2005-03-29 Thread Fredrik Lundh
max(01)* [EMAIL PROTECTED] wrote:

 see what i mean?

not really, but maybe

arg = {pc2: 666, pc1: Addio...}
fun_con_pc(**arg)

is what you want?

/F 



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


Re: Why tuple with one item is no tuple

2005-03-29 Thread Ville Vainio
 Antoon == Antoon Pardon [EMAIL PROTECTED] writes:

Antoon Op 2005-03-27, Joal Heagney schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:
 snip
 So python choose a non-deterministic direction. To me (2,3) + (4,5)
 equals (6,8). I don't dispute that having an operator to combine
 (2,3) and (4,5) in (2,3,4,5) is usefull, but they should never have
 used the + for that.
 
 (alph, bravo) + (delta, max) -- (alphdelta, bravomax)

Antoon No, that wouldn't be the result. You are still using +
Antoon for concatenation, even if only on strings. I say python
Antoon should have used something else for concatenation (string
Antoon concatenation included)

To me, nothing is more natural than ab + cd == abcd. Also [1,2]
+ [3,4] == [1,2,3,4]. Dot product is not really too useful in real
world (non-mathematical) apps.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Max files in unix folder from PIL process

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

Rowdy wrote:
 
 FreeDB (CD database) stores one file per CD in one directory per
 category.  The misc category/directory on my FreeBSD 5.3 system
 currently contains around 481,571 small files.  The rock
 directory/category contains 449,208 files.
 
 As some have said, ls is *very* slow on these directories, but otherwise
 there don't seem to be any problems.
  

I assume you're all using Linux.  The GNU version of ls does two things
that slow it down.  The System V and BSD versions were pretty much
identical, in that they processed the argv array in whatever order the
shell passed it in.  The GNU version re-orders the argv array and stuffs
all the arguments into a queue.  No big deal if you're just doing ls,
but for ls multiple directory names it can slow it down for large
argv[n] and/or recursive/deep ls.

The other thing it does different from SysV/BSD ls is that it provides
for default options in an environment variable.  If those env settings
specify to always use color, that will slow directory processing _way_
down, identically to the -F option.  That's because the color and -F
options _require_ a stat() on each and every file in the directory. 
Standard ls with no options (or old SysV/BSD ls that came with no
options) works nearly as fast as os.listdir() in Python, because it
doesn't require a stat().

The only thing faster, from a shell user's viewpoint, is 'echo *'.  That
may not be much help;-)

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


good design method calls

2005-03-29 Thread Charles Hartman
I know the answer to this is going to be It depends . . ., but I want 
to get my mind right. In Fowler's *Refactoring* I read: Older 
languages carried an overhead in subroutine calls, which deterred 
people from small methods (followed by the basic Extract Method 
advice). In Skip Montanaro's Python Performance Tips 
(http://manatee.mojam.com/~skip/python/fastpython.html) I read: . . .  
use local variables wherever possible. If the above loop is cast as a 
function, append and upper become local variables. Python accesses 
local variables much more efficiently than global variables.

These two pieces of advice imply opposite kinds of code revisions. 
Obviously they have different purposes, and both are right at different 
times. I wonder if anyone has some wisdom about how to think about when 
or how often to do which, how to balance them ultimately, and so on.

Charles Hartman
Professor of English, Poet in Residence
the Scandroid is at: http://cherry.conncoll.edu/cohar/Programs
http://villex.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: convert user input to Decimal objects using eval()?

2005-03-29 Thread Julian Hernandez Gomez
On Tuesday 29 March 2005 03:04, Raymond Hettinger wrote:
 from decimal import Decimal
 import re

 number = re.compile(r((\b|(?=\W))(\d+(\.\d*)?|\.\d+)([eE][+-]?\d{1,3})?))
 deciexpr = lambda s: number.sub(rDecimal('\1'), s)

 for s in ('1.0001+0.111',
    '+21.3e-5*85-.1234/81.6',
    '1.0/7'):
     print '%s\n  -- %r' % (s, eval(s))
     s = deciexpr(s)
     print '%s\n  -- %r\n' % (s, eval(s))

Wow!

Thank you so much!!!

now I can do my simple math function evaluator much more reliable !

Thanks again!

-- 
Julián
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why tuple with one item is no tuple

2005-03-29 Thread Ville Vainio
 Ville == Ville Vainio [EMAIL PROTECTED] writes:

Ville To me, nothing is more natural than ab + cd ==
Ville abcd. Also [1,2] + [3,4] == [1,2,3,4]. Dot product is
Ville not really too useful in real world (non-mathematical)
Ville apps.

... and of course by dot product, I don't mean dot product at all. I
was thinking of summing vectors, which is not that much more common
either.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Optimisation Hints (dict processing and strings)

2005-03-29 Thread OPQ
Hi all,


I'd happy to have you share some thougts about ultimate optimisations
on those 2 topics:

(1)- adding one caractere at the end of a string (may be long)
(2)- in a dict mapping a key to a list of int, remove every entrie
where the list of int have of length  2


So far, my attempts are
for (1): 
longone=longone + char # where len(char)== 1
I known that string concatenation is time consuming, but a small test
on timeit seems to show that packing and creating an array for those 2
elements is equally time consuming


for (2):
for k in hash.keys()[:]: # Note : Their may be a lot of keys here
   if len(hash[k])2:
  del hash[k]


Here again, I think the hash.keys duplication can be time *and* memory
consuming. But still better than (I suppose - no time it yet)
hash=dict([(k,v) for (k,v) in hash if len(v)1])


I know that I can experiment further with timeit, but still would like
to hear from your experience.

Thanks ! 

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


Re: [Newbie] How do I get better at Python programming?

2005-03-29 Thread Larry Bates
1) If you write for MS Windows Get a copy of Python Programming on
Win32.

2) Get a copy of Python Cookbook (2nd Edition just shipped).  It
has 100's of examples with detailed explanations of what the
code does.  It starts out with very simple recipes but by the
end of the book you are covering very advanced techniques.

3) Read the standard library documentation and source code.  You
can learn a lot.

4) Read this list every day.  I learn something daily.

Larry Bates

Anon wrote:
 I've gotten off to a good start for programming using Python (my first
 programming language).  I can do the basics (different kinds of loops,
 variables, functions), but I'm not too good with classes yet.  I've
 written some really small programs just for kicks (most involve
 statistics of different situations using random numbers).
 
 I'd like to get to the next level, but I'm not sure how.  Are there any
 suggestions for continuing to learn?  How did you guys learn?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Little Q: how to print a variable's name, not its value?

2005-03-29 Thread Ron_Adam
On 28 Mar 2005 23:01:34 -0800, Dan Bishop [EMAIL PROTECTED] wrote:

 def print_vars(vars_dict=None):
...if vars_dict is None:
...   vars_dict = globals()
...for var, value in vars_dict.items():
...   print '%s = %r' % (var, value)
...
 myPlace = 'right here'
 myTime = 'right now'
 print_vars()
print_vars = function print_vars at 0x401e0d84
__builtins__ = module '__builtin__' (built-in)
myTime = 'right now'
myPlace = 'right here'
__name__ = '__main__'
__doc__ = None


Fred = 5
John = 8
Winner = John
 
Both John and Winner are pointing to the literal '8'.

Mixing data and program code, ie.. variable names as data, is not a
good idea.

Dictionaries are one of pythons best features. ;)


Ron

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


Re: Secure scripts variables

2005-03-29 Thread Serge Orlov
Florian Lindner wrote:
 Hello,
 given the following situation:

 I have a script which is readable and executable by a user, but not
 writable.
 The users executes the scripts, it reads in a value and based on this
 value  it computes a result and stores it in a variable.
 Can the user read out the value of this variable?

Yes.

 If yes, can he be prevented to do so?

Only if the sensitive part of your script runs under different
user. See thread about storing passwords in a script:

http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/91e4c114c5114e92


 (It's a ordinary user on a Linux system with access to the python
 interpreter.)

If there is a will, there is a way :) I used to run a persistant server
on Solaris as ordinary user. The trick is to create an entry in crontab
that will periodically (every 10 minutes) check if your server is
running, if not, start it up. Note however, after that it's not a good
idea to keep sensitive files in your home directory (like your tax
forms or browsing history), because if you make an error in your server
and it will be hacked, then you risk exposing all your files.


  Serge.

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


Re: Optimisation Hints (dict processing and strings)

2005-03-29 Thread Peter Hansen
OPQ wrote:
I'd happy to have you share some thougts about ultimate optimisations
on those 2 topics:
(1)- adding one caractere at the end of a string (may be long)
longone=longone + char # where len(char)== 1
I known that string concatenation is time consuming, but a small test
on timeit seems to show that packing and creating an array for those 2
elements is equally time consuming
You've misunderstood the comments about this area.
String concatenation is *not* time consuming.
*Repeated* concatenations *will become very time
consuming*, along an exponential curve.  That's
what the discussions about O(n^2) are referring
to.  A single string concatenation is definitely
going to be faster than any amount of converting
to other data structures and such.
Basically, to concatenate two strings, Python
simply adds their sizes together and allocates
a new memory area of sufficient size, then copies
the bytes from each string to the new area.  Not
much overhead there, for a single concatenation.
The problem comes when you try to scale this.
At some point, the overhead of allocating and
deallocating all the intermediate strings becomes
much larger than other approaches would take.
For example, by building a list with references
to all the strings, then using join(), you save
on the intermediate steps.  Join performs the
length-summation and memory allocation steps
only once, and copies each individual string into
the final area only once.  Much faster, provided
the overhead of growing a list as you append()
string references is small enough.  And it is,
since growing a list is not O(n^2) in Python
(though I don't recall exactly what it is).
The key with this stuff is to realize that neither
approach is inherently faster: it depends on how
much concatenation you are doing.  It could be
that concatenating up to four strings is faster
than using the append/join technique, or it could
be that it's faster up to twenty strings.
When you're not talking hundreds of operations,
and when you're not talking about actual *measured*
performance problems (in other words, when we would
call it premature optimization), focus on the
readability of the code and on keeping it simple
and clean.  Worry about the correctness of the code,
and leave optimization worries till later.  (But
understand this big O stuff well enough to
be able to avoid the real problem areas, when
possible.)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Table of Python Packages, updated

2005-03-29 Thread Seo Sanghyeon
Hello, comp.lang.python, and catalog-sig,

Some of you may remember my mail with the very same subject
last year. :-) I have continued to maintain the table, and here's
the updated result:

http://sparcs.kaist.ac.kr/~tinuviel/pypackage/list.cgi

304 Python projects indexed, with links to PyPI, FreeBSD port,
Debian deb, Gentoo ebuild, NetBSD pkgsrc, and Fink.

Now I am thinking about adding the version tracking.

What do you think? If you have any suggestion, correction or
omission, please mail me!

P.S. I'm not subscribed. Please CC.

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


Re: Optimisation Hints (dict processing and strings)

2005-03-29 Thread Daniel Dittmar
OPQ wrote:
for (1): 

longone=longone + char # where len(char)== 1
I known that string concatenation is time consuming, but a small test
on timeit seems to show that packing and creating an array for those 2
elements is equally time consuming
- use cStringIO instead
- or append all chars to a list and do .join (listvar)
for (2):
for k in hash.keys()[:]: # Note : Their may be a lot of keys here
   if len(hash[k])2:
  del hash[k]
Here again, I think the hash.keys duplication can be time *and* memory
consuming. But still better than (I suppose - no time it yet)
hash=dict([(k,v) for (k,v) in hash if len(v)1])
- Try if it isn't faster to iterate using items instead of iterating 
over keys
- use the dict.iter* methods to prevent building a list in memory. You 
shouldn't use these values directly to delete the entry as this could 
break the iterator:

for key in [k for (k, v) in hash.iteritems () if len (v)  2]:
del hash (key)
This of course builds a list of keys to delete, which could also be large.
- also: hash.keys()[:] is not necessary, hash.keys () is already a copy
Daniel
--
http://mail.python.org/mailman/listinfo/python-list


Re: good design method calls

2005-03-29 Thread Peter Hansen
Charles Hartman wrote:
I know the answer to this is going to be It depends . . ., but I want 
to get my mind right. In Fowler's *Refactoring* I read: Older languages 
carried an overhead in subroutine calls, which deterred people from 
small methods (followed by the basic Extract Method advice). In Skip 
Montanaro's Python Performance Tips 
(http://manatee.mojam.com/~skip/python/fastpython.html) I read: . . .  
use local variables wherever possible. If the above loop is cast as a 
function, append and upper become local variables. Python accesses local 
variables much more efficiently than global variables.

These two pieces of advice imply opposite kinds of code revisions. 
Obviously they have different purposes, and both are right at different 
times. I wonder if anyone has some wisdom about how to think about when 
or how often to do which, how to balance them ultimately, and so on.
While I don't see that Skip's specific comment in any way
implies that one should not write functions (doesn't it
*say* to write a function?), you are correct at least in
the implication that Fowler's advice about creating lots
of small functions can carry a performance cost in Python.
Python functions have a relatively high setup overhead.
On the other hand, most of refactoring is or should be
focused on improving the structure of code (removing
duplication, improving readability, generalizing, etc)
and *not* on improving performance.  Why should be?
Because in general focusing on improving performance is
wasted effort, often with negative results when you
look at the big picture.
I suspect you've seen the repeated comments in this
comp.lang.python about premature optimization (the
root of all evil in programming etc. etc.).
Optimization rarely *improves* code readability, and
often involves a decrease in generality or other
tradeoffs.  If it conflicts this much with advice
from the refactoring world, you'd do well to pay
close attention to *why* you are trying to change
your code.  If it's for performance reasons, then
don't pay a lot of attention to the Fowler stuff.
Otherwise ignore things like Skip's comment above,
and focus on making the code readable.
The thing that has helped me most in writing efficient
Python is to remember that *I'm using Python*, and
it's already rather slower than C for many of the
things I do.  Why am I using Python?  Not for speed,
clearly, so worrying about speed is probably a little
silly.  I use Python because of the readability,
because I can write it about ten times faster than
I can write in other languages, and because I have
access to such a wide array of outstanding libraries
that someone else has already optimized.  So in
the end, my definition of efficient gets revised,
I lower my standards to the point where my current
code is plenty fast, and I pay attention to the
other things Skip says :-) but don't spend a lot of
time trying hard to use local variables unless it
makes my code more readable in some way.
Sorry for the rant...  I didn't intend it to head
that way when I started out, but I seem to be on a
bit of an anti-optimization bent today. :-)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Retrieve Icons Associated To An Extension?

2005-03-29 Thread andrea . gavana
Hello NG,

  I have searched everyweher, and I am not able to find a solution...
basically, I am constructing a GUI with wxPython, in which I have a list.
In this list control, I have some file. I would like to associate (to every
file) its icon (on Windows). I have searched about the use of Mark
Hammond's win32all extensions and also ctypes, but I didn't find a
solution. Could anyone please provide a very simple example on how to
retrieve an icon associated to a file extension on Windows?

Thank you a lot.

Andrea.


--
 Message for the recipient only, if received in error, please notify the
sender and read http://www.eni.it/disclaimer/


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


Re: Table of Python Packages, updated

2005-03-29 Thread Skip Montanaro

Seo Hello, comp.lang.python, and catalog-sig, Some of you may remember
Seo my mail with the very same subject last year. :-) I have continued
Seo to maintain the table, and here's the updated result:

Seo http://sparcs.kaist.ac.kr/~tinuviel/pypackage/list.cgi

Very nice.  I have a couple questions.  What do the pink/grey cell
backgrounds mean?  Would it make sense to add a distutils column for those
packages that can be installed from source using python setup.py install,
or do you assume that all the listed packages have that capability?

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


Re: tkinter destroy()

2005-03-29 Thread max(01)*
Eric Brunel wrote:
On Tue, 29 Mar 2005 10:37:10 GMT, max(01)* [EMAIL PROTECTED] wrote:
hi people.
when i create a widget, such as a toplevel window, and then i destroy
it, how can i test that it has been destroyed? the problem is that even
after it has been destroyed, the instance still exists and has a tkinter
name, so testing for None is not feasible:
  import Tkinter
  fin = None
  fin1 = Tkinter.Toplevel()
  fin1.destroy()
  print fin1
.1075951116

The winfo_exists method is what you want:
print fin1.winfo_exists()
0
However, I'm curious about *why* you want to do that: since *you* made 
the call to destroy, what would you want to do anything with a widget 
you've already destroyed?
my main window has a button that opens another toplevel window. this 
button is bound to a method that creates the window and does some other 
processing *only if* the windows does not exist yet (otherwise, the user 
could click more on the button and multiple copies of the window would 
pop up, which is not what i want... in fact what i do is to assign None 
to a variable called self.dialogo in my main application code, then i do 
self.dialogo = Toplevel() inside the method...)

in this precise moment, though, it comes to my mind that i could achieve 
the purpose simply activating/deactivating the button according to a flag...

anyway, i attach the code, so you can see better what i mean...
anyone who has to say anything about is welcome of course...
it is a tentative adapration of a program found in the tcl/tk package demo
---cut here---
from Tkinter import *
class MiaApp:
  def __init__(self, genitore):
self.mioGenitore = genitore
self.fonte = (Helvetica, 12)
self.fonteVar = (Helvetica, 14)
self.quadro_grande = Frame(genitore)
self.quadro_grande.pack(expand = YES, fill = BOTH)
self.msg = Label(self.quadro_grande)
self.msg.configure(
  font = self.fonte,
  wraplength = 10c,
  justify = LEFT,
  text = uSono qui sotto presentati tre pulsanti a spunta. \
Premendo un pulsante, se ne varia lo stato di selezione e si \
imposta una variabile a un valore che indica lo stato del \
pulsante stesso. Premendo il pulsante \u00ABMostra \
Variabili\u00BB si possono vedere i valori correnti delle \
variabili.
  )
self.msg.pack(side = TOP)
self.pulsanti = Frame(self.quadro_grande)
self.pulsanti.pack(side = BOTTOM, fill = X, padx = 2m)
self.pulsanti_spunta = Frame(self.quadro_grande)
self.pulsanti_spunta.pack(side = TOP, fill = X, padx = 2m)
self.annulla = Button(self.pulsanti)
self.annulla.configure(
  text = Annulla,
  command = self.mioGenitore.destroy
  )
self.annulla.pack(side = LEFT, expand = YES)
self.var = Button(self.pulsanti)
self.var.configure(
  text = Mostra Variabili,
  command = self.pulsanteMostraVariabiliPremuto
  )
self.var.pack(side = LEFT, expand = YES)
self.tergicristalli = IntVar()
self.b1 = Checkbutton(self.pulsanti_spunta)
self.b1.configure(
  text = Tergicristalli a posto,
  variable = self.tergicristalli,
  relief = FLAT
  )
self.b1.pack(
  side = TOP,
  pady = 2,
  anchor = W
  )
self.freni = IntVar()
self.b2 = Checkbutton(self.pulsanti_spunta)
self.b2.configure(
  text = Freni a posto,
  variable = self.freni,
  relief = FLAT
  )
self.b2.pack(
  side = TOP,
  pady = 2,
  anchor = W
  )
self.autista = IntVar()
self.b3 = Checkbutton(self.pulsanti_spunta)
self.b3.configure(
  text = Autista sobrio,
  variable = self.autista,
  relief = FLAT
  )
self.b3.pack(
  side = TOP,
  pady = 2,
  anchor = W
  )
self.dialogo = None
  def mostraVariabili(self, *argomenti):
self.dialogo = Toplevel()
self.dialogo.wm_title(Valori delle variabili)
self.dialogo.quadro_grande = Frame(self.dialogo)
self.dialogo.quadro_grande.pack(expand = YES, fill = BOTH)
self.dialogo.titolo = Label(self.dialogo.quadro_grande)
self.dialogo.titolo.configure(
  text = Valori delle variabili:,
  width = 20,
  font = self.fonteVar
  )
self.dialogo.titolo.pack(side = TOP, fill = X)
lung = 1
for i in argomenti:
  if len(i)  lung:
lung = len(i)
self.dialogo.dq = {}
self.dialogo.dn = {}
self.dialogo.dv = {}
for i in argomenti:
  self.dialogo.dq[i] = Frame(self.dialogo.quadro_grande)
  self.dialogo.dq[i].pack(
side = TOP,
anchor = W,
fill = X
)
  self.dialogo.dn[i] = Label(self.dialogo.dq[i])
  self.dialogo.dn[i].configure(
text = i + : ,
width = lung + 2,
anchor = W
)
  self.dialogo.dn[i].pack(
side = LEFT
)
  self.dialogo.dv[i] = Label(self.dialogo.dq[i])
  self.dialogo.dv[i].configure(
textvariable = self.freni,  ### FIXME
anchor = W
)
  self.dialogo.dv[i].pack(
side = LEFT,
  

Re: hiding a frame in tkinter

2005-03-29 Thread Fredrik Lundh
faramarz yari wrote:

 def do_unpack(f):
f.pack_forget()
 ...
 b=Button(f3,text=hello,command=do_unpack(f3))

 it does not work  the interpreter does not claim any error.

it works perfectly fine, but it doesn't do what you want.

do_unpack(f3)

is a function call, so you're calling the function *before* you create
the button, and you're then passing the return value (None) to the
button widget.

if you want to use the function as a callback, use a lambda:

b=Button(..., command=lambda: do_unpack(f3))

or a local function

def cb():
do_unpack(f3)
b=Button(..., command=cb)

/F 



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


Re: passing keyword args as a parameter

2005-03-29 Thread max(01)*
Fredrik Lundh wrote:
max(01)* [EMAIL PROTECTED] wrote:

see what i mean?

not really, but maybe
arg = {pc2: 666, pc1: Addio...}
fun_con_pc(**arg)
is what you want?
precisely! thanks a lot!
macs
--
http://mail.python.org/mailman/listinfo/python-list


Re: Retrieve Icons Associated To An Extension?

2005-03-29 Thread Will McGugan
[EMAIL PROTECTED] wrote:
Hello NG,
  I have searched everyweher, and I am not able to find a solution...
basically, I am constructing a GUI with wxPython, in which I have a list.
In this list control, I have some file. I would like to associate (to every
file) its icon (on Windows). I have searched about the use of Mark
Hammond's win32all extensions and also ctypes, but I didn't find a
solution. Could anyone please provide a very simple example on how to
retrieve an icon associated to a file extension on Windows?
Check out MimeTypesManager in the wxPython demo app (under More 
Windows/Controls). That seems to do what you want..

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


serial module NEWBE HELP!

2005-03-29 Thread Ron
Is this built into any of the python versions? Need it! Using 2.3.5 and 
doesn't seem to have it.Newbe needs help!email[EMAIL PROTECTED]  Thanks Ron 


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


Re: Which is easier? Translating from C++ or from Java...

2005-03-29 Thread Patrick Useldinger
[EMAIL PROTECTED] wrote:
Patrick Useldinger wrote:
Depends on what language you know best. But Java is certainly easier
to
read than C++.

There's certainly some irony in those last two sentences. However, I
agree with the former. It depends on which you know better, the style
of those who developed each and so forth. Personally, I'd prefer C++.
Not really.
If you know none of the languages perfectly, you are less likely to miss 
something in Java than in C++ (i.e. no , * and stuff in Java).

However, if you are much more familiar with one of the two, you're less 
likely to miss things there.

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


Re: Table of Python Packages, updated

2005-03-29 Thread Seo Sanghyeon
http://sparcs.kaist.ac.kr/~tinuviel/pypackage/list.cgi

On Tue, Mar 29, 2005 at 09:30:24AM -0600, Skip Montanaro wrote:

 Very nice.  I have a couple questions.  What do the pink/grey cell
 backgrounds mean?

Pink background is not packaged, grey background is in progress.

For in progress items, links to (for now) Debian Bug Tracking System,
FreeBSD Problem Report, and Gentoo Bugzilla are provided.

For the summary line, Debian 208(41) means 208 projects are already
packaged, and 41 projects are in the progress of packaging.

 Would it make sense to add a distutils column for those
 packages that can be installed from source using python setup.py
 install or do you assume that all the listed packages have that
 capability?

Are you suggesting linking to the project's homepage, or upstream
source tarball? I am not sure whether that makes sense...

On the other hand, I think that if there are projects in the table
that doesn't use distutils yet, they should be fixed.

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


Re: Table of Python Packages, updated

2005-03-29 Thread Skip Montanaro

 Would it make sense to add a distutils column for those packages
 that can be installed from source using python setup.py install or
 do you assume that all the listed packages have that capability?

Seo Are you suggesting linking to the project's homepage, or upstream
Seo source tarball? I am not sure whether that makes sense...

Seo On the other hand, I think that if there are projects in the table
Seo that doesn't use distutils yet, they should be fixed.

That was more what I was getting at, just identification of packages that
are installed with distutils.

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


Re: Optimisation Hints (dict processing and strings)

2005-03-29 Thread Aaron Bingham
Peter Hansen [EMAIL PROTECTED] writes:

 You've misunderstood the comments about this area.
 String concatenation is *not* time consuming.
 *Repeated* concatenations *will become very time
 consuming*, along an exponential curve.  That's
 what the discussions about O(n^2) are referring
 to.  

For the record, O(n^2) is /not/ exponential, but polynomial.  A
function with exponential complexity would have, e.g. O(A^n) for some
constant A, which would be /much/ worse than the behavior of repeated
string concatenation.

Regards,

-- 

Aaron Bingham
Software Engineer
Cenix BioScience GmbH


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


Re: Little Q: how to print a variable's name, not its value?

2005-03-29 Thread Bill Mill
On Tue, 29 Mar 2005 14:34:39 GMT, Ron_Adam [EMAIL PROTECTED] wrote:
 On 28 Mar 2005 23:01:34 -0800, Dan Bishop [EMAIL PROTECTED] wrote:
 
  def print_vars(vars_dict=None):
 ...if vars_dict is None:
 ...   vars_dict = globals()
 ...for var, value in vars_dict.items():
 ...   print '%s = %r' % (var, value)
 ...
  myPlace = 'right here'
  myTime = 'right now'
  print_vars()
 print_vars = function print_vars at 0x401e0d84
 __builtins__ = module '__builtin__' (built-in)
 myTime = 'right now'
 myPlace = 'right here'
 __name__ = '__main__'
 __doc__ = None
 
 Fred = 5
 John = 8
 Winner = John
 
 Both John and Winner are pointing to the literal '8'.

ummm, yes, of course they are. What's your point?

 
 Mixing data and program code, ie.. variable names as data, is not a
 good idea.

Down with eval! Exile exec! A pox on both their houses!

(i.e. I respectfully disagree that mixing data with program code is a bad idea)

Peace
Bill Mill
bill.mill at gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numarray newbie question

2005-03-29 Thread ChinStrap
Are there no windows binaries for SciPy for python 2.4 yet?  I try to
run the installer and it complains that it can't find python 2.3.

Besides that, vectorize is exactly what i want.

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


truncating a file from the top down

2005-03-29 Thread rbt
Hi guys,
I need to truncate a file from the top down. I imagine doing something 
like this:

if os.stat says the file is too big:
read the file
trim = only keep the last 2008 bytes (This is where I get stuck)
write trim back out to the original file
Would someone demonstrate the *best* most efficient way of doing this?
Thanks,
rbt
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numarray newbie question

2005-03-29 Thread Robert Kern
ChinStrap wrote:
Are there no windows binaries for SciPy for python 2.4 yet?  I try to
run the installer and it complains that it can't find python 2.3.
No, not yet.
Besides that, vectorize is exactly what i want.
--
Robert Kern
[EMAIL PROTECTED]
In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die.
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


Re: truncating a file from the top down

2005-03-29 Thread Mike Rovner
rbt wrote:
if os.stat says the file is too big:
read the file
trim = only keep the last 2008 bytes (This is where I get stuck)
write trim back out to the original file
Would someone demonstrate the *best* most efficient way of doing this?
if os.stat says the_file is too big:
  fh = open(the_file, 'rb')
  fh.seek(2008, 2)
  data = fh.read()
  fh.close()
  assert len(data)==2008 # you may want some error processing here
  fh = open(the_file, 'wb')
  fh.write(data)
  fh.close()
/m
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numarray newbie question

2005-03-29 Thread ChinStrap
Oh well. I am downloading all the things to build it, but in the mean
time I just did:

def get_y_mat(x_ind,y_ind):

return self.y_min + y_ind*self.dy

def get_x_mat(x_ind,y_ind):

return self.x_min + x_ind*self.dx

self.x_mat=fromfunction(get_x_mat,matshape)
self.y_mat=fromfunction(get_y_mat,matshape)

def fxy(x_ind,y_ind):
x=self.x_min + x_ind*self.dx
y=self.y_min + y_ind*self.dx
return f(x,y)

def vxy(x_ind,y_ind):
x=self.x_min + x_ind*self.dx
y=self.y_min + y_ind*self.dx
return v(x,y)

self.f_mat=fromfunction(fxy,matshape)
self.v_mat=fromfunction(vxy,matshape)

As you can see I am just repeating calculations in fxy and vxy that I
have already done for x_mat and y_mat.  This is still faster than
saying:

self.f_mat = array([f(x,y) for x in x_mat for y in y_mat],matshape)

by a noticable amount.

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


Re: Max files in unix folder from PIL process

2005-03-29 Thread Kane
Yes I'm talking Linux not BSD so with any luck you won't have the same
'ls' issue; it is not a crash but painfully slow.  The only other issue
I recall is wildcards fail if they encompass too many files (presumably
a bash/max command line size).

I would expect the various GUI file managers may give unpredictable
results; I would also not rely on remotely mounting the bigdir
cross-platform.

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


Re: serial module NEWBE HELP!

2005-03-29 Thread Peter Hansen
Ron wrote:
Is this built into any of the python versions? Need it! Using 2.3.5 and 
doesn't seem to have it.Newbe needs help!email[EMAIL PROTECTED]  Thanks Ron 
PySerial has never been built in to any standard v
distribution of Python, but it's an easy download
and the web page is the first hit in Google if
you type python serial...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question

2005-03-29 Thread shama . bell
Whats the file that has to be mapped? Can this be a list? Can this list
be initialized to 512?

Thanks,
-SB

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


Python performance tips page moved to wiki

2005-03-29 Thread Skip Montanaro
I dumped my old fastpython.html web page:

http://manatee.mojam.com/~skip/python/fastpython.html

in favor of a page on the Python wiki:

http://www.python.org/moin/PythonSpeed/PerformanceTips

Now everybody can help fix warts, add content, etc, etc, etc.

References to the old page are redirected to the new one.  Have at it.

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


Re: Finding attributes in a list

2005-03-29 Thread infidel
You can use the new 'sorted' built-in function and custom compare
functions to return lists of players sorted according to any criteria:

 players = [
... {'name' : 'joe', 'defense' : 8, 'attacking' : 5, 'midfield' : 6,
'goalkeeping' : 9},
... {'name' : 'bob', 'defense' : 5, 'attacking' : 9, 'midfield' : 6,
'goalkeeping' : 3},
... {'name' : 'sam', 'defense' : 6, 'attacking' : 7, 'midfield' : 10,
'goalkeeping' : 4}
... ]
 def cmp_attacking(first, second):
... return cmp(second['attacking'], first['attacking'])
...
 [p['name'] for p in sorted(players, cmp_attacking)]
['bob', 'sam', 'joe']


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


Re: xml marshal of general (but non Python standard) class

2005-03-29 Thread syd
Thank you Martin.  I had not considered pickle, and I've done my
research.  However, I'm still having problems:

Your foo class (for pickle and xml dumps) works fine for me.
 f=Foo()
 f.thanksTo='Martin'
 f.howMany=100
 pickle.dumps(f)
(i__main__\nFoo\np0\n(dp1\nS'thanksTo'\np2\nS'Martin'\np3\nsS'howMany'\np4\nI100\nsb.

But for my identifiedPeaks class (for instance), it has trouble.  This
class contains a list of peak classes IdentifiedPeaks.Peak...

 from IdentifiedPeaks import IdentifiedPeaks
 identifiedPeaks=IdentifiedPeaks()
 identifiedPeaks.read(open('input/analysisReport.txt'))
 pickle.dumps(identifiedPeaks)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File /usr/lib/python2.3/pickle.py, line 1386, in dumps
Pickler(file, protocol, bin).dump(obj)
  File /usr/lib/python2.3/pickle.py, line 231, in dump
self.save(obj)
  File /usr/lib/python2.3/pickle.py, line 338, in save
self.save_reduce(obj=obj, *rv)
File /usr/lib/python2.3/pickle.py, line 433, in save_reduce
save(state)
  File /usr/lib/python2.3/pickle.py, line 293, in save
f(self, obj) # Call unbound method with explicit self
  File /usr/lib/python2.3/pickle.py, line 663, in save_dict
self._batch_setitems(obj.iteritems())
  File /usr/lib/python2.3/pickle.py, line 677, in _batch_setitems
save(v)
  File /usr/lib/python2.3/pickle.py, line 293, in save
f(self, obj) # Call unbound method with explicit self
  File /usr/lib/python2.3/pickle.py, line 614, in save_list
self._batch_appends(iter(obj))
  File /usr/lib/python2.3/pickle.py, line 629, in _batch_appends
save(x)
  File /usr/lib/python2.3/pickle.py, line 338, in save
self.save_reduce(obj=obj, *rv)
  File /usr/lib/python2.3/pickle.py, line 415, in save_reduce
save(args)
  File /usr/lib/python2.3/pickle.py, line 293, in save
f(self, obj) # Call unbound method with explicit self
  File /usr/lib/python2.3/pickle.py, line 576, in save_tuple
save(element)
  File /usr/lib/python2.3/pickle.py, line 293, in save
f(self, obj) # Call unbound method with explicit self
  File /usr/lib/python2.3/pickle.py, line 760, in save_global
raise PicklingError(
pickle.PicklingError: Can't pickle class 'IdentifiedPeaks.Peak': it's
not found as IdentifiedPeaks.Peak

xml.marshal has the problem I mentioned before...

 xml.marshal.generic.dumps(identifiedPeaks)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File /usr/lib/python2.3/site-packages/_xmlplus/marshal/generic.py,
line 59, in dumps
L = [self.PROLOGUE + self.DTD] + self.m_root(value, dict)
  File /usr/lib/python2.3/site-packages/_xmlplus/marshal/generic.py,
line 104, in m_root
L = ['%s' % name] + self._marshal(value,dict) + ['/%s' % name]
  File /usr/lib/python2.3/site-packages/_xmlplus/marshal/generic.py,
line 92, in _marshal
return getattr(self, meth)(value, dict)
AttributeError: Marshaller instance has no attribute
'm_IdentifiedPeaks'

Help would be hugely appreciated.

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


Re: good design method calls

2005-03-29 Thread Charles Hartman
On Mar 29, 2005, at 10:36 AM, Peter Hansen wrote:
Sorry for the rant...  I didn't intend it to head
that way when I started out, but I seem to be on a
bit of an anti-optimization bent today. :-)
No, that's very helpful; thanks.
Charles Hartman
--
http://mail.python.org/mailman/listinfo/python-list


problem with tkinter

2005-03-29 Thread max(01)*
hello.
the following code:
  1 from Tkinter import *
  2
  3 class MiaApp:
  4   def __init__(self, genitore):
  5 self.mioGenitore = genitore
  6 self.i = IntVar()
  7 self.i.set(42)
  8 self.s = StringVar()
  9 self.s.set(Baobab)
 10 self.lab = {}
 11 self.lab[self.i] = Label(self.mioGenitore)
 12 self.lab[self.i].configure(width = 30, relief = RIDGE,
 13   text = [vuota])
 14 self.lab[self.i].pack()
 15 self.lab[self.s] = Label(self.mioGenitore)
 16 self.lab[self.s].configure(width = 30, relief = RIDGE,
 17   text = [vuota])
 18 self.lab[self.s].pack()
 19 self.but = Button(self.mioGenitore)
 20 self.but.configure(text = Vai!, command = self.procedi)
 21 self.but.pack()
 22   def procedi(self):
 23 for var in (self.i, self.s):
 24   self.lab[var].configure(textvariable = var)
 25
 26 radice = Tk()
 27 miaApp = MiaApp(radice)
 28 radice.mainloop()
is intended
--
http://mail.python.org/mailman/listinfo/python-list


Re: truncating a file from the top down

2005-03-29 Thread Fredrik Lundh
Mike Rovner wrote:

 if os.stat says the_file is too big:
   fh = open(the_file, 'rb')
   fh.seek(2008, 2)

should be

fh.seek(-2008, 2)

right?

   data = fh.read()
   fh.close()
   assert len(data)==2008 # you may want some error processing here
   fh = open(the_file, 'wb')
   fh.write(data)
   fh.close()

or

if os.path.getsize(the_file)  TOO_BIG:
fh = open(the_file, 'rb+')
fh.seek(-2008, 2)
data = fh.read()
fh.seek(0) # rewind
fh.write(data)
fh.truncate()
fh.close()

/F 



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


problem with tkinter

2005-03-29 Thread max(01)*
hello.
the following code:
  1 from Tkinter import *
  2
  3 class MiaApp:
  4   def __init__(self, genitore):
  5 self.mioGenitore = genitore
  6 self.i = IntVar()
  7 self.i.set(42)
  8 self.s = StringVar()
  9 self.s.set(Baobab)
 10 self.lab = {}
 11 self.lab[self.i] = Label(self.mioGenitore)
 12 self.lab[self.i].configure(width = 30, relief = RIDGE,
 13   text = [vuota])
 14 self.lab[self.i].pack()
 15 self.lab[self.s] = Label(self.mioGenitore)
 16 self.lab[self.s].configure(width = 30, relief = RIDGE,
 17   text = [vuota])
 18 self.lab[self.s].pack()
 19 self.but = Button(self.mioGenitore)
 20 self.but.configure(text = Vai!, command = self.procedi)
 21 self.but.pack()
 22   def procedi(self):
 23 for var in (self.i, self.s):
 24   self.lab[var].configure(textvariable = var)
 25
 26 radice = Tk()
 27 miaApp = MiaApp(radice)
 28 radice.mainloop()
is intended to make a window with 2 labels and a button, such that 
pressin the button you get the labels display the content of two 
variables. it does not work, of course, as intended. is there anybody 
who can point me in the right direction? (the problem seems to be that 
the command option wants a variable name, not a string containing that 
name).

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


Wanted: New Python Success Stories

2005-03-29 Thread Stephan Deibel
Hi,

O'Reilly Associates is going to be printing volume III of the
Python Success Stories series in June and I'm looking for
submissions of new stories.
   
The stories have been quite valuable for people introducing
Python to new users and companies.

The deadline for me to receive stories for editing is May 1st and
the deadline for the final edited, approved story going to
O'Reilly is June 1st.

The existing stories are online here:

http://pythonology.org/success

There's more info about writing one here:

http://pythonology.org/successguide

The biggest hurdle is usually getting approval from the company
to write about Python.  It may require some educating about open
source to get past rules against endorsing commercial products
(which Python obviously isn't).

If you have any questions, please let me know.

Thanks,

Stephan Deibel
Pythonology.com

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


Problem in designing a global directory in python

2005-03-29 Thread Tian
I want to create a object directory called Context in my program, which
is based on a dict to save and retrieve values/objects by string-type
name. I have the definition like this:

utils.py

global sysctx

class Context:
def __init__(self):
def set(self, name, obj, overwrite=True):
def get(self, name):
def has(self, name):

def init():
global sysctx
sysctx = Context()

def getContext():
global sysctx
return sysctx
-

init() is called somewhere at the beginning of the program.
In other modules, i want to use this in the following manner,

   from utils import *
   getContext().set(...)

but SOMETIMES I met following error located in getContext()
 NameError: global name 'sysctx' is not defined

I found that when a module is in the same directory as utils.py, when I
can simply use utils for importing, there is no such problem. But
when i was writing a module in a deeper directory than utils.py, which
has to use the full module name for importing, such as:

   from myproj.utils import *
   getContext().set(...)

I got this error.

What should I do to correct that?

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


Re: Distributing closed source modules

2005-03-29 Thread Dave Brueck
Fuzzyman wrote:
Dave Brueck wrote:
By futile I meant that, if the code ends up running on a user's
machine, then
a sufficiently motivated person could crack it wide open, regardless
of
implementation language - the only way to truly protect the code is
to never let
it out of your hands (i.e. it's accessible just via a web service).


I understand what you are saying - using hte word 'futilew' implies
that code is *likely* to be broken, not that it is *theoretically
possible* for it to be broken. If code has a small user base it is
probable that there is plenty that can be done to make breaking the
code a lot harder. There are also legitimate reasons why someone would
want to do this. 'Futile' is definitely a misleading response :-)3
Not really. For all practical purposes, shipping .pyc files is probably 
sufficient for most of the software out there: (1) it's a high enough fence 
for almost all users, (2) for most programs, getting the source code and being 
able to do something with it are two very different things, and (3) for most 
programs, there really is no proprietary magic worth protecting.

So, when somebody says it's not good enough, and they need something better, I 
have to admit I'm initially skeptical of their perceived need for better 
protection of the source code (there _are_ some cases where it should be 
protected, but they are much less common than people seem to think). One of two 
things is probably true in these cases:

1) The value of the source code is overestimated - yes, it's a nice program, but 
 there's not really anything in there to warrant the higher 
development/deployment/debugging costs associated with more security. As such, 
nobody is really going to care enough to crack the code. And if anybody does, 
it's unlikely that they'll actually do anything with the code. Thus, the effort 
to secure the code more is futile - it's ineffective because the effort will 
never provide any benefit.

OR
2) The code really does have some innovative, proprietary algorithm, like a 
video codec with wildly improved compression (that for some reason you've 
implemented in pure Python ;-) ). If the value of the code is really high, then 
no amount of security is going to prevent people from getting at it - trying to 
protect your code is futile because no matter how high a wall you create, 
sufficiently determined people will climb over it. Plus, protecting the source 
code may be the least of your worries (if they're willing to steal your code, 
they may just as well be willing to use your library illegally, etc.).

It's a question that often comes up on comp.lang.python - and the reply
is often don't bother, it's not possible - and why do you want to do
that anyway. This is a response that is likely to turn people towards
other languages
Perhaps the response could be framed better, but at the same time it _is_ a 
pretty honest response, and maybe Python really _isn't_ the language for such 
people. It's just like people who ask for curly braces - Python is not the 
language for them. So if I asked for braces, a lot of the c.l.py responses would 
be geared towards helping me understand that they aren't really needed, but if I 
insist that I have to have them, then maybe Python isn't for me. :)

So, when the question comes up, I don't mind offering some suggestions, but the 
suggestions will always include the disclaimer that it's probably a waste of 
time  effort - IMO leaving that part out would be misleading.

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


Re: Little Q: how to print a variable's name, not its value?

2005-03-29 Thread Cameron Laird
In article [EMAIL PROTECTED],
Bill Mill  [EMAIL PROTECTED] wrote:
.
.
.
(i.e. I respectfully disagree that mixing data with program code is a bad idea)
.
.
.
Most applications (as opposed to system) developers should be doing
it rarely.  VERY often when they seem inclined to do so, it's just a
symptom of a confused design.

In no way do I mean to restrict knowledgeable metaclass authors, LISPers,
debugger inventors, or other legitimate exceptions to my claim.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem in designing a global directory in python

2005-03-29 Thread F. Petitjean
Le 29 Mar 2005 09:50:46 -0800, Tian a écrit :
 I want to create a object directory called Context in my program, which
 is based on a dict to save and retrieve values/objects by string-type
 name. I have the definition like this:
 
 utils.py
 
 global sysctx
# you are in the global scope of the utils module. This global sysctx
# has no meaning, replace by
sysctx = None  # create a global 'sysctx' name in utils namespace
 
 class Context:
class Context(object):  # why not use new-style classes, we are in
2005
 def __init__(self):
# I suppose that there is some __doc__ and code :-)
 def set(self, name, obj, overwrite=True):
 def get(self, name):
 def has(self, name):
 
 def init():
 global sysctx
 sysctx = Context()
 
 def getContext():
 global sysctx
 return sysctx
 -
 
 init() is called somewhere at the beginning of the program.
 In other modules, i want to use this in the following manner,
 
from utils import *
Please do not use the from module import *  form
from utils import getContext
getContext().set(...)
You can also restrict the exported names of utils.py by adding a
__all__ = ('getContext',)
in utils.py.
 
 but SOMETIMES I met following error located in getContext()
  NameError: global name 'sysctx' is not defined
 
 I found that when a module is in the same directory as utils.py, when I
 can simply use utils for importing, there is no such problem. But
 when i was writing a module in a deeper directory than utils.py, which
 has to use the full module name for importing, such as:
 
from myproj.utils import *
getContext().set(...)
 
 I got this error.
 
 What should I do to correct that?
See above :-)  and post a follow-up to report if the issue is solved.
 
PS sorry for bad english. I am not a native speaker.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)

2005-03-29 Thread Steven Bethard
Ville Vainio wrote:
Raymond == Raymond Hettinger [EMAIL PROTECTED] writes:

Raymond If the experience works out, then all you're left with is
Raymond the trivial matter of convincing Guido that function
Raymond attributes are a sure cure for the burden of typing
Raymond import statements.
For one thing, it would make it harder to find the functions from the
docs. It's easy to find the doc for 'itertools', but iter object
methods would require browsing that infamous Chapter 2 of the
documentation...
Well, it would only make them as hard to find as, say, dict.fromkeys, 
which is probably the best parallel here.  Of course iter would have to 
be documented as a builtin type.  I don't find the argument builtin 
type methods are hard to find convincing -- the solution here is to fix 
the documentation, not refuse to add builtin types.

Apart from that, I don't really see the advantage in moving away from
itertools.
True it's not a huge win.  But I'd argue that for the same reasons that 
dict.fromkeys is a dict classmethod, the itertools methods could be iter 
classmethods (or staticmethods).  The basic idea being that it's nice to 
place the methods associated with a type in that type's definiton.  The 
parallel's a little weaker here because calling iter doesn't always 
produce objects of type iter:

py class C(object):
... def __iter__(self):
... yield 1
...
py iter(C())
generator object at 0x011805A8
But note that iter does produce 'iterator' objects for the old 
__getitem__ protocol:

py class C(object):
... def __getitem__(self, index):
... if index  5:
... raise IndexError
... return index
...
py iter(C())
iterator object at 0x01162EF0
I guess the real questions are[1]:
* How much does iter feel like a type?
* How closely are the itertools functions associated with iter?
STeVe
[1] There's also the question of how much you believe in OO tenets like 
functions closely associated with a type should be members of that type...
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Newbie] How do I get better at Python programming?

2005-03-29 Thread Tim Jarman
Roy Smith wrote:

 keep in mind, however, that not all problems in life can be solved with 
 software. 

+1 QOTW 

-- 
Website: www DOT jarmania FULLSTOP com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: truncating a file from the top down

2005-03-29 Thread Mike Rovner
Right. Thanks for the correction.
Fredrik Lundh wrote:
Mike Rovner wrote:

if os.stat says the_file is too big:
 fh = open(the_file, 'rb')
 fh.seek(2008, 2)

should be
fh.seek(-2008, 2)
right?

 data = fh.read()
 fh.close()
 assert len(data)==2008 # you may want some error processing here
 fh = open(the_file, 'wb')
 fh.write(data)
 fh.close()

or
if os.path.getsize(the_file)  TOO_BIG:
fh = open(the_file, 'rb+')
fh.seek(-2008, 2)
data = fh.read()
fh.seek(0) # rewind
fh.write(data)
fh.truncate()
fh.close()
/F 


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


Re: Little Q: how to print a variable's name, not its value?

2005-03-29 Thread Bill Mill
On Tue, 29 Mar 2005 18:08:04 GMT, Cameron Laird [EMAIL PROTECTED] wrote:
 In article [EMAIL PROTECTED],
 Bill Mill  [EMAIL PROTECTED] wrote:
 .
 .
 .
 (i.e. I respectfully disagree that mixing data with program code is a bad 
 idea)
 .
 .
 .
 Most applications (as opposed to system) developers should be doing
 it rarely.  VERY often when they seem inclined to do so, it's just a
 symptom of a confused design.

On that point I can agree. I just wanted to say that there are
valuable uses for mixing code and data. As soon as I sent my email
out, I realized that I meant to say that mixing data with program code
is *not always* a bad idea.

Particularly, yelling at this guy for wanting to figure out a
variable's name is, I think, overzealous. If he just wants to use it
for debugging, then I don't know why he needs to be shouted down.

 
 In no way do I mean to restrict knowledgeable metaclass authors, LISPers,
 debugger inventors, or other legitimate exceptions to my claim.

I'm confused. Are you ron_adam, cameron laird, or both?

Either way, your point is well taken, and I should have been clearer
in my overly glib email.

Peace
Bill Mill
bill.mill at gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: modes for AES encryption?

2005-03-29 Thread Chris Curvey
Chris Curvey wrote:
I'm trying to use the AES module in the Python Cryptography Toolkit.  I 
need to set the mode to ECB/NoPadding, and there's a reference to a 
Mode parameter in the new() function, but no examples for AES.  Who 
can point me in the right direction?
Answering my own question for posterity...ECB is your *only* option for 
AES, and you have to do your own padding (pad with \0 to emulate 
NoPadding).

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


Re: code for Computer Language Shootout

2005-03-29 Thread igouy
We've made it somewhat easier to contribute programs.

No need to subscribe to the mailing-list.
No need for a user-id or login.

See the FAQ How can I contribute a program?
http://shootout.alioth.debian.org/faq.php

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


Re: xml marshal of general (but non Python standard) class

2005-03-29 Thread Martin v. Löwis
syd wrote:
But for my identifiedPeaks class (for instance), it has trouble.  This
class contains a list of peak classes IdentifiedPeaks.Peak...
What precisely is the name of the class. You say it is
IdentifiedPeaks.Peak, but...
from IdentifiedPeaks import IdentifiedPeaks
Here you import IdentifiedPeaks.IdentifiedPeaks, not
IdentifiedPeak.Peak.
pickle.PicklingError: Can't pickle class 'IdentifiedPeaks.Peak': it's
not found as IdentifiedPeaks.Peak
Here it claims there is no class IdentifiedPeaks.Peak, and I tend to
believe it. Could it be that this class does not exist under this name?
Python needs to pickle the full class name so that unpickle can find
the class. It uses (klass.__module__).(klass.__name__); if the class
is nested in another class, pickle cannot find out. So I suggest
to move the Peak class toplevel into the module. My guess is
that it is nested inside IdentifiedPeaks. The simplest fix might be
be to put
Peak=IdentifiedPeaks.Peak
into IdentifiedPeaks.py; better would be to move the class.
AttributeError: Marshaller instance has no attribute
'm_IdentifiedPeaks'
That would happen if IdentifiedPeaks is a new-style class (i.e.
inheriting from object). marshal has only generic support for instance
objects; each additional type needs separate support. You can provide
that support by inheriting from Marshaller, adding m_ functions for all
missing types. Each function needs to return a list of XML substrings,
e.g. through
  def m_IdentifiedPeaks(self, peaks, dict):
  L = [ 'IdentifiedPeaks' ]
  for p in peaks.getPeaks():
  L += self._marshal(p)
  L += [ '/IdentifiedPeaks' ]
  return L
The dict parameter keeps the object references for cycle and
shared reference detection. Whether or not you need cycle support
depends on your application.
Alternatively, patches to support new-style classes in a more
general way are welcome.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem in designing a global directory in python

2005-03-29 Thread Tian
I have tried using sysctx=None instead of global sysctx, but it
doesn't work either.
It seems my initialization work in the previous calling of init() has
no persistent effect when utils is imported using from myproj.utils
import getContext.

What's weird, when a module is in the same directory as utils.py, where
I can simply use utils for importing, there is no such problem.

Any other suggestions?

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


Re: good design method calls

2005-03-29 Thread Ron_Adam
On Tue, 29 Mar 2005 09:09:37 -0500, Charles Hartman
[EMAIL PROTECTED] wrote:

I know the answer to this is going to be It depends . . ., but I want 
to get my mind right. In Fowler's *Refactoring* I read: Older 
languages carried an overhead in subroutine calls, which deterred 
people from small methods (followed by the basic Extract Method 
advice). In Skip Montanaro's Python Performance Tips 
(http://manatee.mojam.com/~skip/python/fastpython.html) I read: . . .  
use local variables wherever possible. If the above loop is cast as a 
function, append and upper become local variables. Python accesses 
local variables much more efficiently than global variables.

These two pieces of advice imply opposite kinds of code revisions. 
Obviously they have different purposes, and both are right at different 
times. I wonder if anyone has some wisdom about how to think about when 
or how often to do which, how to balance them ultimately, and so on.

Charles Hartman
Professor of English, Poet in Residence
the Scandroid is at: http://cherry.conncoll.edu/cohar/Programs
http://villex.blogspot.com


It depends... ;)

Converting small functions to inline, usually should  only be done in
the inner most loops to optimize performance if it's needed.  Moving
calculations out of those loops by doing them ahead of time is also
good. 

It's good practice in python to put all of your code in functions or
class's even if it's a single main() function.  

def main()
  (program code)

main()

Then you avoid the slower globals unless you declare them with the
global statement.

If main, or any other functions, get too big or complex, split them up
as needed. 

Ron




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


Re: Which is easier? Translating from C++ or from Java...

2005-03-29 Thread cjl
Hey all:

Thanks for the responses...

I've found a third open source implementation in pascal (delphi), and
was wondering how well that would translate to python?

-cjl

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


Re: truncating a file from the top down

2005-03-29 Thread rbt
Mike Rovner wrote:
Right. Thanks for the correction.
Fredrik Lundh wrote:
Mike Rovner wrote:

if os.stat says the_file is too big:
 fh = open(the_file, 'rb')
 fh.seek(2008, 2)

should be
fh.seek(-2008, 2)
right?

 data = fh.read()
 fh.close()
 assert len(data)==2008 # you may want some error processing here
 fh = open(the_file, 'wb')
 fh.write(data)
 fh.close()

or
if os.path.getsize(the_file)  TOO_BIG:
fh = open(the_file, 'rb+')
fh.seek(-2008, 2)
data = fh.read()
fh.seek(0) # rewind
fh.write(data)
fh.truncate()
fh.close()
/F


Thanks for the info guys!
--
http://mail.python.org/mailman/listinfo/python-list


cgi and multipart/form-data?

2005-03-29 Thread Chris Curvey
I have a form like this:
form method=post enctype=multipart/form-data
input type=file name=myFile
input type=text name=foo
input type=submit
/form
When I submit this form to my Python script using the CGI module, I seem 
to get the myFile variable, but I don't seem to the foo variable.

Interestingly, if I take out the myFile variable (or specify a much 
smaller file) I do get the value for foo.

The files that I'm trying to handle are 400-500Kb in size...is there 
something I need to do (cgi.maxlen?) to let cgi handle big files?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem in designing a global directory in python

2005-03-29 Thread Bruno Desthuilliers
Tian a écrit :
I want to create a object directory called Context in my program, which
is based on a dict to save and retrieve values/objects by string-type
name. I have the definition like this:
utils.py

global sysctx
class Context:
def __init__(self):
def set(self, name, obj, overwrite=True):
def get(self, name):
def has(self, name):
def init():
global sysctx
sysctx = Context()
def getContext():
global sysctx
return sysctx
Why using a (not so) global variable here ? If your problem is to make 
sure you have only one instance of Context in your program, there are 
cleaner solutions - one of them being a Singleton (you'll find all 
needed doc and exemples on the net - google is your friend !-).

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


Need Help: Server to pass py objects

2005-03-29 Thread Sells, Fred
I have a legacy system with data stored in binary files on a remote server.
I need to access and modify the content of those files from a webserver
running on a different host.  (All Linux)

I would like to install a server on the legacy host that would use my python
code to translate between the legacy files and Python Objects that represent
the subset of data I care about, then pass those Python objects back and
forth to my webserver, which would then manage the http I/F to various
clients.

My organization prefers to use open source software.

Can anyone suggest some products to research further?
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >