ANN: Beginning Python (Practical Python 2.0)

2005-10-19 Thread Magnus Lie Hetland
I guess it has actually been out for a while -- I just haven't
received my copies yet... Anyways: My book, Beginning Python: From
Novice to Professional (Apress, 2005) is now out. It is an expanded
and revised version of Practical Python (Apress, 2002). More
information can be found at

  http://hetland.org/writing/beginning-python

Thanks,

- Magnus

-- 
Magnus Lie HetlandPreparing to stand by.
http://hetland.org-- Microsoft Windows
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

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


Re: write a loopin one line; process file paths

2005-10-19 Thread [EMAIL PROTECTED]
it will be added in 2.5 I beleve. At the moment, you can:

predicate and true expression or false expression

like :
 os.paths.exists(something) and print it is there or file not found

I am practicing FP in python and it is in general doable with the help
of itertools and add the needed functions as needed, like scanl/scanl1
etc.

A few things I don't like about python for FP is that it relies heavily
on exception which make these one liners not possible in many case.

Example:

a=[]
a[0] would raise exception

I usually prefer None as a special value which can be handled in normal
flow(filter out, may be x is None and something or otherthing). But
the liberal use of Exception force you to structure the program either
in a very odd way(test with hasattr/haskey etc. before use) or needs
lots of try/except blocks. I am using a python XHTML template Kid which
relies on one-liner and found it very difficult.

However, if you don't really need one-liner but just FP style to
shorten the program, it is fine but I just find the try/except block
quite ugly.

Then there is the side effect of iterators/generators which unless you
know can burn you badly(especially when you are chaining these objects
in these multiple map/filter calls), as mentioned in another post.

Xah Lee wrote:
 Thanks. Here's how the inner loop should be:

 imgPaths2=map(lambda x: (x, re.sub( r^(.+?)-s(\.[^.]+)$,r\1\2, x)),
 imgPaths)

 though, now i just need something like

 map( lambda x: os.path.exists(s)? x[1]:x[0],impPaths2)

 but Pyhton doesn't support the
 test ? trueResult : falseResult
 construct.

 (the semantic of this construct, of a conditional that RETURNS A
 EXPRESSION, all in one line, is important in functional programing.
 Perl supports it. In Mathematica, it's simply the form If[testExpr,
 trueExpr, falseExpr]. In lisp, similar: (if testExpr trueExpr
 falseExpr) )

 is there a way to similate it?

  Xah
  [EMAIL PROTECTED]
 ∑ http://xahlee.org/

 [EMAIL PROTECTED] wrote:
  what do you mean by one line ? Using map/filter, I believe it is
  possible.
 
  Somthing like:
 
  map(lambda (s,f): os.path.exists(f) and f or s,
  map(lambda x: (x, re.replace(x, -s,)), imgPaths)
 
  My regex is a bit rusty but I hope you got the idea of what I am trying
  to do. If there is a way to make the re return without destroying x,
  the outer map is not needed I believe(that is run it twice, once for
  getting the filename to do the testing, then again based on the testing
  result).
 

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

Re: Hygenic Macros

2005-10-19 Thread David Pokorny
Hi,

Thanks - this cookbook entry is very cool!

I am somewhat worried about function call overhead from the infix hack 
though... on second consideration, the infix issue is not as important 
as eventually boosting the speed of the inner loop to which 
matrixmultiply() belongs. For those who are interested in things like 
fast math, I found

http://www.scipy.org/documentation/weave/weaveperformance.html

very eye-opening. For many of the examples cited there, it is possible 
to simply treat the source as a string and then do the necessary macro 
transformations before passing it off to a compiler...

David

Robert Kern wrote:
 David Pokorny wrote:
 
Hi,

Just wondering if anyone has considered macros for Python. I have one 
good use case. In R, the statistical programming language, you can 
multiply matrices with A %*% B (A*B corresponds to pointwise 
multiplication). In Python, I have to type

import Numeric
matrixmultiply(A,B)

which makes my code almost unreadable.
 
 
 Well, dot(A, B) is better. But if you must:
 
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-19 Thread David Schwartz

Roedy Green [EMAIL PROTECTED] wrote in 
message news:[EMAIL PROTECTED]

 On Tue, 18 Oct 2005 20:30:42 -0700, David Schwartz
 [EMAIL PROTECTED] wrote or quoted :

No, taken stupidly. Hint: would or would not MS executives disobeying
the law constitute a betrayal of their obligation to their shareholders?

 You stated it literally as if making maximum profit for the
 shareholders were the only consideration in determining conduct.

No, I did not. I said that their obligation is to their shareholders.

 If that is not what you mean, I think you need to hedge more.

I was perfectly clear. This is a lot of deliberate misunderstanding 
going on in this thread and very little of it is from my side.

DS


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


Re: Microsoft Hatred FAQ

2005-10-19 Thread David Schwartz

Roedy Green [EMAIL PROTECTED] wrote in 
message news:[EMAIL PROTECTED]

 On Tue, 18 Oct 2005 20:34:55 -0700, David Schwartz
 [EMAIL PROTECTED] wrote or quoted :

 As for obligations to community, no, there is no such obligation. An
executive who devoted his company to his community against his 
shareholders'
wishes should be fired. The company exists as a vehicle to execute the
desires of the shareholders. That's why they get to vote on who runs it.

 Why should loyalty to company trump all other loyalties -- family,
 law, species,  community, country, religion ... ?

Perhaps you aren't following the thread, but I was talking about the 
obligations a company has, not the obligations any individual has. And I was 
talking about obligations *to* individuals.

Your criticism would be very appropriate if I said that individuals only 
owe loyalty to companies. But what I said is that Microsoft (a company) owes 
an obligation to its shareholders (people). That is, that companies exist 
purely to benefit people.

It is funny that your accusation is based on assuming I said exactly the 
opposite of what I actually said.

DS


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


Re: Jargons of Info Tech industry

2005-10-19 Thread David Schwartz

Xah Lee [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 Rethink what you are saying. You'll see that what you propose as
 reasons for one, is actually for the other.

Nonsense. It is plain error to change what someone said and claim they 
said it, even if you think that what you are changing isn't important.

DS


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


Re: UI toolkits for Python

2005-10-19 Thread Alex Martelli
Mike Meyer [EMAIL PROTECTED] wrote:

 [EMAIL PROTECTED] (Alex Martelli) writes:
  Mike Meyer [EMAIL PROTECTED] wrote:
  What surprises me is that marketing types will accept turning away -
  what's the current internet user base? 200 million? - 10 million
  potential customers without a complaint. Or maybe they just don't get
  told that that's what's going on.
  In firms where marketing has lots of power, they may indeed well decide
  to pursue those 10 millions by demanding an expenditure of effort
  that's totally out of proportion
 
 What makes you think that the expenditure of effort is totally out of
 proportion? In my experience, that isn't the case - at least if you
 go into it planning on doing things that way. Retrofitting a site that
 was built without any thought but make it work in my favoriter
 browser in my favorite configuration can be a radically different
 thing.

Why, of course -- coding a site to just one browser would be foolish
(though there exist sites that follow that strategy, it's still
despicable).  What I'm talking about is sites that are _supposed_ to be
able to support a dozen browsers, in three or four versions each, not to
mention a dozen features each of which the user might have chosen to
disable (for a total of 2**12 == 4096 possibilities).  Of course, the
site's poor authors cannot possibly have tested the 4096 * 12 * 3.5
possibilities, whence the _supposed_ to be.

We ARE talking about moving from supporting 95% to supporting
(*supposedly*!) 100%, after all -- very much into the long, *LONG* tail
of obscure buggy versions of this browser or that, which SOME users
within those last centiles may have forgotten to patch/upgrade, etc.
And THAT is what makes the effort totally out of proportion (differently
from the effort to go from 60% to 95%, which, while far from negligible,
is well within sensible engineering parameters).


  Maybe that's part of the explanation for the
  outstanding success of some enterprises founded by engineers, led by
  engineers, and staffed overwhelmingly with engineers, competing with
  other firms where marketing wield power...?
 
 You mean like google? Until recently, they're an outstanding example
 of doing things right, and providing functionality that degrades
 gracefully as the clients capabilities go down.

I'm not sure what you mean by until recently in this context.  AFAIK,
we've NEVER wasted our efforts by pouring them into the quixotic task of
supporting *100%* of possible browsers that may hit us, with the near
infinite number of combinations of browsers, versions and disabled
feature that this would require.  One may quibble whether the target
percentage should be, say, 93%, 95%, or 97%, and what level of
degradation can still be considered graceful around various axes, but
the 100% goal which you so clearly imply above would, in my personal
opinion, be simply foolish now, just as it would have been 3 years ago.


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


Re: Microsoft Hatred FAQ

2005-10-19 Thread Luke Webber
David Schwartz wrote:
 Roedy Green [EMAIL PROTECTED] wrote in 
 message news:[EMAIL PROTECTED]
On Tue, 18 Oct 2005 20:30:42 -0700, David Schwartz
[EMAIL PROTECTED] wrote or quoted :
 
   No, taken stupidly. Hint: would or would not MS executives disobeying
the law constitute a betrayal of their obligation to their shareholders?
 
You stated it literally as if making maximum profit for the
shareholders were the only consideration in determining conduct.
 
 No, I did not. I said that their obligation is to their shareholders.

As much as I hate to jump in on this thread, well I'm gonna...

I think you'll find that companies have all manner of legal obligations. 
Certainly to their shareholders, but beyond that they have an obligation 
  to their clients, who pay them for their services, and to any 
individual or entity which might be harmed by their actions.

A classic case in point would be Philip Morris, who did everything they 
could to protect their shareholders, but who shirked their duty of care 
to their customers and the the public at large. They have since paid 
heavily for that failure.

If that is not what you mean, I think you need to hedge more.
 
 I was perfectly clear. This is a lot of deliberate misunderstanding 
 going on in this thread and very little of it is from my side.

All that means to me is that your misunderstanding is not deliberate. g

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


Re: global interpreter lock

2005-10-19 Thread Tommy . Ryding
Thanks,
PyThread_release_lock() is implemented in all thread_xxx.h files.

So I thought right but specified my question like a stupid ;)

//T

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


Re: Tkinter or Python issue?

2005-10-19 Thread Eric Brunel
On Tue, 18 Oct 2005 22:30:33 -0400, Ron Provost [EMAIL PROTECTED] wrote:

 Hello,

 I'm using python 2.4.2 on Win XP Pro.  I'm trying to understand a behavior
 I'm seeing in some Tkinter code I have.  I've reduced my question to a small
 piece of code:


 #BEGIN CODE
 #
 import Tkinter as Tk
 import tkFont

 sampleText = Here is a test string.  This is more text
 Here is a second line of text.  How much
 more can I type.  I can't think of anything else to type.
 

 root = Tk.Tk( )
 t = Tk.Text( root )
 t.pack( )

 t.insert( Tk.END, sampleText )

 t.tag_config( 'AB', font=tkFont.Font( family='ariel', size=24,
 weight=tkFont.BOLD ) )
 t.tag_config( 'TBU', font=tkFont.Font( family='times', size=10,
 weight=tkFont.BOLD, underline=1 ) )

Here is what I think is happening:
- The first tag_config creates a font using tkFont.Font. At tcl level, this 
font is not known as an object as in Python, but just as a font name, which is 
a string. This name happens to be built using the internal identifier for the 
Python object.
- Once this tag_config is over, no Python variable references your tkFont.Font 
instance anymore. It is is fact still known at tcl level (via the font name), 
but Python doesn't know that. So the reference counter for your tkFont.Font 
instance falls to 0, and the object is discarded.
- The second tag_config seems to create a new font using tkFont.Font. 
Unfortunately, since the previous font has been discarded, the space occupied 
by this font is reused for the new font. So the new font happens to have the 
same internal identifier as the font object created by the first tkFont.Font. 
So its name is in fact the same as your previous font, and is registered as 
such at tcl level. So in fact, you didn't create a new font at tcl level, but 
modified the previous one.

All this actually happens by accident. If you add something allocating some 
memory between the two tag_config, you'll certainly see your code working. It 
works when I run it myself...

[snip]
 f1 = font=tkFont.Font( family='ariel', size=24, weight=tkFont.BOLD )
 f2 = font=tkFont.Font( family='times', size=10, weight=tkFont.BOLD,
 underline=1 )
 t.tag_config( 'AB', font=f1 )
 t.tag_config( 'TBU', font=f2 )

You should now see why it works here: your first tkFont.Font is remembered at 
Python level in a variable. So it is not discarded once the tag_config is over. 
So the second tkFont.Font is not allocated at the same location, so it doesn't 
have the same id, and it doesn't have the same name at tcl level. This is the 
general solution to the problem: keep your fonts in Python variables, so they 
won't be discarded and their names will never be re-used. You could have 
written:

f1 = font=tkFont.Font( family='ariel', size=24, weight=tkFont.BOLD )
t.tag_config( 'AB', font=f1 )
f2 = font=tkFont.Font( family='times', size=10, weight=tkFont.BOLD, underline=1 
)
t.tag_config( 'TBU', font=f2 )

This should still work. The order is not important; it's just the fact that 
your fonts are actually known at Python level which prevents Tkinter to reuse 
their name.

BTW, this is a variant of a well known problem biting newbies regularly, 
documented here:
http://tkinter.unpythonic.net/wiki/Images

It's basically the same problem for images: it does not suffice to reference an 
image at tcl level; it must also be referenced at Python level or it will be 
discarded by Python and you won't be able to use it in your widgets.

HTH
-- 
python -c print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter or Python issue?

2005-10-19 Thread Fredrik Lundh
Eugene Druker wrote:

 tkFont.Font(...) is a class instance, while you need font description.

Font instances are font descriptors.

 f = tkFont.Font(family=ariel, size=24, weight=tkFont.BOLD)
 f
tkFont.Font instance at 0x00A3AC60
 print f
font10726496

 t.tag.config( 'TBU', font=('times', 12, 'bold','underline') )
 t.tag_config( 'AB', font=('arial',24,'bold') )

the problem here is a variation of the old garbage collection problem (Tcl
uses names as references, so the fact that Tk uses an object isn't enough to
keep Python's GC away from it).  the solution is to hold on to the objects
in Python.

/F 



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


Re: Microsoft Hatred FAQ

2005-10-19 Thread Alan Connor
On comp.os.linux.misc, in [EMAIL PROTECTED], Michael Heiming wrote:
body not downloaded

This is your 7th post on this thread, Michael.

You spend a lot of time griping about trolls. Maybe you should
consider not feeding them, you stupid hypocrite.

To all the shit-for-brains trolls that are polluting these groups
with this crap, which I haven't even bothered to read:

I've killfiled every one of your aliases here, and I'm sure that
they aren't the first of your aliases I've killfiled and that
they won't be the last.

I don't hate M$, I LOVE Linux.

As for what YOU punks think about it, I couldn't care less.

Aren't your Mommys coming home soon? You know what will happen
if she finds you playing with her computer again.

AC


-- 
Homepage: http://home.earthlink.net/~alanconnor/
Fanclub: http://www.pearlgates.net/nanae/kooks/alanconnor.shtml
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a raised exception from other thread

2005-10-19 Thread Antoon Pardon
Op 2005-10-18, dcrespo schreef [EMAIL PROTECTED]:
 Before, after, or during the .start() call, or somewhere else?

 I'd like to catch *just after* the .start() call.

 I'm quite sure the problem you are trying to solve can be solved, but
 you are still describing part of the solution you believe you need,
 rather than explaining why you want to do this (which may let us show
 you other, simpler or cleaner ways to accomplish your goals).

 The thing is that I have in ProgramB a class derived from
 threading.Thread, that runs a TCPServer, listening to a port on local
 ip address.

 As you surely know, you have to specify certain parameters when
 instantiating the tcpserver:

 SocketServer.TCPServer(server_address, RequestHandlerClass)
 where server_address is a tuple (ip,port)
 ip has to be one of three modes of values (If I remember well):

 1. A null string ''
Listens on all IP local address

 2. A string containing the local IP address where you want it to listen
Listens only in the specified local IP address

 3. A string containing localhost.
Listens only for connections from localhost.

 Here comes the problem:
 When you specify the case number 2, the IP must be valid for the
 computer where the program runs, otherwise, it raises an exception
 saying that Can't assign requested address.
 The TCPServer class, defined in a module, is ran (instantiatedly) from
 the main program through a started thread. The thread also is in the
 same module as TCPServer class.
 It looks like (it's much more code than this. If you want the whole
 code, tell me):

 MainProgram.py
 ...
 SrvrTCP = module.ThreadedTCPServer(ip,port)
 SrvrTCP.start()
 #Here, I want to know if the TCPServer started well.
 ...


 module.py
 ...
 class ThreadedTCPServer(threading.Thread):

 def __init__(self, ip,port):
 threading.Thread.__init__(self)
 self.ip= ip
 self.port= port

 def run(self):
 TCPServer((self.ip,self.port)) #Here, if the self.ip is
 invalid, it raises an exception.

Just a suggestion, but since it is the main thread you want notified,
you could use signals here. Something like the following:

MainProgram.py

class TCPProblem(Exception):
  pass

def signalcallback(signum, frame):
  raise TCPProblem

signal.signal(signal.SIGHUP, signalcallback)

SrvrTCP = module.ThreadedTCPServer(ip,port)
SrvrTCP.start()
...


module.py

mainpid = os.getpid()

class ThreadedTCPServer(threading.Thread):

def __init__(self, ip,port):
threading.Thread.__init__(self)
self.ip= ip
self.port= port

def run(self):
try:
  TCPServer((self.ip,self.port)) #Here, if the self.ip is invalid, it 
raises an exception.
except ...:
  os.kill(mainpid, signal.SIGHUP)
  
-- 
Antoon Pardon

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


Re: A little help with time calculations

2005-10-19 Thread Steve Holden
iminal wrote:
 what i have so far is :
 
 # Get values needed to make time calculations
 CT = input(input your chronometer time (ex. 07:21:46): )
 CE = input(input your chronometer correction (ex. 00:01:32): )
 CEfastslow = raw_input(is your chronometer correction fast or
 slow: )
 
 #decide either to subtract or add CE from/to CT
 if CEfastslow == fast:
 CEfastslow = CT - CE
 if CEfastslow == slow:
 CEfastslow = CT + CE
 
 but this just doesnt deal with the numbers in time format its acting
 like they are just regualr integers adding them up like regular numbers
 
Well, how is the interpreter supposed to know that they are times? 
Remember that the Python language doesn't have times as a basic data 
type, and input(...) treats what you enter as Python data (unlike 
raw_input()).

 i am trying to figure out what u posted and it seems a little
 complicated im trying to add it in somehow and figure out exactly what
 its doing but still looking for a little easier of a way
 
Well, the code I posted was untested, and I find two things wrong with 
it straight away: Firstly, it won't include leading zeros when 
converting seconds to a time, and secondly it puts the hours, minutes 
and seconds in the wrong order.

 thanks so far
 
The idea, though, is to read strings lime 07:20:44 and convert them 
into something that Python *can* do arithmetic on. I defined a function, 
timetosecs, that would let you do this.

So your program should look something like:

# Put function definitions here ...
CT = raw_input(input your chronometer time (ex. 07:21:46): )
CE = raw_input(input your chronometer correction (ex. 00:01:32): )
CEfastslow = raw_input(is your chronometer correction fast or slow: )

Tsecs = timetosecs(CT)
Esecs = timetosecs(CE)

#decide either to subtract or add CE from/to CT
if CEfastslow == fast:
 CEfastslow = Tsecs - Esecs
if CEfastslow == slow:
 CEfastslow = Tsecs + Esecs

print New time:, secstotime(CEfastslow)

Hope this gets you a bit closer to a solution.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: UI toolkits for Python

2005-10-19 Thread Paul Rubin
[EMAIL PROTECTED] (Alex Martelli) writes:
  You mean like google? Until recently, they're an outstanding example
  of doing things right, and providing functionality that degrades
  gracefully as the clients capabilities go down.
 
 I'm not sure what you mean by until recently in this context.  AFAIK,
 we've NEVER wasted our efforts by pouring them into the quixotic task of
 supporting *100%* of possible browsers that may hit us, with the near
 infinite number of combinations of browsers, versions and disabled
 feature that this would require.

The non-graphics-oriented Google services like search, news, and
groups, have worked perfectly well with lynx until recently.  No
javascript required, no image display required, and no cookies required.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nested escape chars in a shell command

2005-10-19 Thread Juho Schultz
Eli Criffield wrote:
 I'm try run an ssh command in pexpect and I'm having trouble getting
 everything escaped to do what i want.
 
 Here's a striped down script showing what i want to do.
 
 --
 #!/usr/bin/env python
 import pexpect
 import sys
 if len(sys.argv)  3:
 print ssh.py host command
 sys.exit(1)
 
 host = sys.argv[1]
 command = sys.argv[2]
 
 child = pexpect.spawn('''sh -x -c stty -echo ; ssh -t -o
 'StrictHostKeyChecking no' %s '%s' |awk '{print \%s:\$0}' 
 '''%(host,command,host), timeout=30)
 
 child.setlog(sys.stdout)
 child.expect(pexpect.EOF)
 --
 
 The problem in the pexpect.spawn line, It doesn't like the \%s:\ part
 of the awk command. This is necessary so i can see what server the
 command is running on, In the full script the command will be running
 on about 100 servers at a time.
 It parses out into:
 + stty -echo
 + ssh -t -o 'StrictHostKeyChecking no' testserver date
 + awk '{print testserver:$0}'
 It totally strips out the 
 
 The stty -echo is required because part of what the program does is it
 tries to remember any passwords that are asked for, So you can run a
 command like su -c id and it will remember roots password for the
 next
 server and try that. -echo keeps the root password from being echoed to
 the screen.
 
 The second problem with the command is while su -c id works (taking
 out the awk part) running any command with more then one word after the
 -c in su fails, It strips out the '
 like so:
 ./sshexpect testserver su -c 'ls -l /root'
 + stty -echo
 + ssh -t -o 'StrictHostKeyChecking no' testserver 'su -c ls' -l /root
 su: user /root does not exist
 
 I have tried every combination of escaping i can think of can i can't
 get either problem solved.
 
 Any ideas?
 
 Eli
 

You can pass the argument list of your command to
pexpect.spawn(comm, args=['arg1','arg2'])
If the argument list is empty, pexpect tries to get the arguments
from the comm you passed to it. I guess this gives you problems.

Try using the args parameter. 
Simplest would be args=[' '] just to avoid the processing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: write a loopin one line; process file paths

2005-10-19 Thread Xah Lee

[EMAIL PROTECTED] wrote:
 it will be added in 2.5 I beleve. At the moment, you can:

 predicate and true expression or false expression

Ah, i see. Here's the full code again:

# -*- coding: utf-8 -*-
# python

import re, os.path

imgPaths=[u'/Users/t/t4/oh/DSCN2059m-s.jpg',
u'/Users/t/t4/oh/DSCN2062m-s.jpg', u'/Users/t/t4/oh/DSCN2097m-s.jpg',
u'/Users/t/t4/oh/DSCN2099m-s.jpg', u'/Users/t/Icons_dir/icon_sum.gif']

# change the image path to the full sized image, if it exists
# that is, if image ends in -s.jpg, find one without the '-s'.

imgPaths2=[]
for myPath in imgPaths:
p=myPath
(dirName, fileName) = os.path.split(myPath)
(fileBaseName, fileExtension)=os.path.splitext(fileName)
if(re.search(r'-s$',fileBaseName,re.U)):
p2=os.path.join(dirName,fileBaseName[0:-2]) + fileExtension
if os.path.exists(p2): p=p2
imgPaths2.append(p)

imgPaths3 = map( lambda x: os.path.exists(x[1]) and x[1] or x[0],
map(lambda x: (x, re.sub( r^(.+?)-s(\.[^.]+)$,r\1\2, x)),
imgPaths))

print imgPaths2 == imgPaths3

--

 A few things I don't like about python for FP is that it relies heavily
 on exception which make these one liners not possible in many case.
 ...

yeah i know how it feels. I haven't had much experience with Python
yet... but doing it in Perl gets all twisted. (especially when one
tries to use trees as data structure (nested lists) in Perl)

besides syntactical issues, another thing with doing functional
programing in imperative languages is that they become very inefficent.
Functional languages are optimized by various means of functional
programings styles. Doing them in imperative languages usually comes
with a order of execution penalty because imperative language compilers
are usually dumb.

though, one can't totally blame for Python's lack of ability to do
functional programing. Its language's syntax of using indentations for
blocks by design, pretty much is in odds with functional programing's
sequencing of functions and other ways. (such as generic mechanism for
prefix/postfix syntax, or macros or other transformations and patterns,
or heavy reliance on the free flow of expressions/values)

I don't blame Python that it doesn't cater to functional programing BY
DESIGN. But i do hate the mother fucking fuckheads Pythoners for one
thing that they don't know what functional programing really is, and on
the other hand fucking trumpet their righteousness and lies thru their
teeth of their ignorance. (that Guido guy with his Python 3000 article
on his blog is one example, possibly forgivable in that particular
instance. (http://xahlee.org/perl-python/python_3000.html))

(excuse me for lashing out)

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

 like :
  os.paths.exists(something) and print it is there or file not found

 I am practicing FP in python and it is in general doable with the help
 of itertools and add the needed functions as needed, like scanl/scanl1
 etc.

 A few things I don't like about python for FP is that it relies heavily
 on exception which make these one liners not possible in many case.

 Example:

 a=[]
 a[0] would raise exception

 I usually prefer None as a special value which can be handled in normal
 flow(filter out, may be x is None and something or otherthing). But
 the liberal use of Exception force you to structure the program either
 in a very odd way(test with hasattr/haskey etc. before use) or needs
 lots of try/except blocks. I am using a python XHTML template Kid which
 relies on one-liner and found it very difficult.

 However, if you don't really need one-liner but just FP style to
 shorten the program, it is fine but I just find the try/except block
 quite ugly.

 Then there is the side effect of iterators/generators which unless you
 know can burn you badly(especially when you are chaining these objects
 in these multiple map/filter calls), as mentioned in another post.


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

Re: how to return correct value of update stmt

2005-10-19 Thread Steve Holden
[EMAIL PROTECTED] wrote:
 hi
 i use odbc to update a table in a database but i always get return
 value of -1
 even though i tried to return an integer. the table is updated though
 ...
 sql = 
update table
set column = 0
where col = %s
select @@rowcount
 
   % (var1)
 
 try:
 s = odbc.odbc(connectstring)
 cur = s.cursor()
 res = cur.execute(sql)
 s.commit()
 s.close()
 cur.close()
 s = None
 cur = None
 print res
 return res
 except:
 print 'error while processing ', sys.exc_type,sys.exc_value
 
 
 how to properly get a positive return ?
 thanks
 
Is the table actually being updated?

The definition of the cursor.execute() method in

http://www.python.org/peps/pep-0249.html

specifically says Return values are not defined. So if you are seeing 
the database do the right thing I'd stop worrying about the return 
value. If exceptions aren't being raised and the database is doing what 
you want, what's the problem?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Sequence and/or pattern matching

2005-10-19 Thread Séb
Hi everyone,

I'm relatively new to python and I want to write a piece of code who do
the following work for data mining purpose :

1) I have a list of connexion between some computers. This list has
this format :

Ip A   Date Ip B
......  ...
192.168.0.119.10.2005   192.168.0.2
192.168.0.319.10.2005   192.168.0.1
192.168.0.419.10.2005   192.168.0.6
......  ...

2) I want to find if there are unknown sequences of connexions in my
data and if these sequences are repeated along the file :

For example :

Computer A connects to Computer B then
Computer B connects to Computer C then
Computer C connects to Computer A

3) Then, the software gives the sequences it has found and how many
times they appear...

I hope this is clear, point 2) is where I have my main problem. Has
someone an idea where to start and if there's already something coded ?

Thanks

Séb

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


Re: write a loopin one line; process file paths

2005-10-19 Thread [EMAIL PROTECTED]

Xah Lee wrote:
 besides syntactical issues, another thing with doing functional
 programing in imperative languages is that they become very inefficent.
 Functional languages are optimized by various means of functional
 programings styles. Doing them in imperative languages usually comes
 with a order of execution penalty because imperative language compilers
 are usually dumb.

The itertools module and the new generator feature tries to make this
better as it is lazily evaluated, in a sense. But its side effect is
nasty. Usable though need to twist my mind a bit, not like when I do it
in haskell. But the occasion imperative dip makes some of my programs
easier to code.


 though, one can't totally blame for Python's lack of ability to do
 functional programing. Its language's syntax of using indentations for
 blocks by design, pretty much is in odds with functional programing's
 sequencing of functions and other ways. (such as generic mechanism for
 prefix/postfix syntax, or macros or other transformations and patterns,
 or heavy reliance on the free flow of expressions/values)

That I am not sure. haskell also use this indentation but I don't see a
problem about it. One thing I find it odd though is the @decorator
construct. I just don't understand why it is viewed as simple. It
becomes very ugly IMO when there is a number of it, I am doing some web
apps which requres varies decorators(one over the other).

@format
@login_block
@validate
@something
def my_func():

I find it easier to read and under stand in the form of

format(login_block(validate(something(my_func) though haskell's $
and . is even better.

format.login_block.validate.somethin.my_func


 I don't blame Python that it doesn't cater to functional programing BY
 DESIGN. But i do hate the mother fucking fuckheads Pythoners for one
 thing that they don't know what functional programing really is, and on
 the other hand fucking trumpet their righteousness and lies thru their
 teeth of their ignorance. (that Guido guy with his Python 3000 article
 on his blog is one example, possibly forgivable in that particular
 instance. (http://xahlee.org/perl-python/python_3000.html))

That seems to be the case, I mean the design. For fairness, list
comphrehension sometimes looks cleaner, though becomes ugly when you do
the pipe/chain like programming in FP(multiple for). This again is an
odd choice. It seems to be a flattening of multiple line for loop, yet
at the same time python seems to be moving towards being more
explicit(no map/filter/etc as they can be done in for loop).

But I believe Python is designed for easy to code and read and maintain
in mind. One has to admit that without some training, FP is not very
intuitive, my head spin when I see haskell code. A for loop is easier
to understand.

Well, if you want clean FP, you can always try haskell which is getting
better and better in terms of real world module support(file system,
network etc).

 (excuse me for lashing out)
 
  Xah
  [EMAIL PROTECTED]
 ∑ http://xahlee.org/

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

Re: Any 3state Check Tree Ctrl for wxPython available?

2005-10-19 Thread Franz Steinhaeusler
On Mon, 17 Oct 2005 12:14:47 +0200, Petr Prikryl [EMAIL PROTECTED]
wrote:

Hi,

I am experimenting with wxPython on Windows box. 
What I need to implement is a check tree control
with 3 states for each checkbox: unchecked, checked,
gray checked. The status of the checkbox should reflect
the status of the children. When ALL children are checked,
then the status should be checked. When NO children
are checked, the status should be unchecked. When 
SOME children are selected, the status should be
checked with gray background.

I have found something else that could be valuable
after I start understand that:

http://mitglied.lycos.de/drpython/CheckTreeCtrl.tar 


Hello Petr,

It is incidentally from my webpage :)

I uploaded it once, because I didn't find it anywhere
on the web; a person asked for it and I had it on 
my harddisk.

Anyway, is there something similar with 3 states
available around?

To your problem: 

What about enhancing/deriving from CheckTreeCtrl
and exending it?


Thanks for your time and experience,

pepr

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


Re: Sequence and/or pattern matching

2005-10-19 Thread Alex Martelli
Séb [EMAIL PROTECTED] wrote:

 Hi everyone,
 
 I'm relatively new to python and I want to write a piece of code who do
 the following work for data mining purpose :

Essentially, if I understand correctly, you want to detect LOOPS given a
sequence of directed connections A-B.  loop detection and graph
would then be the keywords to search for, in this case.

 2) I want to find if there are unknown sequences of connexions in my
 data and if these sequences are repeated along the file :
 
 For example :
 
 Computer A connects to Computer B then
 Computer B connects to Computer C then
 Computer C connects to Computer A

Does this then imply you're only interested in loops occurring in this
*sequence*, i.e., is order of connections important?  If the sequence of
directed connections was, say, in the different order:

B-C
A-B
C-A

would you want this detected as a loop, or not?


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


dynamical importing

2005-10-19 Thread Joerg Schuster
Hello,

I need to import modules from user defined paths. I.e. I want to do
something
like:

module_dir = sys.argv[1]

my_path = os.path.join(module_dir, 'bin', 'my_module')

from my_path import my_object

Obviously, it doesn't work this way. How would it work?

Jörg Schuster

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


Re: UI toolkits for Python

2005-10-19 Thread Steve Holden
Alex Martelli wrote:
 Mike Meyer [EMAIL PROTECTED] wrote:
[... browser audience discussion ...]
What makes you think that the expenditure of effort is totally out of
proportion? In my experience, that isn't the case - at least if you
go into it planning on doing things that way. Retrofitting a site that
was built without any thought but make it work in my favoriter
browser in my favorite configuration can be a radically different
thing.
 
 
 Why, of course -- coding a site to just one browser would be foolish
 (though there exist sites that follow that strategy, it's still
 despicable).  What I'm talking about is sites that are _supposed_ to be
 able to support a dozen browsers, in three or four versions each, not to
 mention a dozen features each of which the user might have chosen to
 disable (for a total of 2**12 == 4096 possibilities).  Of course, the
 site's poor authors cannot possibly have tested the 4096 * 12 * 3.5
 possibilities, whence the _supposed_ to be.
 
 We ARE talking about moving from supporting 95% to supporting
 (*supposedly*!) 100%, after all -- very much into the long, *LONG* tail
 of obscure buggy versions of this browser or that, which SOME users
 within those last centiles may have forgotten to patch/upgrade, etc.
 And THAT is what makes the effort totally out of proportion (differently
 from the effort to go from 60% to 95%, which, while far from negligible,
 is well within sensible engineering parameters).
 
 
 
Maybe that's part of the explanation for the
outstanding success of some enterprises founded by engineers, led by
engineers, and staffed overwhelmingly with engineers, competing with
other firms where marketing wield power...?

You mean like google? Until recently, they're an outstanding example
of doing things right, and providing functionality that degrades
gracefully as the clients capabilities go down.
 
 
 I'm not sure what you mean by until recently in this context.  AFAIK,
 we've NEVER wasted our efforts by pouring them into the quixotic task of
 supporting *100%* of possible browsers that may hit us, with the near
 infinite number of combinations of browsers, versions and disabled
 feature that this would require.  One may quibble whether the target
 percentage should be, say, 93%, 95%, or 97%, and what level of
 degradation can still be considered graceful around various axes, but
 the 100% goal which you so clearly imply above would, in my personal
 opinion, be simply foolish now, just as it would have been 3 years ago.
 

In mine, too. It's often useful to remember the so-called 80/20 rule 
which, in software terms, I often state as you can get 80% of the 
functionality for 20% of the cost. Among other things I theorise that 
this accounts for the vast numbers of abandoned open source projects 
lurking on the Internet (but let's not follow that red herring any further).

Of course, if the final 20% of a project's functionality accounts for 
80% of the cost then the stark arithmetical truth would be that each 
functionality percentage point costs sixteen times what the first eighty 
points did.

In practice the situation is never linear, and the truth is that there 
is a situation of diminishing returns which rarely justifies supporting 
those final additional hold-outs with obsolete platforms. This is as 
much an economic decision as a marketing one, but a good engineer knows 
instinctively that there is a desirable cut-off point beyond which 
adding further functionality is a waste of engineering effort.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: dynamical importing

2005-10-19 Thread Laurent Rahuel
Hi,

I guess you need to look at __import__

Regards,

Laurent.

Joerg Schuster wrote:

 Hello,
 
 I need to import modules from user defined paths. I.e. I want to do
 something
 like:
 
 module_dir = sys.argv[1]
 
 my_path = os.path.join(module_dir, 'bin', 'my_module')
 
 from my_path import my_object
 
 Obviously, it doesn't work this way. How would it work?
 
 Jörg Schuster

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


Re: Microsoft Hatred FAQ

2005-10-19 Thread Roedy Green
On Tue, 18 Oct 2005 23:16:32 -0700, David Schwartz
[EMAIL PROTECTED] wrote or quoted :

No, I did not. I said that their obligation is to their shareholders.

 If that is not what you mean, I think you need to hedge more.

I was perfectly clear. This is a lot of deliberate misunderstanding 
going on in this thread and very little of it is from my side.


You have a problem because there are many other people saying similar
things to you who mean something much more extreme. If you don't
intend that, you need to be more precise in your language.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-19 Thread Roedy Green
On Tue, 18 Oct 2005 23:18:31 -0700, David Schwartz
[EMAIL PROTECTED] wrote or quoted :

Perhaps you aren't following the thread, but I was talking about the 
obligations a company has, not the obligations any individual has. And I was 
talking about obligations *to* individuals.

To me that makes no sense. Microsoft is an abstraction. It can't do
anything. It can't make decisions. Only the individuals to work for it
or on the board can, though they may do it in Microsoft's name.  If
you want to talk about moral action, obligation etc. you can't divorce
that from the people who do the actions.

-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to organize Python files in a (relatively) big project

2005-10-19 Thread spinner
I have this problem myself, and as I am a recent Python convert my
aproach may not be conventional - but as it is working for me I thought
I would share.

First off you need to split your code into logical objects.  In my case
I have an obvious client and server object,  But within each I have
individual stand alone major objects and so my directory structure
reflects this...

Prog Dir
-- MainApp.py
Bin
__init__.py
--- main.py
--- lib.py
Client
__init__.py
--- main.py
Browser 1
__init__.py
--- main.py
--- B1_file1.py
--- B1_file2.py
Browser 2
__init__.py
--- main.py
--- B2_file1.py
--- B2_file2.py
Server
__init__.py
--- main.py
Server Object 1
__init__.py
--- main.py
--- SO1_file1.py
--- SO1_file2.py
Server Object 2
__init__.py
--- main.py
--- SO2_file1.py
--- SO2_file2.py


Each main.py file is used to call each downstream main.py file be it as
a thread or once only run.  The beauty of this idea is that if I want
to completely change say Server Object 2, I can do whatever I like
within the downstream directory as the only outside call is via an
external reference to the main.py file.

If you have a mind, you could have a library file of common apps held
within the bin directory that you can make available to all downstream
modules.

As I say - it only works if you can logically split your program into
independent blocks.

If there is a more Pythonesque way of doing this I be grateful if
someone could share.

HTH

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


Re: Microsoft Hatred FAQ

2005-10-19 Thread Roedy Green
On Wed, 19 Oct 2005 07:10:55 GMT, Alan Connor [EMAIL PROTECTED]
wrote or quoted :

To all the shit-for-brains trolls that are polluting these groups
with this crap, which I haven't even bothered to read:

A single thread does not pollute a group. It is trivially easy to
ignore a thread.  If your newsreader does not support that feature,
try an different newsreader.  See
http://mindprod.com/jgloss/newsgroups.html

It is a big thread. Obviously people are interested in it even if you
are not.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UI toolkits for Python

2005-10-19 Thread Steve Holden
Claudio Grondi wrote:
 Steve Holden [EMAIL PROTECTED] schrieb im Newsbeitrag
 news:[EMAIL PROTECTED]
 
Claudio Grondi wrote:
[...]
Do I miss here something?


While you are correct in saying (I paraphrase) that HTML interfaces
nowadays can offer a rich graphical interface, it can be quite difficult
to manage state maintenance between the two components (web server, web
client) in the system.


The cause of confusion here is, that HTML interfaces don't necessary
 
 need a
 
web server and HTTP to work. I mean, that Internet Browsers
have an API which allow access to them directly, so they can be used
 
 without
 
a server as a kind of GUI library supporting widgets programmed
in HTML and JavaScript  (I haven't used them yet in this form, but I
 
 think
 
it should be no problem - right or not?).


You are perfectly correct that interfaces can be programmed in the
browser. As has already been said, with the adoption of standards like
CSS2, it's even possible to make such stuff run across multiple browser
platforms (at the moment, though, just try writing an interface that
makes table rows appear and disappear in a cross-browser fashion: you'll
find the stylesheet techniques you need to use for Mozilla and IE are
very different). But this doesn't help you at all if you are trying to
interface to Python logic.

A proper GUI runs all functionality inside a single process, and
allows much easier control over complex interactions, creation of
dynamic dialogues, and so on.

Complex and dynamic is in my eyes possible with HTML and JavaScript, so
 
 I
 
still don't see where is a problem with this approach. I have programmed
already a HTML and JavaScript driven server platform and know about (the
solvable) problems with the back-button and sessions (it is sure not the
easiest way of programming a GUI).
The only disadvantage of not using plugins or Java is, that real time
interactions are not possible, but this is in my eyes usually not the
requirement for a standard kind of GUI with no gaming, no Virtual
 
 Reality
 
and no timing of user response down to milliseconds (but consider, that
 
 with
 
a good speed of connection it is even possible to play blitz chess over
 
 the
 
Internet).


So, back to the subject: with an HTML/Javascript interface, how do you
propose to bolt Python logic into the same process? Or do you admit that
the application that interacts with such an interface either has to be
all JavaScript or in a separate process?
 
 I haven't used it in such configuration yet, but I mean, that it is not a
 bad idea to use local DHTML files (i.e. HTML with JavaScript) combined with
 a Python driven HTTP server like e.g. Karrigell which makes it possible to
 access local files by executing Python scripts triggerred by demand raised
 by submitting to it DHTML form data resulting from user input.
 So mixing JavaScript in local DHTML files for performing what can be done
 with JavaScript inside HTML and a HTTP server capable of executing Python
 scripts will do the job which JavaScript alone can't because of lack of
 access to the local file system and another parts of the computer system on
 which such kind of UI is executed.

Indeed. But this again partitions the problem into client functionality 
and server functionality residing in two separate processes, albeit on 
the same computer, with the previously-mentioned state maintenance 
problems. This issue isn't new, you know.

 Another possible scenario I have in mind is to control the Internet browser
 directly from a Python script using DHTML as a language for definition of
 appearance and specification of necessary data processing of in the browser
 displayed UI. This way the Internet browser and HTML with JavaScript can be
 considered an UI toolkit for use in Python.
 Hope with this above to have got Python back on topic.
 
That is, I suppose, a possibility, but you certainly can't claim it 
would be platform-independent. Unless you know of some common control 
interface respected by both Internet Exploder and Firefox ;-)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: dynamical importing

2005-10-19 Thread Fredrik Lundh
Joerg Schuster wrote:

 I need to import modules from user defined paths. I.e. I want to do
 something like:

 module_dir = sys.argv[1]

 my_path = os.path.join(module_dir, 'bin', 'my_module')

 from my_path import my_object

 Obviously, it doesn't work this way. How would it work?

some alternatives:

- if you want the modules to remain imported:

try:
sys.path.insert(0, os.path.join(module_dir, bin))
module = __import__(my_module)
finally:
del sys.path[0]
object = module.my_object

- if you're only interested in the object:

namespace = {}
execfile(os.path.join(module_dir, bin, my_module + .py), namespace)
object = namespace[my_object]

/F 



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


Re: dynamical importing

2005-10-19 Thread John Abel
Try:

userModule = _importModule( pathToModule )

def _importModule( moduleName ):
modName = __import__ ( moduleName )
modComponents = moduleName.split( '.' )
for indivComp in modComponents[ 1: ]:
modName = getattr( modName, indivComp )

return modName

HTH,

J

Joerg Schuster wrote:

Hello,

I need to import modules from user defined paths. I.e. I want to do
something
like:

module_dir = sys.argv[1]

my_path = os.path.join(module_dir, 'bin', 'my_module')

from my_path import my_object

Obviously, it doesn't work this way. How would it work?

Jörg Schuster

  


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


Re: Microsoft Hatred FAQ

2005-10-19 Thread David Schwartz

Luke Webber [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 As much as I hate to jump in on this thread, well I'm gonna...

 I think you'll find that companies have all manner of legal obligations. 
 Certainly to their shareholders, but beyond that they have an obligation 
 to their clients, who pay them for their services, and to any individual 
 or entity which might be harmed by their actions.

They have obligations to their clients because (and only because) 
failure to provide the services they contract to provide will result in 
lawsuits and harm to the shareholders. All other obligations come from the 
harm these failures will do to the shareholders. First and formost, 
companies exist to do the will of their shareholders.

 A classic case in point would be Philip Morris, who did everything they 
 could to protect their shareholders, but who shirked their duty of care to 
 their customers and the the public at large. They have since paid heavily 
 for that failure.

You mean their shareholders paid heavily. ;)

If that is not what you mean, I think you need to hedge more.

 I was perfectly clear. This is a lot of deliberate misunderstanding 
 going on in this thread and very little of it is from my side.

 All that means to me is that your misunderstanding is not deliberate. g

No misunderstanding. Corporations exist specifically to do the will of 
their shareholders. There are other theoritcal models of corporations (for 
example, wherein the shareholders only provide the capital to execute the 
will of the directors), but Microsoft is certainly not a corporation of this 
type.

DS


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


Re: How to organize Python files in a (relatively) big project

2005-10-19 Thread Giovanni Bajo
TokiDoki wrote:

 At first, I had all of my files in one single directory, but now, with
 the increasing number of files, it is becoming hard to browse my
 directory. So, I would want to be able to divide the files between 8
 directory, according to their purpose. The problem is that it breaks
the 'import's between my files. And besides,AFAIK, there is no
 easy way to import a
 file that is not in a subdirectory of the current file

Remember that the directory where you start the toplevel script is always
included in the sys.path. This means that you can have your structure like
this:

main.py
   |
   | - - pkg1
   | - - pkg2
   | - - pkg3

Files in any package can import other packages. The usual way is to do import
pkgN and then dereference. Within each package, you will have a __init__.py
which will define the package API (that is, will define those symbols that you
can access from outside the package).

Typically, you only want to import *packages*, not submodules. In other words,
try to not do stuff like from pkg1.submodule3 import Foo, because this breaks
encapsulation (if you reorganize the structure of pkg1, code will break). So
you'd do import pgk1 and later pkg1.Foo, assuming that pkg1.__init__.py
does something like from submodule3 import Foo. My preferred way is to have
__init__.py just do from submodules import *, and then each submodule defines
__all__ to specify which are its public symbols. This allow for more
encapsulation (each submodule is able to change what it exports in a
self-contained way, you don't need to modify __init__ as well).

Moreover, the dependence graph between packages shouldn't have loops. For
instance, if pkg3 uses pkg1, pkg1 shouldn't use pkg3. It makes sense to think
of pkg1 as the moral equivalent of a library, which pkg3 uses.
-- 
Giovanni Bajo


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


Re: Microsoft Hatred FAQ

2005-10-19 Thread David Schwartz

Roedy Green [EMAIL PROTECTED] wrote in 
message news:[EMAIL PROTECTED]

 On Tue, 18 Oct 2005 23:18:31 -0700, David Schwartz
 [EMAIL PROTECTED] wrote or quoted :

Perhaps you aren't following the thread, but I was talking about the
obligations a company has, not the obligations any individual has. And I 
was
talking about obligations *to* individuals.

 To me that makes no sense. Microsoft is an abstraction. It can't do
 anything. It can't make decisions. Only the individuals to work for it
 or on the board can, though they may do it in Microsoft's name.  If
 you want to talk about moral action, obligation etc. you can't divorce
 that from the people who do the actions.

If anything that makes the objection even less meaningful. The objection 
was:

 Why should loyalty to company trump all other loyalties -- family,
 law, species,  community, country, religion ... ?

And the answer is that I'm not talking about loyalty to company but 
loyalty to shareholders, which are people. Of course, a person is never 
required to do anything that actually conflicts with their conscience, 
although in some cases this may require you to quit.

DS


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


Re: Sequence and/or pattern matching

2005-10-19 Thread Séb

 Essentially, if I understand correctly, you want to detect LOOPS given a
 sequence of directed connections A-B.  loop detection and graph
 would then be the keywords to search for, in this case.

Exactly, but the sequence has to be discovered by the piece of code !

 Does this then imply you're only interested in loops occurring in this
 *sequence*, i.e., is order of connections important?  If the sequence of
 directed connections was, say, in the different order:

 B-C
 A-B
 C-A

 would you want this detected as a loop, or not?

Yes, it would be nice to detect it as a loop, with for example a
threshold. Btw, it would be nice to ignore additional connections in
such a way :

B-C # Normal connection
D-E # Additional connection to ignore
A-B # Normal connection
C-A # Normal connection

Would it be possible ?

Thank you very much

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


Re: How to organize Python files in a (relatively) big project

2005-10-19 Thread Claudio Grondi
If I understand you right you need a concept in which you can put the files
of your project where you want, i.e. restructure the nesting of directories
storing your scripts without the problem of breaking the import statements.
This will give you not a solution to any problem you maybe have with
managing a large package but is a problem in itself, so I see that you have
a huge number of options to choose from:

1. best is you get a better structure of the project in your mind, so you
don't need frequent changes by resorting your modules into a various
directories (flat is better than nested). Set a size limit of a single
Python script it must reach before you split it into two separate files, so
that the number of your files decreases to a number you can handle with ease
(this depends on how good you are at it).

2. create e.g. an HTML file from which you can view, edit, execute the
scripts you have. In this file you create your nested structure and have
this way the overview you need. The Python files remain in one directory
storing the entire project. This allows you to keep together what belongs
together, but to work with it as the single files were spread over many
categories (I mean directories :).

3. create a Python script which automatically creates an HTML file giving
you the overview of all your scripts from walking the directories your
project files are stored below and put in each of your scripts a function
which on call returns the actual full path of passed name of the file to
import and updates the Python PATH, so that it can be found (e.g
updatePATH('nameOfTheModuleToImport')

4. start to choose from many tools for project management which will keep
you busy for a while and away from the actual work on your project ...

None of these above can solve the supposed actual problem, that the project
grows beyond the capacity to manage it in mind. I know about this limitation
and I have seen programmers failing on projects with increasing size of
them. Usually the dependencies between the single modules in large projects
get more and more complicated. Each next added module making the project
size larger must work with the entire already existing ones and after a
given size of project is reached it becomes really hard (and for some just
impossible) to add a new module to it making the necessary modifications to
existing ones in order to gain the new functionality. Such modifications
result usually in breaks in other parts of the project and in my eyes no
management system can really help in anticipating it at that point. Every
programmer seems to have a limit of a project size he can manage and in my
opinion no tool for structuring it or getting a better overview is of real
help here. The core of the problem is lack of skills required for managing
large projects and it seems, that not everyone who managed to learn to
program is able to acquire this skills necessary to increase the size of a
project over the by his intellectual capacity given limits. That is why
programmer need to work in teams and have a very good manager able to
coordinate their efforts in order to succeed in creating large applications.
In really large projects it is sometimes necessary to work half a year or
more full time on the existing library of code before becoming capable of
writing a single line of additional one.

Publish your code, let others work with it, try to get responses on it and
you will probably get much more out of this than by asking for ways of
managing it.

I am curious if others on this newsgroup agree with what I said above, so I
would be glad to hear about it.

Claudio



TokiDoki [EMAIL PROTECTED] schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
 Hello there,

 I have been programming python for a little while, now. But as I am
 beginning to do more complex stuff, I am running into small organization
 problems.
 It is possible that what I want to obtain is not possible, but I would
 like the advice of more experienced python programmers.

 I am writing a relatively complex program in python that has now around
 40 files.
 At first, I had all of my files in one single directory, but now, with
 the increasing number of files, it is becoming hard to browse my
directory.
 So, I would want to be able to divide the files between 8 directory,
 according to their purpose. The problem is that it breaks the 'import's
between my files. And besides,AFAIK, there is no easy way to import a
 file that is not in a subdirectory of the current file (I suppose I
 could adjust the os.path in every file, but that seems not very elegant
 to me).
 I thought about turning the whole into a package. But I have to change
 every 'import module_name' into
 'from package_name.sub_directory_name import module_name'
 which is a little bit time consuming and not very flexible (if I change
 my mind about the subdirectory a file belongs to, I will have to track
 again every import to correct them)

 So, basically, here is the point: 

Re: Sequence and/or pattern matching

2005-10-19 Thread Ben Sizer
Séb wrote:
 1) I have a list of connexion between some computers. This list has
 this format :

It looks like you want graph theory.

 Ip A   Date Ip B
 ......  ...
 192.168.0.119.10.2005   192.168.0.2
 192.168.0.319.10.2005   192.168.0.1
 192.168.0.419.10.2005   192.168.0.6

That looks like a list of edges between graph nodes, you see. Each node
corresponds to an address and each edge is a connection between two
nodes - ip addresses, in your case.

 2) I want to find if there are unknown sequences of connexions in my
 data and if these sequences are repeated along the file :

 For example :

 Computer A connects to Computer B then
 Computer B connects to Computer C then
 Computer C connects to Computer A

That looks like finding a path between Node A and Node C. This is a
common application of graph theory, and especially when finding routes
(eg. for train journeys, or for AI characters in computer games).

 3) Then, the software gives the sequences it has found and how many
 times they appear...

You can find all the routes between 1 node and others by using
depth-first search (or indeed, any other simple graph search
algorithm). Basically, this says that, for any node, examine all the
nodes it leads to. Then examine those nodes... repeat until you run out
of nodes or find where you're looking for. The only complication is
remembering the route you took.

 I hope this is clear, point 2) is where I have my main problem. Has
 someone an idea where to start and if there's already something coded ?

I found a couple of Python graph libraries on Google but I can't vouch
for their quality. However, writing your own simple graph traversal
algorithm should be quite trivial. I would start by populating a
dictionary where the keys are instances of address A and the values are
lists of address B values for address A. Add each link again with
address B as the key and address A as the value if you need to
represent bidirectional connections. Then you can perform search on
that as required. The only slight complication is avoiding infinite
loops - I might use a dictionary of address-boolean values here and
check off each address as the algorithm progresses.

-- 
Ben Sizer

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


Re: Microsoft Hatred FAQ

2005-10-19 Thread Jerzy Karczmarczuk
Roedy Green wrote:
 On Wed, 19 Oct 2005 07:10:55 GMT, Alan Connor [EMAIL PROTECTED]
 wrote or quoted :
 
 
To all the shit-for-brains trolls that are polluting these groups
with this crap, which I haven't even bothered to read:
 
 
 A single thread does not pollute a group. It is trivially easy to
 ignore a thread.  If your newsreader does not support that feature,
 try an different newsreader.

The pollution *is* there, despite the possibility of individual screening.
The subject and the contents violates some basic nsgroup principles, such as
topicality. One to ten irrelevant postings do no harm. More than hundred -
become annoying. Cross-posting to 5 groups is bad. Please go away.

Claiming that this is an interesting, great thread is utterly silly in this
context. Shall Python newsgroup discuss the trial of Saddam Hussein as well?

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


Re: Upgrading 2.4.1 to 2.4.2

2005-10-19 Thread Ben Sizer

[EMAIL PROTECTED] wrote:
 Not sure that is a good idea on a linux system. MS should be fine, but
 I actually tried that on linux. Didn't realize how much on a linux
 system depends on Python.

I had that problem once, although to be fair it really does depend on
which distribution you use as to how many problems you're going to
have.

Perhaps the way to do it is to install the new Python version in
/usr/local/ (alongside the distro's version is in /usr/ ), then when
you're sure your new version is installed and working, change the
references over - perhaps it's possible to do this with just 1 symbolic
link somewhere.

-- 
Ben Sizer

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


Re: Microsoft Hatred FAQ

2005-10-19 Thread John Bokma
Jerzy Karczmarczuk [EMAIL PROTECTED] wrote:

[ this thread ]
 The pollution *is* there, despite the possibility of individual
 screening. The subject and the contents violates some basic nsgroup
 principles, such as topicality. One to ten irrelevant postings do no
 harm. More than hundred - become annoying. Cross-posting to 5 groups
 is bad. Please go away.

The problem is that adding please stop, please go away postings to this 
thread have 0 effect. Or worse, people posting such messages, and tweaking 
the FollowUp-To: header resulting in more and more pollution.

It doesn't work, sad but true. Best is to kill the entire thread, hope the 
long discussion stays in it, and dies out, and doesn't spark similar 
discussions.

Also refraining from posting to any thread started by Xah Lee (I guess it 
was our troll again), no matter how tempting, might help (I am going to 
try, again).

 Claiming that this is an interesting, great thread is utterly silly
 in this context. Shall Python newsgroup discuss the trial of Saddam
 Hussein as well? 

And should it be crossposted to: comp.lang.perl.misc, comp.unix.programmer, 
comp.lang.java.programmer, and comp.os.linux.misc?


-- 
John   Small Perl scripts: http://johnbokma.com/perl/
   Perl programmer available: http://castleamber.com/
I ploink googlegroups.com :-)

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


Re: UI toolkits for Python

2005-10-19 Thread Claudio Grondi
  Another possible scenario I have in mind is to control the Internet
browser
  directly from a Python script using DHTML as a language for definition
of
  appearance and specification of necessary data processing of in the
browser
  displayed UI. This way the Internet browser and HTML with JavaScript can
be
  considered an UI toolkit for use in Python.
  Hope with this above to have got Python back on topic.
 
 That is, I suppose, a possibility, but you certainly can't claim it
 would be platform-independent.
I haven't seen any really platform-independent software yet and I don't
expect to see any in the future.
It is simply not possible to have one, even if much progress was done lately
in many areas in order to try to approach it as close as possible.

Claudio

Steve Holden [EMAIL PROTECTED] schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
 Claudio Grondi wrote:
  Steve Holden [EMAIL PROTECTED] schrieb im Newsbeitrag
  news:[EMAIL PROTECTED]
 
 Claudio Grondi wrote:
 [...]
 Do I miss here something?
 
 
 While you are correct in saying (I paraphrase) that HTML interfaces
 nowadays can offer a rich graphical interface, it can be quite
difficult
 to manage state maintenance between the two components (web server,
web
 client) in the system.
 
 
 The cause of confusion here is, that HTML interfaces don't necessary
 
  need a
 
 web server and HTTP to work. I mean, that Internet Browsers
 have an API which allow access to them directly, so they can be used
 
  without
 
 a server as a kind of GUI library supporting widgets programmed
 in HTML and JavaScript  (I haven't used them yet in this form, but I
 
  think
 
 it should be no problem - right or not?).
 
 
 You are perfectly correct that interfaces can be programmed in the
 browser. As has already been said, with the adoption of standards like
 CSS2, it's even possible to make such stuff run across multiple browser
 platforms (at the moment, though, just try writing an interface that
 makes table rows appear and disappear in a cross-browser fashion: you'll
 find the stylesheet techniques you need to use for Mozilla and IE are
 very different). But this doesn't help you at all if you are trying to
 interface to Python logic.
 
 A proper GUI runs all functionality inside a single process, and
 allows much easier control over complex interactions, creation of
 dynamic dialogues, and so on.
 
 Complex and dynamic is in my eyes possible with HTML and JavaScript, so
 
  I
 
 still don't see where is a problem with this approach. I have
programmed
 already a HTML and JavaScript driven server platform and know about
(the
 solvable) problems with the back-button and sessions (it is sure not
the
 easiest way of programming a GUI).
 The only disadvantage of not using plugins or Java is, that real time
 interactions are not possible, but this is in my eyes usually not the
 requirement for a standard kind of GUI with no gaming, no Virtual
 
  Reality
 
 and no timing of user response down to milliseconds (but consider, that
 
  with
 
 a good speed of connection it is even possible to play blitz chess over
 
  the
 
 Internet).
 
 
 So, back to the subject: with an HTML/Javascript interface, how do you
 propose to bolt Python logic into the same process? Or do you admit that
 the application that interacts with such an interface either has to be
 all JavaScript or in a separate process?
 
  I haven't used it in such configuration yet, but I mean, that it is not
a
  bad idea to use local DHTML files (i.e. HTML with JavaScript) combined
with
  a Python driven HTTP server like e.g. Karrigell which makes it possible
to
  access local files by executing Python scripts triggerred by demand
raised
  by submitting to it DHTML form data resulting from user input.
  So mixing JavaScript in local DHTML files for performing what can be
done
  with JavaScript inside HTML and a HTTP server capable of executing
Python
  scripts will do the job which JavaScript alone can't because of lack of
  access to the local file system and another parts of the computer system
on
  which such kind of UI is executed.

 Indeed. But this again partitions the problem into client functionality
 and server functionality residing in two separate processes, albeit on
 the same computer, with the previously-mentioned state maintenance
 problems. This issue isn't new, you know.

  Another possible scenario I have in mind is to control the Internet
browser
  directly from a Python script using DHTML as a language for definition
of
  appearance and specification of necessary data processing of in the
browser
  displayed UI. This way the Internet browser and HTML with JavaScript can
be
  considered an UI toolkit for use in Python.
  Hope with this above to have got Python back on topic.
 
 That is, I suppose, a possibility, but you certainly can't claim it
 would be platform-independent. Unless you know of some common control
 interface respected by both Internet Exploder and Firefox ;-)

 regards
   Steve
 

Re: How to organize Python files in a (relatively) big project

2005-10-19 Thread Claudio Grondi
Maybe looking at the todays thread  [dynamical importing] can be helpful
also here.

Claudio
P.S. Below a copy of one of the responses:
:
Joerg Schuster wrote:

 I need to import modules from user defined paths. I.e. I want to do
 something like:

 module_dir = sys.argv[1]

 my_path = os.path.join(module_dir, 'bin', 'my_module')

 from my_path import my_object

 Obviously, it doesn't work this way. How would it work?

some alternatives:

- if you want the modules to remain imported:

try:
sys.path.insert(0, os.path.join(module_dir, bin))
module = __import__(my_module)
finally:
del sys.path[0]
object = module.my_object

- if you're only interested in the object:

namespace = {}
execfile(os.path.join(module_dir, bin, my_module + .py),
namespace)
object = namespace[my_object]

/F


TokiDoki [EMAIL PROTECTED] schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
 Hello there,

 I have been programming python for a little while, now. But as I am
 beginning to do more complex stuff, I am running into small organization
 problems.
 It is possible that what I want to obtain is not possible, but I would
 like the advice of more experienced python programmers.

 I am writing a relatively complex program in python that has now around
 40 files.
 At first, I had all of my files in one single directory, but now, with
 the increasing number of files, it is becoming hard to browse my
directory.
 So, I would want to be able to divide the files between 8 directory,
 according to their purpose. The problem is that it breaks the 'import's
between my files. And besides,AFAIK, there is no easy way to import a
 file that is not in a subdirectory of the current file (I suppose I
 could adjust the os.path in every file, but that seems not very elegant
 to me).
 I thought about turning the whole into a package. But I have to change
 every 'import module_name' into
 'from package_name.sub_directory_name import module_name'
 which is a little bit time consuming and not very flexible (if I change
 my mind about the subdirectory a file belongs to, I will have to track
 again every import to correct them)

 So, basically, here is the point: is there an 'elegant' way to keep my
 files in separate directory and still be able to import between them
 with simple 'import filename'?

 And if not, what would be the standard way to organize numerous python
 files belonging to the same project?

 Thank you,

 TokiDoki


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


Re: override a property

2005-10-19 Thread Robin Becker
Steven Bethard wrote:
 Robin Becker wrote:
 
...
 
 Can you add the object to be observed as another parameter to the add 
 method?
 
 py class ObservableProperty(property):
 ... def __init__(self, *args, **kwargs):
..
 py A.x.add(b, obs2)
 py b.x = 7
 obs2: 7
 
 Probably self._observers should use some sort of weakref dict instead 
 of a regular dict, but hopefully the idea is clear.
 
 STeVe

yes I think this is what Alex is proposing. It probably means abandoning the 
class based observers entirely otherwise there would have to be a decision on 
whether the instance observers take priority and some argument convention on 
whether the class or the instance was being added to.
-- 
Robin Becker

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


Re: dynamical importing

2005-10-19 Thread Fredrik Lundh
John Abel wrote:

 def _importModule( moduleName ):
 modName = __import__ ( moduleName )
 modComponents = moduleName.split( '.' )
 for indivComp in modComponents[ 1: ]:
 modName = getattr( modName, indivComp )

return modName

__import__ takes a module name, not an arbitrary file name.

/F 



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


Re: Well written open source Python apps

2005-10-19 Thread Misto .
I suggest also these:

Spark:
-
http://pages.cpsc.ucalgary.ca/~aycock/spark/

Few files.
I like how doc strings are used for handling the grammar.


Twisted:

http://twistedmatrix.com/

I like everything, from test to comments! (many are funny)


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


Re: write a loopin one line; process file paths

2005-10-19 Thread Xah Lee
Thanks a lot for various notes. Bonono?

I will have to look at the itertools module. Just went to the doc
http://www.python.org/doc/2.4.1/lib/module-itertools.html
looks interesting.

 But I believe Python is designed for easy to code and read and maintain
 in mind.

 One has to admit that without some training, FP is not very
 intuitive, my head spin when I see haskell code. A for loop is easier
 to understand.

This i'm not sure. Of the past couple of years i increasingly developed
a theory (probably well-known among proper experts), that the
difficulty of human feats of various forms, are primarily a perception
and familiarity thing. This may be getting off topic, but i wrote an
essay expresising much of the idea using Juggling as a example:
Difficulty Perceptions in Human Feats
 http://xahlee.org/Periodic_dosage_dir/t2/juggling.html

likewise, i think this applies to mental feats as well. In particular,
i think that whether imperative code or functional code is easier for
the mind is almost ENTIRELY dependent on which one the person is more
familiar with, coulped with a innate attitude one may have picked up.

 Well, if you want clean FP, you can always try haskell which is getting
 better and better in terms of real world module support(file system,
 network etc).

oh Haskell, my love! I am really going to learn it now. (maybe i'll
start A-Java-Haskell-A-Day) This month i just learned and read about
how Perl 6 is implemented in Haskell! (because one Taiwaness hacker
single-handedly by happenstance tried to do it, as a by-product of
learning Haskell) This Pugs (Perl6 in Haskell) really brought two
rather incompatible communities together somewhat for mutual exchange.
(the learning, on the surface, is politely said to be mutual, but i'm
pretty sure it's mostly Perlers learning from the Haskell folks)

... there is a sentiment among the elite tech-geeking morons, early on
imbued by the concept of troll, so that they in general don't
communicate and learn from any other language except their own.
Anything cross-posted is considered as troll, and the inter-language
communication has been essentially completely cut off. Basically, the
only ones generating all the garbage posts are these troll-criers
themselves. (will have to flesh out on this particular point of
net-sociology in a essay some other day.)

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: Microsoft Hatred FAQ

2005-10-19 Thread Antoon Pardon
Op 2005-10-19, David Schwartz schreef [EMAIL PROTECTED]:

 Luke Webber [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]

 As much as I hate to jump in on this thread, well I'm gonna...

 I think you'll find that companies have all manner of legal obligations. 
 Certainly to their shareholders, but beyond that they have an obligation 
 to their clients, who pay them for their services, and to any individual 
 or entity which might be harmed by their actions.

 They have obligations to their clients because (and only because) 
 failure to provide the services they contract to provide will result in 
 lawsuits and harm to the shareholders. All other obligations come from the 
 harm these failures will do to the shareholders. First and formost, 
 companies exist to do the will of their shareholders.

Do I understand correctly.

Lets take the following situation:

A company figures out something is wrong with one of their new models.
They have two options. They can repair the problem or they can leave
it as is and brace the laswsuits that will likely follow. An analysis
shows that the first option is likely to cost more than the second.

As far as I understand you, the company should ship the faulty model.

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


Re: html parser?

2005-10-19 Thread Laszlo Zsolt Nagy
Thorsten Kampe wrote:

* Christoph Söllner (2005-10-18 12:20 +0100)
  

right, that's what I was looking for. Thanks very much.



For simple things like that BeautifulSoup might be overkill.

import formatter, \ 
   htmllib,   \ 
   urllib 

url = 'http://python.org' 

htmlp = htmllib.HTMLParser(formatter.NullFormatter()) 
  

The problem with HTMLParser is that does not handle unclosed tags and/or 
attirbutes given with invalid syntax.
Unfortunately, many sites on the internet use malformed HTML pages. You 
are right, BeautifulSoup is an overkill
(it is rather slow) but I'm affraid this is the only fault-tolerant 
solution.

  Les

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


Re: Python Doc Error: os.makedirs

2005-10-19 Thread pclinch
if os.access( path, os.F_OK):
  print 'path exists'

See also os.stat(path) for further info. about a file or dir.

regards, Paul Clinch

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


Re: Microsoft Hatred FAQ

2005-10-19 Thread Roedy Green
On Wed, 19 Oct 2005 01:54:14 -0700, David Schwartz
[EMAIL PROTECTED] wrote or quoted :

They have obligations to their clients because (and only because) 
failure to provide the services they contract to provide will result in 
lawsuits and harm to the shareholders. All other obligations come from the 
harm these failures will do to the shareholders. 

That's the view of Republican, but it is not the only view.  Some
might say the law trumps that. It does not matter if breaking the law
would be more profitable, you still don't do it.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: write a loopin one line; process file paths

2005-10-19 Thread [EMAIL PROTECTED]

Xah Lee wrote:
 This i'm not sure. Of the past couple of years i increasingly developed
 a theory (probably well-known among proper experts), that the
 difficulty of human feats of various forms, are primarily a perception
 and familiarity thing. This may be getting off topic, but i wrote an
 essay expresising much of the idea using Juggling as a example:
 Difficulty Perceptions in Human Feats
  http://xahlee.org/Periodic_dosage_dir/t2/juggling.html

 likewise, i think this applies to mental feats as well. In particular,
 i think that whether imperative code or functional code is easier for
 the mind is almost ENTIRELY dependent on which one the person is more
 familiar with, coulped with a innate attitude one may have picked up.

But most of us start learning programming with imperative language, I
started with COBOL and Pascal(are they still taught). Then we would hit
the problem of looping one way or another pretty soon. Without a doubt,
some experienced programmer would tell you to use for loop or search
for one. This is even true in two heavily used declarative tools, SQL
and Excel. If there is foldl/scanl/map in SQL, I think it would be much
easier to code. Likewise for Excel, it is very functional(like its
ancestors 1-2-3) then VBA was thrown in.

In fact, I think haskell should be taught in any CS course as it opens
up a completely different way of approaching problem and it is easier
to read than LISP.

 oh Haskell, my love! I am really going to learn it now. (maybe i'll
 start A-Java-Haskell-A-Day) This month i just learned and read about
 how Perl 6 is implemented in Haskell! (because one Taiwaness hacker
 single-handedly by happenstance tried to do it, as a by-product of
 learning Haskell) This Pugs (Perl6 in Haskell) really brought two
 rather incompatible communities together somewhat for mutual exchange.
 (the learning, on the surface, is politely said to be mutual, but i'm
 pretty sure it's mostly Perlers learning from the Haskell folks)
After seeing Haskell, I don't think I would go back to Perl(which I
like better than python but python has the momentum as a general
purpose language). That is why I am doing the think in haskell, code in
python, whenever possible.


 ... there is a sentiment among the elite tech-geeking morons, early on
 imbued by the concept of troll, so that they in general don't
 communicate and learn from any other language except their own.
 Anything cross-posted is considered as troll, and the inter-language
 communication has been essentially completely cut off. Basically, the
 only ones generating all the garbage posts are these troll-criers
 themselves. (will have to flesh out on this particular point of
 net-sociology in a essay some other day.)

May be you can tone down a bit if you want a constructive discussion. I
am too old to have feelings about opinionated posts(and insensitive to)
so I can go through the technical stuff. Confucius said I can always
learn something whenever there is 3 people getting together, lousy
translation :-)

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


Re: Microsoft Hatred FAQ

2005-10-19 Thread Roedy Green
On 19 Oct 2005 09:41:09 GMT, Antoon Pardon [EMAIL PROTECTED]
wrote or quoted :

As far as I understand you, the company should ship the faulty model.

This is what they do.  However, I find it odd people seriously
suggesting that is the way society SHOULD run.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynamical importing

2005-10-19 Thread John Abel
Fredrik Lundh wrote:

John Abel wrote:

  

def _importModule( moduleName ):
modName = __import__ ( moduleName )
modComponents = moduleName.split( '.' )
for indivComp in modComponents[ 1: ]:
modName = getattr( modName, indivComp )

   return modName



__import__ takes a module name, not an arbitrary file name.

/F 



  

Didn't mean to imply that it did.  By pathToModule, I meant spam.ham as 
in 
http://localhost/documentation/Python-Docs-2.4.1/lib/built-in-funcs.html#l2h-6 
( hopefully, that should explain things to the OP ).

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


Re: Microsoft Hatred FAQ

2005-10-19 Thread David Schwartz

Roedy Green [EMAIL PROTECTED] wrote in 
message news:[EMAIL PROTECTED]

 On Wed, 19 Oct 2005 01:54:14 -0700, David Schwartz
 [EMAIL PROTECTED] wrote or quoted :

They have obligations to their clients because (and only because)
failure to provide the services they contract to provide will result in
lawsuits and harm to the shareholders. All other obligations come from the
harm these failures will do to the shareholders.

 That's the view of Republican, but it is not the only view.  Some
 might say the law trumps that. It does not matter if breaking the law
 would be more profitable, you still don't do it.

Did I say their obligation was to secure their shareholders as much 
profit as possible? I said their obligation was to their shareholders.

I am only continuing this off-topic thread on newsgroups that probably 
don't want it because it is a basic principle of fairness that a false or 
distorted comment deserves an rebuttal anywhere that false or distorted 
comment appears. However, it doesn't deserve a full debate anywhere except 
where it's on-topic.

DS


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


Re: Microsoft Hatred FAQ

2005-10-19 Thread David Schwartz

Antoon Pardon [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 A company figures out something is wrong with one of their new models.
 They have two options. They can repair the problem or they can leave
 it as is and brace the laswsuits that will likely follow. An analysis
 shows that the first option is likely to cost more than the second.

 As far as I understand you, the company should ship the faulty model.

It is impossible to respond to this with anything shorter than many 
pages. Google for prudent predator if you want all sides to this question. 
The short answer is maybe.

To the people who think that you obviously shouldn't, ask them the 
following hypothetical: You have a million pounds of grain. Destroying it 
will probably cost at least ten lives due to starvation. The grain, however, 
is contaminated, and selling it will likely make ten people sick, of which 
three will probably die. Should you destroy the grain?

You do have an obligation to the shareholders not to commit fraud in 
their name.

DS


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


Re: dynamical importing

2005-10-19 Thread Joerg Schuster
Thanks a lot to all.

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


problem running a python script using apache,mod_python on linux

2005-10-19 Thread neha
hi,
i m trying to integrate python with apache on linux.For this i m using
mod_python.
I dont see any problem with the versions of python,apache and
mod_python i m using.
the versions i m using are
apache version2.
mod_python v3.1.14
python2.4
The problem is,when i m running my python script,after starting apache
,it is showing me the code it has.

My error_log is showing the following message


[Tue Oct 18 19:01:06 2005] [notice] Apache/2.0.55 (Unix)
mod_python/3.1.4 Python/2.4.2 configured -- resuming normal operations
[Tue Oct 18 19:01:06 2005] [info] Server built: Oct 17 2005 13:07:52
[Tue Oct 18 19:01:06 2005] [debug] prefork.c(956): AcceptMutex: sysvsem
(default: sysvsem)


the access_log is showing this message:
127.0.0.1 - - [18/Oct/2005:19:01:14 +0530] GET /apache_pb.gif
HTTP/1.1 200 2326
127.0.0.1 - - [18/Oct/2005:19:01:19 +0530] GET /test/mptest.py
HTTP/1.1 200 110


from the python script,i m returning an apache.OK ,so i think it goin
on fine,as i m getting 200i.e the hhtp processing is goin on fine.


I have made the required changes to the httpd.conf file
***
LoadModule python_module /home/ngupta/Apache2/modules/mod_python.so


DocumentRoot /home/ngupta/Apache2/htdocs

Directory /
AllowOverride FileInfo
/Directory

***
I m using a .htaccess file placed under Apache2/htdocs/test/
The .htaccess file has the following code
**
AddHandler mod_python .py
PythonHandler mptest
PythonDebug On
**
where mptest is python script and is as follows
**
from mod_python import apache
def handler(req):
req.send_http_header()
req.write(Hello)
return apache.OK
**
so if anyone knows where the problem lies ,please tell me.
thanks.
Neha gupta

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


Re: Microsoft Hatred FAQ

2005-10-19 Thread Antoon Pardon
Op 2005-10-19, David Schwartz schreef [EMAIL PROTECTED]:

 Antoon Pardon [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]

 A company figures out something is wrong with one of their new models.
 They have two options. They can repair the problem or they can leave
 it as is and brace the laswsuits that will likely follow. An analysis
 shows that the first option is likely to cost more than the second.

 As far as I understand you, the company should ship the faulty model.

 It is impossible to respond to this with anything shorter than many 
 pages. Google for prudent predator if you want all sides to this question. 
 The short answer is maybe.

 To the people who think that you obviously shouldn't, ask them the 
 following hypothetical: You have a million pounds of grain. Destroying it 
 will probably cost at least ten lives due to starvation. The grain, however, 
 is contaminated, and selling it will likely make ten people sick, of which 
 three will probably die. Should you destroy the grain?

You could sell it, making it clear to those you sell it to that it is
contaminated grain and explaining what the risk are in consuming this grain.

 You do have an obligation to the shareholders not to commit fraud in 
 their name.

Well then you can't ship the model unless you also make the problem
public. Because shipping the model while you know it has problems
is IMO fraud. Free trade IMO involves correct information about what
is traded.

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


Re: Vim IS a capable IDE [was Re: Vim capable IDE?]

2005-10-19 Thread Chris Lasher
Thanks for the replies, guys! I had no idea Vim was capable of doing
some of those things. The source browser in Vim is slick--I never would
have known about that. As far as the GDB goes, it doesn't look like it
has support for Python, but it's nice to know it's there for C if I get
the chance to learn that language. Where do you guys go to learn all
the capabilities of Vim? Just browsing through vim.org?

The PIDA site is back up and running. It looks like a real winner! I'll
have to download it and give it a whirl.

Thanks again,
Chris

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


Re: A little help with time calculations

2005-10-19 Thread iminal
thanks

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


path

2005-10-19 Thread Shi Mu
I have installed Python 2.3 and I type help() and then Keywords.
I get a list of words. And it says that I can enter any of the words
to get more help.  I enter
and and I get the following error message:
Sorry, topic and keyword documentation is not available because the Python
HTML documentation files could not be found.  If you have installed them,
please set the environment variable PYTHONDOCS to indicate their location.

but I have set both the environment variable, with the path to be
C:\Python23\Doc which includes python23.chm
Why I still got the above error message?
-- 
http://mail.python.org/mailman/listinfo/python-list


path

2005-10-19 Thread Shi Mu
I have installed Python 2.3 and I type help() and then Keywords.
I get a list of words. And it says that I can enter any of the words
to get more help.  I enter
and and I get the following error message:
Sorry, topic and keyword documentation is not available because the Python
HTML documentation files could not be found.  If you have installed them,
please set the environment variable PYTHONDOCS to indicate their location.

but I have set both the environment variable, with the path to be
C:\Python23\Doc which includes python23.chm
Why I still got the above error message?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to organize Python files in a (relatively) big project

2005-10-19 Thread toki doki
Hello again,

Actually, I found a (pretty ugly) workaround to my problem: In every
__init__.py of the subdirectories I created, I add the following lines:

import os.path,sys
for directory,sub_dir,files in os.walk(os.path.normpath(os.path.join(os.path.dirname(__file__),..))):
  sys.path.append(directory)

That add all of the sub-directories of the parent directory to the
sys.path. I can then move my files in the directories I want without
having to change a single line in them.
it may not be very elegant, but for the moment, it will do. 

Actually, after thinking about it, I think that my problem is more a
problem with the os than with python. subdirectories are the only
method most OS provide for file organization. If there was a method
for, for example, add labels to files and then browse files according
to the labels, I wouldn't have this problem. (ok, I could arrange that
with the names of the files, but it doesn't feel the same for me).

Jason Actually, unless I am wrong, you don't need to add the path
of the package with a .pth . It should be done automatically when you
import it.

Giovanni
The usual way is to do import pkgN and then dereference

What do you call 'dereference'? do you mean something like 'import spam.foo foo=spam.foo' ?

My preferred way is to have __init__.py just do from submodules
import *, and then each submodule defines __all__ to specify which are
its public symbols.

Your solution soud interesting (although it doesn't exactly do what I
want in the present case). I would consider it when I have to do
hierarchical packages. However, I think I read somewhere that from
module import * statements could cause (probably small) performance
issue. Do you think this can be the case here?

Anyway, thank you all for your very interesting replies. (and sorry for the double-post)

TokiDoki

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

Re: Yes, this is a python question, and a serious one at that (moving to Win XP)

2005-10-19 Thread Christopher Subich
Chris Lambacher wrote:
 The shell that comes with MSys (from the MinGW guys). Is pretty good, although
 it does have a bit of a problem with stdout output before a process exits, ie
 it will hold back output until the process exits.
 
 As a bonus, the file system is a little more sane, and if you are interested
 in compiling software that is not open source, you are not tied to the Cygwin
 DLL which is GPLed.

Worth mentioning here that cygwin's gcc does allow a -mno-cygwin 
compile-time flag to not link against the cygwin dll.  Cygwin's 
packaging system also includes the MinGW development libraries as an 
easily installable option, for compiling against mingw's stuff; I've 
done it for Python extensions, in fact.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-19 Thread Antoon Pardon
Op 2005-10-19, Roger Blake schreef [EMAIL PROTECTED]:
 In article [EMAIL PROTECTED], Antoon Pardon wrote:
 A company figures out something is wrong with one of their new models.
 They have two options. They can repair the problem or they can leave
 it as is and brace the laswsuits that will likely follow. An analysis
 shows that the first option is likely to cost more than the second.

 What you are desribing is the Ford Pinto. (As you may recall, Ford
 determined that it would cost less to settle the lawsuits of charbroiled
 customers and their families than to fix the poor engineering of the
 gas tank on that car.)

 As far as I understand you, the company should ship the faulty model.

 That is what Ford did for years with the Pinto.

And as far as I understand David Schwartz that was the right decision
of Ford.

 They failed to take into account that beyond the short-term profit
 numbers, there is an effect on the company's reputation and profitibility
 when shipping faulty products in a competitive marketplace. Today's
 U.S. automakers are still suffering from poor reputations they earned
 decades ago.

But that is aftersight. If is always possible that you overlooked
something in your analisis or that some information is unavailable.
So you are forced to take a decision based on the information then
available. Whether or not the problem involves ethics in trading
doesn't change that.

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


Re: How to get a raised exception from other thread

2005-10-19 Thread dcrespo
 Now that may not be perfect, since I'm not familiar with the TCPServer()
 call.  I've sort of assumed it does something quickly and returns, or
 raises an exception if the input is bad.  If it doesn't actually return
 if it starts successfully, you would need a little different approach.
 Probably adding a simple timeout to the self.startEvent.wait() call
 would work.

It's perfect! Thank you very much.

After the .start() call in the main thread, it just waits until was a
succesfull thread start. It's just perfect.

One more thing, I would like to catch the description string of the
error, so I can show it to the user in a Message Box. How can I do that
in the main threa, once that I allready catched the exception?

Thank you so much

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


ANN: Beginning Python (Practical Python 2.0)

2005-10-19 Thread Magnus Lie Hetland
I guess it has actually been out for a while -- I just haven't
received my copies yet... Anyways: My book, Beginning Python: From
Novice to Professional (Apress, 2005) is now out. It is an expanded
and revised version of Practical Python (Apress, 2002). More
information can be found at

  http://hetland.org/writing/beginning-python

Thanks,

- Magnus

-- 
Magnus Lie HetlandPreparing to stand by.
http://hetland.org-- Microsoft Windows
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a raised exception from other thread

2005-10-19 Thread dcrespo
Ok, sorry about the above question. I solved it adding this to the main
thread:

try:
SrvrTCP = module.ThreadedTCPServer(ip,port)
SrvrTCP.start()
except Exception, description:
MsgBox(self,TCPServer
Error:\n\n+str(description),title=TCPServer,style=wx.OK |
wx.ICON_ERROR)
return

Peter, thank you very much.

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


Re: [newbie]Is there a module for print object in a readable format?

2005-10-19 Thread Steven D'Aprano
On Wed, 19 Oct 2005 09:39:48 +0800, James Gan wrote:

 Hi, Steven
 
 :) width parameter do the magic :
 
   pprint.pprint([1,2,3,4,[0,1,2,[3,4]],5], width=1,indent=4)
 [   1,
  2,
  3,
  4,
  [   0,
  1,
  2,
  [   3,
  4]],
  5]
  

That's not what I get. What are you using?

py pprint.pprint([1,2,3,4,[0,1,2], 5], width=1, indent=4)
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: pprint() got an unexpected keyword argument 'width'



-- 
Steven.

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


Re: how to return correct value of update stmt

2005-10-19 Thread eight02645999
hi
yes , the table is updated. Just feels uncomfortable with the return
of -1.
was also concerned that what if the actual table doesn't exist, will it
return -1? 
anyway, i will go check it out ..
thanks

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


RE:

2005-10-19 Thread David Gutierrez
Hugo,
Cual documento es el que leiste.

David.


From: hugo hernandez diaz [EMAIL PROTECTED]
To: python-list@python.org
Date: Tue, 18 Oct 2005 23:03:39 -0600
MIME-Version: 1.0
Received: from smtp-vbr3.xs4all.nl ([194.109.24.23]) by MC8-F32.hotmail.com 
with Microsoft SMTPSVC(6.0.3790.211); Tue, 18 Oct 2005 22:04:25 -0700
Received: from bag.python.org (bag.python.org [194.109.207.14])by 
smtp-vbr3.xs4all.nl (8.13.3/8.13.3) with ESMTP id j9J54MXa061233for 
[EMAIL PROTECTED]; Wed, 19 Oct 2005 07:04:22 +0200 (CEST)(envelope-from 
[EMAIL PROTECTED])
Received: from bag.python.org (bag [127.0.0.1])by bag.python.org (Postfix) 
with ESMTP id 95D231E4032for [EMAIL PROTECTED]; Wed, 19 Oct 2005 
07:04:15 +0200 (CEST)
Received: from bag.python.org (bag [127.0.0.1])by bag.python.org (Postfix) 
with ESMTP id 5BCAF1E4002for python-list@python.org; Wed, 19 Oct 2005 
07:03:40 +0200 (CEST)
Received: from bag (HELO bag.python.org) (127.0.0.1)by bag.python.org with 
SMTP; 19 Oct 2005 07:03:40 +0200
Received: from xproxy.gmail.com (xproxy.gmail.com [66.249.82.207])by 
bag.python.org (Postfix) with ESMTPfor python-list@python.org; Wed, 19 Oct 
2005 07:03:40 +0200 (CEST)
Received: by xproxy.gmail.com with SMTP id t13so5516wxcfor 
python-list@python.org; Tue, 18 Oct 2005 22:03:39 -0700 (PDT)
Received: by 10.70.96.6 with SMTP id t6mr122000wxb;Tue, 18 Oct 2005 22:03:39 
-0700 (PDT)
Received: by 10.70.109.10 with HTTP; Tue, 18 Oct 2005 22:03:39 -0700 (PDT)
X-Message-Info: JGTYoYF78jFNYkjVuLjbNX85tc7/i/AXgguzCWP7ndw=
X-Original-To: python-list@python.org
Delivered-To: [EMAIL PROTECTED]
X-Spam-Status: OK 0.270
X-Spam-Level: **
DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws; s=beta; 
d=gmail.com;h=received:message-id:date:from:to:subject:mime-version:content-type:content-transfer-encoding:content-disposition;b=FLIvjmWGtDhqri9Sr8YsEbgpdJLtM4URogb830Eda/pS+LRylIhvEgXwUstU1Mx/ZUvgk377zjFPDO6aNv9/SZqJlxHkS9RZJEYhx4GjZ4w2mRKYVmirFA1TxXutondJEVbSU9a9l9UfqpW0meVJKGG5Y6nSbIKttyTxRgiWQQQ=
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.6
Precedence: list
List-Id: General discussion list for the Python programming 
languagepython-list.python.org
List-Unsubscribe: 
http://mail.python.org/mailman/listinfo/python-list,mailto:[EMAIL PROTECTED]
List-Archive: http://mail.python.org/pipermail/python-list
List-Post: mailto:python-list@python.org
List-Help: mailto:[EMAIL PROTECTED]
List-Subscribe: 
http://mail.python.org/mailman/listinfo/python-list,mailto:[EMAIL PROTECTED]
Errors-To: [EMAIL PROTECTED]
X-Virus-Scanned: by XS4ALL Virus Scanner
Return-Path: [EMAIL PROTECTED]
X-OriginalArrivalTime: 19 Oct 2005 05:04:26.0637 (UTC) 
FILETIME=[941B5BD0:01C5D46A]

hola la vdd lei su documento pero no le entoendo bien mas que nada
puedo crear algo con este programa si la respuesta es si mas o menos
que si la respuesta en no entoncs pa que sirve a ademas no me pueden
pasar oyta guia mas facil mmm soy medio lento de aprendizaje gracias
--
http://mail.python.org/mailman/listinfo/python-list


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


Re: Dealing with Excel

2005-10-19 Thread Francois Lepoutre
Robert Hicks wrote:
 I need to pull data out of Oracle and stuff it into an Excel
 spreadsheet. What modules have you used to interface with Excel and
 would you recommend it?
 
 Robert
 

http://sourceforge.net/projects/pyexcelerator/
http://sourceforge.net/projects/pyxlwriter/

We use the latter one in the past. As long as
your output is plain enough. It's effective
and MS-free.

The former should be more powerful. Not tested
here.

Hope this helps

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


parser question

2005-10-19 Thread Daniel Sch
Hello *,

I have one format with this structure

A {
x=1
y=3
B {
z  = something here
}
}

C {
}

A {
x=0
y=0
B {
z  = other
}
}

are there parsers for this kind of structure?
specially I am interested in all A blocks

just now, I am trying to solve it with re,

pattern = re.compile(r^\s*A\s*{.*}\s*, re.MULTILINE | re.DOTALL)

A_blocks = pattern.findall( file(myFile).read() )

but since there might be subblocks it will fail finding the closing } 
character

Regards, Daniel


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


Re: Vim IS a capable IDE [was Re: Vim capable IDE?]

2005-10-19 Thread Micah Elliott
On Oct 19, Chris Lasher wrote:
 Where do you guys go to learn all the capabilities of Vim? Just
 browsing through vim.org?

Just type:
   :h
to see extensive info from the User Manual, Reference Manual, and
any plugins.

The near-comprehensive doc list:
   http://vimdoc.sourceforge.net/
I don't see the Reference Manual there.

The User Manual in PDF (which I printed really small on 14 pages and
now carry in my backpack):
   http://www.eandem.co.uk/mrw/vim/usr_doc/index.html

And the Vim Book (which I have only scanned):
   http://www.truth.sk/vim/vimbook-OPL.pdf

-- 
_  _ ___
|\/|icah |- lliott  http://micah.elliott.name  [EMAIL PROTECTED]
   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parser question

2005-10-19 Thread Daniel Sch
 pattern = re.compile(r^\s*A\s*{.*}\s*, re.MULTILINE | re.DOTALL)

correction

pattern = re.compile(r^\s*A\s*{.*?}\s*, re.MULTILINE | re.DOTALL)

I forgot to make it non gready :)


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


Re: Dealing with Excel

2005-10-19 Thread Larry Bates
Using ODBC interface to Oracle Excel can do this without
any external (Python) program.  Just:

1) Create a ODBC DSN that interfaces with Oracle
2) In Excel do Data-Get External Data-New Database Query
3) Tell Excel what tables/columns/order/filtering you want

You can even save the Database Query for later re-use.
If you want, you can automate this process using Python
COM+ interface to Excel.

Larry Bates

Robert Hicks wrote:
 I need to pull data out of Oracle and stuff it into an Excel
 spreadsheet. What modules have you used to interface with Excel and
 would you recommend it?
 
 Robert
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a module for print object in a readable format?

2005-10-19 Thread dcrespo
Maybe you don't have an up to date python version. I'm using 2.4.2.
I tried:

import pprint
pprint.pprint([1,2,3,4,[0,1,2,[3,4]],5], width=1,indent=4)
[   1,
2,
3,
4,
[   0,
1,
2,
[   3,
4]],
5]

Works fine.

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


Re: UI toolkits for Python

2005-10-19 Thread Ed Jensen
Claudio Grondi [EMAIL PROTECTED] wrote:
 I haven't seen any really platform-independent software yet and I don't
 expect to see any in the future.
 It is simply not possible to have one, even if much progress was done lately
 in many areas in order to try to approach it as close as possible.

Java + Swing is probably as good as it gets when the goal is to write
platform independent software.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [newbie]Is there a module for print object in a readable format?

2005-10-19 Thread Micah Elliott
On Oct 20, Steven D'Aprano wrote:
 That's not what I get. What are you using?
 
 py pprint.pprint([1,2,3,4,[0,1,2], 5], width=1, indent=4)
 Traceback (most recent call last):
   File stdin, line 1, in ?
 TypeError: pprint() got an unexpected keyword argument 'width'

I find it useful to have all relevant python versions (as listed on
http://www.python.org/download/) installed on my primary test
machines.  It really helps me with portability testing:

   $ ls /usr/local/bin/python*
   /usr/local/bin/python
   /usr/local/bin/python2.0
   /usr/local/bin/python2.1
   /usr/local/bin/python2.2
   /usr/local/bin/python2.3
   /usr/local/bin/python2.4

Then I see that v2.3 didn't have 'width':

   $ python2.3 -c 'import pprint; pprint.pprint([1,2,3,4,[0,1,2], 5],
   width=1, indent=4)'
   Traceback (most recent call last):
 File string, line 1, in ?
 TypeError: pprint() got an unexpected keyword argument 'width'

But v2.4 does:

   $ python2.4 -c 'import pprint; pprint.pprint([1,2,3,4,[0,1,2], 5],
   width=1, indent=4)'
   [   1,
   2,
   3,
   4,
   [   0,
   1,
   2],
   5]

-- 
_  _ ___
|\/|icah |- lliott  http://micah.elliott.name  [EMAIL PROTECTED]
   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: path

2005-10-19 Thread pclinch

The python help function does not use python23.chm, which is a windows
only help file. You must open it from a menu item or the desktop
explorer. It does contain an entry for and.

Other platforms usually have documentation in html format, which is why
you get a confusing error message.

Regards, Paul Clinch

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


Re: parser question

2005-10-19 Thread Micah Elliott
On Oct 19, Daniel Sch�le wrote:
 I have one format with this structure
 
 A {
 x=1
 y=3
 B {
 z  = something here
 }
 }
 
 C {
 }
 
 A {
 x=0
 y=0
 B {
 z  = other
 }
 }
 
 are there parsers for this kind of structure?
 specially I am interested in all A blocks
 
 just now, I am trying to solve it with re,

You might be able to tackle this easily enough with REs if your
structures don't nest arbitrarily.  It's hard to tell if this deserves
a formal grammar based on the example.  If it does, you could try PLY
http://www.dabeaz.com/ply/ (which I've had a pleasant experience
with in the past) or any of the other parsers listed on the PLY site's
Other Python Parsing Tools.

-- 
_  _ ___
|\/|icah |- lliott  http://micah.elliott.name  [EMAIL PROTECTED]
   
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: UI toolkits for Python

2005-10-19 Thread Paul Boddie
Mark Roseman wrote:
 What I'm suggesting is taking the effort you'd put to the 5%, and
 applying that effort instead to making the 95% even better.  If that
 extra effort would affect conversion rates, it's a justifiable option.

Yes, but isn't this where the 90/10 rule kicks in? In other words, you
transfer the effort from the 5% of users you don't care about, but then
just end up adding polish to the majority solution which doesn't
significantly improve conversion rates, all because you've done the
most effective work to convert those users already.

In this case it's even more perilous: adding polish could quite
easily eliminate parts of your audience, resulting in an only slightly
more plush red carpet being offered to significantly fewer people.

Paul

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


Re: UI toolkits for Python

2005-10-19 Thread Paul Boddie
Steve Holden wrote:

[80/20 rule]

 This is as much an economic decision as a marketing one, but a good engineer
 knows instinctively that there is a desirable cut-off point beyond which
 adding further functionality is a waste of engineering effort.

But Mike Meyer's point was that the Web standards are designed to allow
fancy functionality where it's available but for the experience to
degrade gracefully where such functionality isn't available. For
example, you have all the events module attributes in XHTML, but take
away the events capability in the browser and there's a decent chance
for the semantics of the application to remain the same: no, you don't
get instant updates of the page when you select some menu item, but the
user can still have a similar experience which involves slightly more
inconvenience - they have to submit the page and get back an updated
version from the server.

It's misleading to claim that designing in such a way requires huge
additional development, especially since the standards are constructed
in such a way to facilitate such designs. It goes without saying that
implementing advanced functionality on Netscape 3.x and NCSA Mosaic
would be a costly and ultimately non-viable burden, but that isn't the
issue for many Web applications and wasn't the point being made.

Paul

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


Re: [newbie]Is there a module for print object in a readable format?

2005-10-19 Thread Kent Johnson
Micah Elliott wrote:
 On Oct 20, Steven D'Aprano wrote:
 
That's not what I get. What are you using?

py pprint.pprint([1,2,3,4,[0,1,2], 5], width=1, indent=4)
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: pprint() got an unexpected keyword argument 'width'
 
 
 I find it useful to have all relevant python versions (as listed on
 http://www.python.org/download/) installed on my primary test
 machines.

If you want to know when a feature was introduced, the docs are often helpful:

pprint( object[, stream[, indent[, width[, depth)
snip
Changed in version 2.4: The parameters indent, width and depth were added. 

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


Re: parser question

2005-10-19 Thread Kent Johnson
Micah Elliott wrote:
 You might be able to tackle this easily enough with REs if your
 structures don't nest arbitrarily.  It's hard to tell if this deserves
 a formal grammar based on the example.  If it does, you could try PLY
 http://www.dabeaz.com/ply/ (which I've had a pleasant experience
 with in the past) or any of the other parsers listed on the PLY site's
 Other Python Parsing Tools.

A more complete list is here:
http://www.nedbatchelder.com/text/python-parsers.html

I have found pyparsing easy to work with.

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


Re: write a loopin one line; process file paths

2005-10-19 Thread Jeremy Jones
Xah Lee wrote:

Peter Hansen wrote:
  

Xah Lee wrote:


If you think i have a point, ...
  

You have neither that, nor a clue.



Dear Peter Hansen,

My messages speak themselfs. You and your cohorts's stamping of it does
not change its nature. And if this is done with repetitiousness, it
gives away your nature.

It is not necessary to shout against me. But if you must refute (and
that is reasonable), try to put content into your posts.
(see Philosophies of Netiquette at
http://xahlee.org/UnixResource_dir/writ/phil_netiquette.html)
  

Xah,

Thanks for the comic relief of this link.  The first item of comedy came 
from the following two sentences:

'''
Then at the other extreme is the relatively rare Victorian propensity 
where each post is a gem of literature carefully crafted and researched 
for an entire century of readers to appreciate and archive. Xah, Erik 
Naggum, and [censored] posts are exemplary of this style, to name a few 
acquaintances like myself.
'''

I really don't know which is funnier, that you stated these sentences at 
all, or that you probably believe them.  Several things disqualify you 
from gaining my classification of scholarly (not that you give a fart 
what I think):

- poor spelling
- poor grammar
- rambling style with lack of cohesive thought
- non-interesting, non-original ideas in your posts
- invalid or incorrect points in your discourse

The next piece of humor came from these sentences:

'''
Go to a newsgroup archive such as dejanews.com and search for your 
favorite poster.  If you find a huge quantity of terse posts that is 
tiring, boring, has little content, and in general requires you to 
carefully follow the entire thread to understand it, then you know 
you've bumped into a conversationalist.
'''

By your definition, you mostly fit into the conversationalist 
category.  The only thing that may keep you out of that category is that 
your ramblings are typically lengthy.  So, what you provide is a large 
number of lengthy, tiring, boring, content-less, non-cohesive posts.  
Funny that you bash the conversationalists when you have so much in 
common with them.

The third point of humor in this link was the paypal link at the top of 
the page:

'''
If you spend more than 30 minutes on this site, please send $1 to me. Go 
to http://paypal.com/ and make a payment to [EMAIL PROTECTED] Or send to: 
P. O. Box 390595, Mountain View, CA 94042-0290, USA.
'''

It's humorous to think of anyone spending more than 30 minutes on your 
site (apart from the obvious stunned amazement at the content, quite 
like the can't stop watching the train wreck phenomenon).  It's even 
more humorous to think of anyone gaining value from it.  But I wouldn't 
be surprised to hear that some people have actually sent you money.

If you deem fit, create a alt.fan.XahLee, and spare the rest of Python
community of your politics. I appreciate your fandom.

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

  


sorry-folks-for-feeding-the-troll-ly y'rs,

- jmj

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

ssl and timeout issue

2005-10-19 Thread Tarek Ziadé
Hello,

I cannot manage to use socket timeouts with an  imap ssl connector,and i 
badly *need* it  :'(

I have already mentionned it here: 
http://archives.free.net.ph/message/20050620.151244.e5390efe.en.html

Does anyone have a solution ?

(I thought of coding my own threaded timer over the ssl socket, but...)


Tarek

Traceback:

 from imaplib import IMAP4_SSL, IMAP4_SSL_PORT
 import socket
 test = IMAP4_SSL('mail..com', 993)
 test.sock.settimeout(10)
 test.login('[EMAIL PROTECTED]', 'password')
Traceback (most recent call last):
  File stdin, line 1, *in* ?
  File /usr/lib/python2.4/imaplib.py, line 480, *in* login
typ, dat = self._simple_command('LOGIN', user, self._quote(password))
  File /usr/lib/python2.4/imaplib.py, line 1028, *in* _simple_command
*return* self._command_complete(name, self._command(name, *args))
  File /usr/lib/python2.4/imaplib.py, line 858, *in* _command_complete
typ, data = self._get_tagged_response(tag)
  File /usr/lib/python2.4/imaplib.py, line 959, *in* _get_tagged_response
self._get_response()
  File /usr/lib/python2.4/imaplib.py, line 876, *in* _get_response
resp = self._get_line()
  File /usr/lib/python2.4/imaplib.py, line 969, *in* _get_line
line = self.readline()
  File /usr/lib/python2.4/imaplib.py, line 1135, *in* readline
char = self.sslobj.read(1)
socket.sslerror: The read operation timed out
 test = IMAP4_SSL('mail..com', 993)
 test.login('[EMAIL PROTECTED]', 'password')
('OK', ['LOGIN Ok.'])

-- 
Tarek Ziadé | Nuxeo RD (Paris, France)
CPS Plateform : http://www.cps-project.org
mail: tziade at nuxeo.com | tel: +33 (0) 6 30 37 02 63
You need Zope 3 - http://www.z3lab.org/

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


Converting 2bit hex representation to integer ?

2005-10-19 Thread Madhusudan Singh
Hi

I am using binascii.b2a_hex to convert some binary data to hex. The result
is a two bit hex representation (i. e., without the leading 0x). How do I
convert the resulting two bit representation into an integer ?

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


Re: Converting 2bit hex representation to integer ?

2005-10-19 Thread Larry Bates
Can you give us an example.  I don't know what two bit
hex means (takes at least 4 bits to make a hex digit).

Now I'm going to try to guess:

If the data is binary then all you need to do is to
use the struct.unpack module to convert to integer.

Larry Bates

Madhusudan Singh wrote:
 Hi
 
 I am using binascii.b2a_hex to convert some binary data to hex. The result
 is a two bit hex representation (i. e., without the leading hex). How do I
 convert the resulting two bit representation into an integer ?
 
 Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Doc Error: os.makedirs

2005-10-19 Thread Dr. Who

Xah Lee wrote:
 i think the function shouldn't complain if dir already exists. How is a
 programer to distinguish if the dir already exists, or if there's a
 problem creating the dir?

Of course it should thrown an exception because it was unable to do
what it was asked: create a directory.  The fact that the directory
already exists is irrelevant to the function...it still failed to
create the directory.

And I have had situations where attempting to create a directory that
already exists was an error condition.

Jeff

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


Re: problem running a python script using apache,mod_python on linux

2005-10-19 Thread Brad Teale
Neha,

 I have made the required changes to the httpd.conf file
 ***
 LoadModule python_module /home/ngupta/Apache2/modules/mod_python.so

Did you also add the line:
AddModule mod_python.c

 DocumentRoot /home/ngupta/Apache2/htdocs
 
 Directory /
 AllowOverride FileInfo
 /Directory
 
 ***
 I m using a .htaccess file placed under Apache2/htdocs/test/
 The .htaccess file has the following code
 **
 AddHandler mod_python .py
 PythonHandler mptest
 PythonDebug On
 **

I didn't see anything else that jumps out.

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


Re: Converting 2bit hex representation to integer ?

2005-10-19 Thread Madhusudan Singh
Larry Bates wrote:

 Can you give us an example.  I don't know what two bit
 hex means (takes at least 4 bits to make a hex digit).

Like 64(base 16)=100.
I am referring to 64 in the above.

 
 Now I'm going to try to guess:
 
 If the data is binary then all you need to do is to
 use the struct.unpack module to convert to integer.

Doesn't unpack presume that the input is a string ? If so, is it safe to
convert binary data to string using str() ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting 2bit hex representation to integer ?

2005-10-19 Thread Madhusudan Singh
Madhusudan Singh wrote:

 Larry Bates wrote:
 
 Can you give us an example.  I don't know what two bit
 hex means (takes at least 4 bits to make a hex digit).
 
 Like 64(base 16)=100.
 I am referring to 64 in the above.
 
 
 Now I'm going to try to guess:
 
 If the data is binary then all you need to do is to
 use the struct.unpack module to convert to integer.
 
 Doesn't unpack presume that the input is a string ? If so, is it safe to
 convert binary data to string using str() ?

Followup to this :

I just tried :

n=str(x)
print struct.unpack(b,n)

I get (51,)

The corresponding output of binascii.b2a_hex(x) is 33.

And 51_10=33_16. So that checks out. What is the deal with the parenthesis
and the comma ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html parser?

2005-10-19 Thread leonardr
To extract links without the overhead of Beautiful Soup, one option is
to copy what Beautiful Soup does, and write a SGMLParser subclass that
only looks at 'a' tags. In general I think writing SGMLParser
subclasses is a big pain (which is why I wrote Beautiful Soup), but
since you only care about one type of tag it's not so difficult:

from sgmllib import SGMLParser

class LinkParser(SGMLParser):
def __init__(self):
SGMLParser.__init__(self)
self.links = []
self.currentLink = None
self.currentLinkText = []

def start_a(self, attrs):
#If we encounter a nested a tag, end the current a tag and
#start a new one.
if self.currentLink != None:
self.end_a()
for attr, value in attrs:
if attr == 'href':
self.currentLink = value
break
if self.currentLink == None:
self.currentLink = ''

def handle_data(self, data):
if self.currentLink != None:
self.currentLinkText.append(data)

def end_a(self):
self.links.append([self.currentLink,
   .join(self.currentLinkText)])
self.currentLink = None
self.currentLinkText = []

Since this ignores any tags other than 'a', it will strip out all tags
from the text within an 'a' tag (this might be what you want, since
your example shows an 'img' tag being stripped out). It will also close
one 'a' tag when it finds another, rather than attempting to nest them.

a href=foo.phpThis text has bembedded HTML tags/b/a
=
[['foo.php', 'This text has embedded HTML tags']]

a href=foo.phpThis text has a name=anchoran embedded
anchor/a.
=
[['foo.php', 'This text has '], ['', 'an embedded anchor']]

Alternatively, you can subclass a Beautiful Soup class to ignore all
tags except for 'a' tags and the tags that they contain. This will give
you the whole Beautiful Soup API, but it'll be faster because Beautiful
Soup will only build a model of the parts of your document within 'a'
tags. The following code seems to work (and it looks like a good
candidate for inclusion in the core package).

from BeautifulSoup import BeautifulStoneSoup

class StrainedStoneSoup(BeautifulStoneSoup):
def __init__(self, interestingTags=[a], *args):
args = list(args)
args.insert(0, self)
self.interestingMap = {}
for tag in interestingTags:
self.interestingMap[tag] = True
apply(BeautifulStoneSoup.__init__, args)

def unknown_starttag(self, name, attrs, selfClosing=0):
if self.interestingMap.get(name) or len(self.tagStack)  1:
BeautifulStoneSoup.unknown_starttag(self, name, attrs,
selfClosing)

def unknown_endtag(self, name):
if len(self.tagStack)  1:
BeautifulStoneSoup.unknown_endtag(self, name)

def handle_data(self, data):
if len(self.tagStack)  1:
BeautifulStoneSoup.handle_data(self, data)

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


Re: Converting 2bit hex representation to integer ?

2005-10-19 Thread Fredrik Lundh
Madhusudan Singh wrote:

 Can you give us an example.  I don't know what two bit
 hex means (takes at least 4 bits to make a hex digit).

 Like 64(base 16)=100.
 I am referring to 64 in the above.

that's two digits, not two bits.

 print int(64, 16)
100

 Now I'm going to try to guess:

 If the data is binary then all you need to do is to
 use the struct.unpack module to convert to integer.

 Doesn't unpack presume that the input is a string ? If so, is it safe to
 convert binary data to string using str() ?

since Python uses string objects to hold binary data, that shouldn't be
necessary.

(struct also supports the CPython low-level buffer protocol, so it works
with any type that sees itself as a string of bytes).

/F 



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


Re: Threads and socket.setdefaulttimeout

2005-10-19 Thread Russell Warren
Thanks for the detailed repsone... sorry for the lag in responding to
it.

After reading and further thought, the only reason I was using
setdefaulttimeout in the first place (rather then using a direct
settimeout on the socket) was because it seemed like the only way (and
easy) of getting access to the seemingly deeply buried socket being
used by xmlrpclib.  That was prior to me using threads of course.  I
then started trying to make this solution work with thread, but it is
now too convoluted as you say.  Now I think the best solution is likely
to redirect my efforts at getting access to the socket used by
xmlrpclib so that I can set it's timeout directly.  I'm still unclear
how to do this cleanly, though.

Getting to some of your comments.

 When you say one thread affects another, I see that your example uses
 the same function for both threads. IMHO it's much better to override
 the thread's run() method than to provide a callable at thread creating
 time. That way you can be sure each thread's execution is firmly in the
 context of the particular thread instance's namespace.

 having said all this, I don't think that's your issue.

Correct - the bottom code is nothing to do with my code and was only to
quickly prove that it was cross-thread.

 This seems extremely contorted, and I'm pretty sure we can find a better
 way.

Couldn't agree more!

 The threads' network calls should be yielding process control during
 their timeout period to allow other runnable threads to proceed. That's

Yep.  This is not causing me any problem.

 You are aware, I presume, that you can set a timeout on each socket
 individually using its settimeout() method?

Yes, but I momentarily had forgot about it... as mentioned I ended up
making the since-bad choice of using setdefaulttimeout to get timeouts
set on the inaccessible sockets.  Then I carried it too far...

 See above. However, this *does* require you to have access to the
 sockets, which is tricky if they are buried deep in some opaque object's
 methods.

Any help on how to crack the safe would be appreciated.

 There are locks! I suspect what you need is a threading.Rlock object,
 that a thread has to hold to be able to modify the (global) default
 timeout. This isn't a full solution to your problem, though, as you have
 correctly deduced.

Not quite what I was after I don't think since potentially interfering
code needs to check the lock (via acquire) to avoid conflict.  What I
guess I mean is something general for the process saying never ever
interrupt this block og code by running code on another thread,
regardless of whether the other thread(s) check a lock.  Thinking more
about it it seems unreasonable so I'll drop the question.

Russ

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


Re: Threads and socket.setdefaulttimeout

2005-10-19 Thread Steve Holden
Russell Warren wrote:
 Thanks for the detailed repsone... sorry for the lag in responding to
 it.
[discussion of problems with timeouts on threaded code's sockets]
 
 Not quite what I was after I don't think since potentially interfering
 code needs to check the lock (via acquire) to avoid conflict.  What I
 guess I mean is something general for the process saying never ever
 interrupt this block og code by running code on another thread,
 regardless of whether the other thread(s) check a lock.  Thinking more
 about it it seems unreasonable so I'll drop the question.
 

Well, I'm about out of ideas, but c.l.py is a very inventive group, so 
maybe someone else will be able to contribute a bright thought. Anyone?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


question about timestamp and MySQLdb

2005-10-19 Thread Sean Berry
I am using MySQLdb to connect to a database and retrieve a timestamp from a 
table.  The problem is I want the timestamp as a long, unformatted and all.

In the table I have a timestamp like this
20051019111617

But, when I retrieve the value and print it I get
 2005-10-19 11:16:17

I want the numeric version, not the converted date.  Any suggestions? 


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


Controlling exception handling of logging module

2005-10-19 Thread sj
Suppose the following are part of a long file and executed:

logging.basicConfig(stream = sys.stderr, level=logging.INFO)
logging.info(%d %d, 1, 2, 3)# buggy

Python prints the traceback of the error as follows:

Traceback (most recent call last):
  File .../local/lib/python2.4/logging/__init__.py, line 706, in emit
msg = self.format(record)
  File .../local/lib/python2.4/logging/__init__.py, line 592, in
format
return fmt.format(record)
  File .../local/lib/python2.4/logging/__init__.py, line 382, in
format
record.message = record.getMessage()
  File .../local/lib/python2.4/logging/__init__.py, line 253, in
getMessage
msg = msg % self.args
TypeError: not all arguments converted during string formatting

It tells why error occurred, but the traceback is not helpful to locate
where it occurred.  I believe that's because the logging module caught
and ate up the exception.  I understand that this is a sensible setting
as logging shouldn't harm the main program, but in the debugging phase,
I really want this exception to propagate up so that I can easily
locate from my code.  Is there any way to control this behavior so the
error is not handled by the logging module itself?

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


  1   2   3   >