Re: do "some action" once a minute

2006-05-09 Thread Sybren Stuvel
Petr Jakes enlightened us with:
> I would like to do "some action" once a minute. My code (below)
> works, I just wonder if there is some more pythonic approach or some
> "trick" how to do it differently.

I'd use the Threading module, and the Timer object from that module to
be more precise. There you can simply say "call this function in 60
seconds" or something similar. Then your program just sleeps until
it's time to call the function.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Memory leak in Python

2006-05-09 Thread Sybren Stuvel
[EMAIL PROTECTED] enlightened us with:
> I have a python code which is running on a huge data set. After
> starting the program the computer becomes unstable and gets very
> diffucult to even open konsole to kill that process. What I am
> assuming is that I am running out of memory.

Before acting on your assumptions, you need to verify them. Run 'top'
and hit 'M' to sort by memory usage. After that, use 'ulimit' to limit
the allowed memory usage, run your program again, and see if it stops
at some point due to memory problems.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-line lambda proposal.

2006-05-09 Thread Sybren Stuvel
Kaz Kylheku enlightened us with:
> I've been reading the recent cross-posted flamewar, and read Guido's
> article where he posits that embedding multi-line lambdas in
> expressions is an unsolvable puzzle.
> [...]
>   a = lambda(x, y), lambda(s, t), lambda(u, w): u + w
> statement1
> statement2
>   lambda:
> statement3
> statement4

I think it's a very ugly solution. If you need multiple lines in your
lambda, use an inner function. If you need a couple of single-line
lambdas and use them in a multi-line expression, assign them to a name
and use that name in their stead.

>   a = lambda(x, y):
> return x + y

And what's the advantage of that above this?

def a(x, y):
return x + y

> More examples: lambda defined in a function call argument
>
>   a = foo(lambda (x, y)):
> return x + y
>
> Confusing? Not if you read it properly. "A lambda function is
> constructed with arguments x, y and passed to foo, and the result is
> assigned to a. Oh, and by the way, the body of the
> lambda is: return x + y."

I think it's very, very ugly. Use inner functions for that. They are a
much cleaner solution than this.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


PythonWin's Check (any other Lint tool) ?

2006-05-09 Thread Davy
Hi all,

I am using PythonWin from ActivePython. And I use the GUI button
'Check' to check the .py file.

But the Check did not give out a check list. It just show "Check
failed" or "Check successful".

Is the Check list saved in other where or is there any other Lint tool?

Any suggestions will be appreciated!
Best regards,
Davy

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


Re: Import data from Excel

2006-05-09 Thread Dale Strickland-Clark
Try this:

from win32com.client import GetObject, constants

def GetExcelData(self, strFilePath):
""" Extract the data from the Excel sheet. 
Returns tuple of tuples representing the rows and cells."""
# The following line extracts 
# all the data from sheet 1 of the spreadsheet
return GetObject(strFilePath).Sheets(1).UsedRange.Value


N/A wrote:

> Hi,
> Is it possible to import data from Excel for doing numerical analysis in
> Python? If so how? Thank u!

-- 
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk

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


Why 3.0/5.0 = 0.59999...

2006-05-09 Thread Davy
Hi all,

I used to be a Matlab user. And want to use Python to replace some
Matlab work.

When I type 3.0/5.0, the result is 0.5...

Is there some precision loss? And how to overcome it?

Any suggestions will be appreciated!
Best regards,
Davy

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


Re: how to construct a binary-tree using python?

2006-05-09 Thread Antoon Pardon
Op 2006-05-06, hankssong schreef <[EMAIL PROTECTED]>:
> Hi everyone, I'm wondering whether it's possible to construct a
> binary-tree using python.
> Since python don't have pointer, it can't dynamically allocate memory
> like C language.
> But some important data structures like linked list, binary-tree and
> hash table are closely linked with dynamic memory technology.
>
> Any help that can be provided would be greatly appreciated.

You may have a look here:

http://www.pardon-sleeuwaegen.be/antoon/avltree.html

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


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread michele . simionato
Ken Tilton wrote:
> Python has a weak lambda, statements do not always
> return values, it does not have macros, and I do not know if it has
> special variables.

I am pretty much ignorant of Common Lisp, but I have the impression
they are the
same as Scheme parameters, i.e. thread-local dynamically scoped
variables
(feel free to correct me if I am mistaken). If I am right, here is how
you would emulate them in recent versions of Python:

import threading, time

special = threading.local()
special.x = 0

def getx():
return special.x

def set_x(value):
special.x = value
time.sleep(3-value) # thread-2 completes after thread-1
print "%s is setting x to %s" % (threading.currentThread(), getx())

if __name__ == '__main__':
print getx() # => 0
threading.Thread(None, lambda : set_x(1)).start() # => 1
threading.Thread(None, lambda : set_x(2)).start() # => 2
time.sleep(3)
print getx() # => 0

   Michele Simionato

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


Re: Enumerating Regular Expressions

2006-05-09 Thread Dale Strickland-Clark
Any regular expression that has an asterisk in it has an infinite number of
possible matches.

If it has two asterisks, that's an infinite number squared and that's a
really big number.

You wouldn't want to print them out.


[EMAIL PROTECTED] wrote:

> Hi all,
> 
> Does anybody know of a module that allows you to enumerate all the
> strings a particular regular expression describes?
> 
> Cheers,
> -Blair

-- 
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk

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


Re: Import data from Excel

2006-05-09 Thread Mirco Wahab
Hi,

> Is it possible to import data from Excel for 
> doing numerical analysis in Python? If so how? 

use John Machins glamouros 'xlrd'
http://www.lexicon.net/sjmachin/xlrd.htm

form his documentation:

  import xlrd
book = xlrd.open_workbook("myfile.xls")
print "The number of worksheets is", book.nsheets
print "Worksheet name(s):", book.sheet_names()
sh = book.sheet_by_index(0)
print sh.name, sh.nrows, sh.ncols
print "Cell D30 is", sh.cell_value(rowx=29, colx=3)
for rx in range(sh.nrows):
print sh.row(rx)

This module is (imho) quite useful. No
need for installed Windows or Office.

Regards

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


Re: Why 3.0/5.0 = 0.59999...

2006-05-09 Thread Dale Strickland-Clark
Have you looked at the decimal module?

python
Python 2.4 (#1, Mar 22 2005, 21:42:42)
[GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from decimal import *
>>> Decimal("3")/Decimal("5")
Decimal("0.6")
>>>

I don't suppose it is quick but it might do what you want.

Davy wrote:

> Hi all,
> 
> I used to be a Matlab user. And want to use Python to replace some
> Matlab work.
> 
> When I type 3.0/5.0, the result is 0.5...
> 
> Is there some precision loss? And how to overcome it?
> 
> Any suggestions will be appreciated!
> Best regards,
> Davy

-- 
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk

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


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Michele Simionato
Alex Martelli wrote:
 yes, if that was my only
> choice, I'd much rather use small, simple Scheme than huge, complicated,
> rich, powerful Common Lisp.  ((But in this case I'm biased by early
> experiences, since when I learned and used Lisp-ish languages there WAS
> no Common Lisp, while Scheme was already there, although not quite the
> same language level as today, I'm sure;-)).

Alas, today Scheme is not minimal at all. I mean, the document
describing the standard is short, but real implementations are pretty
rich.
I am also surprised by your claim in this thread that Scheme macros are
simpler than
Common Lisp macros;  perhaps, you are not familiar with syntax-case.
BTW, there is still research going on on macros, for instance look at
http://srfi.schemers.org/srfi-72/srfi-72.html which is pretty nice.
Just to bring some info in yet another useless usenet flamewar.

Michele Simionato

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


Re: Python's regular expression?

2006-05-09 Thread Mirco Wahab
Hi Duncan

> Nick Craig-Wood wrote:
>> Which translates to
>>   match = re.search('(blue|white|red)', t)
>>   if match:
>>   else:
>>  if match:
>>  else:
>> if match:
> 
> This of course gives priority to colours and only looks for garments or 
> footwear if the it hasn't matched on a prior pattern. If you actually 
> wanted to match the first occurrence of any of these (or if the condition 
> was re.match instead of re.search) then named groups can be a nice way of 
> simplifying the code:

A good point. And a good example when to use named
capture group references. This is easily extended
for 'spitting out' all other occuring categories
(see below).

> PATTERN = '''
> (?Pblue|white|red)
> ...

This is one nice thing in Pythons Regex Syntax,
you have to emulate the ?P-thing in other
Regex-Systems more or less 'awk'-wardly ;-)

> For something this simple the titles and group names could be the 
> same, but I'm assuming real code might need a bit more.
Non no, this is quite good because it involves
some math-generated table-code lookup.

I managed somehow to extend your example in order
to spit out all matches and their corresponding
category:

  import re

  PATTERN = '''
  (?Pblue |white |red)
  |   (?Psocks|tights)
  |   (?Pboot |shoe  |trainer)
  '''

  PATTERN = re.compile(PATTERN , re.VERBOSE)
  TITLES = { 'c': 'Colour', 'g': 'Garment', 'f': 'Footwear' }

  t = 'blue socks and red shoes'
  for match in PATTERN.finditer(t):
  grp = match.lastgroup
  print "%s: %s" %( TITLES[grp], match.group(grp) )

which writes out the expected:
   Colour: blue
   Garment: socks
   Colour: red
   Footwear: shoe

The corresponding Perl-program would look like this:

   $PATTERN = qr/
   (blue |white |red)(?{'c'})
   |   (socks|tights)(?{'g'})
   |   (boot |shoe  |trainer)(?{'f'})
   /x;

   %TITLES = (c =>'Colour', g =>'Garment', f =>'Footwear');

   $t = 'blue socks and red shoes';
   print "$TITLES{$^R}: $^N\n" while( $t=~/$PATTERN/g );

and prints the same:
   Colour: blue
   Garment: socks
   Colour: red
   Footwear: shoe

You don't have nice named match references (?P<..>)
in Perl-5, so you have to emulate this by an ordinary
code assertion (?{..}) an set some value ($^R) on
the fly - which is not that bad in the end (imho).

(?{..}) means "zero with code assertion",
this sets Perl-predefined $^R to its evaluated
value from the {...}

As you can see, the pattern matching related part
reduces from 4 lines to one line.

If you wouldn't need dictionary lookup and
get away with associated categories, all
you'd have to do would be this:

   $PATTERN = qr/
   (blue |white |red)(?{'Colour'})
   |   (socks|tights)(?{'Garment'})
   |   (boot |shoe  |trainer)(?{'Footwear'})
   /x;

   $t = 'blue socks and red shoes';
   print "$^R: $^N\n" while( $t=~/$PATTERN/g );

What's the point of all that? IMHO, Python's
Regex support is quite good and useful, but
won't give you an edge over Perl's in the end.

Thanks & Regards

Mirco

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


Re: Is this a good use of __metaclass__?

2006-05-09 Thread Joel Hedlund
Hi!

Thanks for taking the time to answer. I will definitely have a look at writing 
dispatchers.

 > The problem you have with your metaclass version, is the infamous
 > metaclass conflict.

I think I solved the problem of conflicting metaclasses in this case and I 
posted it as a reply to Bruno Desthuilliers in this thread. Do you also think 
that's a bad use of __metaclass__? It's not that I'm hellbent on using 
metaclasses - I'm just curious how people think they should be used.

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


Re: Is this a good use of __metaclass__?

2006-05-09 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> Hi!
> 
> Thank you for a quick and informative response!
> 
> 
>>I'd go for 'manually decorating' anyway. Metaclasses can be really handy
>>for framework-like stuff, but for the use case you describe, I think the
>>explicit decorator option is much more, well, explicit - and also more
>>flexible - than metaclass black magic.
> 
> 
> Yes, point taken.
> 
> 
>>This may also help you distinguish 'published' API from implementation (which 
>>is what > CherryPy do)
> 
> 
> Hmm... I'm not sure I understand how manually decorating would help me
> do that? With SimpleXMLRPCServer.register_instance(obj) all public
> methods of obj are published for XMLRPC, decorated or not.

So it's effectively useless (disclaimer : I've never used
SimpleXMLRPCServer).

(snip)
> 
>>You would then have a 'server' class that just provides common
>>services and dispatch to specialized objects.
>  
> Neat. It won't play nice with dir() or SimpleXMLRPCServer's
> introspection functions though (system.listMethods(),
> system.methodHelp()). That may be a showstopper, or do you know of any
> fixes?

Nope - well, at least not without digging into SimpleXMLRPCServer's
internals, but if it (-> the solution I suggested) makes things more
complicated, it's a bad idea anyway.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this a good use of __metaclass__?

2006-05-09 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> I played around with my old code before I saw your post, and I believe
> I've found a solution that's a bit neater than what I had before. I
> thought I could just as well post it if you're interested and have the
> time. This one uses multiple inheritance, but it's legal and there's
> only one metaclass.
> 
(snip code)

Seems quite clean.




-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Antoon Pardon
Op 2006-05-09, Pisin Bootvong schreef <[EMAIL PROTECTED]>:
>
> Joe Marshall wrote:
>> Alex Martelli wrote:
>> Most languages allow `unnamed numbers'.  The `VAT_MULTIPLIER' argument
>> is a
>> strawman.  Would you want to have to use a special syntax to name the
>> increment
>> in loop?
>>
>>  defnumber zero 0
>>  defnumber one { successor (zero); }
>>
>>  for (int i = zero; i < limit; i += one) { ...}
>>
>> If you language allows unnamed integers, unnamed strings, unnamed
>> characters, unnamed arrays or aggregates, unnamed floats, unnamed
>> expressions, unnamed statements, unnamed argument lists, etc.  why
>> *require* a name for trivial functions?
>> Wouldn't all the other constructs benefit by having a required name as
>> well?
>>
>
> Is this a Slippery Slope fallacious argument?
> (http://c2.com/cgi/wiki?SlipperySlope)

No it is not.

> "if python required you to name every function then soon it will
> require you to name every number, every string, every immediate result,
> etc. And we know that is bad. Therefore requiring you to name your
> function is bad So Python is bad"

I think this is a strawman. IMO requiring to name a function can
make things cumbersome.

I don't suppose anyone thinks the following is good practice.

one = 1.
lst.append(one)


Yet this practice is forced upon you in a number of cases when
you require functions to be named. Look at the following:

def incr_cnt_by_one(obj):
  obj.cnt += 1

treat_all(lst, incr_cnt_by_one)

So the question I have is: Why is requiring me to give this function
a name considered a good thing, when it leads to a situation that
is considered bad practice in case of a number.

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


clear memory? how?

2006-05-09 Thread N/A
Hi all,
I am learning Python. Just wondering how to clear saved memory in 
Python? Like in Matlab I can simply use "clear all" to clear all saved 
memory.

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


Re: Why 3.0/5.0 = 0.59999...

2006-05-09 Thread Mirco Wahab
Hi Davy

> When I type 3.0/5.0, the result is 0.5...

try:

>>> print (3.0/5.0)
0.6

> Is there some precision loss? And how to overcome it?

Make sure the result gets piped
through some floating point con-
version  (like print, %s etc.)

BTW, the 0.59998 value
is the "exact" calculated value
corresponding to your floating point
accuracy (34/2 digits).


Regards

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


Re: combined files together

2006-05-09 Thread Eric Deveaud
Gary Wessle wrote:
> 
>  I need to traverse those files in the order they were created
>  chronologically. listdir() does not do it, is there a way besides
>  build a list then list.sort(), then for element in list_of_files open
>  element?

are the name of the files describing the cration date, or have to rely on the
creation date ?

if the name allows to discriminate the chronology, check glob module.

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


Re: Memory leak in Python

2006-05-09 Thread Peter Tillotson
1) Review your design - You say you are processing a large data set,
just make sure you are not trying to store  3 versions. If you are
missing a design, create a flow chart or something that is true to the
code you have produced. You could probably even post the design if you
are brave enough.

2) Check your implementation - make sure you manage lists, arrays etc
correctly. You need to sever links (references) to objects for them to
get swept up. I know it is obvious but easy to do in a hasty implementation.

3) Verify and test problem characteristics, profilers, top etc. It is
hard for us to help you much without more info. Test your assumptions.

Problem solving and debugging is a process, not some mystic art. Though
sometime the Gremlins disappear after a pint or two :-)

p

[EMAIL PROTECTED] wrote:
> I have a python code which is running on a huge data set. After
> starting the program the computer becomes unstable and gets very
> diffucult to even open konsole to kill that process. What I am assuming
> is that I am running out of memory.
> 
> What should I do to make sure that my code runs fine without becoming
> unstable. How should I address the memory leak problem if any ? I have
> a gig of RAM.
> 
> Every help is appreciated.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Rob Warnock
Pisin Bootvong <[EMAIL PROTECTED]> wrote:
+---
| No matter how scalable your language is, you cannot make a 100MHz/128MB
| server serve 100,000 client a second over the internet.
+---

Sure you can! That's ~1000 CPU cycles/request, which [assuming at least
a 100BASE-TX NIC] is plenty to service 100K *small* requests/s...  ;-}

Of course, you might have to write it in assembler on bare metal,
but the good news is that with only a 1000 cycle budget, at least
the code won't be very large!  ;-}


-Rob [someone who remembers 0.5 MIPS DEC PDP-10s being used
  for >100 simultaneous commercial timesharing users]

-
Rob Warnock <[EMAIL PROTECTED]>
627 26th Avenue http://rpw3.org/>
San Mateo, CA 94403 (650)572-2607

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


Re: Enumerating Regular Expressions

2006-05-09 Thread blair . bethwaite
Dale Strickland-Clark wrote:
> Any regular expression that has an asterisk in it has an infinite number of
> possible matches.
>
> If it has two asterisks, that's an infinite number squared and that's a
> really big number.
>
> You wouldn't want to print them out.

We've been over this already.  Why are people getting stuck on infinite
regular languages?  I've made it quite clear that I'm only really
interested in doing this for finite languages, but that shouldn't
matter anyway.  Maybe I should phrase it differently; I want a tool
that can enumerate a regex, with support for generating each string
described by the regex in some predefined order.  So something like:
# pattern is the regex representing language L
reg_lang_gen = re.compile('pattern').enumerator()
while len(s) < n:
   s = reg_lang_gen.next()   # get next string in L
   ...

It's easy to imagine a problem where you'd want to enumerate a regex
that represents an infinite regular language.  E.g. a particularly dumb
bruteforce password cracker, you might want to keep generating strings
from the language of choice until you find one that matches your
encrpyted version, naturally you might want to stop if you hadn't found
it within 10 characters or so.

Cheers,
-B

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


Re: Is this a good use of __metaclass__?

2006-05-09 Thread Michele Simionato
Joel Hedlund wrote:
> It's not that I'm hellbent on using
> metaclasses - I'm just curious how people think they should be used.

There are very few good use cases for metaclasses. *You should use a
metaclass
only when you want the additional metaclass-induced behavior to be
inherited
in the children classes.*

Here is a made up example (it assume you know the cmd.Cmd class in the
standard
library). Suppose you want to use a metaclasses to add aliases to the
"do_*"
methods of a subclass of cmd.Cmd. You can do it in this way:

import cmd

class make_oneletter_aliases_for_commands(type):
"""Typically used in Cmd classes."""
def __init__(cls, name, bases, dic):
for name,func in dic.iteritems():
if name.startswith("do_"):
firstletter = name[3]
setattr(cls, "do_" + firstletter, func)

class Cmd(cmd.Cmd, object): # make it a new-style class, so that super
works
__metaclass__ = make_oneletter_aliases_for_commands
def preloop(self):
"""Done once at the beginning."""
cmd.Cmd.preloop(self)
self.do_greetings("World!")

def do_greetings(self, arg):
"""Display a greeting message."""
print "Hello, %s!" % arg

def do_help(self, arg):
"""Print this help message."""
super(Cmd, self).do_help(arg)

def do_quit(self,arg):
"""Exit the command-loop."""
return 'quit' # anything != None will do

if __name__ == '__main__':
Cmd().cmdloop()

Here is how you use it:

$ python cmd_with_aliases.py
Hello, World!!
(Cmd) h

Documented commands (type help ):

g  greetings  h  help  q  quit

(Cmd) g World
Hello, World!
(Cmd) q

The metaclass has generated the methods 'do_h', 'do_g' and 'do_q' as
aliases for 'do_help', 'do_greetings', 'do_quit' respectively. You
could have
done the same without a metaclass, with a function modifying the class.
However every time you subclass Cmd (or a subclass of it), you would
have to invoke
the function again to generate the aliases corresponding to the new
methods in the subclass. The metaclass performs this step
automagically,
simplifying the life of your users.

If you don't care about giving magic abilities to the subclasses of
subclasses
you don't need a metaclass. For real use of metaclasses, see the Zope
framework code. 

Michele Simionato

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


Re: Why 3.0/5.0 = 0.59999...

2006-05-09 Thread Jeremy Sanders
Davy wrote:

> Is there some precision loss? And how to overcome it?


See
 http://docs.python.org/tut/node16.html
for some useful information.

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Embedding Python

2006-05-09 Thread gavinpaterson
Dear Pythoners,

I am writing as I am having trouble embedding a Python program into a
Win XP C++ console application.

I have written a script file for importing and I am trying to use the
example for "Pure Embedding" found in the product documentation.

The program fails to successfully execute past the line:

if (pFunc && PyCallable_Check(pFunc))

I have checked the pFunc pointer at runtime and it is not null so I
assume that the PyCallable_Check fails.

If I define my function in python in file "multiply.py" as:

def multiply(a,b):
print "Will compute", a, "times", b
c = 0
for i in range(0, a):
c = c + b
return c

Then in VC++ I call the program with arguments:

multiply multiply 23 3

Then I'd expect a successful result, the file seems to be getting
parsed if multiply.pyc is available, but the function multiply does
not seem to be callable - where am I going wrong?






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


Re: utility functions within a class?

2006-05-09 Thread bruno at modulix
John Salerno wrote:
> John Salerno wrote:
> 
>> [EMAIL PROTECTED] wrote:
>>
>>> Even if you don't end up referring to self or any instance
>>> attributes within the method
>>
>>
>> Hmm, follow-up: I *do* plan to refer to instance attributes inside
>> these methods (self.something), but does that require that they be
>> instance methods, or can they still reference 'self' since they are
>> inside the class?
>>
>> They won't be called directly from an instance, which is why I
>> wondered about making them static or class methods, but can static or
>> class methods use self, or does it have to be an instance method in
>> that case?
> 
> 
> Ugh, sorry about another post, but let me clarify: In these utility
> functions, I need to refer to an attribute of an instance,

So you want ordinary methods.

> but these
> functions will be called from another method in the class, not from the
> instance itself.

yes, they will:

class Parrot(object):
   def _func1(self, whatever):
 print whatever

  def talk(self):
 self._func1('vroom')

> Is this even possible, or would 'self' have no meaning
> when used this way?

You probably noticed that 'self' (or whatever you name it - but better
to stick to convention) *must* be defined as the first param of a
'method'. The reason for it is that what we commonly call 'methods' are
in fact plain Python functions. It's only when they are looked up on an
instance that they are wrapped into a 'method' object (read about the
descriptor protocol to learn how...), that in turn calls the function,
passing it the instance as first param.

For saying it short (warning: over-simplification ahead), the usual
method call idiom:

  myObj.myMethod(arg)

is syntactic sugar for:

  myObj.__class__.myMethod(myObj, arg)


HTH.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Embedding Python in C++ Problem

2006-05-09 Thread gavinpaterson
Dear Pythoners,

I am trying to embed a Python script into a C++ application for the
first time.

Although I have used the example 5.3 Pure Embedding I am having
problems with calling the function defined in my program.

If I define function multiply in module "multiply.py"

def multiply(a,b):
print "Will compute", a, "times", b
c = 0
for i in range(0, a):
c = c + b
return c

Then call the program with the following arguments:

multiply multiply 2 3

Then I'd expect to see the result appear in stdout. The compiled
module is found but the program fails to get past:

if (pFunc && PyCallable_Check(pFunc))

I am using VC7.1 on windows XP. Where am I going wrong?






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


Re: utility functions within a class?

2006-05-09 Thread bruno at modulix
John Salerno wrote:
> [EMAIL PROTECTED] wrote:
> 
>> I'm having trouble deciphering what this bit means - "but these
>> functions will be called from another method in the class, not from the
>> instance itself", I don't think it makes sense.
> 
> 
> Yeah, I'm starting to see that as I tried to implement it. Here's what I
> came up with, which works:
> 
> def generate(self, filename):
> self.head = self.generate_head()
> self.body = self.generate_body()
> 
> So the two generate_* methods are called from within another class
> method,

here, generate() is *not* a class method, it's an instance method (which
is the default).

> and it seemed necessary to still call them from an instance.
> What I originally meant was that they would not be called from an
> instance *outside* the class itself, i.e. they won't be used when
> writing another script, they are only used by the class itself.

Yeps, that's pretty common in any OO language. In most mainstream OOPLs,
these methods would have the 'protected' access restriction modifier. In
Python, we rely on the convention that an attribute whose name is
prefixed with a single underscore is an implementation detail - not part
of the API - and should not be called by client code. Just renaming
these two methods is enough to warn users of your code that they're on
their own if they start messing with them.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: utility functions within a class?

2006-05-09 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> John Salerno wrote:
> 
>>What I originally meant was that they would not be called from an
>>instance *outside* the class itself, i.e. they won't be used when
>>writing another script, they are only used by the class itself.
> 
> 
> Yep, so you want to encapsulate the functionality that those methods
> provide, 
>
> which is the whole point of building them in a class in the
> first place.  And you want them to be private to the class so that they
> do not form part of the classes public/external interface.
> 
> In python, as discussed earlier :), you can make them semi-private by
> using the '__method_name'

Blair, please, don't give bad advices. The 'double-leading-underscore'
stuff has some side-effects (name-mangling), and is meant to protect an
attribute from accidental overloading. The convention for 'protected'
attributes (which should really be named 'implementation attributes') is
a *single* leading underscore.


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PythonWin's Check (any other Lint tool) ?

2006-05-09 Thread [EMAIL PROTECTED]
Hello,
There're a pylint (http://www.logilab.org/projects/pylint) and
pychecker (http://pychecker.sourceforge.net/) projects.
Eugene

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


Re: utility functions within a class?

2006-05-09 Thread bruno at modulix
John Salerno wrote:
> John Salerno wrote:
> 
>> [EMAIL PROTECTED] wrote:
>>
>>> John Salerno wrote:
>>>
 What I originally meant was that they would not be called from an
 instance *outside* the class itself, i.e. they won't be used when
 writing another script, they are only used by the class itself.
>>>
>>>
>>> Yep, so you want to encapsulate the functionality that those methods
>>> provide, which is the whole point of building them in a class in the
>>> first place.  And you want them to be private to the class so that they
>>> do not form part of the classes public/external interface.
>>
>>
>> But it's right that they should still be regular instance methods? So
>> from within the class I still call them as self._generate_head(), etc.?
> 
> 
> I tried the underscore method, but I was still able to call it as a
> regular instance method in the interpreter. Is that what's supposed to
> happen?

Yes. Language-inforced access restriction is totally useless (and is
quite easy to defeat in C++ and Java FWIW). Python's philosophy is that
programmers are not braindead monkey-coders that must be protected
(pardon the pun) from their own stupidity. There's no way to idiot-proof
a code anyway, so why bother ? The single-underscore prefix means
'implementation, don't touch or else', and this is quite enough. Most
python programmers won't touch it - unless they have perfectly valid
reasons to do so (yes, it happens), and then they will implicitely
accept the consequences.


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Import data from Excel

2006-05-09 Thread Tim Golden
[Dale Strickland-Clark]
| from win32com.client import GetObject, constants
| 
| def GetExcelData(self, strFilePath):
| """ Extract the data from the Excel sheet. 
| Returns tuple of tuples representing the rows and cells."""
| # The following line extracts 
| # all the data from sheet 1 of the spreadsheet
| return GetObject(strFilePath).Sheets(1).UsedRange.Value

Amazing! I never knew you could do that -- GetObject against
a registered file path, I mean. Certainly beats my trying to
remember whether you call .Open on an Excel Application, Workbook,
Worksheet or something else altogether. 

Thanks, Dale.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Pisin Bootvong

Rob Warnock wrote:
> Pisin Bootvong <[EMAIL PROTECTED]> wrote:
> +---
> | No matter how scalable your language is, you cannot make a 100MHz/128MB
> | server serve 100,000 client a second over the internet.
> +---
>
> Sure you can! That's ~1000 CPU cycles/request, which [assuming at least
> a 100BASE-TX NIC] is plenty to service 100K *small* requests/s...  ;-}
>
> Of course, you might have to write it in assembler on bare metal,
> but the good news is that with only a 1000 cycle budget, at least
> the code won't be very large!  ;-}
>

Well, I was really asking for a service that really service something
complicate and useful though :-D

And donot forget to account for OS CPU time (well may be you can write
your own OS for it too :-D )


>
> -Rob [someone who remembers 0.5 MIPS DEC PDP-10s being used
>   for >100 simultaneous commercial timesharing users]
>
> -
> Rob Warnock   <[EMAIL PROTECTED]>
> 627 26th Avenue   http://rpw3.org/>
> San Mateo, CA 94403   (650)572-2607

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


Re: clear memory? how?

2006-05-09 Thread Diez B. Roggisch
N/A wrote:

> Hi all,
> I am learning Python. Just wondering how to clear saved memory in
> Python? Like in Matlab I can simply use "clear all" to clear all saved
> memory.

You don't - python does it for you. It is called garbage collection. All you
have to to is get into granny-mode(tm): forget about things. That means:
once an object is not referenced by your code anymore, it will be cleaned
up.

For example:

>>> l = range(10)
>>> del l

will make python garbage collect the list referred to by l. Actually, this
will work too:


>>> l = range(10)
>>> l = None

Because l now refers another object (None in this case), the _list_ that was
refered beforehand gets freed as it's reference counter is reduced by one.

Generally speaking: don't worry.

HTH,

Diez

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


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Stefan Nobis
[EMAIL PROTECTED] (Alex Martelli) writes:

> if anonymous functions are available, they're used in even more
> cases where naming would help

Yes, you're right. But don't stop here. What about expressions? Many
people write very complex expression, that are hard to understand. A
good language should forbid these abuse and don't allow expressions
with more than 2 or maybe 3 operators!

Forbid everything that might be abused and you have a perfect
language?

I like Python and I teach Python, I'm also used to Java and C#. But
one of the best solutions to problems of beginners and not so
brilliant programmers is something like the Dr. Scheme enviroment:
Choose your language level yourself. Everyting (allowed constructs,
error messages,...) will be adjusted to your choosen level. And
experts have all at their fingertips they want and need. Code isn't
blowed up and screwed with workaround for language limitations (that
are aimed at beginners and less capable programmers).

Why only adjust to the less capable people? Give everyone what they
need and want! :)

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


Re: Python's regular expression?

2006-05-09 Thread bruno at modulix
Davy wrote:
> Hi all,
> 
(snip)
> Does Python support robust regular expression like Perl?

Yes.

> And Python and Perl's File content manipulation, which is better?

>From a raw perf and write-only POV, Perl clearly beats Python (regarding
 I/O, Perl is faster than C - or it least it was the last time I benched
it on a Linux box).

>From a readability/maintenance POV, Perl is a perfect nightmare.

> Any suggestions will be appreciated!

http://pythonology.org/success&story=esr


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hyperthreading locks up sleeping threads

2006-05-09 Thread Robin Becker
[EMAIL PROTECTED] wrote:
> Below are 2 files.  The first is a Python program that isolates the
> problem within less than 1 hour (often just a few minutes).  The second
> is a C++ program that shows that the Win32 Sleep() function works as
> expected (ran from Friday afternoon until Monday morning).
> 
> Note, the Python programs hangs (stops responding) with hyper-threading
> turned on (a BIOS setting), but works as expected with hyper-threading
> turned off.
..
I ran this on winxp ht+python-2.4.3 for about 16 hours and no lockup.
-- 
Robin Becker

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


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Rob Warnock
Pisin Bootvong <[EMAIL PROTECTED]> wrote:
+---
| Rob Warnock wrote:
| > | No matter how scalable your language is, you cannot make a
| > | 100MHz/128MB server serve 100,000 client a second over the internet.
| > +---
| >
| > Sure you can! That's ~1000 CPU cycles/request, which [assuming at least
| > a 100BASE-TX NIC] is plenty to service 100K *small* requests/s...  ;-}
| 
| Well, I was really asking for a service that really service something
| complicate and useful though :-D
+---

If "only" being useful is enough, 100 cycles is enough for a DNS server,
or an NTP server, or even a stub HTTP server that delivers some small
piece of real-time data, like a few realtime environmental sensors
[temperature, voltages, etc.].

+---
| > Of course, you might have to write it in assembler on bare metal,
| > but the good news is that with only a 1000 cycle budget, at least
| > the code won't be very large!  ;-}
| 
| And donot forget to account for OS CPU time (well may be you can write
| your own OS for it too :-D )
+---

Uh... What I meant by "bare metal" is *no* "O/S" per se, only a
simple poll loop servicing the attention flags[1] of the various
I/O devices -- a common style in lightweight embedded systems.


-Rob

[1] a.k.a. "interrupt request" bits, except with interrupts not enabled.

-
Rob Warnock <[EMAIL PROTECTED]>
627 26th Avenue http://rpw3.org/>
San Mateo, CA 94403 (650)572-2607

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


Re: do "some action" once a minute

2006-05-09 Thread Petr Jakes
Thanks for your comment. It is mainly English issue (I am not native
English speaker).

OK, to be more specific, I would like to run the code, when the value
of seconds in the timestamp become say "00".
The whole code will run in the infinitive loop and other actions will
be executed as well, so it can not "sleep" for 60 seconds :).

Regards

Petr

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


two of pylab.py

2006-05-09 Thread Gary Wessle
Hi

I use debian/testing linux Linux debian/testing 2.6.15-1-686 

I found some duplicate files in my system, I don't if the are both
needed, should I delete one of the groups below and which one?

-rw-r--r-- 1 root root 80375 2006-01-24 00:28 
/usr/lib/python2.3/site-packages/matplotlib/pylab.py
-rw-r--r-- 1 root root 96202 2006-05-07 13:44 
/usr/lib/python2.3/site-packages/matplotlib/pylab.pyc
-rw-r--r-- 1 root root 96202 2006-05-07 13:45 
/usr/lib/python2.3/site-packages/matplotlib/pylab.pyo
-rw-r--r-- 1 root root31 2004-12-10 03:05 
/usr/lib/python2.3/site-packages/pylab.py
-rw-r--r-- 1 root root   160 2006-05-07 13:44 
/usr/lib/python2.3/site-packages/pylab.pyc
-rw-r--r-- 1 root root   160 2006-05-07 13:45 
/usr/lib/python2.3/site-packages/pylab.pyo


my sys.path shows that /usr/lib/python2.3/site-packages/ is present.


$cat /usr/lib/python2.3/site-packages/pylab.py
from matplotlib.pylab import *


This imports all names except those beginning with an underscore (_).

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


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Pisin Bootvong

Antoon Pardon wrote:
> Op 2006-05-09, Pisin Bootvong schreef <[EMAIL PROTECTED]>:
> > Is this a Slippery Slope fallacious argument?
> > (http://c2.com/cgi/wiki?SlipperySlope)
>
> No it is not.
>
> [...]
>
> So the question I have is: Why is requiring me to give this function
> a name considered a good thing, when it leads to a situation that
> is considered bad practice in case of a number.
>
> --

Slippery Slope::
   "Argumentation that A is bad, because A might lead to B, and B
to C, and we all know C is very bad."

> Why is requiring me to give this function
> a name considered a good thing, when it leads to a situation that
> is considered bad practice in case of a number.

A === "requiring me to give function a name"
no B
C === "requiring me to give number a name"

"Argumentation that requiring one to give function a name is bad,
because that might lead to requiring one to give number a name, and we
all know that that is very bad."


Now you tell me which part of that is not Slippery slope argument.

  -- Or are you trying to make a sarcastic joke? I'm sorry if I didn't
get it. --

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


Re: Memory leak in Python

2006-05-09 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> I have a python code which is running on a huge data set. After
> starting the program the computer becomes unstable and gets very
> diffucult to even open konsole to kill that process. What I am assuming
> is that I am running out of memory.
> 
> What should I do to make sure that my code runs fine without becoming
> unstable. How should I address the memory leak problem if any ? I have
> a gig of RAM.
> 
> Every help is appreciated.

Just a hint : if you're trying to load your whole "huge data set" in
memory, you're in for trouble whatever the language - for an example,
doing a 'buf = openedFile.read()' on a 100 gig file may not be a good
idea...



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Controlling non-python programs with python

2006-05-09 Thread Wesley Brooks
Dear All,Tried to post once before but it seemed to get trapped in the system due to a suspect heading.I would like to create and pass keyboard, mouse, and analogue device events another program in order to control it, perhaps over a network if it requires too much processing power to be done on the same machine. I'm trying to see if it is possible to control another application using python. In this case I'm trying to control a car simulator by taking screen shots, and passsing the control events to the program.
I'm guessing this must be possible as people have written python based vnc software.Cheers for your help.Wesley Brooks
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: two of pylab.py

2006-05-09 Thread Diez B. Roggisch
Gary Wessle wrote:

> Hi
> 
> I use debian/testing linux Linux debian/testing 2.6.15-1-686
> 
> I found some duplicate files in my system, I don't if the are both
> needed, should I delete one of the groups below and which one?


Do you have any problems related to pylab? Or are you concerned about disk
consumption?

> -rw-r--r-- 1 root root 80375 2006-01-24 00:28
> /usr/lib/python2.3/site-packages/matplotlib/pylab.py -rw-r--r-- 1 root
> root 96202 2006-05-07 13:44
> /usr/lib/python2.3/site-packages/matplotlib/pylab.pyc -rw-r--r-- 1 root
> root 96202 2006-05-07 13:45
> /usr/lib/python2.3/site-packages/matplotlib/pylab.pyo
> -rw-r--r-- 1 root root31 2004-12-10 03:05
> /usr/lib/python2.3/site-packages/pylab.py
> -rw-r--r-- 1 root root   160 2006-05-07 13:44
> /usr/lib/python2.3/site-packages/pylab.pyc
> -rw-r--r-- 1 root root   160 2006-05-07 13:45
> /usr/lib/python2.3/site-packages/pylab.pyo
> 
> 
> my sys.path shows that /usr/lib/python2.3/site-packages/ is present.
> 
> 
> $cat /usr/lib/python2.3/site-packages/pylab.py
> from matplotlib.pylab import *
> 
> 
> This imports all names except those beginning with an underscore (_).

So it appears to be some sort of alias for matplotlib.pylab. And unless you
want to risk that other packages that rely on the import

import pylab

to fail, you should keep things as they are.

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


Re: Possible constant assignment operators ":=" and "::=" for Python

2006-05-09 Thread Christophe
Fredrik Lundh a écrit :
> Christophe wrote:
> 
> 
>>I think you've made a mistake in your example.
> 
> 
>  >>> constant A = []
>  >>> def foo(var):
>  ... var.append('1')
>  ... print var
>  ...
>  >>> b = A
>  >>> foo(b)
>  >>> foo(b)
> 
> 
>>>and this ?
>>>
>>>>>> constant A = []
>>>>>> print A is A
>>
>>Obviously, False.
> 
> 
> why obviously ? why shouldn't a constant be constant ?
> 
>  

Because the name A is bound by the compiler to mean construct a new 
object since [] is mutable.

Same reason why :

 >>> def A(): return []
 >>> print A() is A()
False

It gives btw one possible implementation ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Chris Uppal
Alex Martelli wrote:

> I think it's reasonable to make a name a part of functions, classes and
> modules because they may often be involved in tracebacks (in case of
> uncaught errors): to me, it makes sense to let an error-diagnosing
> tracebacks display packages, modules, classes and functions/methods
> involved in the chain of calls leading to the point of error _by name_.

It seems to me that there's something of a circularity here.  Either in your
logic if applied to language design in general, or as a self-perpetuating habit
when applied to Python in particular.

The assumption is that functions are in some sense rather "big" things -- that
each function performs a well-defined action which can be understood in
isolation.  That may well be true in idiomatically written Python (I've never
cared for the look of the language myself, so I don't know what's considered
"normal"), but it isn't true in general.  With the assumption, it makes sense
to say that every function /could/ have a name, and so, why not /give/ it a
name ?  But without the assumption, when many little anonymous functions are
used, the idea of giving them all names appears pettifogging to the point of
idiocy.  If the language and/or culture expects that all/most functions will be
named, then "little" functions (in my sense) won't be used; hence the
self-perpetuating habit.  But I don't think that the underlying logic supports
that habit independently of its own self-perpetuating nature.

E.g. consider the Smalltalk code (assumed to be the body of a method):

aCollection
do: [:each |
each > 0 ifTrue: [^ true]].
^ false.

which iterates over a collection checking to see if any element is > 0. If so
then the method answers true ("^" -- spelled "return" in Java), otherwise it
answers false.  In that code,
[^ true]
is syntactically and semantically an anonymous function, which is only invoked
if the antecedent is true (in point of fact the compiler inlines that function
away but I don't think that's relevant here).  The passage beginning
[:each | ...
and reaching to the matching ] is also an anonymous function with one parameter
(each) which is applied to each element of the collection in turn.  (In this
case it really is an anonymous function, even at the implementation level.)
What "name" would you give to either of them ?  I don't believe that /any/ name
is possible, and certainly that no name is desirable.

In my working Smalltalk environment today, there are 60099 methods defined
across 3369 classes.  In that codebase there are 38112 anonymous functions.  Do
you really want to have to find names for them all ?

-- chris


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


Re: Python's regular expression?

2006-05-09 Thread Duncan Booth
Mirco Wahab wrote:

> If you wouldn't need dictionary lookup and
> get away with associated categories, all
> you'd have to do would be this:
> 
>$PATTERN = qr/
>(blue |white |red)(?{'Colour'})
>   |   (socks|tights)(?{'Garment'})
>   |   (boot |shoe  |trainer)(?{'Footwear'})
>/x;
> 
>$t = 'blue socks and red shoes';
>print "$^R: $^N\n" while( $t=~/$PATTERN/g );
> 
> What's the point of all that? IMHO, Python's
> Regex support is quite good and useful, but
> won't give you an edge over Perl's in the end.

If you are desperate to collapse the code down to a single print statement 
you can do that easily in Python as well:

>>> PATTERN = '''
  (?Pblue |white |red)
  |   (?Psocks|tights)
  |   (?Pboot |shoe  |trainer)
  '''
>>> t = 'blue socks and red shoes'
>>> print '\n'.join("%s:%s" % (match.lastgroup,
match.group(match.lastgroup))
for match in re.finditer(PATTERN, t, re.VERBOSE))
Colour:blue
Garment:socks
Colour:red
Footwear:shoe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using time.sleep() in 2 threads causes lockup whenhyper-threading is enabled

2006-05-09 Thread Serge Orlov
Dennis Lee Bieber wrote:
> On 8 May 2006 15:44:04 -0700, "Serge Orlov" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>
> > The test program in question doesn't require a dedicated machine and it
> > doesn't consume a lot of CPU resources since it sleeps most of the
> > time.
> >
>   Yet... Do we have any evidence that other activity on the machine
> may or may not affect the situation? There is a big difference between
> leaving a machine idle for a few hours to see if it hangs, vs doing
> normal activities with a process in the background (and what about
> screen savers? network activity?)

But what if other processes will actually help to trigger the bug? IMHO
both situations (idle or busy) are equal if you don't know what's going
on.

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


wxPython IEHtmlWindow mystery - dependencies?

2006-05-09 Thread gjzusenet
Hi

I've been using an IEHtmlWindow in my script with no problems, but it
seems that for people with a clean installation of XP SP2 it fails like
such:

Traceback (most recent call last):
  File "htmlloader.py", line 509, in load
  File "PythonCard\model.pyo", line 340, in __init__
  File "PythonCard\resource.pyo", line 86, in __init__
  File "PythonCard\resource.pyo", line 91, in __init__
  File "PythonCard\resource.pyo", line 91, in __init__
  File "PythonCard\resource.pyo", line 96, in __init__
  File "PythonCard\resource.pyo", line 139, in enforceSpec
  File "PythonCard\resource.pyo", line 30, in loadComponentModule
ImportError: cannot import module 'iehtmlwindow

As soon as a simple session of windowsupdate is run (with just the
hotfixes etc.) the problem seems to disappear.

So,do you know which update exactly is needed to prevent the error, and
why does it happen in the first place anyway?

Any ideas?

Thanks

~G

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


wxPython IEHtmlWindow mystery - dependencies?

2006-05-09 Thread gjzusenet
Hi

I've been using an IEHtmlWindow in my script with no problems, but it
seems that for people with a clean installation of XP SP2 it fails like
such:

Traceback (most recent call last):
  File "htmlloader.py", line 509, in load
  File "PythonCard\model.pyo", line 340, in __init__
  File "PythonCard\resource.pyo", line 86, in __init__
  File "PythonCard\resource.pyo", line 91, in __init__
  File "PythonCard\resource.pyo", line 91, in __init__
  File "PythonCard\resource.pyo", line 96, in __init__
  File "PythonCard\resource.pyo", line 139, in enforceSpec
  File "PythonCard\resource.pyo", line 30, in loadComponentModule
ImportError: cannot import module 'iehtmlwindow

As soon as a simple session of windowsupdate is run (with just the
hotfixes etc.) the problem seems to disappear.

So,do you know which update exactly is needed to prevent the error, and
why does it happen in the first place anyway?

Any ideas?

Thanks

~G

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


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Antoon Pardon
Op 2006-05-09, Pisin Bootvong schreef <[EMAIL PROTECTED]>:
>
> Antoon Pardon wrote:
>> Op 2006-05-09, Pisin Bootvong schreef <[EMAIL PROTECTED]>:
>> > Is this a Slippery Slope fallacious argument?
>> > (http://c2.com/cgi/wiki?SlipperySlope)
>>
>> No it is not.
>>
>> [...]
>>
>> So the question I have is: Why is requiring me to give this function
>> a name considered a good thing, when it leads to a situation that
>> is considered bad practice in case of a number.
>>
>> --
>
> Slippery Slope::
>"Argumentation that A is bad, because A might lead to B, and B
> to C, and we all know C is very bad."

But I have seen noone here argue that requiring functions to be named
leads to requiring all variables to be named. 

>> Why is requiring me to give this function
>> a name considered a good thing, when it leads to a situation that
>> is considered bad practice in case of a number.
>
> A === "requiring me to give function a name"
> no B
> C === "requiring me to give number a name"
>
> "Argumentation that requiring one to give function a name is bad,
> because that might lead to requiring one to give number a name, and we
> all know that that is very bad."

That is not the arguement I'm making.

The argument is that a particular pratice is considered bad coding,
(with an example giving a number) and then showing that requiring
a name for a function, almost makes such a practice inevitable (for
certain functions used as parameters)

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


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread Chris Uppal
Pisin Bootvong wrote:

> Slippery Slope::
>"Argumentation that A is bad, because A might lead to B, and B
> to C, and we all know C is very bad."

For the Slippery Slope criticism to be applicable, there would have to be some
suggestion that removing anonymous functions /would actually/ (tend to) lead to
removing anonymous values in general.  There was no such suggestion.

The form of the argument was more like reasoning by analogy: if context A has
features like context B, and in B some feature is known to be good (bad) then
the analogous feature in A is also good (bad).  In that case an attack on the
validity of the argument would centre on the relevance and accuracy of the
analogy.

Alternatively the argument might be seen as a generalisation/specialisation
approach.  Functions are special cases of the more general notion of values.
We all agree that anonymous values are a good thing, so anonymous functions
should be too.  If you parse the argument like that, then the attack should
centre on showing that functions have relevant special features which are not
shared by values in general, and so that we cannot validly deduce that
anonymous functions are good.

-- chris


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


Re: Econometrics in Panel data?

2006-05-09 Thread DeepBlue
so are you saying that Python is not an appropriate language for doing 
econometrics stuff?


Dennis Lee Bieber wrote:
> On Tue, 09 May 2006 05:58:10 +0800, DeepBlue <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:
> 
>> Hi all,
>>
>> I am new to Python. Just wondering can Python able to do econometric 
>> regression in either Time-series or pooled (panel) data? As well as test 
>> for hetero, autocorrelation, or endogeneity?
> 
>   Can you do such in FORTRAN, COBOL, SNOBOL, APL, C, Matlab, Maple,
> Excel, Turing Machine? Most likely...
> 
>   Is there a pre-built library to compute such? No idea...
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python

2006-05-09 Thread Serge Orlov
gavinpaterson wrote:
> Dear Pythoners,
>
> I am writing as I am having trouble embedding a Python program into a
> Win XP C++ console application.
>
> I have written a script file for importing and I am trying to use the
> example for "Pure Embedding" found in the product documentation.
>
> The program fails to successfully execute past the line:
>
> if (pFunc && PyCallable_Check(pFunc))
>
> I have checked the pFunc pointer at runtime and it is not null so I
> assume that the PyCallable_Check fails.

Looking at the source in "Pure Embedding" I see that it is supposed to
print an error message if PyCallable_Check fails, have you got the
message?

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


Re: advanced number recognition in strings?

2006-05-09 Thread Dan Sommers
On Mon, 8 May 2006 17:16:20 + (UTC),
[EMAIL PROTECTED] (Roy Smith) wrote:

> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>> we want extract numbers from strings and wonder if there is already a
>> module around for doing this. An example in our case would look like
>> this:
>> 
>> 0.032 +/- 0.5 x 10(-4)
>> 
>> it would even be helpful to have a routine which does not recognise the
>> +/- , but at least the 10(-4).

[ ... ]

> That being said, e-notation does not represent uncertainty, but then
> again, neither does an IEEE float.  To keep the uncertainty, you need
> to create a new numeric class which stores the mantissa, the
> uncertainty, and the exponent.  Perhaps you could get away with
> storing the mantissa and exponent as a standard float, but you'd still
> need to store the uncertainty.  Then you'd (presumably) need to define
> a whole set of math operators which did something useful with these
> numbers.  For example, what should:

For a physics course I took a couple of years ago, I developed a
number-like class that kept track of uncertainties through various
calculations.  I used a float for both the value and the uncertainty,
and wrote my own __str__ method to make the output look nice.  I didn't
have to parse anything at run-time, though.  I half-implemented the code
to track units as well (IOW, I implemented just enough to meet my own
requirements).

I can post the code somewhere if anyone is interested.

> x = 0.032 +/- 0.5 x 10(-4)
> y = 0.032 +/- 1.0 x 10(-4)
> print x == y

> print out?

Regards,
Dan

-- 
Dan Sommers

"I wish people would die in alphabetical order." -- My wife, the genealogist
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critic of Guido's blog on Python's lambda

2006-05-09 Thread David C.Ullrich
On Mon, 08 May 2006 18:46:57 -0400, Ken Tilton <[EMAIL PROTECTED]>
wrote:

>
>
>David C. Ullrich wrote:
>> On 08 May 2006 12:53:09 -0700, [EMAIL PROTECTED] (Thomas
>> F. Burdick) wrote:
>> 
>> 
>>>Ken Tilton <[EMAIL PROTECTED]> writes:
>>>
>>>
No, you do not want on-change handlers propagating data to other
slots, though that is a sound albeit primitive way of improving
self-consistency of data in big apps. The productivity win with
VisiCalc was that one simply writes rules that use other cells, and
the system keeps track of what to update as any cell changes for
you. You have that exactly backwards: every slot has to know what
other slots to update. Ick.
>>>
>>>No no, that's fine and the way it should be: when you change a slot,
>>>it should know who to update.  And that's also the way it works in
>>>Cells.  The trick is that Cells takes care of that part for you:
>> 
>> 
>> I'm glad you said that - this may be what he meant, but it seems
>> more plausible than what he actually said.
>
>There may be some confusion here because there are two places for code 
>being discussed at the same time, and two sense of propagation.
>
>the two places for code are (1) the rule attached to A which is 
>responsible for computing a value for A and (2) a callback for A to be 
>invoked whenever A changes. Why the difference?
>
>In Cells, A is a slot such as 'background-color'. Whenever that changes, 
>we have to do something more. On Mac OS9 it was "InvalidateRect" of the 
>widget. In Cells-Tk, it is:
> (Tcl_interp "mywidget configure -background ")
>
>In my OpenGL GUI, it is to rebuild the display-list for the widget.
>
>That is the same no matter what rule some instance has for the slot 
>background-color, and different instances will have different rules.
>
>As for propagating, yes, Cells propagates automatically. More below on 
>that. What I saw in the example offered was a hardcoded on-change 
>callback that was doing /user/ propagation form B to A (and B to A! ... 
>doesn't that loop, btw? 

No, there's no looping in the example. Yes, the code determining what
b returns should be attached to b instead of to a, but the code I
gave does work as advertised. (I mean give me a break - I provided
a sample use so you could simply run it. Installing Python is not
hard.)

If you, um, look at the code you see that "cells.a = 42" triggers
cells.__setattr__, which fires a's callback; the callback then
reaches inside and sets the value of b _without_ going through
__setattr__, hence without triggering b's callback.

In Cells you can't have A depend on B and also B depend on A?
That seems like an unfortunate restriction - I'd want to be
able to have Celsius and Farenheit, so that setting either
one sets the other.

Of course if there are no loops it's easier to see how
you managed to do the stuff you were talking about elsewhere,
(at least sometimes) delaying execution until needed.

>Anyway...)
>
>> 
>> 
>>>all
>>>the *programmer* has to care about is what values a slot depends on --
>>>Cells takes care of inverting that for you, which is important because
>>>that's a job that a computer is much better at than a human.
>> 
>> 
>> Fine. I suppose that is better; if b is going to return a + 1
>> the fact that this is what b returns should belong to b, not
>> to a. So a has an update list including b, so when a's value
>> is set a tells b it needs to update itself.
>> 
>> If we're allowed to pass (at some point, to some constructor
>> or other) something like (b, a + 1, [a]), which sets up a
>> cell b that shall return a + 1, and where the [a] is used
>> in the constructor to tell a to add b to a's update list
>> then this seems like no big deal.
>> 
>> And doing that doesn't seem so bad - now when the programmer
>> is writing b he has to decide that it should return a + 1
>> and also explicitly state that b shall depend on a; this
>> is all nice and localized, it's still _b_ telling _a_ to
>> add b to a's update list, and the programmer only has
>> to figure out what _b_ depends on when he's writing _b_.
>> Doesn't seem so bad. 
>> 
>> But of course it would be better to be able to pass just 
>> something morally equivalent to (b, a + 1) to whatever 
>> constructor and have the system figure out automatically 
>> that since b returns a + 1 it has to add a to b's update 
>> list. There must be some simple trick to accomplish that 
>> (using Python, without parsing code).
>
>Right, you do not want to parse code. It really would not work as 
>powerfully as Cells, which notice any dynamic access to another cell 
>while a rule is running. So my rule can call a function on "self" (the 
>instance that wons the slot being calculated, and since self can have 
>pointers to other instances, the algorithm can navigate high and low 
>calling other functions before finally reading another ruled slot. You 
>want to track those.
>
>> Exactly what the trick is I 
>> don't see immediately.
>
>To compute a value for a 

Re: ascii to latin1

2006-05-09 Thread Richie Hindle

[Serge]
> def search_key(s):
> de_str = unicodedata.normalize("NFD", s)
> return ''.join(cp for cp in de_str if not
>unicodedata.category(cp).startswith('M'))

Lovely bit of code - thanks for posting it!

You might want to use "NFKD" to normalize things like LATIN SMALL
LIGATURE FI and subscript/superscript characters as well as diacritics.

-- 
Richie Hindle
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do "some action" once a minute

2006-05-09 Thread Diez B. Roggisch
Petr Jakes wrote:

> Thanks for your comment. It is mainly English issue (I am not native
> English speaker).
> 
> OK, to be more specific, I would like to run the code, when the value
> of seconds in the timestamp become say "00".
> The whole code will run in the infinitive loop and other actions will
> be executed as well, so it can not "sleep" for 60 seconds :).

The you have to go for a thread, as otherwise you'd have to create all sorts
of checks in your program to check for the current date. That therad then
could wait like this:


import time
def seconds():
return time.localtime()[5]


def wait_for_seconds(secs=0):
while seconds() != secs:
time.sleep(.5)

def foo(): 
# initial wait
wait_for_seconds()
do_something()
while True:
   time.sleep(50)
   wait_for_seconds
   do_something()


Diez

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


Re: Tkfont.families does not list all installed fonts

2006-05-09 Thread Eric Brunel
On 7 May 2006 23:55:05 -0700, Atul <[EMAIL PROTECTED]> wrote:

> Hi,
>
> I have installed a truetype font (.ttf) on a linux machne (SUSE linux
> 10, KDE) by copying it to my .fonts folder. I can use the font in all
> applications like open-office and firefox browser.
>
> However, I cannot use the font in a python app that I am writing. The
> list returned by Tkfont.families does not contain this particular font.

I don't know the Suse distro, but it seems on "modern" Linux  
distributions, there are 2 levels of font support: the first is the  
"native" X support, the second is provided by the graphical toolkit you're  
using (Qt with KDE, but I think OpenOffice & FireFox use Gtk).  
Unfortunately, tk - and therefore Tkinter - only sees the fonts at the X  
level, and not those at the Qt/Gtk level. But apparently, dropping your  
font file in your .fonts directory only makes the font available for  
Qt/Gtk, not for X. You can check that by running the command xlsfonts in a  
terminal: I really suspect your font will not appear in the list.

To make the font visible at X level, you should make your .fonts directory  
a component of the X font path:
- Go to your .fonts directory.
- Check if the directory contains file named fonts.dir; If it does, check  
that the file contains a line referencing your .ttf file. If it does, skip  
the next 2 steps.
- Create the fonts.scale file describing your TrueType fonts; this is done  
via a distribution-dependent utility, usually mkfontscale or ttmkfdir.
- Create the fonts.dir file describing all the fonts in the directory by  
running mkfontdir in it.
- Add the directory to you X font path by running the command: xset +fp  
~/.fonts

This last step is for testing purposes only, since its results won't  
survive your X session. You'll have to find a way to do it each time you  
log to your session, or each time your X server is restarted. You may also  
add your font file to a global font directory so that X will automatically  
see it when it starts (you'll have to rebuild the fonts.scale and  
fonts.dir files as above).

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


installing numpy

2006-05-09 Thread Gary Wessle
Hi

I am trying to install NumPy in my debian/testing linux
2.6.15-1-686. 

with no numpy for debian/testing, I am left alone, since the
experimental version available by debian will result in a dependency
nightmares,

so after unpacking the downloaded file "numpy-0.9.6.tar.gz"
which crated a directory in my home directory called numpy-0.9.6 with 


-rw-r--r--  1 fred fred 1537 2006-01-21 19:12 LICENSE.txt
-rw-r--r--  1 fred fred  246 2006-01-22 12:44 MANIFEST.in
drwxr-xr-x 11 fred fred 4096 2006-05-08 20:06 numpy
-rw-r--r--  1 fred fred 1472 2006-03-14 19:27 PKG-INFO
-rw-r--r--  1 fred fred  476 2006-01-07 08:29 README.txt
-rw-r--r--  1 fred fred 1164 2006-05-08 20:06 semantic.cache
-rwxr-xr-x  1 fred fred 2516 2006-03-13 18:02 setup.py



$cat README.txt
...
To install:

python setup.py install

The setup.py script will take advantage of fast BLAS on your system if
it can find it.  You can help the process with a site.cfg file.

If fast BLAS and LAPACK cannot be found, then a slower default version
is used. 
...


do I issue the command above "python setup.py install" from the
unpacked directory numpy-0.9.6, would it put the packages in the
correct places in my system, I was under the impression that a
numpy.py is unpacked and then I place it the sys.path but this is not
the case here.


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


Re: Is there any plan to port python to ACCESS Palm Linux Platform?

2006-05-09 Thread Diez B. Roggisch
heidan wrote:

> Another quick question about python and palm?
> 
> As we all have known that ACCESS has planned to build Palm OS on top of

I didn't know.

> Linux, is there any plan to port python to THIS future PALM OS?

How is anybody going to plan something that requires something that is just
planned?

Python runs on lots of platforms, and linux-based ones certainly stand a
good chance for becoming one - but only after the platform exists somebody
can start working on that, don't you think?

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


Re: installing numpy

2006-05-09 Thread Christoph Haas
On Tue, May 09, 2006 at 09:03:31PM +1000, Gary Wessle wrote:
> I am trying to install NumPy in my debian/testing linux
> 2.6.15-1-686. 
> 
> with no numpy for debian/testing, I am left alone, since the
> experimental version available by debian will result in a dependency
> nightmares,

What about "python-numeric"? Found through "apt-cache search numpy".

Kindly
 Christoph
-- 
Please reply to the list - not to me personally. Personal replies are ignored.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enumerating Regular Expressions

2006-05-09 Thread Diez B. Roggisch
> I thought that was the case, I've found a paper on the topic at least.
> Maybe once I've finished some other work I'll give it a shot.  It seems
> like a fairly useful thing to be able to do with a regular expression
> so I just guessed that somebody must have done it already. 

Just wandering: whatfor do you perceive it useful? I've been done quite a
few things with rexes - yet never it occured to me that I'd be in need of
enumeration all the gazillion of possible matches. YMMV - so what for?

Regards,

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


Re: Problem - Serving web pages on the desktop (SimpleHTTPServer)

2006-05-09 Thread Paul Boddie
Ben wrote:
>
> Perhaps someone can help me. For some reason, when my Python script runs
> and loads an HTML page in a new browser window at the local host
> (desktop), the links to my stylesheet and all the images are broken. I
> did check the HTML file by itself...everything loaded fine ;)

I've just had a brief look at the SimpleHTTPServer documentation, and
whilst I may have misunderstood what is required from the admittedly
dry prose, I think I can make a few suggestions.

> Here's my script:
> 
> # File: webbrowser-test.py
>
> import webbrowser, SimpleHTTPServer
> from StringIO import StringIO
>
> f=open('testpage.html', 'rb')
> myPage = f.read()

Here, you're reading the page to serve it up later, but why aren't you
letting the handler fetch the page from the file? Surely, that's what
the handler does in this case.

> class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
>  def send_head(self):
>  self.send_response(200)
>  self.send_header("Content-type", "text/html")
>  self.end_headers()
>  return StringIO(myPage)

Here, you're serving up the page. However, send_head appears not to be
part of the public interface to the handler, so it looks like you're
overriding some fairly fundamental behaviour of the handler which stops
any other file from being served as well. Perhaps you should remove
this method.

> webbrowser.open("http://127.0.0.1:8000";, new=0, autoraise=1)
> SimpleHTTPServer.test(MyRequestHandler)
>
> 
>
> Here's my sample directory:
> -
> webbrowser-test.py
> testpage.html
> m_files/
> |_stylesheet.css
> |_logo.gif
> 

With testpage.html in the current directory, without the send_head
method, you should still get the page served up. However, you need to
make sure that the files in the subdirectory are referenced properly in
your page: something like "m_files/logo.gif" should cause the logo to
be fetched.

> Thanks for having a look. My next step is to process form input using
> AJAX. I'll post working snippets of code here as I progress.

Good luck!

Paul

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


Python editor recommendation.

2006-05-09 Thread DeepBlue
Hi all,

Can any one please recommend me an editor for coding Python. Thank u.
I have Komodo (www.activestate.com) in my mind. Is the editor any good?

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


Re: installing numpy

2006-05-09 Thread Gary Wessle
Christoph Haas <[EMAIL PROTECTED]> writes:

> On Tue, May 09, 2006 at 09:03:31PM +1000, Gary Wessle wrote:
> > I am trying to install NumPy in my debian/testing linux
> > 2.6.15-1-686. 
> > 
> > with no numpy for debian/testing, I am left alone, since the
> > experimental version available by debian will result in a dependency
> > nightmares,
> 
> What about "python-numeric"? Found through "apt-cache search numpy".

is no longer maintained, notice my previous post titled "Numerical
Python Tutorial errors"

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


Re: Python editor recommendation.

2006-05-09 Thread Fabio Zadrozny
Check http://wiki.python.org/moin/IntegratedDevelopmentEnvironments.

I'd reccommend pydev (http://pydev.sf.net) or the pydev extensions if
you're willing to spend some bucks (http://www.fabioz.com/pydev).

-- FabioOn 5/9/06, DeepBlue <[EMAIL PROTECTED]> wrote:
Hi all,Can any one please recommend me an editor for coding Python. Thank u.I have Komodo (www.activestate.com) in my mind. Is the editor any good?regards.--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python editor recommendation.

2006-05-09 Thread imcs ee
free and vim or wingide
On 5/9/06, DeepBlue <[EMAIL PROTECTED]> wrote:
Hi all,Can any one please recommend me an editor for coding Python. Thank u.I have Komodo (
www.activestate.com) in my mind. Is the editor any good?regards.--http://mail.python.org/mailman/listinfo/python-list

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

eval and exec in an own namespace

2006-05-09 Thread Jens
Hi,

has anyone an idea why the following code does not work.


s = """
def a(n):
  return n*n

def b(t):
  return a(t)
"""

ns = {}
exec(s, {}, ns)
eval("b(2)", ns, {})

executing this script raises an exception (NameError: global name 'a'
is not defined) in the last line.

Hope for your help.

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


Re: ascii to latin1

2006-05-09 Thread Luis P. Mendes
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Richie Hindle escreveu:
> [Serge]
>> def search_key(s):
>> de_str = unicodedata.normalize("NFD", s)
>> return ''.join(cp for cp in de_str if not
>>unicodedata.category(cp).startswith('M'))
> 
> Lovely bit of code - thanks for posting it!
> 
> You might want to use "NFKD" to normalize things like LATIN SMALL
> LIGATURE FI and subscript/superscript characters as well as diacritics.
> 

Thank you very much for your info.  It's a very good aproach.

When I used the "NFD" option, I came across many errors on these and
possibly other codes: \xba, \xc9, \xcd.

I tried to use "NFKD" instead, and the number of errors was only about
half a dozen, for a universe of 60+ names, on code \xbf.

It looks like I have to do a search and substitute using regular
expressions for these cases.  Or is there a better way to do it?


Luis P. Mendes
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFEYINaHn4UHCY8rB8RAqLKAJ0cN7yRlzJSpmH7jlrWoyhUH1990wCgkxCW
9d7f/FyHXoSfRUrbES0XKvU=
=eAuO
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


What to use for adding syntax for hierarcical trees, metaclasses, tokenize.py or PLY?

2006-05-09 Thread glomde
Hi I would like to extend python so that you could create hiercical
tree structures (XML, HTML etc) easier and that resulting code would be
more readable.

The syntax i would like is something like the below:

# Example creating html tree

'*!*' is an operator that creates an new node
'*=*' is an operator that sets an attribute.

bodyNode = body()

*!* bodyNode:
  *=* color = blue
  *=* bg  = white
  for i in headings:
 *!* H1(heading[i]):


This would translate to something like this in python:
bodyNode = body()
if True:
   bodyNode.attr['color'] = blue
   bodyNode.attr['bg'] = white
   for i in headings:
 if True:
bodyNode.append(H1(heading[i]))

I think that with the added syntax you get better overview on how your
tree looks like.

But the thing is how to implement my added syntax. I dont want to mess
with Python source code to add the syntax. So I searched a bit on the
net and think there might be three alternatves.

1. MetaClasses. I tried to understand them but my head almost exploded
:-). But my conclusion was that it is not possible with metaclasses.
Since this is a real syntax change.

2. Tokenize.py. I modify tokenize.py to recognize my new operators
'#!#' and '#=#' and then I write a parser that exports the code. This
option I understand somewhat how to implement. But I would reduce my
own code for the parser, so is there any parser that can handle
tokenize.py input? So that I could somehow write rules for my code.

3. Use PLY or any other python parser. Write rules for my language. But
would I need to writerules that can handle the whole python
languager? Then this seems to be overkill. I would just
like to recognize my added syntax and convert that. So I would really
like to have a rule file that handles python and then add rules for my
syntax. Are there any Python rule file for the python language and a
python parser for it? Then I could just add my syntax to the rule file
and be able to create the output.

I would be very thankfull for any hints or thougts on how to do it.

Best regards,

G

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


Re: Multi-line lambda proposal.

2006-05-09 Thread Antoon Pardon
Op 2006-05-09, Scott David Daniels schreef <[EMAIL PROTECTED]>:
> Kaz Kylheku wrote:
>> I've been reading the recent cross-posted flamewar, and read Guido's
>> article where he posits that embedding multi-line lambdas in
>> expressions is an unsolvable puzzle.
>> 
>> So for the last 15 minutes I applied myself to this problem and come up
>> with this off-the-wall proposal for you people. Perhaps this idea has
>> been proposed before, I don't know.
>
> Well, ask yourself, what is the complexity, and what is the
> benefit.  You are solving a problem that causes very little
> pain, and introducing a mechanism that is likely to inspire
> thousands of lines of unmaintainable code.  Essentially, a
> rule that says, "if it is not a simple expression, pick a
> name for it" is just not a bad idea.

Well I guess that seems a good rule of thumb.

The problem is that even a simple "expression" sometimes requires
a name in python or turns it into a more complex function. 

Take the following example:

def incr_cnt_by_one(obj):
  obj.cnt += 1

IMO that is simple enough not to require a name. But it is almost
impossible to put this behaviour in a lambda. If you do you end
up with something like:

  lambda obj: setattr(obj, 'cnt', obj.cnt + 1)


So maybe a general lambda is indeed impossible in python. A pity
IMO, but not that big a deal. 

But the limit that certain statements are not expressions makes
that you sometimes require a name even with some simple stuff
like:

  def Raise_ValueError():
raise ValueError

  RegisterErrorFunction(Raise_ValueError)

What would be so horrible if we could do the following:

  RegisterErrorFunction(lambda: raise ValueError)

or

  treat_all(aList, lambda obj: obj.cnt += 1)

-- 
Antoon Pardon

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


Re: installing numpy

2006-05-09 Thread Christoph Haas
On Tue, May 09, 2006 at 09:43:50PM +1000, Gary Wessle wrote:
> Christoph Haas <[EMAIL PROTECTED]> writes:
> 
> > On Tue, May 09, 2006 at 09:03:31PM +1000, Gary Wessle wrote:
> > > I am trying to install NumPy in my debian/testing linux
> > > 2.6.15-1-686. 
> > > 
> > > with no numpy for debian/testing, I am left alone, since the
> > > experimental version available by debian will result in a dependency
> > > nightmares,
> > 
> > What about "python-numeric"? Found through "apt-cache search numpy".
> 
> is no longer maintained, notice my previous post titled "Numerical
> Python Tutorial errors"

Are you sure? The last update of the Debian package was slightly over a
month ago (http://packages.qa.debian.org/p/python-numeric.html).

And the description text reads:
"""
Description: Numerical (matrix-oriented) Mathematics for Python
 The Numeric Extensions to Python (NumPy) ...
"""

And finally the /usr/share/doc/python-numeric/copyright.Debian reads:
"It was downloaded from http://numpy.sourceforge.net/";

Kindly
 Christoph

P.S.: Your mail client seems break the references. Your reply doesn't show
  up as a proper followup to my posting.
-- 
Please reply to the list - not to me personally. Personal replies are ignored.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enumerating Regular Expressions

2006-05-09 Thread Tim Chase
> Why are people getting stuck on infinite regular
> languages?  I've made it quite clear that I'm only really
>  interested in doing this for finite languages, but that
> shouldn't matter anyway.

The power of regular expressions is that they define a 
consice means to encapsulate an infinite number of inputs. 
If you're not tapping this power, the general wisdom is to 
not use regular expressions.

That said, unless you can ensure you don't have an infinite 
grammer (in particular, no asterisks or plus-signs or 
unbounded ranges like "{4,}"), you then have the problem of 
how to navigate that infinite set.

Taking for example the most common/simple regexp:

".*"

That matches any and every string.  There's a whole library 
of Congress for which every written work will match that 
string.  It sounds a lot like Jorge Luis Borges's 1956 "The 
Library of Babel".

Do you begin searching depth-first with "a" and then "aa" 
and then "aaa"?  Or do you begin breadth-first with "a", 
then "b"...then "z", then "aa", "ab", ...?  Depth-first is 
far more efficient when searching a branching set of data, 
but when you have infinite depth, it will take a while ;) 
Alternatively, you can use some sort of iterative-deepening 
search which puts an increasing bound on how deep the 
depth-first search will go before giving up for that 
particular iteration.  Googling on "iteritave deepening" 
should bring back some ideas for that one.

If you truely have a finite grammer, it would be feasible to 
write some sort of parser, ugly as it might be.  As a first 
pass, I'd have my parser emit python code to write N nested 
loops to try each combination of each element, so something like

"[a-zA-Z_][a-zA-Z0-9_]"

became something like

def tries():
s1 = set(range(ord('a'),ord('z')+1))
s1.add(range(ord('A'),ord('Z')+1))
s1.add(ord('_'))
s2 = set(range(ord('a'),ord('z')+1))
s2.add(range(ord('A'),ord('Z')+1))
s2.add(range(ord('0'),ord('9')+1))
s2.add(ord('_'))
for a1 in s1:
for a2 in s2:
yield "%s%s" % (chr(a1), chr(a2))

Thus, the input regexp would generate python code that you 
could then include in your project.  Ugly, but a possible 
solution.  There are lots of peculiarities though that would 
need to be handled.  Branching, escaped characters in 
character sets (well, escaping in general is a headache).

An alternative might be brute-forcing your regexp:

for a1 in range(0,256):
for a2 in range(0,256):
s = "%s%s" % (chr(a1),chr(a2))
m = re.match(s)
if m:
yield s

nested to however deep you're interested in.

All will be slow.  All are pretty ugly.

-tkc





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


Re: Econometrics in Panel data?

2006-05-09 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
DeepBlue  <[EMAIL PROTECTED]> wrote:
>so are you saying that Python is not an appropriate language for doing 
>econometrics stuff?
>
>
>Dennis Lee Bieber wrote:
>> On Tue, 09 May 2006 05:58:10 +0800, DeepBlue <[EMAIL PROTECTED]> declaimed 
>> the
>> following in comp.lang.python:
>> 
>>> Hi all,
>>>
>>> I am new to Python. Just wondering can Python able to do econometric 
>>> regression in either Time-series or pooled (panel) data? As well as test 
>>> for hetero, autocorrelation, or endogeneity?
>> 
>>  Can you do such in FORTRAN, COBOL, SNOBOL, APL, C, Matlab, Maple,
>> Excel, Turing Machine? Most likely...
>> 
>>  Is there a pre-built library to compute such? No idea...
.
.
.
While I count on Dennis to speak for himself, I'll interrupt
and say that, yes, Python is an appropriate language for
econometrics--but not an ideal one.

There's been quite a bit of Python-based work on financial
analytics in the past.  I don't have a convenient handle on
who all has done this, and what they've done, but I'm certain
that research will yield results.  Python boasts quite a few
general advantages that make it apt for these tasks.

There is not, however, a readily-accessible library targeted
for this sort of work.  If I had the opportunity to work in
econometrics now, I'd think seriously about R, Lisp, and
Mathematica, and see what's available among the functional
languages, along with Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's DSLs

2006-05-09 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Alex Martelli <[EMAIL PROTECTED]> wrote:
>Cameron Laird <[EMAIL PROTECTED]> wrote:
>   ...
>> On this one isolated matter, though, I'm confused, Alex:  I sure
>> think *I* have been writing DSLs as specializations of Python,
>> and NOT as "a language in its own right".  Have I been fooling
>> myself, or are you making the point that Lisp-based DSLs live in
>> a larger syntactic universe than Python's, or ...?
>
>With Lisp (or Scheme, for that matter), a DSL "lives" in exactly the
>same world as the base language, while being able to add or tweak
>whatever syntax it needs; with Python (or C++ or Java, for that matter),
>a DSL is either a completely separate beast (parsed, compiled, perhaps
>interpreted in the "host" language), or else it uses exactly the same
>syntax as used in the host language.  To rapidly build, experiment with,
>and tweak, DSL's, a language with macros is thus advantaged.
>
>As to how crucial that is for _production_ (as opposed to _research_)
>purposes, well, obviously I prefer having no macros (or else I'd use
>some form of Lisp, or perhaps Dylan -- at least for my own private
>purposes, such as my long-standing personal research into the
>fundamentals of contract bridge -- while in fact I prefer to use Python
>for those purposes just as for others).  But that doesn't make me blind
>to the advantages of macros for DSL-building purposes (if I was totally
>sold on both Python AND macros, I think I might build a macro
>preprocessor on top of Python -- the current ASL-based compiler probably
>makes that task much more feasible than it used to be -- but, macros
>would be somewhat complicated as in Dylan, not extremely easy as in
>Scheme [[or, I guess, Common Lisp, though I have no real experience with
>those -- on the surface they look murkier than Scheme's, but that may be
>just an issue of habit on my part]]).
>
>
>Alex

Ah!  I understand much better now.

You correctly distinguish, say, Lisp, Dylan, ... from Python, C,
Java, ... for their syntactic aptness at construction of DSLs.
I don't want that to mislead readers, though, who might thus fail
to see how Python *is* different from C, Java, ..., in its
convenience for implementation of a particular kind of Python-
looking DSL.  As you know, it's easy (if heavy with security
consequences) in Python to eval(), and it's not in C or Java.
The Python run-time builds in a complete interpreter, and that's
different from the base functionality of C or Java.

A consequence is that, in Python, it's an exercise for a beginner
to write, say an assembler whose syntax is a sequence of function
calls (http://www.unixreview.com/documents/s=9133/ur0404e/ >).
C or Java can't really boast the same.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Deferred Evaluation in Recursive Expressions?

2006-05-09 Thread birchb
While working on type expressions I am rather stuck for a
way to express recursive types.  A simple example of this is a
singly-linked list of integers. In some languages you have compiler
syntax
which suspends evaluation so you can have recursive types. e.g.

   typedef Linked_List := int, Linked_List

In LISP I would use a macro.

I have tried using classes:

   class Linked_List(object):
 typedef = (int, Linked_List)

The closest I have got in Python is the following:

   Linked_List = (int, lambda: Linked_List)  # linked list of int

this is OK, because lambda makes closure which is not executed. However
it required the user of the type expression to call any lfunctions
found whilst traversing the tree.

To make this a little more OO, I could use a constructor to wrap the
function:

   Linked_List = (int, recursive(lambda: Linked_List))  # linked
list of int

but I am not satisfied with the "look".

Any suggestions?

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


import in execv after fork

2006-05-09 Thread Rotem
Hello,

We have been encountering several deadlocks in a threaded Python
application which calls subprocess.Popen (i.e. fork()) in some of its
threads.

This has occurred on Python 2.4.1 on a 2.4.27 Linux kernel.

Perliminary analysis of the hang shows that the child process blocks
upon entering the execvp function, in which the import_lock is acquired
due to the following line:

def _execvpe(file, args, env=None):
from errno import ENOENT, ENOTDIR
...

It is known that when forking from a pthreaded application, acquisition
attempts on locks which were already locked by other threads while
fork() was called will deadlock.

Due to these oddities I was wondering if it would be better to extract
the above import line from the execvpe call, to prevent lock
acquisition attempts in such cases.

I'd appreciate any opinions you might have on the subject.


Thanks in advance,

Rotem

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


Re: List of lists of lists of lists...

2006-05-09 Thread bruno at modulix
Ángel Gutiérrez Rodríguez wrote:
> I would like to have a list of lists N times deep, and my solution is (in
> pseudocode):
> 
> def deep(x):
>   a=[x]
>   return a

Hint : what's exactly the difference between deep(x) and [x] ?

> mylist=[]
> for N: mylist=deep(mylist)
> 
> Is there a more elegant way to do it?

for N:
  mylist = [mylist]


> The maine idea is: from a list having the numbre of steps along N
> dimensions, generate a list with an item at each possible point.
> 
> Example 1: N=2  list=[2,3]  result=[[1,2],[1,2],[1,2]]
> Example 2: N=3  list=[3,1,2]  result=[[[1,2,3]],[[1,2,3]]]

I'm afraid I don't understand. Could you forgive my stupidity and
re-explain this a bit more clearly ?

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: installing numpy

2006-05-09 Thread Christoph Haas
(Replying to my own posting... how I hate that...)

On Tue, May 09, 2006 at 02:07:15PM +0200, Christoph Haas wrote:
> On Tue, May 09, 2006 at 09:43:50PM +1000, Gary Wessle wrote:
> > Christoph Haas <[EMAIL PROTECTED]> writes:
> > 
> > > On Tue, May 09, 2006 at 09:03:31PM +1000, Gary Wessle wrote:
> > > > I am trying to install NumPy in my debian/testing linux
> > > > 2.6.15-1-686. 
> > > > 
> > > > with no numpy for debian/testing, I am left alone, since the
> > > > experimental version available by debian will result in a dependency
> > > > nightmares,
> > > 
> > > What about "python-numeric"? Found through "apt-cache search numpy".
> > 
> > is no longer maintained, notice my previous post titled "Numerical
> > Python Tutorial errors"
> 
> Are you sure? The last update of the Debian package was slightly over a
> month ago (http://packages.qa.debian.org/p/python-numeric.html).

Yes, you are right. "python-numeric" refers to NumPy but contains the
"Numeric" version of it (24-2). It's pretty misleading.

I'll ask the package maintainer about the status of python-numpy in Debian
and hopefully come back with news.

Kindly
 Christoph
-- 
Please reply to the list - not to me personally. Personal replies are ignored.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What to use for adding syntax for hierarcical trees, metaclasses, tokenize.py or PLY?

2006-05-09 Thread Michele Simionato
glomde wrote:


You should look at the compiler package and at the new AST in Python
2.5.
For easy things tokenize could be enough, though. Notice that in Python
2.5 tokenize
grew a new 'untokenize' function which is pretty useful. See
http://docs.python.org/dev/lib/module-tokenize.html for examples.


   Michele Simionato

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


Re: import in execv after fork

2006-05-09 Thread Rotem
Another workaround could be re-assigning a new lock to import_lock
(such a thing is done with the global interpreter lock) at
PyOS_AfterFork or pthread_atfork.

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


Re: installing numpy

2006-05-09 Thread Raymond L. Buvel
Gary Wessle wrote:
> Hi
> 
> I am trying to install NumPy in my debian/testing linux
> 2.6.15-1-686. 
> 


When installing from source on a Debian system, you want the installed
package to wind up in /usr/local/lib/python2.x/site-packages (where x
represents the version of Python you are running the installer from).
This allows you to keep it separate from the apt managed directories and
allows for easy removal/upgrade.  So the command you want to execute
from root is

python setup.py install --prefix=/usr/local

By the way, to get NymPy to use the high-performance libraries, you must
install these libraries and the associated -dev packages before running
the Python install.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why list.sort() don't return the list reference instead of None?

2006-05-09 Thread bruno at modulix
Lawrence Oluyede wrote:
> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> 
> 
>>However, I wonder why L.sort() don't return the reference L, the
>>performance of return L and None may be the same. 
> 
> 
> It's not "the same". sort() does not return anything.

Yes it does : it returns the None object.

> 
>>Why?
>  
> I've just explained to you and so the others: by default operations on mutable
> objects are in place.

this is pure non-sens :

class MyList(list):
   def sort(self):
 return sorted(self)

This is a mutable object, and the sort() is not in place.

class MyObj(object):
   def __init__(self, name):
 self.name = name

   def sayHello(self):
 return "hello from %s" self.name

This is another mutable object, and I fail to see how 'in place' could
sensibly have any meaning when applied to sayHello().

Also, and FWIW, the fact that a method modifies the object it's called
on doesn't technically prevent it from returning the object:

class MyOtherList(list):
  def sort(self, *args, **kw):
list.sort(self, *args, **kw)
return self

> s = "abc"
> s.upper()
> 
> does return another string. String are immutable references.

Strings are immutable *objects*.




-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ascii to latin1

2006-05-09 Thread Richie Hindle

[Luis]
> When I used the "NFD" option, I came across many errors on these and
> possibly other codes: \xba, \xc9, \xcd.

What errors?  This works fine for me, printing "Ecoute":

import unicodedata
def search_key(s):
de_str = unicodedata.normalize("NFD", s)
return ''.join([cp for cp in de_str if not
unicodedata.category(cp).startswith('M')])
print search_key(u"\xc9coute")

Are you using unicode code point \xc9, or is that a byte in some
encoding?  Which encoding?

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


Re: Why list.sort() don't return the list reference instead of None?

2006-05-09 Thread bruno at modulix
vbgunz wrote:
> to throw fire on the fuel (:P), you can get the value back to an
> in-place mutable change with a single expression...
> 
> mylist = [2,3,4,1]
> print mylist.sort() or mylist
> 
> might not be too pythonic or maybe it is. I guess depends on what side
> of the glass you might wish to view the solution :)

Anyway, please do us a favor : avoid using such a thing in production
code !-)



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Accessing std::wstring in Python using SWIG

2006-05-09 Thread Shankar
Hello,

I have a C++ dll with one class which has one public function.
This function returns an std::list as an argout.
I am using SWIG to generate Python extensions for this dll.

I have the following code in python to access the string from the list.

.
.
for item in myList:
  print str(item)
.
.

When I run this program I see that the address of the string is printed, but 
not the actual content.
Within Python code how can I dereference this wstring pointer to actually 
print the value and not the address.

Thanks in advance,
With best regards,
Shankar 


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


Re: ascii to latin1

2006-05-09 Thread Serge Orlov
Richie Hindle wrote:
> [Serge]
> > def search_key(s):
> > de_str = unicodedata.normalize("NFD", s)
> > return ''.join(cp for cp in de_str if not
> >unicodedata.category(cp).startswith('M'))
>
> Lovely bit of code - thanks for posting it!

Well, it is not so good. Please read my next message to Luis.

>
> You might want to use "NFKD" to normalize things like LATIN SMALL
> LIGATURE FI and subscript/superscript characters as well as diacritics.

IMHO It is perfectly acceptable to declare you don't interpret those
symbols.  After all they are called *compatibility* code points. I
tried "a quater" symbol: Google and MSN don't interpret it. Yahoo
doesn't support it at all.

NFKD form is also more tricky to use. It loses semantic of characters,
for example if you have character "digit two" followed by "superscript
digit two"; they look like 2 power 2, but NFKD will convert them into
22 (twenty two), which is wrong. So if you want to use NFKD for search
your will have to preprocess your data, for example inserting space
between the twos.

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


Re: ascii to latin1

2006-05-09 Thread Serge Orlov
Luis P. Mendes wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> Richie Hindle escreveu:
> > [Serge]
> >> def search_key(s):
> >> de_str = unicodedata.normalize("NFD", s)
> >> return ''.join(cp for cp in de_str if not
> >>unicodedata.category(cp).startswith('M'))
> >
> > Lovely bit of code - thanks for posting it!
> >
> > You might want to use "NFKD" to normalize things like LATIN SMALL
> > LIGATURE FI and subscript/superscript characters as well as diacritics.
> >
>
> Thank you very much for your info.  It's a very good aproach.
>
> When I used the "NFD" option, I came across many errors on these and
> possibly other codes: \xba, \xc9, \xcd.

What errors? normalize method is not supposed to give any errors. You
mean it doesn't work as expected? Well, I have to admit that using
normalize is a far from perfect way to  implement search. The most
advanced algorithm is published by Unicode guys:
 If you read it you'll understand
it's not so easy.

>
> I tried to use "NFKD" instead, and the number of errors was only about
> half a dozen, for a universe of 60+ names, on code \xbf.
> It looks like I have to do a search and substitute using regular
> expressions for these cases.  Or is there a better way to do it?

Perhaps you can use unicode translate method to map the characters that
still give you problems to whatever you want.

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


Re: Python editor recommendation.

2006-05-09 Thread BartlebyScrivener
I'm on Windows XP, and I like Komodo a lot. It does php, html, perl,
python, ruby etc. It's just a tad slow to load (takes about 10 seconds
on my AMD Athlon 2700), but I usually leave it on all day, so I don't
notice. If you're on Linux you might ask others. 

rpd

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


Re: Enumerating Regular Expressions

2006-05-09 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> Hi all,
> 
> Does anybody know of a module that allows you to enumerate all the
> strings a particular regular expression describes?
> 
> Cheers,
> -Blair
> 

By hand write down a generator that will solve the simplest case of '.*' as a
regexp, and filter the output of that by the given regexp ?

- seriously, that's an interesting question, thanks for asking it ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deferred Evaluation in Recursive Expressions?

2006-05-09 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> While working on type expressions I am rather stuck for a
> way to express recursive types.  A simple example of this is a
> singly-linked list of integers. In some languages you have compiler
> syntax
> which suspends evaluation so you can have recursive types. e.g.
> 
>typedef Linked_List := int, Linked_List
> 
> In LISP I would use a macro.
> 
> I have tried using classes:
> 
>class Linked_List(object):
>  typedef = (int, Linked_List)
> 
> The closest I have got in Python is the following:
> 
>Linked_List = (int, lambda: Linked_List)  # linked list of int
> 
> this is OK, because lambda makes closure which is not executed. However
> it required the user of the type expression to call any lfunctions
> found whilst traversing the tree.
> 
> To make this a little more OO, I could use a constructor to wrap the
> function:
> 
>Linked_List = (int, recursive(lambda: Linked_List))  # linked
> list of int
> 
> but I am not satisfied with the "look".
> 
> Any suggestions?

If you are after lazy evaluation: no - there is no chance python will grow
that (Well, maybe there is some PEP out there - but if, it weould be for
Py3K)

The natural approach for your actual example though would be a generator.
Which, when used in for .. in .. even looks natural to the eye:

def squares():
c =  1
while True:
  yield c ** 2

for n in squares():
... # do something fancy


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


Re: How can I do this with python ?

2006-05-09 Thread Harold Fellermann
Better go for the subprocess module. It is supposed to replace os.popen
and has a much nicer interface.

- harold -

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


Re: hyperthreading locks up sleeping threads

2006-05-09 Thread Roel Schroeven
[EMAIL PROTECTED] schreef:
> Below are 2 files.  The first is a Python program that isolates the
> problem within less than 1 hour (often just a few minutes).  The second
> is a C++ program that shows that the Win32 Sleep() function works as
> expected (ran from Friday afternoon until Monday morning).
> 
> Note, the Python programs hangs (stops responding) with hyper-threading
> turned on (a BIOS setting), but works as expected with hyper-threading
> turned off.
> 
> This problem happens on Windows only (not on Linux for days).

> The operating system is MS Windows XP Professional.

> Could someone with a hyper-threading (or dual core or multi processor)
> CPU please
> confirm this bug?

Doesn't lock up on my system after 6 hours. Windows XP Pro, Python 
2.4.2, hyperthreading Pentium 4.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: Python editor recommendation.

2006-05-09 Thread Dale Strickland-Clark
Vim.

Everything else is Notepad.

DeepBlue wrote:

> Hi all,
> 
> Can any one please recommend me an editor for coding Python. Thank u.
> I have Komodo (www.activestate.com) in my mind. Is the editor any good?
> 
> regards.

-- 
Dale Strickland-Clark
Riverhall Systems www.riverhall.co.uk
We're recruiting. See the web site for details.

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


Re: do "some action" once a minute

2006-05-09 Thread Irmen de Jong
Petr Jakes wrote:
> OK, to be more specific, I would like to run the code, when the value
> of seconds in the timestamp become say "00".
> The whole code will run in the infinitive loop and other actions will
> be executed as well, so it can not "sleep" for 60 seconds :).

Have a look at my 'Kronos' task scheduler (based on the sched module).
Available via http://www.razorvine.net/downloads.html

It may provide the functionality you want.

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


Re: clear memory? how?

2006-05-09 Thread Andrew Gwozdziewycz
Glad to see you're trying Python instead of Matlab. Python was never  
meant to be a replacement for Matlab. It's a general purpose  
programming language like Java, or C#. Though it has very little in  
common with either of those languages. Since Python is a general  
purpose language, if you want Matlab like functionality, you need to  
rely on some other libraries that exist out there. Matplotlib, NumPy  
to name a few will make your Matlab- to Python transition go much  
more smoothly. You might also want to check out ipython, which is  
just a different interface to the python toplevel.


On May 9, 2006, at 4:27 AM, N/A wrote:

> Hi all,
> I am learning Python. Just wondering how to clear saved memory in
> Python? Like in Matlab I can simply use "clear all" to clear all saved
> memory.
>
> Thank u!
> -- 
> http://mail.python.org/mailman/listinfo/python-list

---
Andrew Gwozdziewycz
[EMAIL PROTECTED]
http://www.23excuses.com
http://ihadagreatview.org
http://and.rovir.us


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


Re: ascii to latin1

2006-05-09 Thread Richie Hindle

[Serge]
> I have to admit that using
> normalize is a far from perfect way to  implement search. The most
> advanced algorithm is published by Unicode guys:
>  If you read it you'll understand
> it's not so easy.

I only have to look at the length of the document to understand it's not
so easy.  8-)  I'll take your two-line normalization function any day.

> IMHO It is perfectly acceptable to declare you don't interpret those
> symbols.  After all they are called *compatibility* code points. I
> tried "a quater" symbol: Google and MSN don't interpret it. Yahoo
> doesn't support it at all. [...]
> if you have character "digit two" followed by "superscript
> digit two"; they look like 2 power 2, but NFKD will convert them into
> 22 (twenty two), which is wrong. So if you want to use NFKD for search
> your will have to preprocess your data, for example inserting space
> between the twos.

I'm not sure it's obvious that it's wrong.  How might a user enter
"2" into a search box?  They might enter a genuine
"" in which case you're fine, or they might enter
"2^2" in which case it depends how you deal with punctuation.  They
probably won't enter "2 2".

It's certainly not wrong in the case of ligatures like LATIN SMALL
LIGATURE FI - it's quite likely that the user will search for "fish"
rather than finding and (somehow) typing the ligature.

Some superscripts are similar - I imagine there's a code point for the
"superscript st" in "1st" (though I can't find it offhand) and you'd
definitely want to convert that to "st".

NFKD normalization doesn't convert VULGAR FRACTION ONE QUARTER into
"1/4" - I wonder whether there's some way to do that?

> After all they are called *compatibility* code points.

Yes, compatible with what the user types.  8-)

-- 
Richie Hindle
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enumerating Regular Expressions

2006-05-09 Thread Mirco Wahab
Hi blair.bethwaite

> I want a tool that can enumerate a regex, 
> with support for generating each string
> described by the regex in some predefined order.  

If you run the regex against some target
string, this is gonna be easy (but maybe
not what you want).

If you have the string 'Python' and run
a regex pattern \w+(greedy!) against it,
the result should read:

 match:Python
 match:Pytho
 match:Pyth
 match:Pyt
 match:Py
 match:P
 match:.ython
 match:.ytho
 match:.yth
 match:.yt
 match:.y
 match:..thon
 match:..tho
 match:..th
 match:..t
 match:...hon
 match:...ho
 match:...h
 match:on
 match:o
 match:.n

These are then your strings resulting from "\w+"
This can be extracted by implanting code into
the regex, it generates the strings for you then.

I dont exaclty how to do this in Python,
but in the 'Gem-Liar' you would do a simple:

  $re = qr/
  \w+   ## <-- insert your regex code here
  (?{print "match:",'.'x$-[0],$&,"\n"}) (?!) ## this prints it
  /x;

  $_ = "Python!";   ## against which string
  1 while /$re/g;   ## print them out


This should somehow work in Python
too, but my skills aren't up to the
task ;-)

Regards

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


  1   2   3   >