Re: dependency algorithm

2007-11-14 Thread Henry
Hi -

You want to linearise a dependency graph. The standard way to do this is to
do a depth first search on the graph and output the nodes in reverse order
of their finishing times (although your example looks like you want them in
the reverse order, that is starting with the node on which nothing depends
rather than the node that depends on nothing). Doing this iteratively is a
bit of a pain because you have to keep track of the 'current' node, doing it
recursively is a no-no for large graphs because the stack will have depth
O(E) in the worst case.

What follows is a simple linearisation that doesn't a) detect loops or b) do
things iteratively which puts the stack at risk. I almost find it easier to
do a separate loop check via very similar means. Excuse the un-idiomatic
nature of the code, I'm not yet a proper pythonista :)

edges = [ (0,1), (1,2), (2,3) ]
n = 4

adj_list = [ [[ e for (s,e) in edges if s == i ], False ] for i in xrange(n)
] # You seem to be 1-based, but I've ignored that here

def linearise( adj ):
order = []
for i in xrange( len( adj ) ):
visit( i, adj, order )
return order

def visit( i, adj, order ):
if adj[i][1] == True:
return

adj[i][1] = True

for child in adj[i][0]:
visit( child, adj, order )

order.append( i )

HTH,

Henry



On 14/11/2007, Tom Jones <[EMAIL PROTECTED]> wrote:
>
> Hi,
>
> Consider tuples of the above numbers in the form:
>(a,b)
>
> Suppose this relation means:
>a depends on b
>
> Given a list of tuples, I would like an algorithm to return the proper
> ordering of the elements...and if the ordering has a loop (which in this
> case, prevents a proper ordering), then it should return None.
>
> For example,
>
>
>[(1,2),(2,3),(3,4)]
> should give:
>[4,3,2,1]
>
>
>[(3,2),(1,3),(2,4)]
> should give:
>[4,2,3,1]
>
>
>[(1,4),(4,3),(2,3)]
> should give:
>[3,2,4,1]  or [3,4,2,1]  (which one doesn't matter)
>
>
>[(1,2), (2,3), (3,2)]
> should give
>None, since it cannot be resolved
>
>
> I'm sure this is a standard problem (mro, resolving inheritance?), but
> this is a simplified case since each element can directly depend on only
> one other element (thus, multiple inheritance is not allowed)...but many
> elements can depend on the same element (no limit on the number of
> classes which subclass another class).  A quick hack is simple enough to
> code, but I am wondering if there are 'standard' ways of performing this
> task in this limited scope.
>
> Thanks.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Recursive insertion of a line

2007-11-19 Thread Henry
On 19/11/2007, Francesco Pietra <[EMAIL PROTECTED]> wrote:
>
> New to the list and just beginning with Python (Linux B console). Urgent
> problem before I can correctly program:
>
> How to insert "TER" records recursively, i.e. some thousand fold,  in a
> file
> like in the following example? "H2 WAT" is the only constant
> characteristic of
> the line after which to insert "TER"; that distinguishes also for lines
> for
> other atoms. Just to illustrate what I want to do - for those unfamiliar
> with
> this type of file - a three-line set between two "TER" defines a water
> molecule, with a set of xyz coordinates for each atom.
>

If every molecule is water, and therefore 3 atoms, you can use this fact to
insert TER in the right place. You don't need recursion:

f = open( "atoms.txt", "rt" )
lineCount = 0
for line in f.xreadlines( ):
lineCount = lineCount + 1
print line
if lineCount == 3:
lineCount = 0
print "TER"
f.close( )

You could do the above in fewer lines with a regex (this would also work
even if all molecules weren't water), which would probably be neater, but is
left as an exercise for the reader :) There are probably much better
idiomatic ways to do this, and I defer to much more experienced Python
programmers to show you them.

HTH,

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

Re: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-14 Thread Henry
>
> > There's no finite state machine involved here, since this isn't a
> > regular expression in the strictest sense of the term---it doesn't
> > translate to a finite state machine, since backreferences are
> > involved.
> >
> > Mark
>
>
> What is it?
>


The language of strings of 1s whose length is prime is not regular, so can't
be recognised by a finite state automata. Essentially you still need some
memory to remember where you've got up to in the factoring process, and the
amount of memory is dependent on the length of the string (more factors to
try), so it can't be done with finite storage.

Sketch proof that prime is not regular:

If P = {1^p | p is prime} is regular, then there exists x, z and y s.t. x.y^
k.z is in P for all k >= 0.

Assume l = |x.z| >= 2 (smaller than 2 has direct counterexamples, left as
easy exercise!). Consider w = x.y^l.z Then l | |w|. But since l >= 2, that
means that |w| is not prime. Therefore w is not in P, contradicting our
assumption.

Sorry for slightly OT post :)

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

Determine actually given command line arguments

2013-05-14 Thread Henry Leyh

Hello,
I am writing a program that gets its parameters from a combination of 
config file (using configparser) and command line arguments (using 
argparse).  Now I would also like the program to be able to _write_ a 
configparser config file that contains only the parameters actually 
given on the commandline.  Is there a simple way to determine which 
command line arguments were actually given on the commandline, i.e. does 
argparse.ArgumentParser() know which of its namespace members were 
actually hit during parse_args().


I have tried giving the arguments default values and then looking for 
those having a non-default value but this is really awkward, especially 
if it comes to non-string arguments.  Also, parsing sys.argv looks 
clumsy because you have to keep track of short and long options with and 
without argument etc. i.e. all things that I got argparse for in the 
first place.


Thanks && Greetings,
Henry
--
http://mail.python.org/mailman/listinfo/python-list


Re: Determine actually given command line arguments

2013-05-15 Thread Henry Leyh

On 15.05.2013 14:24, Roy Smith wrote:

In article ,
  Henry Leyh  wrote:


Is there a simple way to determine which
command line arguments were actually given on the commandline, i.e. does
argparse.ArgumentParser() know which of its namespace members were
actually hit during parse_args().


I think what you're looking for is sys.argv:

$ cat argv.py
import sys
print sys.argv

$ python argv.py foo bar
['argv.py', 'foo', 'bar']


Thanks, but as I wrote in my first posting I am aware of sys.argv and 
was hoping to _avoid_ using it because I'd then have to kind of 
re-implement a lot of the stuff already there in argparse, e.g. parsing 
sys.argv for short/long options, flag/parameter options etc.


I was thinking of maybe some sort of flag that argparse sets on those 
optional arguments created with add_argument() that are really given on 
the command line, i.e. those that it stumbles upon them during parse_args().


Regards,
Henry

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


Re: Determine actually given command line arguments

2013-05-15 Thread Henry Leyh

On 15.05.2013 15:00, Oscar Benjamin wrote:

On 15 May 2013 13:52, Henry Leyh  wrote:

On 15.05.2013 14:24, Roy Smith wrote:


In article ,
   Henry Leyh  wrote:


Is there a simple way to determine which
command line arguments were actually given on the commandline, i.e. does
argparse.ArgumentParser() know which of its namespace members were
actually hit during parse_args().



I think what you're looking for is sys.argv:

$ cat argv.py
import sys
print sys.argv

$ python argv.py foo bar
['argv.py', 'foo', 'bar']


Thanks, but as I wrote in my first posting I am aware of sys.argv and was
hoping to _avoid_ using it because I'd then have to kind of re-implement a
lot of the stuff already there in argparse, e.g. parsing sys.argv for
short/long options, flag/parameter options etc.

I was thinking of maybe some sort of flag that argparse sets on those
optional arguments created with add_argument() that are really given on the
command line, i.e. those that it stumbles upon them during parse_args().


I don't know about that but I imagine that you could compare values
with their defaults to see which have been changed.


Yes, I was trying that and it sort of works with strings if I use 
something sufficiently improbable like "__UNSELECTED__" as default.  But 
it gets difficult with boolean or even number arguments where you just 
may not have valid "improbable" defaults.  You could now say, so what, 
it's the default anyway.  But in my program I would like to distinguish 
between given and not given arguments rather than between default and 
non-default.


Regards,
Henry

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


Re: Determine actually given command line arguments

2013-05-15 Thread Henry Leyh

On 15.05.2013 16:08, Skip Montanaro wrote:

Yes, I was trying that and it sort of works with strings if I use something sufficiently improbable 
like "__UNSELECTED__" as default.  But it gets difficult with boolean or even number 
arguments where you just may not have valid "improbable" defaults.  You could now say, so 
what, it's the default anyway.  But in my program I would like to distinguish between given and not 
given arguments rather than between default and non-default.


Initialize all your arg variables to None, then after command line
processing, any which remain as None weren't set on the command line.
At that point, set them to the actual defaults.  I think that's a
pretty common idiom.

Note: I am an old cranky dude and still use getopt.  This idiom is
pretty easy there.  YMMV with argparse or optparse.


Unfortunately, argparse wants to know the type of the argument and the 
boolean arguments (those with action=store_true) can't be initialized 
with None.


However, maybe I could convert boolean arguments to something like

  parser.add_argument('--foo', type=str, nargs='?', const='True', 
default=None)


I'd then have to check for string 'True' rather than for boolean True, 
though.


Regards,
Henry

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


Re: Determine actually given command line arguments

2013-05-15 Thread Henry Leyh

On 15.05.2013 17:29, Roy Smith wrote:

In article ,
Henry Leyh   wrote:

On 15.05.2013 14:24, Roy Smith wrote:

In article ,
   Henry Leyh  wrote:


Is there a simple way to determine which
command line arguments were actually given on the commandline, i.e. does
argparse.ArgumentParser() know which of its namespace members were
actually hit during parse_args().


I think what you're looking for is sys.argv:

$ cat argv.py
import sys
print sys.argv

$ python argv.py foo bar
['argv.py', 'foo', 'bar']


Thanks, but as I wrote in my first posting I am aware of sys.argv and
was hoping to _avoid_ using it because I'd then have to kind of
re-implement a lot of the stuff already there in argparse, e.g. parsing
sys.argv for short/long options, flag/parameter options etc.


Sorry, I missed that.

I'm not clear on exactly what you're trying to do.  You say:


Now I would also like the program to be able to _write_ a
configparser config file that contains only the parameters actually
given on the commandline.


I'm guessing what you're trying to do is parse the command line first,
then anything that was set there can get overridden by a value in the
config file?  That seems backwards.  Usually, the order is:

1) built-in default
2) config file (possibly a system config file, then a per-user one)
3) environment variable
4) command-line argument

It sounds like you're doing it in the reverse order -- allowing the
config file to override the command line.


No.  The program reads a general config file in $HOME, something like 
~/.programrc; then parses the command like for '-c FILE' and, if FILE is 
present reads it; then parses the command line remains for more 
arguments which overwrite everything previously set.  (For the record, 
this split parsing is done with two argparse parsers.  The first parses 
for '-c FILE' with parse_known_args().  If there is a FILE, its contents 
is used as defaults for a second parser (using set_options()) which then 
parses the remains that were returned by the first parser's 
parse_known_args().)


But now I would also like to be able to _write_ such a config file FILE 
that can be read in a later run.  And FILE should contain only those 
arguments that were given on the command line.


Say, I tell argparse to look for arguments -s|--sopt STRING, -i|--iopt 
INT, -b|--bopt [BOOL], -C CONFFILE.  Then 'prog -s bla -i 42 -C cfile' 
should produce a confparser compatible cfile which contains


  [my_options]
  sopt = blah
  iopt = 42

and not 'bopt = False' (if False was the program's default for bopt).

Regards,
Henry

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


Re: Determine actually given command line arguments

2013-05-16 Thread Henry Leyh

On 16.05.2013 08:08, Jussi Piitulainen wrote:

Henry Leyh writes:


But now I would also like to be able to _write_ such a config file
FILE that can be read in a later run.  And FILE should contain only
those arguments that were given on the command line.

Say, I tell argparse to look for arguments -s|--sopt STRING,
-i|--iopt INT, -b|--bopt [BOOL], -C CONFFILE.  Then 'prog -s bla -i
42 -C cfile' should produce a confparser compatible cfile which
contains

[my_options]
sopt = blah
iopt = 42

and not 'bopt = False' (if False was the program's default for
bopt).


Could you instead write those options that differ from the defaults?
You could parse an actual command line and an empty command line, and
work out the difference.

So 'prog -i 3' would not cause 'iopt = 3' to be written if 3 is the
default for iopt, but would that be a problem?


That's what the program does at the moment.  However, I'm not quite 
happy with it.  Generally, the user doesn't know what's the default and 
it would be confusing if 'prog -i 3' doesn't make 'iopt = 3' turn up in 
the file at the end.  There may also be the case when the user (for 
whatever reason) _wants_ the default in the file.


I think I will try the opposite instead: the program writes the whole 
set of options to the file.  This would produce a complete and 
consistent configuration which automatically reflects the hierarchy in 
which the options were set.  And the user can sort it out by hand if he 
wants.


Regards,
Henry

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


Re: Why 'files.py' does not print the filenames into a table format?

2013-06-15 Thread Jarrod Henry
Nick, at this point, you need to hire someone to do your work for you.

We are not here to do your job.  I would suggest finding a coder for hire
and letting them do this job correctly.

Thanks.


On Sat, Jun 15, 2013 at 2:38 PM, Nick the Gr33k wrote:

> Hello,
>
> Trying to browse 
> http://superhost.gr/?page=**files.pywith 
> tailing -F of the error_log i noticed that error log outputs no error!
>
> So that means that the script is correct.
>
> here are the directory app's files.
>
> [email protected] [~/www/data/apps]# ls -l
> total 412788
> drwxr-xr-x 2 nikos nikos 4096 Jun 12 12:03 ./
> drwxr-xr-x 6 nikos nikos 4096 May 26 21:13 ../
> -rwxr-xr-x 1 nikos nikos 13157283 Mar 17 12:57 100\ Mythoi\ tou\
> Aiswpou.pdf*
> -rwxr-xr-x 1 nikos nikos 29524686 Mar 11 18:17 Anekdotologio.exe*
> -rw-r--r-- 1 nikos nikos 42413964 Jun  2 20:29 Battleship.exe
> -rw-r--r-- 1 nikos nikos 51819750 Jun  2 20:04 Luxor\ Evolved.exe
> -rw-r--r-- 1 nikos nikos 60571648 Jun  2 14:59 Monopoly.exe
> -rwxr-xr-x 1 nikos nikos  1788164 Mar 14 11:31 Online\ Movie\ Player.zip*
> -rw-r--r-- 1 nikos nikos  5277287 Jun  1 18:35 O\ Nomos\ tou\ Merfy\
> v1-2-3.zip
> -rwxr-xr-x 1 nikos nikos 16383001 Jun 22  2010 Orthodoxo\ Imerologio.exe*
> -rw-r--r-- 1 nikos nikos  6084806 Jun  1 18:22 Pac-Man.exe
> -rw-r--r-- 1 nikos nikos 45297713 Jun 10 12:38 Raptor\ Chess.exe
> -rw-r--r-- 1 nikos nikos 25476584 Jun  2 19:50 Scrabble.exe
> -rwxr-xr-x 1 nikos nikos 49141166 Mar 17 12:48 To\ 1o\ mou\ vivlio\ gia\
> to\ skaki.pdf*
> -rwxr-xr-x 1 nikos nikos  3298310 Mar 17 12:45 Vivlos\ gia\
> Atheofovous.pdf*
> -rw-r--r-- 1 nikos nikos  1764864 May 29 21:50 V-Radio\ v2.4.msi
> -rw-r--r-- 1 nikos nikos  3511233 Jun  4 14:11 Ευχή\ του\ Ιησού.mp3
> -rwxr-xr-x 1 nikos nikos 66896732 Mar 17 13:13 Κοσμάς\ Αιτωλός\ -\
> Προφητείες.pdf*
> -rw-r--r-- 1 nikos nikos   236032 Jun  4 14:10 Σκέψου\ έναν\ αριθμό.exe
>
>
> The code is as follows:
>
> # ==**==**
> ==**===
> # Convert wrongly encoded filenames to utf-8
> # ==**==**
> ==**===
> path = b'/home/nikos/public_html/**data/apps/'
> filenames = os.listdir( path )
>
> utf8_filenames = []
>
> for filename in filenames:
> # Compute 'path/to/filename'
> filename_bytes = path + filename
> encoding = guess_encoding( filename_bytes )
>
> if encoding == 'utf-8':
> # File name is valid UTF-8, so we can skip to the next
> file.
> utf8_filenames.append( filename_bytes )
> continue
> elif encoding is None:
> # No idea what the encoding is. Hit it with a hammer until
> it stops moving.
> filename = filename_bytes.decode( 'utf-8',
> 'xmlcharrefreplace' )
> else:
> filename = filename_bytes.decode( encoding )
>
> # Rename the file to something which ought to be UTF-8 clean.
> newname_bytes = filename.encode('utf-8')
> os.rename( filename_bytes, newname_bytes )
> utf8_filenames.append( newname_bytes )
>
> # Once we get here, the file ought to be UTF-8 clean and the
> Unicode name ought to exist:
> assert os.path.exists( newname_bytes.decode('utf-8') )
>
>
> # Switch filenames from utf8 bytestrings => unicode strings
> filenames = []
>
> for utf8_filename in utf8_filenames:
> filenames.append( utf8_filename.decode('utf-8') )
>
> # Check the presence of a database file against the dir files and delete
> record if it doesn't exist
> cur.execute('''SELECT url FROM files''')
> data = cur.fetchall()
>
> for url in data:
> if url not in filenames:
> # Delete spurious
> cur.execute('''DELETE FROM files WHERE url = %s''', url )
>
>
> # ==**==**
> ==**===
> # Display ALL files, each with its own download button
> # ==**==**
> ==**===
> print('''
>  
>  
> ''')
>
> try:
> cur.execute( '''SELECT * FROM files ORDER BY lastvisit DESC''' )
> data = cur.fetchall()
>
> for row in data:
> (filename, hits, host, lastvisit) = row
> lastvisit = lastvisit.strftime('%A %e %b, %H:%M')
>
> print('''
> 
> 
>name="filename" value="%s"> 
>   
> %s 
>   
> %s 
>   
> %s 
> 
> 
> ''' % (filename, hits, host, lastvisit) )
> print( ''

Pushing for Pythoncard 1.0

2011-05-02 Thread John Henry
Attempt to push Pythoncard to a 1.0 status is now underway.  A
temporary website has been created at:

http://code.google.com/p/pythoncard-1-0/

The official website continues to be http://pythoncard.sourceforge.net/

Pythoncard is such a wonderful package that it would be a shame to
allow development for the package to go stagnant.   The Python
community deserves to continue enjoying the simplicity of Pythoncard
for creating a GUI Python application.

In the last few years, I've added a number of widgets and functions to
the package.  The present effort is to simply incorporate all of the
changes I've made to the package, create an installer, push it out the
door and announce to the world that Pythoncard 1.0 is here, and is
here to stay.

Here's a partial list of widgets and functions added:

Widgets:

PDFWindow, FlashWindow, MatplotlibCanvasWindow, MultiSelectionList,
Drag-&-drop enabled tree control, IEHTMLWindow

Backgrounds:

MDIParentWindow, MDIChildWindow, MDISashWindow, multi-panel Background
Window,

Tools:

Updated layoutmanager supporting the newly added widgets, and a
revived action manager (provide list of actions or events associated
with widgets in a context-sensitive fashion - no more needs to
memorize which widget can do what).

and others.

I realize that there are other GUI packages that enjoyed far more
support from the Python community in the last few years and have, as a
result, a more extensive feature list, and more modern looks.  My hats
off to those developers.  So, please re-frame from responding to this
message or send me emails regarding xyz package and how that one is
"better", more "modern" than Pythoncard, or that xyz package had xxx
feature already.

I like Pythoncard because it's so simple for most GUI applications I
build that it's almost laughable.  I've benefited tremendously from
having Pythoncard around and now it's my turn to chip in and repay a
small debt to Pythoncard.

For x-Pythoncard users (and particularly developers), if you are
unable to lend a helping hand, please at least join or re-join the
Pythoncard mailing list and let your voice be heard.



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


scope of function parameters

2011-05-29 Thread Henry Olders
I just spent a considerable amount of time and effort debugging a program. The 
made-up code snippet below illustrates the problem I encountered:

def main():
a = ['a list','with','three elements']
print a
print fnc1(a)
print a

def fnc1(b):
return fnc2(b)

def fnc2(c):
c[1] = 'having'
return c

This is the output:
['a list', 'with', 'three elements']
['a list', 'having', 'three elements']
['a list', 'having', 'three elements']

I had expected the third print statement to give the same output as the first, 
but variable a had been changed by changing variable c in fnc2.

It seems that in Python, a variable inside a function is global unless it's 
assigned. This rule has apparently been adopted in order to reduce clutter by 
not having to have global declarations all over the place.

I would have thought that a function parameter would automatically be 
considered local to the function. It doesn't make sense to me to pass a global 
to a function as a parameter.

One workaround is to call a function with a copy of the list, eg in fnc1 I 
would have the statement "return fnc2(b[:]". But this seems ugly.

Are there others who feel as I do that a function parameter should always be 
local to the function? Or am I missing something here?

Henry




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


Re: scope of function parameters

2011-05-29 Thread Henry Olders

Henry




On 2011-05-29, at 5:47 , Wolfgang Rohdewald wrote:

> On Sonntag 29 Mai 2011, Henry Olders wrote:
>> It seems that in Python, a variable inside a function is
>> global unless it's assigned.
> 
> no, they are local
> 
>> I would have thought that a function parameter would
>> automatically be considered local to the function. It doesn't
>> make sense to me to pass a global to a function as a
>> parameter.
> 
> it is local. But consider what you actually passed:
> You did not pass a copy of the list but the list itself.
> You could also say you passed a reference to the list.
> All python variables only hold a pointer (the id) to
> an object. This object has a reference count and is
> automatically deleted when there are no more references
> to it.
> 
> If you want a local copy of the list you can either
> do what you called being ugly or do just that within
> the function itself - which I think is cleaner and
> only required once.
> 
> def fnc2(c):
>   c = c[:]
>c[1] = 'having'
>return c

Thank you, Wolfgang. That certainly works, but to me it is still a workaround 
to deal with the consequence of a particular decision. From my perspective, a 
function parameter should be considered as having been assigned (although the 
exact assignment will not be known until runtime), and as an assigned variable, 
it should be considered local.

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


Re: scope of function parameters (take two)

2011-05-30 Thread Henry Olders

On 2011-05-29, at 4:30 , Henry Olders wrote:

> I just spent a considerable amount of time and effort debugging a program. 
> The made-up code snippet below illustrates the problem I encountered:
> 
> def main():
>   a = ['a list','with','three elements']
>   print a
>   print fnc1(a)
>   print a
>   
> def fnc1(b):
>   return fnc2(b)
> 
> def fnc2(c):
>   c[1] = 'having'
>   return c
> 
> This is the output:
> ['a list', 'with', 'three elements']
> ['a list', 'having', 'three elements']
> ['a list', 'having', 'three elements']
> 
> I had expected the third print statement to give the same output as the 
> first, but variable a had been changed by changing variable c in fnc2.
> 
> It seems that in Python, a variable inside a function is global unless it's 
> assigned. This rule has apparently been adopted in order to reduce clutter by 
> not having to have global declarations all over the place.
> 
> I would have thought that a function parameter would automatically be 
> considered local to the function. It doesn't make sense to me to pass a 
> global to a function as a parameter.
> 
> One workaround is to call a function with a copy of the list, eg in fnc1 I 
> would have the statement "return fnc2(b[:]". But this seems ugly.
> 
> Are there others who feel as I do that a function parameter should always be 
> local to the function? Or am I missing something here?
> 

My thanks to all the people who responded - I've learned a lot. Sadly, I feel 
that the main issue that I was trying to address, has not been dealt with. 
Perhaps I didn't explain myself properly; if so, my apologies.

I am trying to write python programs in a more-or-less functional programming 
mode, ie functions without side effects (except for print statements, which are 
very helpful for debugging). This is easiest when all variables declared in 
functions are local in scope (it would also be nice if variables assigned 
within certain constructs such as for loops and list comprehensions were local 
to that construct, but I can live without  it). 

It appears, from my reading of the python documentation, that a deliberate 
decision was made to have variables that are referenced but not assigned in a 
function, have a global scope. I quote from the python FAQs: "In Python, 
variables that are only referenced inside a function are implicitly global. If 
a variable is assigned a new value anywhere within the function’s body, it’s 
assumed to be a local. If a variable is ever assigned a new value inside the 
function, the variable is implicitly local, and you need to explicitly declare 
it as ‘global’.
Though a bit surprising at first, a moment’s consideration explains this. On 
one hand, requiring global for assigned variables provides a bar against 
unintended side-effects. On the other hand, if global was required for all 
global references, you’d be using global all the time. You’d have to declare as 
global every reference to a built-in function or to a component of an imported 
module. This clutter would defeat the usefulness of the global declaration for 
identifying side-effects." (http://docs.python.org/faq/programming.html)

This suggests that the decision to make unassigned (ie "free" variables) have a 
global scope, was made somewhat arbitrarily to  prevent clutter. But I don't 
believe that the feared clutter would materialize. My understanding is that 
when a variable is referenced, python first looks for it in the function's 
namespace, then the module's, and finally the built-ins. So why would it be 
necessary to declare references to built-ins as globals?

What I would like is that the variables which are included in the function 
definition's parameter list, would be always treated as local to that function 
(and of course, accessible to nested functions) but NOT global unless 
explicitly defined as global. This would prevent the sort of problems that I 
encountered as described in my original post. I may be wrong here, but it seems 
that the interpreter/compiler should be able to deal with this, whether the 
parameter passing is by value, by reference, by object reference, or something 
else. If variables are not assigned (or bound) at compile time, but are 
included in the parameter list, then the binding can be made at runtime.
And I am NOT talking about variables that are only referenced in the body of a 
function definition; I am talking about parameters (or arguments) in the 
function's parameter list. As I stated before, there is no need to include a 
global variable in a parameter list, and if you want to have an effect outside 
of the function, that's what th

Re: scope of function parameters (take two)

2011-05-30 Thread Henry Olders
On 2011-05-31, at 1:13 , Wolfgang Rohdewald wrote:

> 
> what you really seem to want is that a function by default
> cannot have any side effects (you have a side effect if a
> function changes things outside of its local scope). But
> that would be a very different language than python

You're partially right - what I want is a function that is free of side effects 
back through the parameters passed in the function call. Side effects via 
globals or print statements is fine by me. 

python seems to be undergoing changes all the time. List comprehensions were 
added in python 2.0, according to wikipedia. I like list comprehensions and use 
them all the time because they are powerful and concise.
> 
> did you read the link Steven gave you?
> http://mail.python.org/pipermail/tutor/2010-December/080505.html

Yes, I did, thanks.

Henry

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


Re: scope of function parameters (take two)

2011-05-31 Thread Henry Olders
On 2011-05-30, at 20:52 , Benjamin Kaplan wrote:

> On Mon, May 30, 2011 at 5:28 PM, Henry Olders  wrote:
>> 
>> On 2011-05-29, at 4:30 , Henry Olders wrote:
>> 
> 
> Python doesn't have true globals. When we say "global" what we mean is
> "module or built-in". Also, consider this code
> 
> from math import sin
> def redundant_sin(x) :
>return sin(x)
> 
> In Python, everything is an object. That includes functions.  By your
> definition, that function would either have to be written as
> def redundant_sin(sin, x) :
> and you would have to pass the function in every time you wanted to
> call it or have a "global sin" declaration in your function. And you
> would need to do that for every single function that you call in your
> function body.
> 
I don't believe so. Within redundant_sin, x is local, so if I change x, it will 
not change any objects named x outside of the function. As far as sin is 
concerned, if it were passed to redundant_sin via the parameter list, then it 
would be local, but otherwise sin would be looked for in the function 
definition; if not found there, it would be looked for in the module, where it 
would be found. I am not suggesting any changes to how names are looked up or 
scoped.

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


Re: scope of function parameters (take two)

2011-05-31 Thread Henry Olders

On 2011-05-31, at 24:35 , Dan Stromberg wrote:

> 
> On Mon, May 30, 2011 at 5:28 PM, Henry Olders  wrote:
> 
> Be careful not to conflate global scoping or global lifetime, with mutability 
> or pure, side-effect-free functions (callables).  It sounds like what you 
> want is immutability and/or freedom from side effects, which is found most 
> often in (pure) functional languages - which is not what Python is, nor does 
> it attempt to be so.

I think you're right, I've been conflating scoping with side effects caused by 
passing mutable objects. 
> 
> In Python, and in many other languages, if you pass a scalar (or more 
> generally, an object of an immutable type) to a function, and then change the 
> scalar in that function, you only change the scalar within that function, not 
> within the caller.
> 
> However, if you pass an aggregate type like a list (array) or dictionary 
> (hash table), then the formal argument itself that you've passed is still 
> only changeable within that function, however what it points off at _is_ 
> changeable via that formal argument.  This is of course because otherwise 
> passing a 1 gigabyte dictionary to a function would either have to copy the 
> whole dictionary, or implement some sort of Copy-on-Write semantics, or make 
> it somehow readonly.
> 
> If you need side effect-free functions in Python, you'd probably best copy 
> your aggregates, EG:
> 
> import copy
> 
> def main():
>   a = ['a list','with','three elements']
>   print a
>   print fnc1(a)
>   print a
> 
> def fnc1(b):
>   b = copy.deepcopy(b)
>   return fnc2(b)
> 
> def fnc2(c):
>   c = copy.deepcopy(c)
>   c[1] = 'having'
>   return c

Clearly, making a copy within the function eliminates the possibility of the 
side effects caused by passing in mutable objects. Would having the 
compiler/interpreter do this automatically make python so much different? What 
if it were optional, like nested scopes were in python 2.1 until they became 
standard in 2.2?

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


Invoking Python from Python

2005-11-08 Thread John Henry
Hi all,

I have a need to create a Python script on the fly from another Python
program and then execute the script so created.  Do I need to invoke
Python through os.spawnl or is there a better way?

Thanks,

--
John

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


Cut and paste an EPS file

2005-12-02 Thread John Henry
I am looking for a Python tookit that will enable me to cut section of
a picture out from an EPS file and create another EPS file.

I am using a proprietary package for doing certain engineering
calculations.  It creates single page x-y line plots that has too much
blank spaces around the plotted area located at the top 2/3 of the
page.  I like to be  "cut" that white space out by extracting the image
out and may be scale it up - while keeping the bottom 1/3 unchanged.

Does anybody has any suggestions?

Thanks,

--
JH

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


Re: Cut and paste an EPS file

2005-12-02 Thread John Henry
Thanks for the reply.

Yes, that would have been too easy :=)

If I change the bbox, I would cut out the lower 1/3 of the plot.   I
only want to apply it to the top 2/3 of the page.

Regards,

--
JH

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


Re: Writing portable applications (Was: Jargons of Info Tech industry)

2005-08-29 Thread Henry Law
On Sat, 27 Aug 2005 14:35:05 -0400, Mike Meyer <[EMAIL PROTECTED]> wrote:

>Ulrich Hobelmann <[EMAIL PROTECTED]> writes:
>> Mike Meyer

I wonder could you guys stop cross-posting this stuff to
comp.lang.perl.misc?   The person who started this thread - a
well-known troll - saw fit to post it there, and now all your posts
are going there too. 
-- 

Henry Law   <>< Manchester, England 
-- 
http://mail.python.org/mailman/listinfo/python-list


optparse alternative

2005-03-14 Thread Henry Ludemann
I've been writing an optparse alternative (using getopt) that is at a
stage where I'd be interested in people's opinions. It allows you to
easily creating command line interfaces to existing functions, using
flags (which are optional) and arguments. It will automatically print a
nicely formatted usage (eg: -h or --help), and easily & automatically
validates parameter existence and type.

You can download it, and read a bit more about it, at


I'm interested in comments and criticisms; I've tried to write it
according to the python coding guildlines.

Example usage of a cmdline usage;

$ python test.py --help
Usage: test.py [OPTIONS] SOMEARG
An example to show usage of command line

Arguments
SOMEARG   Some float argument

Mandatory arguments to long flags are mandatory for short options
too
-h, --helpShow this help page
-s, --setflag Set the flag

Email bug reports to [EMAIL PROTECTED]

Source for the above example;

def someFunc(someArg, someFlag = False):
print "Flag value =", someFlag
print "Arg value =", someArg

from cmdline.Command import Command
command = Command(someFunc, "An example to show usage of command
line", "Email bug reports to [EMAIL PROTECTED]")
command.addFlag('s', 'setflag', 'Set the flag', 'someFlag')
command.addArgument('SOMEARG', 'Some float argument', 'someArg',
float)
command.invoke()

Normal use of test.py would have given

$ python test.py 3
Flag value =  False
Arg value = 3.0

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


Re: optparse alternative

2005-03-14 Thread Henry Ludemann
Thanks for the comments...
Steven Bethard wrote:
Looks interesting, but is it really that different from optparse?
In the sense that they both do the same thing, no, not really. But the
way they do it is quite different; optparse bases itself on setting
variables, while this module is for invoking functions. I like this way
a better, as it acts as a more 'usual' client of the code, in the sense
that it uses publically exposed interfaces rather then internal
variables for passing the information. That said, the reason I started
this was that at the time I wasn't aware of optparse; my search through
the help needed to be a bit more thorough. When I found optparse, I
decided to continue on with this approach (mostly because I was having
fun with it).
I do like the fact that you can specify a type with a conversion 
function.  (In optparse, AFAIK, to add a new type you have to write 
your own subclass of Option that screws with Option.TYPES and 
Option.TYPE_CHECKER, which I've always thought was kinda nasty.)
Yeah, it works quite nicely; as it is a general function, you can use
your own methods for creating arbitrary objects (so long as they take
one parameter (a string)).
But I wonder if it wouldn't be better to extend optparse with the 
functionality instead of writing an entirely new module...
The way of getting the data through to the program is quite different
(method vs data), so that would be a fairly radical change / addition
for optparse.
--
http://mail.python.org/mailman/listinfo/python-list


Re: optparse alternative

2005-03-14 Thread Henry Ludemann

* The more I think about it, the more I like that you're basically 
constructing options to match a function signature.  But I can imagine 
that this might be too restrictive for some uses.  It might be worth 
having an alternate interface that provides an options object like 
optparse does.

It is matching options to a function signiture, and for complex methods, 
this might be too restrictive (for example, you'd get methods with 10 - 
20 params). That said, many cases don't have this many things that can 
be set.

Although your point about providing an alternate interface is a good one...
* Any reason why you aren't using new-style classes?

Ignorance. I'll look into it...
* I think the code would be easier to navigate in a single module.

It might be easier to navigate (eg: when you want to go to a method 
implmentation), but from a maintenance point of view I feel modular code 
is easier... Mostly this is instint from other languages (mostly c++).

* Your code alternates between underscore_names and camelCaseNames. 
Might be better to stick with one or the other.  (PEP 8 suggests the 
former.)

Yeah, I coded it before I looked at PEP8. Initially it was all camel 
case, and I attempted to retrofit it. It seems like classes should still 
be CamelCase, yes?

* File specific comments:
Argument.py:
Drop the get_name method; name attribute is already accessible.  (The 
property builtin makes getters and setters generally unnecessary.)

CommandArgument.py:
Drop the get_param_name method; param_name attribute is already 
accessible

Flag.py:
__init__ should have defaults where applicable (e.g. the comments say 
you can provide None for short_flag, but it doesn't default to this). 
Should also probably produce an error if neither short_flag nor 
long_flag is set.  (Or do this in Command._add_options)

In get_value, use "self.argument is None" not "self.argument == None".
get_flag_name should default to long_flag, not short_flag
Command.py:
add_flag should call _validate_param_name *before* _add_options (in 
case an exception is raised and caught).

In _get_params,
for arg_index in range(len(method_args)):
arg = method_args[arg_index]
could be replaced with
for arg_index, arg in enumerate(method_args):

Will do...
MulipleLines.py:
Can you use the (standard library) textwrap module instead?  Seems 
like they do about the same thing, but I haven't looked in too much 
detail.

Doh! Yep, they do the same thing. This is another case of my not 
checking the standard library well enough.

Hope these comments are at least marginally useful. ;)

Yes, very useful. Thanks very much for spending the time to go over it...
--
http://mail.python.org/mailman/listinfo/python-list


Re: optparse alternative

2005-03-14 Thread Henry Ludemann

As far as I can tell, your module has one functional advantage over
optparse--it validates arguments as well as options.
Functionality wise, that is probably about it. It is more from a 
seperation of command line / functionality code that I wrote this; that 
the command line code should be seperate from the actual functional code.

The rest seems to be cosmetics, and personally I prefer the cosmetics 
of optparse.
All to their own... I actually wrote this before I was aware of 
optparse, and so didn't consider the benefits / disadvantages of that 
way of doing it. It's simply a different approach. That said, what I 
like about this approach is that it is non-obtrusive on the functional code.

For one thing, it uses the variable/function naming style found 
throughout
most of the stdlib. 
True... I originally wrote the code in camel case, and have attempted to 
change it to the standard from PEP 8. I guess I missed a few things :-)

optparse has also been widely used and tested for
the last four years.
Again, true, but then again, this module (unlike optparse) uses the 
standard getopt module for all command line parsing, which has been 
around for even longer. So the bugs are all in the method invoking (my 
code), and not in the parsing. 

I think you would be better off trying to extend optparse to deal with
non-option arguments, and you can tap into the installed base of
existing optparse users and even get your code included in the stdlib
if Greg Ward agrees. Whereas that's really unlikely for an entirely
new module--there just isn't the need for a THIRD way to do the same
thing.
Yeah, a third module would be a bit redundent. I had actually written 
most of this module before I became aware of optparse (it was one of 
those bash the head against the wall moments when I found it), but 
decided to continue with this version because I liked the cosmetics of 
it (it seemed less intrusive on the functional code). Once it was more 
or less finished, I decided to clean it up and post it in the hope it 
might be useful to someone else, and perhaps more, to get any comments 
that could improve it. And besides, variety is the spice of life :-)

Just a suggestion.
Thanks for your comments...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Program Translation - Nov. 14, 2013

2013-11-17 Thread Henry Law

On 17/11/13 14:37, E.D.G. wrote:

All of my own important programs are written using Perl.  I am starting
to run into calculation speed limitations with one of the programs.


Your Perl code is, er, sub-optimal.  There is absolutely no point in 
doing benchmarks until you've improved the code.


I've got an idea; why not re-write it all in C?

--

Henry LawManchester, England
--
https://mail.python.org/mailman/listinfo/python-list


Error in IDLE

2015-08-17 Thread Henry Quansah
I just installed python. But I'm unable to access IDLE after several clicks
and double clicks. I even tried repairing by trying to reinstall but I have
the same issue.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why do Perl programmers make more money than Python programmers

2013-05-05 Thread Henry Law

On 05/05/13 18:11, Ignoramus16992 wrote:

According to CIO.com


What an amusing thread; lightened my (non-programmer) day.

--

Henry LawManchester, England
--
http://mail.python.org/mailman/listinfo/python-list


testing array of logicals

2006-07-12 Thread John Henry
Hi list,

Is there a more elagant way of doing this?

# logflags is an array of logicals
test=True
for x in logflags:
   test = test and x
print test

--
Thanks,

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


Re: testing array of logicals

2006-07-13 Thread John Henry

Simon Brunning wrote:
> On 12 Jul 2006 11:14:43 -0700, John Henry <[EMAIL PROTECTED]> wrote:
> > Is there a more elagant way of doing this?
> >
> > # logflags is an array of logicals
> > test=True
> > for x in logflags:
> >test = test and x
> > print test
>
> min(logflags)
>

!!!


> I feel dirty now. ;-)
>

ROFL

Thanks to everybody that replied.


> --
> Cheers,
> Simon B,
> [EMAIL PROTECTED],
> http://www.brunningonline.net/simon/blog/

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


Better utilization of duo-core?

2006-07-13 Thread John Henry
Hi list,

I have a Python ap that starts another non-Pythoon ap for number
crunching.  My new notebook comes with a duo-core CPU.  I tried
manually running 2 copies of my ap at the same time) and it appears to
run the whole job faster (or at least the CPU loading level as show by
the task manager appears so).  So, I want my Python code to do this
automatically.

How do I detect whether I have additional CPUs in the system?  The
google search turns up answer about a Sun workstation but not Windows
XP.

Thanks,

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


Re: testing array of logicals

2006-07-13 Thread John Henry

Simon Forman wrote:
> >
> > False not in logflags
> >
>
> Or, if your values aren't already bools
>
> False not in (bool(n) for n in logflags)
> 
> 
> 
> Peace,
> ~Simon

Very intriguing use of "not in"...

Thanks,

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


Cyclic class definations

2006-07-18 Thread John Henry
Hi list,

I am trying to understand better Python packaging.  This might be a
messed up class hierachy but how would I break this cyclic relatioship?

In file A:

from B import B_Class

Class_A_Main():
   def 
   def SomeMethod(self):
  res=B_Class(self)

Class_A_SubClass(Class_A_Main):
   def ...


In file B:

Class B_Class():
   def __init__(self,parent):
  ...
   def SomeMethod(self):
  res=C_Class(self)


In file C:

from file A import Class_A_SubClass

Class C_Class(Class_A_SubClass):
   def __init__(self, parent):
  ...


As you can see, the cyclic relationship exists because C_Class is a
sub-class of SubClass which is in turn a sub-class of Class_A_Main and
in one of the methods of Class_A, it has a need to create a C_Class
object.

I tried to merge the files A and C (by placing C_Class behind A_Class)
and have the method in A_Class create C_Class directly but that doesn't
work because Python says C_Class is not defined when it's processing
the A_Class method.   May be somebody can tell me how to "forward
declare" a class?

Regards,

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


Re: Cyclic class definations

2006-07-18 Thread John Henry
I think I got the answer by playing around a bit.   It appears you
*don't* need to forward declare things.  For example, the following
code works:

class a:
  def run(self):
new_a=a_sub()
new_a.print_it()

class a_sub(a):
  def print_it(self):
print "Hi"

b=a().run()

Regards,


John Henry wrote:
> Hi list,
>
> I am trying to understand better Python packaging.  This might be a
> messed up class hierachy but how would I break this cyclic relatioship?
>
> In file A:
>
> from B import B_Class
>
> Class_A_Main():
>def 
>def SomeMethod(self):
>   res=B_Class(self)
>
> Class_A_SubClass(Class_A_Main):
>def ...
>
>
> In file B:
>
> Class B_Class():
>def __init__(self,parent):
>   ...
>def SomeMethod(self):
>   res=C_Class(self)
>
>
> In file C:
>
> from file A import Class_A_SubClass
>
> Class C_Class(Class_A_SubClass):
>def __init__(self, parent):
>   ...
>
>
> As you can see, the cyclic relationship exists because C_Class is a
> sub-class of SubClass which is in turn a sub-class of Class_A_Main and
> in one of the methods of Class_A, it has a need to create a C_Class
> object.
>
> I tried to merge the files A and C (by placing C_Class behind A_Class)
> and have the method in A_Class create C_Class directly but that doesn't
> work because Python says C_Class is not defined when it's processing
> the A_Class method.   May be somebody can tell me how to "forward
> declare" a class?
> 
> Regards,

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


Re: Cyclic class definations

2006-07-18 Thread John Henry
Thanks for the note, Nick.

I ended up with cycles as a historical reason.  Some code that were
written long time ago did not anticipate that part of it will get
sub-classed.

Thanks again.

Nick Vatamaniuc wrote:
> John,
> Cycles are tricky. Python is an interpreted dynamic language, whatever
> object you instantiate in your methods is a different thing than class
> hierarchy. Your class hierarchy is fine: ClassA->ClassASubclass->ClassC
> and it should work.  If it doesn't, create a quick mock example and
> post it along with the error.
>
> In general try to model your problem to avoid cycles if possible, I
> know sometimes they are un-avoidable, but more often then not, they
> are. Python might or might not allow cycles in certain situations
> (packages, imports, class hierarchy and during usage i.e. in your
> semantics) but regardless, if they make your code hard to understand so
> try to not introduce them if possible.
>
> Hope this helps,
> Nick V.
>
>
> John Henry wrote:
> > Hi list,
> >
> > I am trying to understand better Python packaging.  This might be a
> > messed up class hierachy but how would I break this cyclic relatioship?
> >
> > In file A:
> >
> > from B import B_Class
> >
> > Class_A_Main():
> >def 
> >def SomeMethod(self):
> >   res=B_Class(self)
> >
> > Class_A_SubClass(Class_A_Main):
> >def ...
> >
> >
> > In file B:
> >
> > Class B_Class():
> >def __init__(self,parent):
> >   ...
> >def SomeMethod(self):
> >   res=C_Class(self)
> >
> >
> > In file C:
> >
> > from file A import Class_A_SubClass
> >
> > Class C_Class(Class_A_SubClass):
> >def __init__(self, parent):
> >   ...
> >
> >
> > As you can see, the cyclic relationship exists because C_Class is a
> > sub-class of SubClass which is in turn a sub-class of Class_A_Main and
> > in one of the methods of Class_A, it has a need to create a C_Class
> > object.
> >
> > I tried to merge the files A and C (by placing C_Class behind A_Class)
> > and have the method in A_Class create C_Class directly but that doesn't
> > work because Python says C_Class is not defined when it's processing
> > the A_Class method.   May be somebody can tell me how to "forward
> > declare" a class?
> > 
> > Regards,

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


Can thread start other threads?

2006-07-18 Thread John Henry
Can Python thread start threads?  It appears not.  When I do that, the
sub-threads gets to certain point and just sit there.  If I run the
code serially and not run the sub-thread code as threads, everything is
fine.

I throught the problem is when you run multiple processes of Pythons...

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


Re: Can thread start other threads?

2006-07-18 Thread John Henry
Thanks for the confirmation.

I will see if I can reduce the code down to something managable and
post the failing code.



Diez B. Roggisch wrote:
> John Henry schrieb:
> > Can Python thread start threads?  It appears not.  When I do that, the
> > sub-threads gets to certain point and just sit there.  If I run the
> > code serially and not run the sub-thread code as threads, everything is
> > fine.
>
> It can.
>
> import threading, time
>
>
> class Test(threading.Thread):
>  def __init__(self, num):
>  threading.Thread.__init__(self)
>  self._num = num
>  self.setDaemon(True)
>  self.start()
>
>  def run(self):
>  if self._num > 0:
>  t = Test(self._num - 1)
>  while True:
>  time.sleep(.2)
>  print "T_%i" % self._num
>
>
> t = Test(4)
>
> while True:
>  time.sleep(2.0)
>
>
> > I throught the problem is when you run multiple processes of Pythons...
>
>
> No.
>
> Whatever you do, it must be the cause. Without code - nobody can tell
> you why.
> 
> Diez

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


Re: Threads vs Processes

2006-07-26 Thread John Henry

Chance Ginger wrote:
> On Wed, 26 Jul 2006 10:54:48 -0700, Carl J. Van Arsdall wrote:
>
> > Alright, based a on discussion on this mailing list, I've started to
> > wonder, why use threads vs processes.  So, If I have a system that has a
> > large area of shared memory, which would be better?  I've been leaning
> > towards threads, I'm going to say why.
> >
> > Processes seem fairly expensive from my research so far.  Each fork
> > copies the entire contents of memory into the new process.  There's also
> > a more expensive context switch between processes.  So if I have a
> > system that would fork 50+ child processes my memory usage would be huge
> > and I burn more cycles that I don't have to.  I understand that there
> > are ways of IPC, but aren't these also more expensive?
> >
> > So threads seems faster and more efficient for this scenario.  That
> > alone makes me want to stay with threads, but I get the feeling from
> > people on this list that processes are better and that threads are over
> > used.  I don't understand why, so can anyone shed any light on this?
> >
> >
> > Thanks,
> >
> > -carl
>
> Not quite that simple. In most modern OS's today there is something
> called COW - copy on write. What happens is when you fork a process
> it will make an identical copy. Whenever the forked process does
> write will it make a copy of the memory. So it isn't quite as bad.
>
> Secondly, with context switching if the OS is smart it might not
> flush the entire TLB. Since most applications are pretty "local" as
> far as execution goes, it might very well be the case the page (or
> pages) are already in memory.
>
> As far as Python goes what you need to determine is how much
> real parallelism you want. Since there is a global lock in Python
> you will only execute a few (as in tens) instructions before
> switching to the new thread. In the case of true process you
> have two independent Python virtual machines. That may make things
> go much faster.
>
> Another issue is the libraries you use. A lot of them aren't
> thread safe. So you need to watch out.
>
> Chance

It's all about performance (and sometimes the "perception" of
performance).  Eventhough the thread support (and performance) in
Python is fairly weak (as explained by Chance), it's nonetheless very
useful.  My applications threads a lot and it proves to be invaluable -
particularly with GUI type applications.  I am the type of user that
gets annoyed very quickly and easily if the program doesn't respond to
me when I click something.  So, as a rule of thumb, if the code has to
do much of anything that takes say a tenth of a second or more, I
thread.

I posted a simple demo program yesterday to the Pythoncard list to show
why somebody would want to thread an app.  You can properly see it from
archive.

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


Re: Threads vs Processes

2006-07-26 Thread John Henry


>
> Carl,
>  OS writers provide much more tools for debugging, tracing, changing
> the priority of, sand-boxing processes than threads (in general) It
> *should* be easier to get a process based solution up and running
> andhave it be more robust, when compared to a threaded solution.
>
> - Paddy (who shies away from threads in C and C++ too ;-)

That mythical "process" is more robust then "thread" application
paradigm again.

No wonder there are so many boring software applications around.

Granted.  Threaded program forces you to think and design your
application much more carefully (to avoid race conditions, dead-locks,
...) but there is nothing inherently *non-robust* about threaded
applications.

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


Re: Threads vs Processes

2006-07-27 Thread John Henry

[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] wrote:
> > John Henry wrote:
> > > Granted.  Threaded program forces you to think and design your
> > > application much more carefully (to avoid race conditions, dead-locks,
> > > ...) but there is nothing inherently *non-robust* about threaded
> > > applications.
> >
> > Indeed.  Let's just get rid of all preemptive multitasking while we're
> > at it
>
> Also, race conditions and deadlocks are equally bad in multiprocess
> solutions as in multithreaded ones.  Any time you're doing parallel
> processing you need to consider them.
>

Only in the sense that you are far more likely to be dealing with
shared resources in a multi-threaded application.  When I start a
sub-process, I know I am doing that to *avoid* resource sharing.  So,
the chance of a dead-lock is less - only because I would do it far
less.

> I'd actually submit that initially writing multiprocess programs
> requires more design and forethought, since you need to determine
> exactly what you want to share instead of just saying "what the heck,
> everything's shared!"  The payoff in terms of getting _correct_
> behavior more easily, having much easier maintenance down the line, and
> being more robust in the face of program failures (or unforseen
> environment issues) is usually well worth it, though there are
> certainly some applications where threads are a better choice.

If you're sharing things, I would thread. I would not want to  pay the
expense of a process.

It's too bad that programmers are not threading more often.

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


Re: Threads vs Processes

2006-07-27 Thread John Henry
Nick Craig-Wood wrote:
>
> Here is test prog...
>



Here's a more real-life like program done in both single threaded mode
and multi-threaded mode.  You'll need PythonCard to try this.  Just to
make the point, you will notice that the core code is identical between
the two (method on_menuFileStart_exe).  The only difference is in the
setup code.  I wanted to dismiss the myth that multi-threaded programs
are inherently *evil*, or that it's diffcult to code, or that it's
unsafe.(what ever dirty water people wish to throw at it).

Don't ask me to try this in process!

To have fun, first run it in single threaded mode (change the main
program to invoke the MyBackground class, instead of the
MyBackgroundThreaded class):

Change:

app = model.Application(MyBackgroundThreaded)

to:

app = model.Application(MyBackground)

Start the process by selecting File->Start, and then try to stop the
program by clicking File->Stop.  Note the performance of the program.

Now, run it in multi-threaded mode.  Click File->Start several times
(up to 4) and then try to stop the program by clicking File->Stop.

If you want to show off, add several more StaticText items in the
resource file, add them to the textAreas list in MyBackgroundThreaded
class and let it rip!

BTW: This ap also demonstrates the weakness in Python thread - the
threads don't get preempted equally (not even close).

:-)

Two files follows (test.py and test.rsrc.py):

#!/usr/bin/python

"""
__version__ = "$Revision: 1.1 $"
__date__ = "$Date: 2004/10/24 19:21:46 $"
"""

import wx
import threading
import thread
import time

from PythonCard import model

class MyBackground(model.Background):

def on_initialize(self, event):
# if you have any initialization
# including sizer setup, do it here
self.running(False)
self.textAreas=(self.components.TextArea1,)
return

def on_menuFileStart_select(self, event):
on_menuFileStart_exe(self.textAreas[0])
return

def on_menuFileStart_exe(self, textArea):
textArea.visible=True
self.running(True)
for i in range(1000):
textArea.text = "Got up to %d" % i
##print i
for j in range(i):
k = 0
time.sleep(0)
if not self.running(): break
try:
wx.SafeYield(self)
except:
pass
if not self.running(): break
textArea.text = "Finished at %d" % i
return

def on_menuFileStop_select(self, event):
self.running(False)

def on_Stop_mouseClick(self, event):
self.on_menuFileStop_select(event)
return

def running(self, flag=None):
if flag!=None:
self.runningFlag=flag
return self.runningFlag


class MyBackgroundThreaded(MyBackground):

def on_initialize(self, event):
# if you have any initialization
# including sizer setup, do it here
self.myLock=thread.allocate_lock()
self.myThreadCount = 0
self.running(False)
self.textAreas=[self.components.TextArea1, 
self.components.TextArea2,
self.components.TextArea3, self.components.TextArea4]
return

def on_menuFileStart_select(self, event):
res=MyBackgroundWorker(self).start()

def on_menuFileStop_select(self, event):
self.running(False)
self.menuBar.setEnabled("menuFileStart", True)

def on_Stop_mouseClick(self, event):
self.on_menuFileStop_select(event)

def running(self, flag=None):
self.myLock.acquire()
if flag!=None:
self.runningFlag=flag
flag=self.runningFlag
self.myLock.release()
return flag

class MyBackgroundWorker(threading.Thread):
def __init__(self, parent):
threading.Thread.__init__(self)
self.parent=parent
self.parent.myLock.acquire()
threadCount=self.parent.myThreadCount
self.parent.myLock.release()
self.textArea=self.parent.textAreas[threadCount]

def run(self):
self.parent.myLock.acquire()
self.parent.myThreadCount += 1
if self.parent.myThreadCount==len(self.parent.textAreas):
self.parent.menuBar.setEnabled("menuFileStart", False)
self.parent.myLock.release()

self.parent.on_menuFileStart_exe(self.t

Pywin32 Excel question

2006-08-04 Thread John Henry
I posted the following message to the Pywin32 list but if anybody here
can help, it would be appreciated very much.


Hi list,

I have a need to copy 3 rows of data from the top of my Excel
spreadsheet to another location.  I would have throught that this
should be very straightforward since I've done a fair amount of
Excel/Python programming.  Unforturnately, I am stuck on this one.

The VB Macro says I need to:

Range("1:1,2:2,3:3").Select
Range("A3").Activate
Selection.Copy
Rows("20:20").Select
ActiveSheet.Paste

So, I figure the Python code would be something like:


1) xlSheet=xlApp.ActiveWorkbook.ActiveSheet
2) xlSel=xlSheet.Range("1:1,2:2,3:3").Select()
3) #xlSel=xlSheet.Range("A3").Activate()
4) xlSel.Copy()
5) xlSheet.Rows("20:20").Select()
6) xlSheet.Paste()

Unfortunately, this doesn't work.  After line 2, xlSel becomes "True" -
not a "Selection" and so the code fails at line 4).  I am not sure why
I have to do the "Activate" on line 3 but it didn't matter, the code
still fails at line 4.


What am I doing wrong?

Any help is greatly appreciated.

Regards,

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


Re: Pywin32 Excel question

2006-08-05 Thread John Henry
Somebody on the Pywin32 list helped.  The problem is that:

xlSel=xlSheet.Range("1:1,2:2,3:3").Select()

is wrong.

It should be:

xlSel=xlSheet.Range("1:1,2:2,3:3")
xlSel.Select()

Then I can do the rest.

And no, you don't want to do the xlSheet.Copy().  That copies the
entire workbook and you end up with a new workbook.

But you have to do xlSheet.Paste().   Go figure!




[EMAIL PROTECTED] wrote:
> John Henry wrote:
> > I posted the following message to the Pywin32 list but if anybody here
> > can help, it would be appreciated very much.
> >
> > 
> > Hi list,
> >
> > I have a need to copy 3 rows of data from the top of my Excel
> > spreadsheet to another location.  I would have throught that this
> > should be very straightforward since I've done a fair amount of
> > Excel/Python programming.  Unforturnately, I am stuck on this one.
> >
> > The VB Macro says I need to:
> >
> > Range("1:1,2:2,3:3").Select
> > Range("A3").Activate
> > Selection.Copy
> > Rows("20:20").Select
> > ActiveSheet.Paste
> >
> > So, I figure the Python code would be something like:
> >
> > 
> > 1) xlSheet=xlApp.ActiveWorkbook.ActiveSheet
> > 2) xlSel=xlSheet.Range("1:1,2:2,3:3").Select()
> > 3) #xlSel=xlSheet.Range("A3").Activate()
> > 4) xlSel.Copy()
> > 5) xlSheet.Rows("20:20").Select()
> > 6) xlSheet.Paste()
> >
> > Unfortunately, this doesn't work.  After line 2, xlSel becomes "True" -
> > not a "Selection" and so the code fails at line 4).  I am not sure why
> > I have to do the "Activate" on line 3 but it didn't matter, the code
> > still fails at line 4.
>
> My first guess is that the True returned in step 2 merely tells you
> the requested selection succeeded (the cells on the worksheet
> became highlighted). What would happen if you requested 500
> columns? Would you get False?
>
> My second guess is that step 4 should be xlSheet.Copy() based
> on your using xlSheet.Paste().
>
> For that matter, step 5 doesn't assign the result of the select to a
> variable. Perhaps that indicates that the assignment isn't necessary?
> Or maybe you should test that the selection succeeded before
> attempting to paste?
>
> >
> >
> > What am I doing wrong?
> > 
> > Any help is greatly appreciated.
> > 
> > Regards,

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


What's the cleanest way to compare 2 dictionary?

2006-08-09 Thread John Henry
Hi list,

I am sure there are many ways of doing comparision but I like to see
what you would do if you have 2 dictionary sets (containing lots of
data - like 2 keys and each key contains a dozen or so of records)
and you want to build a list of differences about these two sets.

I like to end up with 3 lists: what's in A and not in B, what's in B
and not in A, and of course, what's in both A and B.

What do you think is the cleanest way to do it?  (I am sure you will
come up with ways that astonishes me  :=) )

Thanks,

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


Re: What's the cleanest way to compare 2 dictionary?

2006-08-09 Thread John Henry

Paddy wrote:
> John Henry wrote:
> > Hi list,
> >
> > I am sure there are many ways of doing comparision but I like to see
> > what you would do if you have 2 dictionary sets (containing lots of
> > data - like 2 keys and each key contains a dozen or so of records)
> > and you want to build a list of differences about these two sets.
> >
> > I like to end up with 3 lists: what's in A and not in B, what's in B
> > and not in A, and of course, what's in both A and B.
> >
> > What do you think is the cleanest way to do it?  (I am sure you will
> > come up with ways that astonishes me  :=) )
> >
> > Thanks,
> I make it 4 bins:
>  a_exclusive_keys
>  b_exclusive_keys
>  common_keys_equal_values
>  common_keys_diff_values
>
> Something like:
>
> a={1:1, 2:2,3:3,4:4}
> b = {2:2, 3:-3, 5:5}
> keya=set(a.keys())
> keyb=set(b.keys())
> a_xclusive = keya - keyb
> b_xclusive = keyb - keya
> _common = keya & keyb
> common_eq = set(k for k in _common if a[k] == b[k])
> common_neq = _common - common_eq
>
>
> If you now simple set arithmatic, it should read OK.
>
> - Paddy.

Thanks, that's very clean.  Give me good reason to move up to Python
2.4.

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


Re: What's the cleanest way to compare 2 dictionary?

2006-08-09 Thread John Henry

John Henry wrote:
> Paddy wrote:
> > John Henry wrote:
> > > Hi list,
> > >
> > > I am sure there are many ways of doing comparision but I like to see
> > > what you would do if you have 2 dictionary sets (containing lots of
> > > data - like 2 keys and each key contains a dozen or so of records)
> > > and you want to build a list of differences about these two sets.
> > >
> > > I like to end up with 3 lists: what's in A and not in B, what's in B
> > > and not in A, and of course, what's in both A and B.
> > >
> > > What do you think is the cleanest way to do it?  (I am sure you will
> > > come up with ways that astonishes me  :=) )
> > >
> > > Thanks,
> > I make it 4 bins:
> >  a_exclusive_keys
> >  b_exclusive_keys
> >  common_keys_equal_values
> >  common_keys_diff_values
> >
> > Something like:
> >
> > a={1:1, 2:2,3:3,4:4}
> > b = {2:2, 3:-3, 5:5}
> > keya=set(a.keys())
> > keyb=set(b.keys())
> > a_xclusive = keya - keyb
> > b_xclusive = keyb - keya
> > _common = keya & keyb
> > common_eq = set(k for k in _common if a[k] == b[k])
> > common_neq = _common - common_eq
> >
> >
> > If you now simple set arithmatic, it should read OK.
> >
> > - Paddy.
>
> Thanks, that's very clean.  Give me good reason to move up to Python
> 2.4.

Oh, wait, works in 2.3 too.

Just have to:

from sets import Set as set

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


Re: What's the cleanest way to compare 2 dictionary?

2006-08-10 Thread John Henry
John,

Yes, there are several scenerios.

a) Comparing keys only.

That's been answered (although I haven't gotten it to work under 2.3
yet)

b) Comparing records.

Now it gets more fun - as you pointed out.  I was assuming that there
is no short cut here.  If the key exists on both set, and if I wish to
know if the records are the same, I would have to do record by record
comparsion.  However, since there are only a handful of records per
key, this wouldn't be so bad.  Maybe I just overload the compare
operator or something.

John Machin wrote:
> John Henry wrote:
> > Hi list,
> >
> > I am sure there are many ways of doing comparision but I like to see
> > what you would do if you have 2 dictionary sets (containing lots of
> > data - like 2 keys and each key contains a dozen or so of records)
> > and you want to build a list of differences about these two sets.
> >
> > I like to end up with 3 lists: what's in A and not in B, what's in B
> > and not in A, and of course, what's in both A and B.
> >
> > What do you think is the cleanest way to do it?  (I am sure you will
> > come up with ways that astonishes me  :=) )
> >
>
> Paddy has already pointed out a necessary addition to your requirement
> definition: common keys with different values.
>
> Here's another possible addition: you say that "each key contains a
> dozen or so of records". I presume that you mean like this:
>
> a = {1: ['rec1a', 'rec1b'], 42: ['rec42a', 'rec42b']} # "dozen" -> 2 to
> save typing :-)
>
> Now that happens if the other dictionary contains:
>
> b = {1: ['rec1a', 'rec1b'], 42: ['rec42b', 'rec42a']}
>
> Key 42 would be marked as different by Paddy's classification, but the
> values are the same, just not in the same order. How do you want to
> treat that? avalue == bvalue? sorted(avalue) == sorted(bvalue)? Oh, and
> are you sure the buckets don't contain duplicates? Maybe you need
> set(avalue) == set(bvalue). What about 'rec1a' vs 'Rec1a' vs 'REC1A'?
>
> All comparisons are equal, but some comparisons are more equal than
> others :-)
> 
> Cheers,
> John

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


Re: using python to edit a word file?

2006-08-10 Thread John Henry
John Salerno wrote:
> I figured my first step is to install the win32 extension, which I did,
> but I can't seem to find any documentation for it. A couple of the links
> on Mark Hammond's site don't seem to work.
>
> Anyway, all I need to do is search in the Word document for certain
> strings and either delete them or replace them. Easy enough, if only I
> knew which function, etc. to use.
>
> Hope someone can push me in the right direction.
>
> Thanks.

The easiest way for me to do things like this is to do it in Word and
record a VB Macro.  For instance you will see something like this:

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "save it"
.Replacement.Text = "dont save it"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.CorrectHangulEndings = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchFuzzy = False
End With
Selection.Find.Execute Replace:=wdReplaceAll

and then hand translate it to Win32 Python, like:

   wordApp = Dispatch("Word.Application")
   wordDoc=wordApp.Documents.Add(...some word file name...)
   wordRange=wordDoc.Range(0,0).Select()
   sel=wordApp.Selection
   sel.Find.ClearFormatting()
   sel.Find.Replacement.ClearFormatting()
   sel.Find.Text = "save it"
   sel.Find.Replacement.Text = "dont save it"
   sel.Find.Forward = True
   sel.Find.Wrap = constants.wdFindContinue
   sel.Find.Format = False
   sel.Find.MatchCase = False
   sel.Find.MatchWholeWord = False
   sel.Find.MatchByte = False
   sel.Find.CorrectHangulEndings = False
   sel.Find.MatchAllWordForms = False
   sel.Find.MatchSoundsLike = False
   sel.Find.MatchWildcards = False
   sel.Find.MatchFuzzy = False
   sel.Find.Find.Execute(Replace=constants.wdReplaceAll)
   wordDoc.SaveAs(...some word file name...)

Can't say that this works as I typed because I haven't try it myself
but should give you a good start.

Make sure you run the makepy.py program in the
\python23\lib\site-packages\win32com\client directory and install the
"MS Word 11.0 Object Library (8.3)" (or something equivalent).   On my
computers, this is not installed automatically and I have to remember
to do it myself or else things won't work.

Good Luck.

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


Re: What's the cleanest way to compare 2 dictionary?

2006-08-11 Thread John Henry

John Machin wrote:
> John Henry wrote:
> > John,
> >
> > Yes, there are several scenerios.
> >
> > a) Comparing keys only.
> >
> > That's been answered (although I haven't gotten it to work under 2.3
> > yet)
>
> (1) What's the problem with getting it to work under 2.3?
> (2) Why not upgrade?
>

Let me comment on this part first, I am still chewing other parts of
your message.

When I do it under 2.3, I get:

common_eq = set(k for k in _common if a[k] == b[k])
   ^
SyntaxError: invalid syntax

Don't know why that is.

I can't  upgrade yet.  Some part of my code doesn't compile under 2.4
and I haven't got a chance to investigate further.

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


Re: What's the cleanest way to compare 2 dictionary?

2006-08-11 Thread John Henry
Thank you.  That works.


Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, John Henry
> wrote:
>
> > When I do it under 2.3, I get:
> >
> > common_eq = set(k for k in _common if a[k] == b[k])
> >^
> > SyntaxError: invalid syntax
> >
> > Don't know why that is.
>
> There are no generator expressions in 2.3.  Turn it into a list
> comprehension::
>
>   common_eq = set([k for k in _common if a[k] == b[k]])
> 
> Ciao,
>   Marc 'BlackJack' Rintsch

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


Re: Easy to use distributed system?

2006-08-14 Thread John Henry
I've been using Pyro and it does what I needs it to do for me.

I don't know if it's as fancy as other packages but the price is right.

Jim Jones wrote:
> I am looking for a system in Python that will easily allow me to distribute
> processes across multiple systems?So, if I have a function 'foo', I'd
> like to be able to call something along the lines of
>
> distribute(foo(x))
>
> And have the system figure out which node is available for process, and then
> have the results returned in some sort of callback fashion.
>
> Any insight is greatly appreciated.
> 
> -- 
> Jim
> http://www.runfatboy.net - Exercise for the rest of us.

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


Re: inheritance?

2006-08-15 Thread John Henry
Is this what you're looking for?

class baseClass:
   def __init__(self):
   def fromfile(self, fileObj, byteOrder=None):
   def getVR(self):
   def getGroup(self):
   def getElement(self):
   def getSize(self):
   def getData(self):

class implicitClass(baseClass):
   def __init__(self):
  baseClass.__init__(self)
   def isIVR(self):  #This is a class private method.

class explicitClass(baseClass):
   def __init__(self):
  baseClass.__init__(self)

KraftDiner wrote:
> I have two classes:
>
> class implicitClass:
>def __init__(self):
>def isIVR(self):  #This is a class private method.
>def fromfile(self, fileObj, byteOrder):
>def getVR(self):
>def getGroup(self):
>def getElement(self):
>def getSize(self):
>def getData(self):
>
> class explicitClass:
>def __init__(self):
>def fromfile(self, fileObj):
>def getVR(self):
>def getGroup(self):
>def getElement(self):
>def getSize(self):
>def getData(self):
>
>
> As you can see the interface is almost identical.
>
> How can I define a base class that will abstract
> the type such that I don't know if its really and inplicit
> or explicit object?

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


Re: inheritance?

2006-08-16 Thread John Henry
As others pointed out already, this kind of "if then else"
determination of type is best avoided.

If it looks like a duck, quakes like a duck, must be a duck.

KraftDiner wrote:
> Steven D'Aprano wrote:
> > On Tue, 15 Aug 2006 19:35:11 -0700, KraftDiner wrote:
> >
> > > I have two classes:
> > >
> > > class implicitClass:
> > >def __init__(self):
> > >def isIVR(self):  #This is a class private method.
> >
> > The convention is to flag classes as "private" with a leading underscore:
> >
> > def _isIVR(self):
> >
> > or double underscores for "really private, no, honestly":
> >
> > def __isIVR(self):
> >
> > but google on "python name mangling" before using that.
> >
> > [snip]
> >
> > > As you can see the interface is almost identical.
> > >
> > > How can I define a base class that will abstract
> > > the type such that I don't know if its really and inplicit
> > > or explicit object?
> >
> > Something like this?
> >
> >
> > class baseClass:
> >def __init__(self):
> >raise NotImplementedError("Don't instantiate the base class!")
> >def fromfile(self):
> >def getElement(self):
> ># etc.
> >
> >
> > class implicitClass(baseClass):
> >def __init__(self):
> ># code
> >def _isIVR(self):
> ># code
> >def fromfile(self, fileObj, byteOrder):
> ># code
> > # etc.
> >
> > Now, you can define instance = implicitClass() or explicitClass(). When
> > you come to use instance, you don't need to know whether it is one or the
> > other. If you need to type-test, call "isinstance(instance, baseClass)".
> >
> > The only minor issue is that the fromfile method has a different
> > interface. If you really want to do duck typing, they need to have the
> > same interface. That might be as simple as:
> >
> > class explicitClass(baseClass):
> >def fromfile(self, fileObj, byteOrder=None):
> ># byteOrder is ignored; it is included only for
> ># compatibility with implicitClass
> >
> >
> > Is that what you're asking for?
> >
> Yes I believe so but in fromfile I want to call the appropriate
> method depending on the in a parameter in fromfile...
> like:
> class baseClass:
>def fromfile(self, fileObj, byteOrder=None, explicit=False):
>   if explicit:
>  call fromfile of explicit class
>   else:
> call fromfile of implicit class
> 
> How is that done?
> 
> 
> > 
> > 
> > -- 
> > Steven D'Aprano

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


Re: inheritance?

2006-08-16 Thread John Henry


> Here I tried this example and maybe this will explain the difficulties
> I'm having.
> 1) at the time the baseClass is constructed shouldn't the constructor
> of the appropriate
> type be called.

Not automatically.

> 2) getName is doing nothing...
>
> class baseClass:
>   def __init__(self):
>   pass
>   def fromfile(self, str):
>   if (str == 'A'):
>   a = typeA()
>   else:
>   a = typeB()
>   def getName(self):
>   pass
>
> class typeA(baseClass):
>   def __init__(self):
>   self.name='A'
>   print 'typeA init'
>   def fromfile(self, str=None):
>   print 'typeA fromfile'
>   def getName(self):
>   print self.name
>
> class typeB(baseClass):
>   def __init__(self):
>   self.name='B'
>   print 'typeB init'
>   def fromfile(self, str=None):
>   print 'typeB fromfile'
>   def getName(self):
>   print self.name
>
> bc = baseClass()
> bc.fromfile('A')
> bc.getName()
> bc.fromfile('B')
> bc.getName()
> bc.getName()
>
> log:
> typeA init
> typeB init
>

> >
> > --
> > Steven D'Aprano

Maybe this would help:

class baseClass:
def __init__(self, name):
self.name=name
print 'type'+self.name+' init'
def fromfile(self, str):
if (str == 'A'):
a = typeA()
else:
a = typeB()
def getName(self):
print self.name

class typeA(baseClass):
def __init__(self):
baseClass.__init__(self, "A")
def fromfile(self, str=None):
print 'type'+self.name+' fromfile'

class typeB(baseClass):
def __init__(self):
baseClass.__init__(self, "B")
def fromfile(self, str=None):
print 'type'+self.name+' fromfile'

bcA = typeA()
bcA.fromfile()
bcA.getName()

bcB = typeB()
bcB.fromfile()
bc.getName()

I think you're looking at objects in an inverted way.

typeA is a kind of baseClass, and so is typeB.

not:

baseClass consists of 2 subclasses A and B.

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


Re: inheritance?

2006-08-16 Thread John Henry
Oops!  Forgot to remove fromfile from baseClass.  Wouldn't matter
though.

John Henry wrote:
> > Here I tried this example and maybe this will explain the difficulties
> > I'm having.
> > 1) at the time the baseClass is constructed shouldn't the constructor
> > of the appropriate
> > type be called.
>
> Not automatically.
>
> > 2) getName is doing nothing...
> >
> > class baseClass:
> > def __init__(self):
> > pass
> > def fromfile(self, str):
> > if (str == 'A'):
> > a = typeA()
> > else:
> > a = typeB()
> > def getName(self):
> > pass
> >
> > class typeA(baseClass):
> > def __init__(self):
> > self.name='A'
> > print 'typeA init'
> > def fromfile(self, str=None):
> > print 'typeA fromfile'
> > def getName(self):
> > print self.name
> >
> > class typeB(baseClass):
> > def __init__(self):
> > self.name='B'
> > print 'typeB init'
> > def fromfile(self, str=None):
> > print 'typeB fromfile'
> > def getName(self):
> > print self.name
> >
> > bc = baseClass()
> > bc.fromfile('A')
> > bc.getName()
> > bc.fromfile('B')
> > bc.getName()
> > bc.getName()
> >
> > log:
> > typeA init
> > typeB init
> >
>
> > >
> > > --
> > > Steven D'Aprano
>
> Maybe this would help:
>
> class baseClass:
> def __init__(self, name):
> self.name=name
> print 'type'+self.name+' init'
> def fromfile(self, str):
> if (str == 'A'):
> a = typeA()
> else:
> a = typeB()
> def getName(self):
> print self.name
>
> class typeA(baseClass):
> def __init__(self):
> baseClass.__init__(self, "A")
> def fromfile(self, str=None):
> print 'type'+self.name+' fromfile'
>
> class typeB(baseClass):
> def __init__(self):
> baseClass.__init__(self, "B")
> def fromfile(self, str=None):
> print 'type'+self.name+' fromfile'
>
> bcA = typeA()
> bcA.fromfile()
> bcA.getName()
>
> bcB = typeB()
> bcB.fromfile()
> bc.getName()
>
> I think you're looking at objects in an inverted way.
>
> typeA is a kind of baseClass, and so is typeB.
> 
> not:
> 
> baseClass consists of 2 subclasses A and B.

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


Re: Find out the name of a variable passed as an argument

2006-10-04 Thread John Henry
Algol, anyone?


Andreas Huesgen wrote:
> Hello everybody,
>
> is there a way to receive the name of an object passed to a function
> from within the function.
>
> something like
>
> def foo(param):
>   print theNameOfTheVariablePassedToParam
>
> var1 = "hello"
> var2 = "world"
>
>  >>> foo(var1)
> var1
>
>  >>> foo(var2)
> var2
> 
> thanks in advance,
> 
> greets
> 
> Andreas Huesgen

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


Re: Need array help

2006-10-06 Thread John Henry
Others posted answer to your question.

If you are serious about programming in Python, I highly recommend that
you don't try to think in terms of "I did this in Visual Basic, how do
I do this in Python".   You'll end up with Python code that are nothing
but a VB look alike.   As recommended by others, go througth the
tutorial.  It will be time well spent.


Marion Long Jr wrote:
> I am switching from microsoft visual basic programming to python
> programming. In microsoft
> visual basic you can Dim a variable so that you can add variables by
> changing the number
> on the end of the variable as in the following example;
>
> Dim acct(100)
>
> numoffiles=4
> data=10
> ct=1
> while ct <> numoffiles
> acctfile(ct) = data
> ct= ct + 1
> data= data + ct
> Wend
> The results are;
> acctfile(1)=10
> acctfile(2)=12
> acctfile(3)=15
>
> And you can compare the values of the new variables;
> if acctfile(1) > acctfile(2) then print "yes"
> if acctfile(2) > acctfile(1) then print "yes"
>
> when I try to create acctfile(ct) = data I get the following error;
> ***can't assign to function call. Then it gives the program line of the
> problem
> Here is the progam in python;
>
> numoffiles=4
> data=10
> ct=1
>
> while ct != numoffiles:
> acctfile(ct) =data
> ct += 1
> data= data + ct
> print acctfile(ct)
> 
> Does anybody know how this is done in Python?

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


Re: Converting existing module/objects to threads

2006-10-18 Thread John Henry
Making your code run in thread mode isn't the hard part.  Just add
this:

import  threading

class subcontrollerThread(threading.Thread, subcontroller):
def __init__(self,id,configurationFile):
threading.Thread.__init__(self)
subcontroller.__init__(self,id,configurationFile)
def run(self):
self.process()

threads=[]
# Say we have 5 of the subprocesses
for iThread in range(5):
th=subcontrollerThread(iThread,configurationFile)
threads.append(th)
th.start()

...main thread do whatever...


However, you have to make sure the code inside subcontroller is thread
safe.  That's a topic in itself.


[EMAIL PROTECTED] wrote:
> I have inheirted some existing code, that i will explain in a moment,
> have needed to extend and ultimately should be able to run in threads.
> I've done a bunch of work with python but very little with threads and
> am looking for some pointers on how to implement, and if the lower
> level modules/objects need to be rewritten to use threading.local for
> all local variables.
>
> I have a module that communicates with a hardware device, which reads
> data off of sensors, that can only talk with one controller at a time.
> The controller (my module) needs to (in its simplest form) init,
> configure the device, request data, and write out xml, sleep, repeat.
>
> The new request is that the device needs to be queried until a
> condition is true, and then start requesting data.  So an instance of a
> controller needs to be deadicated to a hardware device forever, or
> until the program endswhich ever comes first.
>
> This currently works in a non-threaded version, but only for one device
> at a time, there is a need to create a single windows(yeach) service
> that talks to many of these devices at once.  I don't need worker
> threads that handle seperate portions of the entire job, i need a
> single application to spawn multiple processes to run through the
> entire communication from configure to report, sleep until the next
> interval time and run again.  The communication could last from 1
> minute to 10 minutes before it ends.
>
>
>   Here is the code layout in pseudocode.
>
> module.Object - controller.Main - handles all socket communications
>
> class subcontroller(controller.Main):
>   def __init__(self,id,configurationFile):
>controller.Main.__init__(self)
>// instantiate variables and local objects that handle
> configuration, logic and data output
>
>   def configure(self,configurationFile):
> //read configurationFile and configure device
>
>   def process(self):
> while 1:
>   //based on configuration file, query the device until condition
> is true and then write xml, sleep until time to repeat and run again.
>
> within controller there are 5 objects and subcontroller is a sinlge
> object that loads other objects from the inherited controller.System
>
> I'm trying to figure out how difficult it is going to be to convert
> this to a threaded application.  The original controller.Main is built
> to talk to devices in series, never in parallel. so no objects are
> considered to be thread safe, but no instance of any of the objects
> should need to share resources with any other instance of teh same
> object.  they would all have unique configuration files and talk to
> devices on unique ip/ports.
>
> on a unix system, forking,while potentially not optimal, would be a
> fine solution, unfortunantely this needs to run on windows.
>
> I know i have left out many details, but hopefully this is enough to at
> least enable some kind soles to lend an opinnion or two.
> 
> many thanks
> jd

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


Re: python GUIs comparison (want)

2006-10-23 Thread John Henry

[EMAIL PROTECTED] wrote:
> Now i began to learn GUI programming. There are so many
> choices of GUI in the python world, wxPython, pyGTK, PyQT,
> Tkinter, .etc, it's difficult for a novice to decide, however.
> Can you draw a comparison among them on easy coding, pythonish design,
> beautiful and generous looking, powerful development toolkit, and
> sufficient documentation, .etc.
> It's helpful for a GUI beginner.
> Thank you.
>
>
> :)Sorry for my poor english.

I like Pythoncard.  Simple.  Get the job done fast.

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


Dealing with multiple sets

2006-10-25 Thread John Henry
Hi list,

If I have a bunch of sets:

a = set((1, 2, 3))
b = set((2, 3))
c = set((1, 3))


What's the cleanest way to say:

1) Give me a list of the items that are in all of the sets? (3 in the
above example)
2) Give me a list of the items that are not in all of the sets? (1,2 in
the above example)

Thanks,

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


Re: Dealing with multiple sets

2006-10-25 Thread John Henry
Oops.  Forgot to mention, I am still using 2.3.


John Henry wrote:
> Hi list,
>
> If I have a bunch of sets:
>
> a = set((1, 2, 3))
> b = set((2, 3))
> c = set((1, 3))
> 
>
> What's the cleanest way to say:
>
> 1) Give me a list of the items that are in all of the sets? (3 in the
> above example)
> 2) Give me a list of the items that are not in all of the sets? (1,2 in
> the above example)
> 
> Thanks,

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


Re: Dealing with multiple sets

2006-10-25 Thread John Henry
Aye!

I did a:

a and b and c

Bonk!

Thanks,


Tim Peters wrote:
> [John Henry]
> > If I have a bunch of sets:
> >
> > a = set((1, 2, 3))
> > b = set((2, 3))
> > c = set((1, 3))
> > 
> >
> > What's the cleanest way to say:
> >
> > 1) Give me a list of the items that are in all of the sets? (3 in the
> > above example)
>
> list(a & b & c)
>
> > 2) Give me a list of the items that are not in all of the sets? (1,2 in
> > the above example)
> 
> list((a | b | c) - (a & b & c))

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


Re: Dealing with multiple sets

2006-10-26 Thread John Henry
Oh, great.  Learn something new everyday.

For this, what I did was to build up a string, and then use eval on the
string.  Very ugly.

Now I can simply do a reduce.

Thanks,



Brian Beck wrote:
> John Henry wrote:
> > What's the cleanest way to say:
> >
> > 1) Give me a list of the items that are in all of the sets? (3 in the
> > above example)
> > 2) Give me a list of the items that are not in all of the sets? (1,2 in
> > the above example)
> >
> > Thanks,
>
> If you have an arbitrary list of sets, reduce comes in handy:
>
> See this recipe:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/476215
>
> py> sets = [set((1, 2, 3)), set((2, 3)), set((1, 3))]
> py> reduce(set.intersection, sets)
> set([3])
>
> py> reduce(set.union, sets)
> set([1, 2, 3])
>
> py> reduce(set.union, sets) - reduce(set.intersection, sets)
> set([1, 2])
> 
> --
> Brian Beck
> Adventurer of the First Order

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


Re: ANN: Leo 4.4.2.1 final released

2006-10-29 Thread John Henry
I downloaded the Windows exe, ran it and a small blank message window
poped up and that was it.

I am still running 2.3.

Edward K. Ream wrote:
> Leo 4.4.2.1 final is now available at:
> http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106
>
> Leo 4.4.2.1 final fixes a recent bug that caused Leo not to create the
> .leoRecentFiles.txt file properly in some situations. There are no known
> significant bugs in this version of Leo.
>
> Leo 4.4.2 final fixes a few bugs and adds support for pymacs.
>
> Leo is a text editor, data organizer, project manager and much more. See:
> http://webpages.charter.net/edreamleo/intro.html
>
> The highlights of Leo 4.4.2:
> 
> - You can now store settings in myLeoSettings.leo without fear of those
> settings
>   being changed by cvs updates or in future versions of Leo.
> - Leo's vnode and tnode classes are now completely independent of the rest
> of Leo.
>   Some api's have been changed.  This 'big reorg' and may affect scripts and
> plugins.
> - Leo's vnode and tnode classes can optionally be compatible with ZODB
> databases,
>   i.e., they can optionally derive from ZODB.Persistence.Persistent.
>   See Chapter 17: Using ZODB with Leo for details.
> - The leoOPML plugin defines commands to read and write OPML files.
> - The slideshow plugin allows Leo to run slideshows defined by @slideshow
> and @slide nodes.
> - The leo_to_rtf and leo_to_html plugins create rtf and html files from Leo
> outlines.
> - Much faster navigation through the outline.
> - When focus is in the outline pane, you can move to headlines by typing the
> first letter of headlines.
> - The find command now optionally closes nodes not needed to show the node
> containing the present match.
> - Numerous changes that make Leo easier to use without using a mouse,
> including new commands and options.
> - Many new minibuffer commands now appear in the Cmds menu.
> - A sax parser can now optionally read .leo files.
>
> Links:
> --
> Leo:http://webpages.charter.net/edreamleo/front.html
> What's new: http://webpages.charter.net/edreamleo/new-4-4-2.html
> Home:   http://sourceforge.net/projects/leo/
> Download:   http://sourceforge.net/project/showfiles.php?group_id=3458
> CVS:http://leo.tigris.org/source/browse/leo/
> Leo's Wiki: http://leo.zwiki.org/FrontPage
> Wikipedia:  http://en.wikipedia.org/wiki/Leo_%28text_editor%29
> Quotes: http://webpages.charter.net/edreamleo/testimonials.html
>
> 
> Edward K. Ream   email:  [EMAIL PROTECTED]
> Leo: http://webpages.charter.net/edreamleo/front.html
> 

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


Re: scared about refrences...

2006-10-30 Thread John Henry
I am no Python guru - just an ordinary user.

There is nothing "scary" about this.  There are (many) situations where
this is actually *desirable* but of course there are (many) situations
where this is an unwelcomed side-effect.

In situations where I don't want this to happen, I simply pass down the
list as an non-mutable object (like converting the list to a tuple).

It took me a little bit of getting used to this concept as well:
everything is either a mutable object, or a non-mutable object.  I just
have to throw away trying to use concept of "pointers" in Python.

SpreadTooThin wrote:
> I'm really worried that python may is doing some things I wasn't
> expecting... but lets see...
>
> if I pass a list to a function def fn(myList):
>
> and in that function I modify an element in the list, then does the
> callers list get modied as well.
>
> def fn(list):
>list[1] = 0
>
> myList = [1, 2, 3]
> print myList
> fn(myList)
> print myList
>
> >>> [1,2,3]
> >>> [1,0,3]
>
> How can I avoid this?  In this case this is a really simplified example
> but the effects are the same...
> How do I specify or create deep copies of objects that may contain
> other objects that may contain other
> object that may contain other objects

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


Re: ANN: Leo 4.4.2.1 final released

2006-10-31 Thread John Henry
Yes, it's Python 2.3, running under Windows XP.

I managed to get it working using the ZIP file.

Thanks,

Edward K. Ream wrote:
> >I downloaded the Windows exe, ran it and a small blank message window poped
> >up and that was it.
> > I am still running 2.3.
>
> I assume you mean Python 2.3, not Leo 2.3 :-)  I know for sure that Leo
> works with Python 2.3. In the future, please report problems to one of Leo's
> forums.  And when reporting problems please tell me what platform you are
> using.
>
> You can probably see more information by running Leo in a console.  See
> Leo's FAQ for instructions:
> http://webpages.charter.net/edreamleo/FAQ.html#how-can-i-run-leo-from-a-console-window
>
> Edward
> 
> Edward K. Ream   email:  [EMAIL PROTECTED]
> Leo: http://webpages.charter.net/edreamleo/front.html
> 

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


Re: ANN: Leo 4.4.2.1 final released

2006-10-31 Thread John Henry
Yes, it's Python 2.3, running under Windows XP.

I managed to get it working using the ZIP file.

Thanks,

Edward K. Ream wrote:
> >I downloaded the Windows exe, ran it and a small blank message window poped
> >up and that was it.
> > I am still running 2.3.
>
> I assume you mean Python 2.3, not Leo 2.3 :-)  I know for sure that Leo
> works with Python 2.3. In the future, please report problems to one of Leo's
> forums.  And when reporting problems please tell me what platform you are
> using.
>
> You can probably see more information by running Leo in a console.  See
> Leo's FAQ for instructions:
> http://webpages.charter.net/edreamleo/FAQ.html#how-can-i-run-leo-from-a-console-window
>
> Edward
> 
> Edward K. Ream   email:  [EMAIL PROTECTED]
> Leo: http://webpages.charter.net/edreamleo/front.html
> 

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


Re: python GUIs comparison (want)

2006-11-06 Thread John Henry
Yes, from a easy of use standpoint, I agree that PythonCard is very
high on the list.

Unfortunately there isn't more "activities" as one would like to see.

On the other hand, that's typical of open-source projects.  We can
always roll up our sleeves and do it ourselves.

At least the multicolumn control isn't particularly complex, should be
able to figure out from the source code how to sort.  I believe I did
that some time ago.   I believe I ended up reshuffling the list...

metaperl wrote:
> [EMAIL PROTECTED] wrote:
> > Paul Boddie wrote:
> >
> > """The figures behind the scenes are quite enlightening for that
> > particular page. If you (or community experiences) don't agree with the
> >
> > rankings (wxPython apparently even easier to learn than PythonCard and
> > Tinder, a bunch of Gtk-based toolkits having more or less "full" Linux
> > scores) then you'll have some surprises, I'm sure. Nevertheless, it's
> > an interesting concept. """
> >
> > Well, I don't know what I was thinking, exactly, when I rated
> > PythonCard's ease of use...so I went back and changed it to rate it a
> > lot higher. The ratings in this script were done a long time ago now
>
> I dropped Pythoncard when I could not sort multi column lists and when
> I posted to the email list and no one answered me.
> 
> But prior to that it was great.

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


Re: adding python scripting to my application

2006-11-06 Thread John Henry
Take a look at:

http://www.swig.org/

Julian wrote:
> Hi, first of all, I have to say I am new to Python. I have been working
> with a finite element analysis program written in c++. now, I am trying
> to 'rebuild' this code (possibly a full re-write) with scripting
> capability. I did some reading on the web, and found that there are two
> ways to do this : extending and embedding. and I still haven't figured
> out what I should be using. I guess the first thing is to figure out
> what I am to do with the scripting capability - at the very least, I
> would like to run parametric analyses - run multiple analysis models by
> changing certain parameters using for loops.
> i found that the commercial fea package - abaqus uses python as well -
> I don't know whether they embedded or extended ? is there any way to
> find out?
> another fea application called OOF2
> (http://www.ctcms.nist.gov/oof/oof2/#features) says "OOF2 is completely
> scriptable in Python". and I don't really understand what that means...
> maybe I haven't grasped the full potential of what python scripting
> could do for an fea program.
>
> can you tell me how to decide what path I should take - embed or extend
> ? or maybe some one could point me to some document/webpage that talks
> about this.
>
> thanks a lot,
> Julian.
>
> PS, my fea program uses its own script to read the analysis model
> information using the c++ iostream and our own parsing functions - but
> I don't have to stick to those function when I am writing the new code.

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


Re: auto indent

2006-11-06 Thread John Henry

M.N.Smadi wrote:
> Hi there;
>
> i have a script that is not indented properly. Is there a way that i can
> have it auto indented.
>
> thanks
> moe smadi

It depends what exactly you mean.  I use Textpad and they have an
"indent selected block" feature.

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


Re: shutil: permission denied errors on windows

2006-11-06 Thread John Henry
I use the copy function a lot and never have problem.  I suggest that
you write a no brainer standalone test code and if it still fails
there, then you have a problem with your installation.

Antoine De Groote wrote:
> Google tells quite some things about it, but none of them are satisfactory.
>
> I'm on Windows, and shutil operations (e.g. move, copy) throw [Errno 13]
> Permission denied all the time, for the source files. It seems that this
> is the case for all my files. But what I don't understand is that
> yesterday it still worked. I didn't change anything on my system though
> (at least not that I am aware of). I restarted the computer several
> times to see if that helped, but it didn't. Also I can't find a process
> that would be using the files...
>
> Has anybody experienced this problem before, or have a solution?
>
> Kind regards,
> antoine
>
> Here's the code that throws the errors
>
> [...]
> for l in files:
>  from_file = os.path.join(dir, l)
>  to_file = from_file.replace(tree_top, backup_dir)
>  try:
>  if not os.path.exists(to_file):
>  log('Copying new  %s' % from_file)
>  counter_new += 1
>  shutil.copy2(from_file, to_file)
>  elif int(os.path.getmtime(from_file)) >
> int(os.path.getmtime(to_file)):
>  log('Copying modified %s' % from_file)
>  counter_mod += 1
>  shutil.copy2(from_file, to_file)
>  elif os.path.getsize(from_file) > os.path.getsize(to_file):
>  log('Sizes differ, but not rest: Copying %s' %
> from_file)
>  counter_special += 1
>  shutil.copy2(from_file, to_file)
>  elif os.path.getsize(from_file) < os.path.getsize(to_file):
>  log('Orig file smaller than backup file: Copying
> %s' % from_file)
>  counter_special += 1
>  shutil.copy2(to_file, backup_dir+'DIFF_SIZE')
>  shutil.copy2(from_file, to_file)
>  else:
>  #log('not treated: %s' % l)
>  pass
>
>  except (OSError, IOError), e:
>  not_accessible += 1
>  print e
> [...]

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


Re: wing ide vs. komodo?

2006-11-06 Thread John Henry
"cool" is in the eyes of the beholder.

While I agree that this can be useful in some situations, I find it
very annoying when all I want (and need) to do is a simple dumber
search and yet it tells me tons of useless searches that I don't care
for.

The inability to debug multi-threaded applications is pretty annoying
too.  It's unacceptable that a "professional" level debugger can't
handle multithreaded code.

But then again, I depend on Wing everyday.  I just have to build my
code with lots of "if debugging, don't thread else thread" type of
constructs...

vj wrote:
> Forgot to mention WING's file search and replace is pretty cool and
> powerful. It keeps checking changes in a different thread. If you want
> to change yyy in say 100 files you would:
>
> 1. specify yyy in the search window
> 2. A list of files get displayed with matching yyy
> 3. As you fix replace yyy in the files the list of files with matching
> yyy reduces automatically. This is very cool and very useful.
>
> Another thing I like about WING is that it warns you if you have tabs
> ans spaces mixed in a file.
> 
> The embedded python shell is also a useful feature.
> 
> VJ

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


Re: shutil: permission denied errors on windows

2006-11-07 Thread John Henry
Okay, it's always good that strange things are repeatable and happens
with simple scripts.

Are you saying "a" is a folder?  So, the failure is only with copying
folder?  Not individual file?



Antoine De Groote wrote:
> Yes it's strange, I never had the problem before, either. It seems now
> to be only the case for folders. A very simple
>
> shutil.copy('a', 'b')
>
> already fails with the error message.
>
> I reinstalled Python, but that didn't change anything...
>
> Regards,
> antoine
>
> John Henry wrote:
> > I use the copy function a lot and never have problem.  I suggest that
> > you write a no brainer standalone test code and if it still fails
> > there, then you have a problem with your installation.
> >
> > Antoine De Groote wrote:
> >> Google tells quite some things about it, but none of them are satisfactory.
> >>
> >> I'm on Windows, and shutil operations (e.g. move, copy) throw [Errno 13]
> >> Permission denied all the time, for the source files. It seems that this
> >> is the case for all my files. But what I don't understand is that
> >> yesterday it still worked. I didn't change anything on my system though
> >> (at least not that I am aware of). I restarted the computer several
> >> times to see if that helped, but it didn't. Also I can't find a process
> >> that would be using the files...
> >>
> >> Has anybody experienced this problem before, or have a solution?
> >>
> >> Kind regards,
> >> antoine
> >>
> >> Here's the code that throws the errors
> >>
> >> [...]
> >> for l in files:
> >>  from_file = os.path.join(dir, l)
> >>  to_file = from_file.replace(tree_top, backup_dir)
> >>  try:
> >>  if not os.path.exists(to_file):
> >>  log('Copying new  %s' % from_file)
> >>  counter_new += 1
> >>  shutil.copy2(from_file, to_file)
> >>  elif int(os.path.getmtime(from_file)) >
> >> int(os.path.getmtime(to_file)):
> >>  log('Copying modified %s' % from_file)
> >>  counter_mod += 1
> >>  shutil.copy2(from_file, to_file)
> >>  elif os.path.getsize(from_file) > 
> >> os.path.getsize(to_file):
> >>  log('Sizes differ, but not rest: Copying %s' %
> >> from_file)
> >>  counter_special += 1
> >>  shutil.copy2(from_file, to_file)
> >>  elif os.path.getsize(from_file) < 
> >> os.path.getsize(to_file):
> >>  log('Orig file smaller than backup file: Copying
> >> %s' % from_file)
> >>  counter_special += 1
> >>  shutil.copy2(to_file, backup_dir+'DIFF_SIZE')
> >>  shutil.copy2(from_file, to_file)
> >>  else:
> >>  #log('not treated: %s' % l)
> >>  pass
> >>
> >>  except (OSError, IOError), e:
> >>  not_accessible += 1
> >>  print e
> >> [...]
> >

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


Re: Pyro stability

2006-11-07 Thread John Henry
Being a non-professional programmer, I've managed to use Pyro to do
what I need to do with very minimal fuss.  In fact, I don't even
understand a lot of what's under the cover.  All I did was to mimic
what one of the sample program is doing and adapted it to my need.

So far I am very happy with Pyro.

And no, I don't need to use profanity to describe to you how amazing I
think Pyro is. :=)

writeson wrote:
> Hi all,
>
> At work I'm considering proposing a solution for our distributed
> processing system (a web based shopping cart that feeds an actual
> printing production line) based on Pyro. I've done some minor
> experiments with this and Pyro looks interesting and like a good
> implementation of what I want. I've got a couple of questions though:
>
> 1)  Has anyone had any experience with Pyro, and if so, have you had
> any stability, or memory use issues running Pyro servers or nameservers
> on the various participating computers? (We have a mixed environment of
> Linux and Windows, but will be heading to an all Linux (RedHat)
> environment soon.
>
> 2)  One of the guys I work with is more inclined to set up XMLRPC
> communication between the processes, and he is also leery of running
> daemon processes. His solution is to have essentially Python CGI code
> that responds to the various XMLRPC requests. Does anyone have any
> opinions on this? I know what mine are already. :)
>
> 3)  I've considered using CORBA, which is more powerful, and certainly
> faster, but it's complexity to set up compared to the rather simple
> work I'm trying to do seems prohibative. Does anyone have any thoughts
> on this?
> 
> Thanks in advance,
> Doug

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


Re: How to choose the right GUI toolkit ?

2006-11-08 Thread John Henry

John Salerno wrote:
> Dan Lenski wrote:
>
> > So, is there another toolkit I should be looking at?
>
> I highly recommend wxPython. It's very mature, full-featured, and
> portable, and fairly easy to learn as well. I can't really compare it to
> other toolkits (not having used any of them, except Tkinter), but it's
> definitely one of the most popular and well-supported ones out there.
>
> http://www.wxpython.org/

I highly recommend that you try PythonCard (which sits on top of
wxPython).  You can get productive very very quickly.  Take a look at:

http://pythoncard.sourceforge.net/walkthrough1.html

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


decorators

2006-11-08 Thread John Henry
I must be very thick.  I keep reading about what decorators are and I
still don't have a good feel about it.  See, for example:

http://alex.dojotoolkit.org/?p=564

What exactly do I use decorators for?

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


decorators

2006-11-08 Thread John Henry
I must be very thick.  I keep reading about what decorators are and I
still don't have a good feel about it.  See, for example:

http://alex.dojotoolkit.org/?p=564

and:

http://soiland.no/software/decorator

What exactly do I use decorators for?

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


Re: How to choose the right GUI toolkit ?

2006-11-09 Thread John Henry

Dan Lenski wrote:
>
> John H.: thanks for pointing out pythoncard.  This looks like it might
> be an excellent substitute for LabView-like GUIs, which all my
> coworkers like.  I personally refuse to read or write LabView code, on
> the grounds that its syntax causes severe brain damage and is
> completely unportable.  But that's a flame for another thread, so to
> speak...
>
> Thanks,
> Dan

I assume you meant that the example programs looks LabView-like GUIs?
PythonCard itself has nothing in common with LabView.   It's more like
HyperCard.

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


Re: How to choose the right GUI toolkit ?

2006-11-09 Thread John Henry


Steve Holden wrote:

> >
> You may find that it starts out fine, but becomes less satisfactory as
> the sophistication of your interfaces increases. Then the problem will
> be that migration to another platform demands a substantial rewrite of
> your application (I have done this for a fairly small app).
>

It all depends on what you need.  You can always "drop down" to calling
wxPython.

> I don't think PythonCard gets much maintenance nowadays.
>

Funny you mention that.  I started that discussion on the PythonCard
list only yesterday.

While it's true that the web pages hasn't been updated to follow up
with the developments, I am delighted to learn that there has been
quite a bit of work going on.

Again, it all depends on what your needs are.  If you need to become
productive in a hurry,  and you are not exactly chasing after the
latest widget, my recommendation is to go with PythonCard.


> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb   http://holdenweb.blogspot.com
> Recent Ramblings http://del.icio.us/steve.holden

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


Re: How to choose the right GUI toolkit ?

2006-11-09 Thread John Henry
Bill Maxwell wrote:
> On 8 Nov 2006 11:49:07 -0800, "John Henry" <[EMAIL PROTECTED]>
> wrote:
>
> >
> >John Salerno wrote:
> >> Dan Lenski wrote:
> >>
> >> > So, is there another toolkit I should be looking at?
> >>
> >> I highly recommend wxPython. It's very mature, full-featured, and
> >> portable, and fairly easy to learn as well. I can't really compare it to
> >> other toolkits (not having used any of them, except Tkinter), but it's
> >> definitely one of the most popular and well-supported ones out there.
> >>
> >> http://www.wxpython.org/
> >
> >I highly recommend that you try PythonCard (which sits on top of
> >wxPython).  You can get productive very very quickly.  Take a look at:
> >
> >http://pythoncard.sourceforge.net/walkthrough1.html
>
>
> I took a brief look at PythonCard almost a year ago and got discouraged
> by what I found, so I stopped looking at it.  I've inserted my notes
> from back then, below.  Does anybody know if these things have been
> fixed in the latest release?
>
> Bill
>
>
> =
> My notes from Fri Dec-23-2005:
>
> This is a list of gripes I have while trying to learn about PythonCard.
> I'm trying to investigate various GUI builders for Python, and
> PythonCard looks promising, but a lot of things are getting in the way.
>
> I installed yesterday, using this installer:
> PythonCard-0.8.1.FIXED.win32.exe
>
> A)  The very first example in the tutorial is wrong!
>
>   On this page:  http://pythoncard.sourceforge.net/documentation.html
>   When you follow this link to try something for the very first time:
>
>   Getting Started in PythonCard by Dan Shafer:
>   http://pythoncard.sourceforge.net/walkthrough1.html
>
>   You quickly see that the minimal.py example doesn't even contain
> this line, even though the tutorial refers to it:
>

I am not sure which one you are referring to but in the
PythonCard\samples\minimal, you will find a minimal.py that says:

#!/usr/bin/python

"""
__version__ = "$Revision: 1.8 $"
__date__ = "$Date: 2005/12/17 15:20:02 $"
"""

from PythonCard import model


class Minimal(model.Background):
def on_menuFileAbout_select(self, event):
pass

if __name__ == '__main__':
app = model.Application(Minimal)
app.MainLoop()



>   def on_menuFileAbout_select(self, event):
>
>   And, of course, if you replace the word "pass" with this, as
> instructed:
>
>   result = dialog.alertDialog(self, 'It works!', 'Showing Off')
>
>   it won't run, because the existing "pass" line isn't inside a def
> inside of a class.
>

No, it didn't work because the author forgot to mention that you have
to do a:

from PythonCard import model, dialog

instead of just:

from PythonCard import model

I just tried it and it works.

>
> B)  Is the Notebook widget really supported?
>
>   In the installed file "changelog.txt" (gets installed as part of
> PythonCard installation), it says:
>
>   "added Notebook component, PageBackground, and testNotebook
>   sample"
>
>   But, the testNotebook sample is nowhere to be found.
>

I haven't come across a need to use Notebook and so I can not say for
sure.  Looking at notebook.py, it appears to be just a simple wrapper
on top of the wxWindow notebook.  I would encourage you to post a
message to the mailing list and ask there.


>   I looked lots of places, including the main SourceForge web site,
> and on the wiki, here:
>
>   http://wiki.wxpython.org/index.cgi/PythonCard
>
>   Both the main website and the wiki seem way out of date, and the
> latest dates I could find on both of them are sometime in 2004.
>

Yes, sometime around 2004, the website updating stopped.   Fortunately,
development didn't.  There are quite a number of new things since then:
new resource editor (now call layout Editor, standalone exe creator,
and so forth).  I even learn that a new sizer handler is in the work.

Not saying that there are 10 programmers working 7/24 on it.  It *is*
an Open Source project nevertheless.   Nobody gets paid for doing it.
 But there are development work going on.


>   Finally, by following the mailing list archive link on the main
> website, I managed to find a reference to the notebook component on the
> ASPN site, where some guy named Brian wonders about the same thing as
> me, concerning the availability of

Re: How to choose the right GUI toolkit ?

2006-11-09 Thread John Henry
Upon closer look, the walkthrough did say:

***
from PythonCard import model

Change that so it says:

from PythonCard import dialog, model

Save the code.
***

So, it works.



John Henry wrote:
> Bill Maxwell wrote:
> > On 8 Nov 2006 11:49:07 -0800, "John Henry" <[EMAIL PROTECTED]>
> > wrote:
> >
> > >
> > >John Salerno wrote:
> > >> Dan Lenski wrote:
> > >>
> > >> > So, is there another toolkit I should be looking at?
> > >>
> > >> I highly recommend wxPython. It's very mature, full-featured, and
> > >> portable, and fairly easy to learn as well. I can't really compare it to
> > >> other toolkits (not having used any of them, except Tkinter), but it's
> > >> definitely one of the most popular and well-supported ones out there.
> > >>
> > >> http://www.wxpython.org/
> > >
> > >I highly recommend that you try PythonCard (which sits on top of
> > >wxPython).  You can get productive very very quickly.  Take a look at:
> > >
> > >http://pythoncard.sourceforge.net/walkthrough1.html
> >
> >
> > I took a brief look at PythonCard almost a year ago and got discouraged
> > by what I found, so I stopped looking at it.  I've inserted my notes
> > from back then, below.  Does anybody know if these things have been
> > fixed in the latest release?
> >
> > Bill
> >
> >
> > =
> > My notes from Fri Dec-23-2005:
> >
> > This is a list of gripes I have while trying to learn about PythonCard.
> > I'm trying to investigate various GUI builders for Python, and
> > PythonCard looks promising, but a lot of things are getting in the way.
> >
> > I installed yesterday, using this installer:
> > PythonCard-0.8.1.FIXED.win32.exe
> >
> > A)  The very first example in the tutorial is wrong!
> >
> > On this page:  http://pythoncard.sourceforge.net/documentation.html
> > When you follow this link to try something for the very first time:
> >
> > Getting Started in PythonCard by Dan Shafer:
> > http://pythoncard.sourceforge.net/walkthrough1.html
> >
> > You quickly see that the minimal.py example doesn't even contain
> > this line, even though the tutorial refers to it:
> >
>
> I am not sure which one you are referring to but in the
> PythonCard\samples\minimal, you will find a minimal.py that says:
>
> #!/usr/bin/python
>
> """
> __version__ = "$Revision: 1.8 $"
> __date__ = "$Date: 2005/12/17 15:20:02 $"
> """
>
> from PythonCard import model
>
>
> class Minimal(model.Background):
> def on_menuFileAbout_select(self, event):
> pass
>
> if __name__ == '__main__':
> app = model.Application(Minimal)
> app.MainLoop()
>
>
>
> > def on_menuFileAbout_select(self, event):
> >
> > And, of course, if you replace the word "pass" with this, as
> > instructed:
> >
> > result = dialog.alertDialog(self, 'It works!', 'Showing Off')
> >
> > it won't run, because the existing "pass" line isn't inside a def
> > inside of a class.
> >
>
> No, it didn't work because the author forgot to mention that you have
> to do a:
>
> from PythonCard import model, dialog
>
> instead of just:
>
> from PythonCard import model
>
> I just tried it and it works.
>
> >
> > B)  Is the Notebook widget really supported?
> >
> > In the installed file "changelog.txt" (gets installed as part of
> > PythonCard installation), it says:
> >
> > "added Notebook component, PageBackground, and testNotebook
> > sample"
> >
> > But, the testNotebook sample is nowhere to be found.
> >
>
> I haven't come across a need to use Notebook and so I can not say for
> sure.  Looking at notebook.py, it appears to be just a simple wrapper
> on top of the wxWindow notebook.  I would encourage you to post a
> message to the mailing list and ask there.
>
>
> > I looked lots of places, including the main SourceForge web site,
> > and on the wiki, here:
> >
> > http://wiki.wxpython.org/index.cgi/PythonCard
> >
> > Both the main website and the wiki seem way out of date, and th

Re: how is python not the same as java?

2006-11-09 Thread John Henry

gavino wrote:
> both are interpreted oo langauges..


I remember the days when I got all excited about Java (many many moons
ago when Java first came out).  I brought a whole truckload of books on
it, even spent 5 days attending a seminar on the subject.   To my great
disappointment, I never got very far with it.   Not being a
"professional programmer" by training, I found it very difficult to go
very far with Java.   Everything was so "un-natural" for me.  So, I
felt back to my little C-corner.

Last year, I got a chance to attend a 5 day class on Python.   Hated it
- for the first 5 minutes (what the , they are using white space
for what)  but from that pont on, never look back.

Not considering myself an advance Python programmer.   Don't matter, I
am very proficient with it.   It allows me to get things done - in a
whole lot less time then I have to do otherwise.

Learning new things about it everyday, finding new and usefull open
source packages for it everyday.

My Java books?  They hit the trash dump long ago

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


Re: How to choose the right GUI toolkit ?

2006-11-11 Thread John Henry
BTW: I did a search and found the testnotebook example from:

http://prdownloads.sourceforge.net/pythoncard/testNotebook.zip?download

and tried it out.  There is one error in the widget.py that I have to
get around.  Changed from:

canvas.setFillColor('gray')

to:

try:
canvas.setFillColor('gray')
except:
pass

and then ran it.   Works!

So, yes, you can do Notebook in Python.  I believe what they are saying
is that Notebook isn't supported fully (yet) in the resourceeditor.


Bill Maxwell wrote:
> On 9 Nov 2006 22:48:10 -0800, "John Henry" <[EMAIL PROTECTED]>
> wrote:
>
> >Upon closer look, the walkthrough did say:
> >
> >***
> >from PythonCard import model
> >
> >Change that so it says:
> >
> >from PythonCard import dialog, model
> >
> >Save the code.
> >***
> >
> >So, it works.
>
>
> Thanks for looking into it.  It sounds like either it has been fixed in
> the newer version -- or I didn't do something correctly.  It's been a
> long time, and I was just going by the notes I made back then.
>
>
>
>
>
>
>
>
>
> >
> >
> >
> >John Henry wrote:
> >> Bill Maxwell wrote:
> >> > On 8 Nov 2006 11:49:07 -0800, "John Henry" <[EMAIL PROTECTED]>
> >> > wrote:
> >> >
> >> > >
> >> > >John Salerno wrote:
> >> > >> Dan Lenski wrote:
> >> > >>
> >> > >> > So, is there another toolkit I should be looking at?
> >> > >>
> >> > >> I highly recommend wxPython. It's very mature, full-featured, and
> >> > >> portable, and fairly easy to learn as well. I can't really compare it 
> >> > >> to
> >> > >> other toolkits (not having used any of them, except Tkinter), but it's
> >> > >> definitely one of the most popular and well-supported ones out there.
> >> > >>
> >> > >> http://www.wxpython.org/
> >> > >
> >> > >I highly recommend that you try PythonCard (which sits on top of
> >> > >wxPython).  You can get productive very very quickly.  Take a look at:
> >> > >
> >> > >http://pythoncard.sourceforge.net/walkthrough1.html
> >> >
> >> >
> >> > I took a brief look at PythonCard almost a year ago and got discouraged
> >> > by what I found, so I stopped looking at it.  I've inserted my notes
> >> > from back then, below.  Does anybody know if these things have been
> >> > fixed in the latest release?
> >> >
> >> > Bill
> >> >
> >> >
> >> > =
> >> > My notes from Fri Dec-23-2005:
> >> >
> >> > This is a list of gripes I have while trying to learn about PythonCard.
> >> > I'm trying to investigate various GUI builders for Python, and
> >> > PythonCard looks promising, but a lot of things are getting in the way.
> >> >
> >> > I installed yesterday, using this installer:
> >> > PythonCard-0.8.1.FIXED.win32.exe
> >> >
> >> > A)  The very first example in the tutorial is wrong!
> >> >
> >> >  On this page:  http://pythoncard.sourceforge.net/documentation.html
> >> >  When you follow this link to try something for the very first time:
> >> >
> >> >  Getting Started in PythonCard by Dan Shafer:
> >> >  http://pythoncard.sourceforge.net/walkthrough1.html
> >> >
> >> >  You quickly see that the minimal.py example doesn't even contain
> >> > this line, even though the tutorial refers to it:
> >> >
> >>
> >> I am not sure which one you are referring to but in the
> >> PythonCard\samples\minimal, you will find a minimal.py that says:
> >>
> >> #!/usr/bin/python
> >>
> >> """
> >> __version__ = "$Revision: 1.8 $"
> >> __date__ = "$Date: 2005/12/17 15:20:02 $"
> >> """
> >>
> >> from PythonCard import model
> >>
> >>
> >> class Minimal(model.Background):
> >> def on_menuFileAbout_select(self, event):
> >> pass
> >>
> >> if __name__ == '__main__':
> >> app = m

Re: How to choose the right GUI toolkit ?

2006-11-12 Thread John Henry
Nice example.


Jussi Salmela wrote:
> John Henry wrote:
> > BTW: I did a search and found the testnotebook example from:
> >
> > http://prdownloads.sourceforge.net/pythoncard/testNotebook.zip?download
> >
> > and tried it out.  There is one error in the widget.py that I have to
> > get around.  Changed from:
> >
> > canvas.setFillColor('gray')
> >
> > to:
> >
> > try:
> > canvas.setFillColor('gray')
> > except:
> > pass
> >
> > and then ran it.   Works!
> >
> > So, yes, you can do Notebook in Python.  I believe what they are saying
> > is that Notebook isn't supported fully (yet) in the resourceeditor.
>
> It's true that the notebook and grid components of wxPython are not
> completely integrated into PythonCard but they can still be used quite
> easily once you figure out how.
>
> The process of figuring out can be made easier by a working example. The
> real life application Blood Pressure Monitor
>
> http://personal.inet.fi/cool/operator/BPMDownload.html
>
> can be used as an example of using the notebook, grid and htmlwin
> widgets in PythonCard.
>
> I use this application to input the pressure values I've registered with
> my own meter and to produce a PDF page with PyChart to hand to my doctor
> to inspect when I visit him twice a year.
>
> Cheers,
> Jussi
> 
> --
> Jussi Salmela
> http://personal.inet.fi/cool/operator/

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


Re: Yield

2006-11-15 Thread John Henry
Thank you.  This is very clear.  I can see that this is useful in lots
of situations.

Fredrik Lundh wrote:
> Mateuszk87 wrote:
>
> > may someone explain "yield" function, please. how does it actually work
> > and when do you use it?
>
> it returns a value from a function without actually terminating the
> function; when the function is resumed, it'll continue to execute after
> the yield.
>
> a function that contains a yield statement is called a "generator", and
> is most often used in a for-in loop, or in other contexts that expect a
> sequence.  the loop is automatically terminated when the function
> returns in a usual way:
>
>  >>> def gen():
> ... yield 1
> ... yield 2
> ... yield 3
> ...
>  >>> for item in gen():
> ... print item
> ...
> 1
> 2
> 3
>  >>> sum(gen())
> 6
>  >>> [str(i) for i in gen()]
> ['1', '2', '3']
>
> you can also use the generator "by hand"; when you call a generator
> function, it returns a special "generator object", and then immediately
> suspends itself.  to run the generator, call its "next" method:
>
>  >>> g = gen()
>  >>> g
> 
>  >>> g.next()
> 1
>  >>> g.next()
> 2
>  >>> g.next()
> 3
>
> when the generator is exhausted, it raises a StopIterator exception:
>
>  >>> g.next()
> Traceback (most recent call last):
>File "", line 1, in 
> StopIteration
>
> reference information:
>
>  http://effbot.org/pyref/yield.htm
> 
> hope this helps!
> 
> 

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


Re: About alternatives to Matlab

2006-11-16 Thread John Henry
Bill Gates will have you jailed! :-)

On a more serious note, is there any alternative to Simulink though?

sturlamolden wrote:
>and is infinitely
> more expensive.
>
> Does anyone wonder why I am not paying for Matlab maintenance anymore?
>
> Sorry Mathworks, I have used your product for years, but you cannot
> compete with NumPy.
> 
> 
> Cheers,
> Sturla Molden

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


How fuzzy is get_close_matches() in difflib?

2006-11-16 Thread John Henry
I am just wondering what's with get_close_matches() in difflib.  What's
the magic?   How fuzzy do I need to get in order to get a match?

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


Re: How fuzzy is get_close_matches() in difflib?

2006-11-16 Thread John Henry
I did try them and I am impressed.  It helped me found a lot of useful
info.   I just want to get a feel as to what constitutes a "match".


Steven D'Aprano wrote:
> On Thu, 16 Nov 2006 16:40:49 -0800, John Henry wrote:
>
> > I am just wondering what's with get_close_matches() in difflib.  What's
> > the magic?   How fuzzy do I need to get in order to get a match?
>
>
> Why don't you try it and see?
>
> >>> from difflib import get_close_matches
> >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
> ['apple', 'ape']
> >>> import keyword as _keyword
> >>> get_close_matches("wheel", _keyword.kwlist)
> ['while']
> >>> get_close_matches("apple", _keyword.kwlist)
> []
> >>> get_close_matches("accept", _keyword.kwlist)
> ['except']
>
>
> Those example, by the way, come from here:
> 
> >>> help(get_close_matches)
> 
> 
> 
> 
> -- 
> Steven

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


Re: How fuzzy is get_close_matches() in difflib?

2006-11-16 Thread John Henry
I encountered a case where I am trying to match "HIDESST1" and
"HIDESCT1" against ["HIDEDST1", "HIDEDCT1", "HIDEDCT2", "HIDEDCT3"]

Well, they both hit "HIDEDST1" as the first match which is not exactly
the result I was looking for.  I don't understand why "HIDESCT1" would
not hit "HIDEDCT1" as a first choice.

Steven D'Aprano wrote:
> On Thu, 16 Nov 2006 20:19:50 -0800, John Henry wrote:
>
> > I did try them and I am impressed.  It helped me found a lot of useful
> > info.   I just want to get a feel as to what constitutes a "match".
>
> The source code has lots of comments, but they don't explain the basic
> algorithm (at least not in the difflib.py supplied with Python 2.3).
>
> There is no single diff algorithm, but I believe that the basic idea is to
> look for insertions and/or deletions of strings. If you want more
> detail, google "diff". Once you have a list of differences, the closest
> match is the search string with the fewest differences.
>
> As for getting a feel of what constitutes a match, I really can't make any
> better suggestion than just try lots of examples with the interactive
> Python shell.
> 
> 
> 
> -- 
> Steven D'Aprano

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


Concatenating strings

2006-06-30 Thread John Henry
Sorry if this is a dumb question.

I have a list of strings (some 10,000+) and I need to concatenate them
together into one very long string.  The obvious method would be, for
example:

alist=["ab","cd","ef",.,"zzz"]
blist = ""
for x in alist:
   blist += x

But is there a cleaner and faster way of doing this?

Thanks,

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


Concatenating strings

2006-06-30 Thread John Henry
Sorry if this is a dumb question.

I have a list of strings (some 10,000+) and I need to concatenate them
together into one very long string.  The obvious method would be, for
example:

alist=["ab","cd","ef",.,"zzz"]
blist = ""
for x in alist:
   blist += x

But is there a cleaner and faster way of doing this?

Thanks,

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


Re: Building Python Based Web Application

2006-09-08 Thread John Henry
Hi folks.

I am interested on this topic as well.

If my application is not database related, what would be a good choice?

I have clients that wish to use my Python applications but I am not
willing to give them the code.  So, I am thinking about setting it up
as a web based application and let them run it from their browser.   If
things go well, may be I can charge them for usage later.

The application will involve getting a data file from the user, do some
processing, and return a result file to the user.   Very modest - to
start.

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


Re: Building Python Based Web Application

2006-09-09 Thread John Henry

Adam Jones wrote:
> John Henry wrote:
> > Hi folks.
> >
> > I am interested on this topic as well.
> >
> > If my application is not database related, what would be a good choice?
> >
> > I have clients that wish to use my Python applications but I am not
> > willing to give them the code.  So, I am thinking about setting it up
> > as a web based application and let them run it from their browser.   If
> > things go well, may be I can charge them for usage later.
> >
> > The application will involve getting a data file from the user, do some
> > processing, and return a result file to the user.   Very modest - to
> > start.
>
> For that kind of usage I don't know if any of the big name web
> frameworks would be worth the effort, especially if returning a result
> file entails making it available for download instead of handing it
> back in the form of an HTML page. At that point all you would really
> need is a controller to handle most of the details of working in HTTP
> and maybe a templating system to help out with the HTML.
>
> The only controller that is available independently that I can comment
> on usefully is Cherrypy. It works pretty well, can run its own web
> server if you like, and seems like it would be simple enough to use for
> what you are talking about.
>
> Without knowing more about your requirements that would be my
> suggestion. I am sure there are other people on this group with more
> experience here who could give more useful commentary.
> 
> -Adam

Thanks, I am checking out CherryPie

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


Re: Help me use my Dual Core CPU!

2006-09-12 Thread John Henry
I don't know what CPython is but I have developed a Python application
under Windows that utilize the Dure Core CPU when it's present.

I don't know that I can say for sure that "threads won't help".  Have
you done some testing before using other approaches to see if it indeed
won't help?


Simon Wittber wrote:
> I've just bought a new notebook, which has a dual core CPU.
>
> I write cross platform games in Python, and I'd really like to be able
> to use this second core (on my machine, and on user's machines) for any
> new games I might write.
>
> I know threads won't help (in CPython at least) so I'm investigating
> other types of concurrency which I might be able to use. I really like
> the PyLinda approach, however I need to be able to pass around all the
> simple python types, which PyLinda won't help me with. Also, PyLinda is
> more focused on distributing computing; I really only want to have 2
> processes cooperating (or 4, if I had 4 CPUs/cores etc).
>
> Is there any cross platform way to share python objects across
> processes? (I've found POSH, but it's old, and doesn't appear to be
> maintained). I could implement my own object space using shared memory,
> but from what I can see, this is not available on Win32.
>
> Are there any other concurrency options I've not discovered yet?
> 
> 
> -Sw.

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


When is it a pointer (aka reference) - when is it a copy?

2006-09-13 Thread John Henry
Hi list,

Just to make sure I understand this.

Since there is no "pointer" type in Python, I like to know how I do
that.

For instance, if I do:

   ...some_huge_list is a huge list...
   some_huge_list[0]=1
   aref = some_huge_list
   aref[0]=0
   print some_huge_list[0]

we know that the answere will be 0.  In this case, aref is really a
reference.

But what if the right hand side is a simple variable (say an int)?  Can
I "reference" it somehow?  Should I assume that:

   aref = _any_type_other_than_simple_one

be a reference, and not a copy?

Thanks,

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


Re: When is it a pointer (aka reference) - when is it a copy?

2006-09-13 Thread John Henry
Thanks for the reply, both to Laszlo and Steve.

Okay, I understand what you're saying.

But what if I need to make a "pointer" to a simple variable.

For instance, in C:

   int i=1
   int *j=&i

   *j = 2
   print i

and you get 2 printed.

In Python,

   i=1
   j=i
   j=2
   print i

and you get 1 printed.

So, if I understand you correctly, I must make the reference to a more
elaborate representation.  Like:

   i=[1,]
   j=i
   j[0]=2
   print i

in order to get 2 printed.

Correct?


Steve Holden wrote:
> John Henry wrote:
> > Hi list,
> >
> > Just to make sure I understand this.
> >
> > Since there is no "pointer" type in Python, I like to know how I do
> > that.
> >
> > For instance, if I do:
> >
> >...some_huge_list is a huge list...
> >some_huge_list[0]=1
> >aref = some_huge_list
> >aref[0]=0
> >print some_huge_list[0]
> >
> > we know that the answere will be 0.  In this case, aref is really a
> > reference.
> >
> > But what if the right hand side is a simple variable (say an int)?  Can
> > I "reference" it somehow?  Should I assume that:
> >
> >aref = _any_type_other_than_simple_one
> >
> > be a reference, and not a copy?
> >
> Yes. Attributes are always object references. The assignment is actually
> the binding of a specific object to a name in some namespace, (r to an
> element of a sequence or other container object.
>
> This applies *whatever* the type of the RHS experession: the expression
> is evaluated to yield an object, and a reference to the object is stored
> in the name or container element.
>
> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb   http://holdenweb.blogspot.com
> Recent Ramblings http://del.icio.us/steve.holden

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


Re: When is it a pointer (aka reference) - when is it a copy?

2006-09-13 Thread John Henry
Thanks for the reply, Grant.

I am not doing things like that - I am just trying to clear up in my
mind the Python concepts.

I understand it now.



Grant Edwards wrote:
> On 2006-09-13, John Henry <[EMAIL PROTECTED]> wrote:
> > Thanks for the reply, both to Laszlo and Steve.
> >
> > Okay, I understand what you're saying.
> >
> > But what if I need to make a "pointer" to a simple variable.
>
> There's no such thing as a "simple variable".  There are
> mutable objects and immutable objects.  Names are bound to
> objects.
>
>   x = 3
>
> The name "x" is bound to an immutable integer object who's
> value is 3.
>
> > For instance, in C:
> >
> >int i=1
> >int *j=&i
> >
> >*j = 2
> >print i
> >
> > and you get 2 printed.
> >
> > In Python,
> >
> >i=1
>
> The name "i" is bound to an immutable integer object who's value is 1.
>
> >j=i
>
> The name "j" is bound to an immutable integer object who's
> value is 1. That may or may not be the same object to which
> "i" is bound.
>
> >j=2
>
> Now the name "j" is bound to an immutable integer object who's
> value is 2.  Rebinding the name "j" to a different object has
> no effect on the object to which "i" is bound.
>
> >print i
> >
> > and you get 1 printed.
>
> Because you've changed neither the object to which "i" is bound
> nor the value of that object (you can't change the values of
> integer objects).
>
> > So, if I understand you correctly, I must make the reference
> > to a more elaborate representation.  Like:
> >
> >i=[1,]
> >j=i
> >j[0]=2
> >print i
> >
> > in order to get 2 printed.
> >
> > Correct?
>
> I suppose, for some values of "correct".  You've bound the
> names "i" and "j" to the same mutable object, then mutated that
> object.  Afterwards "i" and "i" still refer to that mutated
> object.
>
> That'll work as a rather clumsy imitation of the C code, but I
> don't really see what it is you're trying to accomplish. Trying
> to write C code using Python isn't going to be fun or productive[1].
>
> When using Python, you should write Python code. ;)
>
> If you'll explain the actual problem you're trying solve for
> which you think you need C-style "pointers", then somebody will
> be happy to show you how that problem is solved using Python.
>
> [1] There are people here who probably think it fun, but only
> as a brain-teaser.
>
> --
> Grant Edwards   grante Yow!  After THIS, let's go
>   at   to PHILADELPHIA and have
>visi.comTRIPLETS!!

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


Re: windev vs python SOS

2006-09-27 Thread John Henry
I don't know what windev is but presonally, I found Python to be
incredibly productive.

BTW: I recommend that you look into PythonCard.  It sits on top of
wxpython and I found it to be a very productive GUI tool.

stéphane bard wrote:
> hello, my boss ask me to prefer windev to python.
> I have to argue
>
>   - python work on multiple platform (linux, mac, windows)
>   A good point but it didn't interest him. Because
>   we want to choose a language for prototyping.
>   So multi platform is not enough.
>
>   - python and windev are fast to develop
>
>   - windev as a good IDE, python? boa-constructor is ok with wxpython
>
>   - python is open source (that's not an argument for my boss, sorry
> it's  a boss ...)
> 
> any idea for a strong argument ?

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


Re: windev vs python SOS

2006-09-29 Thread John Henry
Why are they all look so gloomy?  I don't see a single smile on their
faces.

:=)


[EMAIL PROTECTED] wrote:
> Hi,
>
> Bruno Desthuilliers a écrit :
> > I've never met a programmer that "loved" Windev.
>
> I have met some here (I'm the guy with a mustache-just kidding but
> actually I was there).
>
> http://www.pcsoft.fr/pcsoft/tdftech/2006/images/Paris/07-IMG_5853.jpg
>
> WinDev is widely used in France and that's a thing because a lot of
> french programmers think that english tools "have to be better".
> 
> --
> Pat

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


Re: How fuzzy is get_close_matches() in difflib?

2006-11-17 Thread John Henry
I suppose you are right.  I guess I ended up with an odd case.

I was thinking that:

To change "HIDE*S*ST1" to "HIDE*D*ST1", all you do is remove the "*S*"
from the source and the "*D*" from the target.

In order to change "HIDE*SC*T1" to "HIDE*DS*T1", I thought you have to
remove 2 characters *SC* from the source.   Then I realize that it's
not true.  If you remove the "C" from the source, and the "D" from the
*DS* of the destination, it's a match (!)

So, yes, they have the same distance!


Antoon Pardon wrote:
> On 2006-11-17, John Henry <[EMAIL PROTECTED]> wrote:
> > I encountered a case where I am trying to match "HIDESST1" and
> > "HIDESCT1" against ["HIDEDST1", "HIDEDCT1", "HIDEDCT2", "HIDEDCT3"]
> >
> > Well, they both hit "HIDEDST1" as the first match which is not exactly
> > the result I was looking for.  I don't understand why "HIDESCT1" would
> > not hit "HIDEDCT1" as a first choice.
>
> H I D E D S T 1 H I D E D C T 1
>
>  H  .   .
>  I.   .
>  D  .   .
>  E.   .
>  S.
>  C.
>  T  .   .
>  1.   .
>
> As far as I can see the distance of HIDEDCT1 to HIDESCT1 is
> the same as the distance of HIDEDCT1 to HIDEDST1. In both
> cases you have to remove one character from the target as well
> as one character from the candidate in order to get the
> same substring.
> 
> -- 
> Antoon Pardon

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


  1   2   3   >