Re: XP rich text cut-n-paste

2006-03-04 Thread Paddy
Thanks Chris,
Scintilla does indeed have the feature, and googling for the term "copy
as RTF" lead me to http://www.pnotepad.org/ which also has the feature.

Now I will have to ask for that feature request as I wuld also like
colourized shell input oo!

(Hmm, must get that credit card authorized so I can make a donation).

- Paddy.

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


Re: how to overload sqrt in a module?

2006-03-04 Thread Michael McNeil Forbes
On Fri, 3 Mar 2006, Steven D'Aprano wrote:

> ... you can do this:
>
> import my_module
> my_module.set_environment("math") # or cmath, or numeric, or whatever
>
> Your my_module will be like this:
>
> # Warning: untested code.
> ENVIRON = None  # global variables sometimes have their uses
>
> def f(x):
>if ENVIRON is None:
>raise ValueError("Uninitialised module!")
># or use a custom exception
>return ENVIRON.sqrt(x)
>
> def set_environment(name):
>global ENVIRON
>ENVIRON = __import__(name)
>
>
> Does this help?

Yes.  However, this raises a question: Is this any different than 
directly modifying the globals, or is it just syntactic sugar.

import math as my_math

def set_environment(name):
 globals()['ENVIRON'] = __import__(name)

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


Re: Passing a method indirectly

2006-03-04 Thread Steve Holden
swisscheese wrote:
> I'm trying to write a function that takes an arbitrary object and
> method.
> The function applies the method to the object (and some other stuff).
> I get error "Test instance has no attribute 'method' "
> How can I make this work?
> 
> def ObjApply (object,method):
>   object.method ()
> 
> class Test:
>   def test1 (self): print "Hello"
>   def test2 (self):
>   ObjApply (self,self.test1)
> 
> ta = Test ()
> ta.test2 ()
> 
Your code appears to be based on a slight misunderstanding of method 
calls. In your Test class you are calling ObjApply with two arguments, 
the second of which is a "bound method" (in other words, it already 
implicitly references the instance of which it is a method).

In still other words, there is really no need for two arguments to 
ObjApply! Perhaps you need to think through your goals more clearly ...

  >>> def ObjApply(method):
  ... method()
  ...
  >>> class Test:
  ...   def test1(self): print "Hello from", self
  ...   def test2(self): ObjApply(self.test1)
  ...
  >>> ts = Test()
  >>> ts.test2()
Hello from <__main__.Test instance at 0x18cd238c>
  >>>

So, what is it you *really* want to do?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

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


Re: how to overload sqrt in a module?

2006-03-04 Thread Michael McNeil Forbes
On Fri, 3 Mar 2006, david mugnai wrote:

[snip]
>
> If I don't misunderstood the problem, you can define an "init" method for
> your module_g
>
> (code not tested)
>
> module_g.py
> ---
>
> _functions = {}
> def init(mathmodule):
>  _function['sqrt'] = getattr(mathmodule, 'sqrt', None)
>
> def _get(name):
>  try:
>return _functions[name]
>  except KeyError:
>raise TypeError("you have to initialize module_g")
>
> def sqrt(x):
>  return _get('sqrt')(x)
>
> main.py
> ---
>
> import math
> import module_g
>
> module_g.init(math)
> print module_g.sqrt(2)

Thanks, this gets me close.  Is there anything really bad about the 
following?  It works exactly as I would like, but I don't want to get in 
trouble down the road:

module_f

import math as my_math

def set_math(custom_math):
 globals()['my_math'] = custom_math

def f(x):
 return my_math.sqrt(x)

>>> import module_f
>>> module_f.f(2)
1.4142135623730951
>>> import cmath
>>> module_f.set_math(cmath)
>>> module_f.f(2j)
(1+1j)

Or, if one wants to use the "from __ import *" form:

from math import *

def set_math(custom_math):
 globals().update(custom_math.__dict__)

def f(x):
 return sqrt(x)

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


Re: The old round off problem?

2006-03-04 Thread sam

David Treadwell wrote:
> exp(x) is implemented by:
>
> 1.  reducing x into the range |r| <=  0.5 * ln(2), such that x = k *
> ln(2) + r
> 2.  approximating exp(r) with a fifth-order polynomial,
> 3.  re-scaling by multiplying by 2^k: exp(x) = 2^k * exp(r)
>
> sinh(x) is mathematically ( exp(x) - exp(-x) )/2 but it's not
> calculated directly that way.
>
> My brain hurts at this point; it's late. I'll have another go at
> hunting down the errors tomorrow. In the interim, does anybody out
> there already know the answer?
>
> :--David
I tried the exp(x) equivalent of sinh(x) and cosh(x) with the same
results.
I think I will write my own or steal the Taylor(f(x),x,n) function in
both C++, and python.

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


Re: Making a tiny script language using python: I need a string processing lib

2006-03-04 Thread Sullivan WxPyQtKinter
I have gone over the shlex and cmd and so, but none of them are
satisfactory. However, I tried to program this this function on my own
and found it pretty easy.

Thank you so much for the suggestion, after all.

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


Re: question about sys.exc_type and sys.exc_value

2006-03-04 Thread John Salerno
David Wahler wrote:

> Are you using the first edition of "Learning Python"? According to
>  that was published in 1999,
> which puts it right around the end of Python 1.5. I'd strongly suggest
> you find a much more recent tutorial, as a lot of python has been
> improved and altered since then (sometimes in incompatible ways).

Actually I'm using the second edition, which is updated to 2.2/2.3. But 
you are right, I just tried it in the command prompt and it does work, 
so my mind can rest tonight.  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to record how long i use the intenet

2006-03-04 Thread Roger Upole

[EMAIL PROTECTED] wrote:
> use python
> use ADSL
> use windows XP
> i want to record the time when i get on the internet and off the
> internet
> into a txt file
> HOW?
>

You might be able to get that out of the event log.
Most types of connections record connect and
disconnect events in the System log with a source
of RemoteAccess.  The win32event module
allows you to read the event log from Python.

 hth
 Roger




== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 
Newsgroups
---= East/West-Coast Server Farms - Total Privacy via Encryption =---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python advocacy in scientific computation

2006-03-04 Thread Robert Kern
Brian Blais wrote:
> here, I've found python to be good, but not great.  matplotlib (pylab) is a 
> really 
> great thing, but is not as straightforward as plotting in Matlab.  Either, 
> you have a 
> window which locks the process until you close it, or you do interactive 
> mode, but 
> the window results disappear if any other window is put on top (like your 
> shell), and 
> has to be manually redrawn.  This makes it far less convenient to deal with 
> in 
> interactive mode.

All I can say is that I've never seen anything like that behavior. Are you tried
using ipython in pylab mode?

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: add an asynchronous exception class

2006-03-04 Thread Christian Stapfer
"Paul Rubin"  wrote in message 
news:[EMAIL PROTECTED]
> "Christian Stapfer" <[EMAIL PROTECTED]> writes:
>> I guess it means the following:
>>
>> "Terminating exceptions" are exceptions that
>> terminate the *thrower* of the exception.
>
> Are you sure?

Am I sure?  - Well no! As I wrote: this  is
just my *guess*.
But if certain terms are not explained
upfront then, I assume, the writer must have
had some "well known" interpretation in mind.
  These two alternatives, the abortion and
the resumption model of exception handling,
are certainly that: "well known". Hence
my guess...

Regards,
Christian 


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


Re: A simple question

2006-03-04 Thread Tuvas
Ahh, that make sense! Thanks a ton!

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


Re: Python advocacy in scientific computation

2006-03-04 Thread Robert Kern
sturlamolden wrote:
> Michael Tobis skrev:
> 
> Being a scientist, I can tell you that your not getting it right. If
> you speak computer science or business talk no scientist are going to
> listen. Lets just see how you argue:

I see we've forgone the standard conventions of politeness and gone straight for
the unfounded assumptions. Fantastic.

>>These include: source and version control and audit trails for runs,
>>build system management, test specification, deployment testing (across
>>multiple platforms), post-processing analysis, run-time and
>>asynchronous visualization, distributed control and ensemble
>>management.
> 
> At this point, no scientist will no longer understand what the heck you
> are talking about. All have stopped reading and are busy doing
> experiments in the laboratory instead. Perhaps it sound good to a CS
> geek, but not to a busy researcher.
> 
> Typically a scientist need to:
> 
> 1. do a lot of experiments
> 
> 2. analyse the data from experiments
> 
> 3. run a simulation now and then

Being a one-time scientist, I can tell you that you're not getting it right. You
have an extremely myopic view of what a scientist does. You seem to be under the
impression that all scientists do exactly what you do. When I was in the
geophysics program at Scripps Institution of Oceanography, almost no one was
doing experiments. The closest were the people who were building and deploying
instruments. In our department, typically a scientist would

1. Write grant proposals.

2. Advise and teach students.

3. Analyze the data from the last research cruise/satellite passover/earthquake.

4. Do some simulations.

5. Write a lot of code to do #3 and #4.

There are whole branches of science where the typical scientist usually spends a
lot of his time in #5. Michael Tobis is in one of those branches, and his
article was directed to his peers. As he clearly stated.

You are not from one of those branches, and you have different needs. That's
fine, but please don't call the kettle black.

> Thus, we need something that is "easy to program" and "runs fast
> enough" (and by fast enough we usually mean extremely fast). The tools
> of choice seems to be Fortran for the older professors (you can't teach
> old dogs new tricks) and MATLAB (perhaps combined with plain C) for the
> younger ones (that would e.g. be yours truly). Hiring professional
> programmers are usually futile, as they don't understand the problems
> we are working with. They can't solve problems they don't understand.

I call shenanigans. Believe me, I would love it if it were true. I make my
living writing scientific software. For a company where half of us have science
degrees (myself included) and the other half have CS degrees, it would be great
advertising to say that none of those other companies could ever understand the
problems scientists face. But it's just not true.

Scientists are an important part of the process, certainly. They're called
"customers." Their needs drive the whole process. The depth and breadth of their
knowledge of the field and the particular problem are necessary to write good
scientific software. But it usually doesn't take particularly deep or broad
knowledge to write a specific piece of software. Once the scientist can reduce
the problem to a set of requirements, the CS guys are a perfect fit. That's what
a good professional programmer does: take requirements and produce software that
fulfills those requirements. They do the same thing regardless of the field. In
my company, everyone pulls their weight, even the person with the philosphy 
degree.

At that point, the CS skillset is perfectly suited to writing good scientific
software. Or at least, any given CS-degree person is no less likely to have the
appropriate skillset than a science-degree person. Frequently, they have a much
broader and deeper skillset that is actually useful to writing scientific
software. Most of the scientists I know couldn't write robust floating point
code to save his life. Or his career.

> What you really ned to address is something very simple:
> 
> Why is Python better a better Matlab than Matlab?
> 
> The programs we need to write typically falls into one of three
> categories:
> 
> 1. simulations
> 2. data analysis
> 3. experiment control and data aquisition
> 
> (that are words that scientists do know)
> 
> In addition, there are 10 things you should know about scientific
> programming:
> 
> 1. Time is money. Time is the only thing that a scientist cannot afford
> to lose. Licensing fees for Matlab is not an issue. If we can spend
> $1,000,000 on specialised equipment we can pay whatever Mathworks or
> Lahey charges as well. However, time spent programming are an issue.
> (As are time time spend learning a new language.)
> 
> 2. We don't need fancy GUIs. GUI coding is a waste of time we don't
> have. We don't care if Python have fancy GUI frameworks or not.

Uh, time is money? Fighting unusable interfaces, GUI or other

Re: A simple question

2006-03-04 Thread Ben Cartwright
Tuvas wrote:
> Why is the output list [[0, 1], [0, 1]] and not [[0,
> 1], [0, 0]]? And how can I make it work right?

http://www.python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list

--Ben

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


Re: A simple question

2006-03-04 Thread [EMAIL PROTECTED]
Skip answered why, but not how to make it work right:

>>> x = [[0]*2 for x in range(2)]
>>> x
[[0, 0], [0, 0]]
>>> x[0][1]=1
>>> x
[[0, 1], [0, 0]]

Cheers,
n

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


Re: A simple question

2006-03-04 Thread skip

>>> x=[[0]*2]*2

This replicates the references.  It doesn't copy objects.

This short transcript demonstrates that concept:

>>> x = [[0, 0], [0, 0]]
>>> map(id, x)
[16988720, 16988160]
>>> y = [[0]*2]*2
>>> y
[[0, 0], [0, 0]]
>>> map(id, y)
[16988520, 16988520]

The object x refers to is a list with references to two other lists.  The
object y refers to is a list with two references to the same list.

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


Re: question about sys.exc_type and sys.exc_value

2006-03-04 Thread David Wahler
John Salerno wrote:
> Here is an exercise from Learning Python that I wrote myself:
>
> import sys
> import traceback
>
> class MyError: pass
>
> def oops():
>  raise MyError()
>
> def safe(func, *args):
>  try:
>  apply(func, args)
>  except:
>  traceback.print_exc()
>  print 'Got', sys.exc_type, sys.exc_value
>
> safe(oops)
>
> And here is the output:
>
> Traceback (most recent call last):
>File "C:/Python24/oops.py", line 11, in safe
>  apply(func, args)
>File "C:/Python24/oops.py", line 7, in oops
>  raise MyError()
> MyError: <__main__.MyError instance at 0x00B475A8>
> Got Queue.Empty
>
> Why does it show Queue.Empty as the values for sys.exc_type and
> sys.exc_value? I guess I can somewhat understand Empty, because the
> instance is basically nothing. But why does it say Queue instead of
> MyError? The sample in the book shows "Got hello world", because hello
> is the error name and world is the extra data. But mine doesn't seem to
> work that way. (They are also using a string exception in the book,
> instead of a class.)
>
> Thanks.

Are you using the first edition of "Learning Python"? According to
 that was published in 1999,
which puts it right around the end of Python 1.5. I'd strongly suggest
you find a much more recent tutorial, as a lot of python has been
improved and altered since then (sometimes in incompatible ways).

If you look at the sys module's documentation at
, you'll notice that
sys.exc_{type,value,traceback} have been deprecated since version 1.5.
That's because there's really no way to use them safely. The reason is
that as global variables, they hold information on the most recent
exception handled _anywhere_ in the program, possibly in another
thread. You should use sys.exc_info() instead, which only returns the
most recent one in the current thread.

If you do a little experimentation, you should notice that your
anomalous result only occurs when you run the code through IDLE -- it
works fine at the command prompt. Also, if you print exc_type and
exc_value first, at the beginning of the except block, it works fine.
The reason for this behavior is that IDLE runs your code in a separate
thread of the same interpreter instance used to run IDLE itself.
Presumably, some code in IDLE's user interface uses a queue to manage
the display, and that results in a Queue.Empty exception being thrown
and caught internally in another thread whenever a line of output is
printed.

The point is that sys.exc_type, sys.exc_value and sys.exc_traceback are
fundamentally unsafe, which is why they've been deprecated for the last
7 years. Incidentally, string exceptions are also deprecated IIRC, so
it's probably best to steer clear of them as well.

Hope this helps,
-- David

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


A simple question

2006-03-04 Thread Tuvas
I know the answer is probably really simple to this, and I feel bad to
even ask, but I can't find the answer anywhere... Let me show what
happened, then ask the question.

>>> x=[[0]*2]*2
>>> x
[[0, 0], [0, 0]]
>>> x[0][1]=1
>>> x
[[0, 1], [0, 1]]
>>>

The question now. Why is the output list [[0, 1], [0, 1]] and not [[0,
1], [0, 0]]? And how can I make it work right? I do know that x[0][1]
will always give the value of that specific coordinate, but never
before have I tried to manipulate rows like this, and I'm finding I
need to. Thanks!

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


Re: The old round off problem?

2006-03-04 Thread David Treadwell
I wish I knew!

So I asked Google. Here's what I learned:

Most implementations are based on, or similar to the implementation  
in the fdlibm package.

sinh(x) and cosh(x) are both based on exp(x). See http:// 
www.netlib.org/cgi-bin/netlibfiles.pl?filename=/fdlibm/e_sinh.c

exp(x) is implemented by:

1.  reducing x into the range |r| <=  0.5 * ln(2), such that x = k *  
ln(2) + r
2.  approximating exp(r) with a fifth-order polynomial,
3.  re-scaling by multiplying by 2^k: exp(x) = 2^k * exp(r)

sinh(x) is mathematically ( exp(x) - exp(-x) )/2 but it's not  
calculated directly that way.

My brain hurts at this point; it's late. I'll have another go at  
hunting down the errors tomorrow. In the interim, does anybody out  
there already know the answer?

:--David

On Mar 4, 2006, at 8:27 PM, sam wrote:

> David I beg I beg
> Can you answer the question?
>
> Also thanks for the information on using the Taylor series.
>
> Sam Schulenburg
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Python advocacy in scientific computation

2006-03-04 Thread David Treadwell
On Mar 4, 2006, at 11:16 PM, Dennis Lee Bieber wrote:

> On Sat, 4 Mar 2006 14:23:10 -0500, David Treadwell
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
>
>> needed programming, be it CS or chemical engineering, taught it in  
>> a  [EMAIL PROTECTED]
>> very linear, bottom-up fashion. First you read inputs, then do Foo,
>> then do Bar, then do (fill in your favorite third-level word).
>>
>   Doesn't quite sound like what was "bottom up" in my day... Sounds
> like an common "input, process, output" design.

Well, you're right about my description--that's what the program  
ended up looking like. It wasn't the way it was written.

Usually, I'd do it more like this:

Find or derive the formula of interest.
Translate the formula into ForTran  (hmmm ... catchy name for a  
language!)
Put the minimum number of statements around the formula to get it to  
run.
Write the UI. Back in the day, a user interface consisted of

   $ENTRY
...
  or

 DATA ...
or, if we were feeling lucky,

   READ (6,*) ... (or whatever)

By the time I finished writing the code, if I was lucky, it looked  
like what I described.
Very few subroutines (Maybe some LINPAC or some other code package),  
lots of the dreaded GOTO statements.
Comment statements? A waste of punch cards and RAM. *LOL*

Then spend weeks squashing bugs.

Shells, wrappers, IF...THEN...ELSE blocks, code with only one input  
and one output were concepts unknown to us.

To put it mildly, I feel very under-served by my formal computer  
education. Perhaps it was just a  matter of bad timing. Still, as one  
post said, they teach us 8 semesters of mathematics and one of  
Fortran, expecting us to learn how to program by ourselves. Pick up  
any older book on "Numerical Methods in the Foo Sciences". They got  
the numbers crunched, but the programming style was wretched. Donald  
Knuth, were were you?

>   "Bottom up", to me, was more: write the code to read/write the data
> records; then use those routines to write code to modify the  
> contents of
> the records; repeat ad infinitum (it seemed) until you reached the  
> main
> program -- which sort of came down to a "fiat lux".
>
>   "Top down/Functional decomposition" ran the other way... Start with
> the main program. Determine what major activities it has to  
> perform, and
> add invocations to stub routines for each of those. Repeat with each
> stub, add invocations to the stubs for the functions it had to
> perform... until you reach the layer that does the "physical work",
> say... Problem with this approach, especially in a poorly thought out
> team, is that you may have widely spaced sections that have to
> manipulate the same file, say -- and end up with multiple routines all
> incompatible to do that.

Been there, done that. Aren't XML and the other structured data  
protocols nice?

>
>   Often I'd (on solo efforts) get to some point, and then reverse, to
> build the low-level routines as a library... I think I've heard that
> defined as "outside in" design.

Sometimes, I'd add so many layers of crud onto the original meat of  
the program, it was just easier to toss the whole thing out. What a  
royal waste of time. Far better to plan ahead.

>
>   In one aspect, OOP is closer to the "bottom up" approach, since one
> is creating "objects" to represent/manipulate the same things one
> started with in "bottom up"; just better encapsulated -- you don't
> suddenly find some routine 10 layers up that is directly manipulating
> the data (object state) with no direct understanding of where this  
> data
> came from, where it is going, etc.

Yes, but the computer doesn't, and never did "understand" the data.  
All of this OOP stuff was invented to help the Programmer and Legacy  
Code Maintainers understand the processing.

>   In my college, it was the business majors that got hit... The
> Statistics II course was 90% number crunching using a statistics  
> package
> (I've forgotten the name of the package -- its been 27 years; and as a
> CS major I only had to take Stat I... SPSS comes to mind: Statistical
> Package for the Social Sciences).

And COBOL. Even in 1977, I used to feel sorry for the people who had  
to program in COBOL.

>
>   Database management was worse: at the time, my textbook went
> "Hierarchical, Network, (theoretical) Relational" (five years later, a
> new edition went "Relational, (historical) Network, (historical)
> Hierarchical". Campus mainframe ran a DBTG Network model DBMS.

As a general rule, the scientists and engineers I know can't  
understand the structure of a database that doesn't fit into MS Excel.

>
>>
>> I still don't get OOP completely, but Python has helped a great deal.
>>
>   I'm still terrible with the more intangible "objects", and various
> inheritance concerns... I do much better when the "objects"  
> directly map
> to tangible things (it is easy to model a radio: components include
> things like "tun

Re: XP rich text cut-n-paste

2006-03-04 Thread Chris Mellon
On 4 Mar 2006 11:39:11 -0800, Paddy <[EMAIL PROTECTED]> wrote:
> Hi,
> Is their a colourized editor/shell that allows you to cut and paste the
> colourized text?
>
> Idle, SPE, Eclipse, and pythonwin all seem to nicely colourize both
> command line input as well as editor windows but when I cut and paste
> (in this case, into OpenOffice Writer), even the paste-special menu
> just allows the pasting of un-adorned text.
>
> i have a work-around: gvim coourizes and allows export as html, but it
> is long-winded.
>

The SciTe editor has a "Copy as RTF" function. It uses the same editor
control as SPE (but not idle, eclipse, or pythonwin), so you might ask
for it as a feature request in SPE.


> Thanks in advance, Paddy.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python advocacy in scientific computation

2006-03-04 Thread beliavsky
Dennis Lee Bieber wrote:

>F90/F95 is scary, isn't it...

>F77 wasn't that big a change from FORTRAN-IV (F66)  (hmmm, we're due
> for another standard, aren't we? 1966, 1977, 1990 [95 was a tweak]...)

Fortran 2003 is the latest standard -- see
http://www.fortran.com/fortran/fcd_announce.html

"The major additions are Object-Oriented Programming and
Interoperability with C [...]. Minor additions include procedure
pointers, finalization of derived-type objects, parameterized derived
types, pointer rank remapping (allows viewing one-dimensional arrays as
higher-dimensional arrays), enumerations, the ASSOCIATE construct
(similar to Pascal's WITH), transferring an allocation (generalization
of the frequently-requested reallocate capability), VOLATILE attribute,
access to the command line and environment variables, standard named
constants for "*" input and output units, access to message text for
input/output and other errors, access to features of the IEEE
floating-point arithmetic standard, longer names and statements,
generalization of expressions for array dimensions and initial values,
user-defined derived-type input/output, asynchronous input/output, and
stream input/output--and this list is not exhaustive."

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


Re: How to except the unexpected?

2006-03-04 Thread Steven D'Aprano
On Sat, 04 Mar 2006 13:19:29 -0800, James Stroud wrote:

> Why catch an error only to re-raise it?

As a general tactic, you may want to catch an exception, print extra
debugging information, then raise the exception again, like this:

try:
x = somedata()
y = someotherdata()
z = process(x, y)
except Exception:
print "Error!"
print "Value of x: %s" % x
print "Value of y: %s" % y
raise


Although that's not the reason the Original Poster is doing this.

The OP is doing it because catching all exceptions masks bugs. There are
certain exceptions which should be allowed through, as they indicate a bug
in the OP's code. Normally the tactic is to catch only the exceptions you
are interested in, and let everything else through, but the OP needs to
catch all exceptions because there are rare exceptions which he can't
predict in advance.



-- 
Steven.

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


Re: spliting on ":"

2006-03-04 Thread Steven D'Aprano
On Sat, 04 Mar 2006 08:54:33 -0800, ss2003 wrote:

> hi
> 
> i have a file with
> 
> xxx.xxx.xxx.xxx:yyy
> xxx.xxx.xxx.xxx:yyy
> xxx.xxx.xxx.xxx:yyy
> xxx.xxx.xxx.xxx
> xxx.xxx.xxx.xxx
> xxx.xxx.xxx.xxx:yyy
> 
> i wanna split on ":" and get all the "yyy" and print the whole line out
> so i did
> 
> print line.split(":")[-1]
> 
> but line 4 and 5 are not printed as there is no ":" to split. It should
> print a "blank" at least.
> how to print out lines 4 and 5 ?
> eg output is
> 
> yyy
> yyy
> yyy
> 
> 
> yyy


There are a few ways of handling this problem. It depends on what you want
to do if your input string looks like this "abc:y:z": should your code
print "y", "z" or even "y:z"?

# look before you leap
line = "abc:y:z"
if ":" in line:
print line.split(":")[-1]  # prints "z"
print line.split(":")[1]  # prints "y"
print line.split(":", 1)[-1]  # prints "y:z"
# if your line only has one colon, the above three lines
# should all print the same thing
else:
print ""



# look before you leap again
L = line.split(":")
if len(L) > 1:
print L[1]
else:
print ""



# use a sentinel value
print (line + ":").split(":", 1)[1][:-1]


-- 
Steven.

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


Re: The old round off problem?

2006-03-04 Thread sam
David I beg I beg
Can you answer the question?

Also thanks for the information on using the Taylor series.

Sam Schulenburg

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


Re: question about sys.exc_type and sys.exc_value

2006-03-04 Thread John Salerno
John Salerno wrote:

> MyError? The sample in the book shows "Got hello world", because hello 
> is the error name and world is the extra data. But mine doesn't seem to 
> work that way. (They are also using a string exception in the book, 
> instead of a class.)

My mistake. In the book the exception is:

MyError = 'hello'

and the extra data is 'world'
-- 
http://mail.python.org/mailman/listinfo/python-list


question about sys.exc_type and sys.exc_value

2006-03-04 Thread John Salerno
Here is an exercise from Learning Python that I wrote myself:

import sys
import traceback

class MyError: pass

def oops():
 raise MyError()

def safe(func, *args):
 try:
 apply(func, args)
 except:
 traceback.print_exc()
 print 'Got', sys.exc_type, sys.exc_value

safe(oops)

And here is the output:

Traceback (most recent call last):
   File "C:/Python24/oops.py", line 11, in safe
 apply(func, args)
   File "C:/Python24/oops.py", line 7, in oops
 raise MyError()
MyError: <__main__.MyError instance at 0x00B475A8>
Got Queue.Empty

Why does it show Queue.Empty as the values for sys.exc_type and 
sys.exc_value? I guess I can somewhat understand Empty, because the 
instance is basically nothing. But why does it say Queue instead of 
MyError? The sample in the book shows "Got hello world", because hello 
is the error name and world is the extra data. But mine doesn't seem to 
work that way. (They are also using a string exception in the book, 
instead of a class.)

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


Re: spliting on ":"

2006-03-04 Thread Peter Hansen
Petr Jakes wrote:
>>I think you're getting caught by the classic and/or trap in Python,
>>trying to avoid using a simple if statement.
> 
> What do you mean by "the classic and/or trap"? Can you give an example
> please?

Sure, see my subsequent reply to Cyril, elsewhere in this thread.

(In summary, and/or is defective when used as a ternary operator if the 
expression after "and" evaluates False.  The list archives can tell you 
more.)

-Peter

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


Re: spliting on ":"

2006-03-04 Thread Peter Hansen
Cyril Bazin wrote:
> Ok, ok, there was a mistake in the code.
> (Of course, it was done on prupose in order to verify if everybody is 
> aware ;-)
> I don't know why it is preferable to compare an object to the object 
> "None" using "is not".
> "==" is, IMHO, more simple. Simple is better than complex.. So I use "==".

The archives could tell you more, but basically on is usually interested 
in *identity* with a singleton object (None), not in whether the object 
on is examining happens to compare equal.  A custom object could be 
designed to compare equal to None in certain cases, even though it *is 
not* None, leading to the "== None" approach being defective code.

In the specific code in question, it won't make any differences, but I 
pointed it out to help folks who don't know this to start developing the 
safer habit, which is always to use "is" and "is not" with None (or, 
generally, with other singletons).

> The correct program is:
> 
> import urllib2
> for line in open("fileName.txt"):
> addr, port  = urllib2.splitport (line)
> print (port == None) and '' or port

Nope, sorry... the point is that the "and/or" pseudo-ternary operator is 
inherently flawed if the operand after "and" evaluates False.  Check 
this out:

 >>> port = None
 >>> print (port == None) and '' or port
None
 >>> print (port != None) and '' or port
None

and even:

 >>> print (port is None) and '' or port
None

So the bug isn't in using "!=" instead of "==", or using equality 
instead of identity comparison, it is in trying to use the and/or 
expression for a purpose it wasn't intended for.

> or
> 
> import urllib2
> for line in open("fileName.txt"):
> addr, port  = urllib2.splitport(line)
> if port == None:
> print ''
> else:
> print port

That should work nicely... and it's more readable too!

Note that in Python 2.5 you should be able to write this as

 print '' if port is None else port
or  print '' if (port is None) else port

but it's quite arguable whether that is better than the simple if/else 
statement in this case.

-Peter

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


Re: Passing a method indirectly

2006-03-04 Thread Farshid Lashkari
You don't need to pass the object along with the method. The method is 
bound to the object. Simply call the method by itself:

def ObjApply(method):
method()

class Test:
def test1 (self): print "Hello"
def test2 (self):
ObjApply(self.test1)

ta = Test ()
ta.test2 ()

If you wanted to pass an unbound method, then it would look like the 
following:

def ObjApply(object,method):
method(object)

class Test:
def test1 (self): print "Hello"
def test2 (self):
ObjApply(self,Test.test1)

ta = Test ()
ta.test2 ()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing a method indirectly

2006-03-04 Thread André

swisscheese wrote:
> I'm trying to write a function that takes an arbitrary object and
> method.
> The function applies the method to the object (and some other stuff).
> I get error "Test instance has no attribute 'method' "
> How can I make this work?
>
> def ObjApply (object,method):
>   object.method ()
>
> class Test:
>   def test1 (self): print "Hello"
>   def test2 (self):
>   ObjApply (self,self.test1)
>
> ta = Test ()
> ta.test2 ()

You need to add one line (2nd one below).

def ObjApply (object, method):
object.method = method
object.method()

class Test:
def test1 (self): print "Hello"
def test2 (self):
ObjApply (self, self.test1)

ta = Test ()
ta.test2 ()

André

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


Passing a method indirectly

2006-03-04 Thread swisscheese
I'm trying to write a function that takes an arbitrary object and
method.
The function applies the method to the object (and some other stuff).
I get error "Test instance has no attribute 'method' "
How can I make this work?

def ObjApply (object,method):
object.method ()

class Test:
def test1 (self): print "Hello"
def test2 (self):
ObjApply (self,self.test1)

ta = Test ()
ta.test2 ()

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


Cryptographically random numbers

2006-03-04 Thread Tuvas
Okay, I'm working on devoloping a simple, cryptographically secure
number, from a range of numbers (As one might do for finding large
numbers, to test if they are prime). My function looks like this:

def cran_rand(min,max):
if(min>max):
x=max
max=min
min=x
range=round(log(max-min)/log(256))
if range==0:
range=1
num=max+1
while(num>max):
num=min+s2num(urandom(range))
return num

Any comments on this? I think it should hold up to a test, it seems to
work alright. Thanks!

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


Re: Suggestions for documentation generation?

2006-03-04 Thread Bo Peng
kpd wrote:
> Hello,
> 
> I have written a C++ library that I've then wrapped with Pyrex.
> Any suggestions to the best-in-class tool to create documentation for
> the libraries?
> 
> I would love to document things in one spot (could be the code) and
> generate html and PDF from there.
> 
> Doxygen (www.doxygen.org) looks to be about the best so far. 
> 
>

I was facing the same problem and took the following approach:

1. write c++ code with doxygen-complaint comments
2. generate XML comments using doxygen
3. parse XML and generate Python docstring
4. insert the docstring into SWIG interface file

I can send you the parser but I do not know if pyrex support python 
docstring.

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


Re: How to except the unexpected?

2006-03-04 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> My suggestion was to use some common sense about the source code and
> apply it.

The common sense to apply is that if the source code says one thing
and the documentation says another, then one of them is wrong and
should be updated.  Usually it's the source code that's wrong, but in
either case, saying to ignore the documentation and follow the code,
rather than repairing the discrepancy somehow, is poor advice.

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


Re: Advice from distutils experts?

2006-03-04 Thread Robert Kern
[EMAIL PROTECTED] wrote:
> I'm doing something a little wierd in one of my projects.  I'm
> generating a C source file based on information extracted from python's
> header files.  Although I can just generate the file and check the
> result into source control, I'd rather have the file generated during
> the install process instead of doing it manually.
> 
> So I'd like to:
> + have the file generated when a unix user runs setup.py install.
> + have the file generated when I create a windows binary
> distribution.
> + not have the file generated when I create source distribution
> .tgz's and .zip's.
> 
> I'd appreciate any pointers on the best way to hook into disutils to do
> this.  And if the answer is "Your crazy, generate the file outside of
> distutils." just let me know.

We do things like this in numpy. We've extended distutils to allow functions in
the sources list for Extension.

from numpy.distutils.core import Extension
from distutils.dep_util import newer

def generate_source_c(ext, build_dir):
target = os.path.join(build_dir, 'source.c')
if newer(__file__, target):
# ... parse Python headers
contents = """
#include "Python.h"
/* ... */
""" % (stuff, more_stuff)
f = open(target, 'w')
f.write(contents)
f.close()
return target

ext = Extension('my_extension',
sources=[generate_source_c],
)

setup(#...
ext_modules=[ext]
)

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: How to except the unexpected?

2006-03-04 Thread James Stroud
Paul Rubin wrote:
> James Stroud <[EMAIL PROTECTED]> writes:
> 
>>>approach. Basically this is reverse engineering the interface from the
>>>source at the time of writing the app.
>>
>>This is using the source as documentation, there is no law against
>>that.
> 
> That's completely bogus.  Undocumented interfaces in the library
> source are allowed to change between Python versions and across Python
> implementations.  If you write your application according to the
> documented interfaces in the Python manual, it should not break when
> someone upgrades to the next Python release.  You should not have to
> depend on undocumented aspects of the Python implementation which
> change out of sync with the application.
> 

My suggestion was to use some common sense about the source code and 
apply it. I've wasted many hours programming to faulty documentation 
when a quick peek at the source code would have saved some serious time. 
   How do you think I happened accross the technique?

I would wager that, in 10 years time, the urllib2 module will not raise 
any exceptions that don't inheret from urllib2.URLError or a built-in 
(i.e. documented) exception; unless, of course, someone made a change in 
a deliberate attempt to win said wager ;o)

>>How things are and how things should be have always been 2 entirely
>>different things. See early books by Robert J. Ringer for a more
>>complete discussion.
> 
> That's like saying programs shouldn't have bugs, but they often do
> anyway.  It doesn't mean the bugs are a good thing or that they
> shouldn't be fixed.

The original reference was to the internet, which seems vast in its 
sources of unforseen peril. If some gracious soul aspires to fix every 
bug in the internet, I invite him to be my guest.

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


Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Tuvas
Okay, I don't know if your farmiliar with the miller-rabin primality
test, but it's what's called a probabalistic test. Meaning that trying
it out once can give fake results. For instance, if you use the number
31 to test if 561 is prime, you will see the results say that it isn't.
Mathematically, the most possible wrong answers is 1/4th of the
numbers. Thus, one should try at least 10 times (A very standard value)
in order to ensure that the number is not a psuedoprime, but indeed a
real prime number. That was the intent of the loop of 10 without using
the number.

If this test fails, it will chose another random number to test.

I could easily test with several small numbers, at least primes up to
20 would greatly reduce the number of miller-rabin tests to perform,
and would speed up the process considerably. Might as well toss it in.

Thanks for the tip on the urandom. I knew there had to be a better
random number generator somewhere. I saw lots of stuff for os specific,
but I'm trying to develop this as os independent.

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


CallBack

2006-03-04 Thread Ramkumar Nagabhushanam
Hello All,
I am trying to integrate the ftpclient (in ftplib) with an application that
has been written I C/C++.
I am able to delete,send change working directories etc. When I receive data
back from the server i.e. Retrieve files, get a directory listing) I want to
pass a callback function to the ftpclient so that the output does not get
displayed on stdout. The code I have written is as shown below. Can anyone
out there give me advise on how to write "c_function" that is called in
ftpTest::DoesFileExist ?Any help will be most appreciated. The code runs
under windows and is compiled with VC++ 6.0. THe code is as shown below.
Regards,
Ram
 
>>> CODE START >>>
// test.cpp : Defines the entry point for the console application.
//
#include 
#include 
#include 
#include 
#include 
#include "C:\Python24\include\Python.h"
 
Class ftpTest
{
Private:
 PyObject *_FTP;
 PyObject *_callBack;
 
Public:
 FtpTest (const char * ipAddress, const char * username, const char *
password); // Open the FTP connection, Initialize python interpreter
 ~ftpTest (); // Close connection and finalize python interpreter
 Int Close ();
 Int GetFile (const char * fileName);
 Int PutFile (const char * fileName);
 Int ChangeDir (const char * dirName);
 Int DoesFileExist (const char * fileName);
 Int DeleteFile (const char * fileName);
 Int ChangePermissions (const char * fileName, const char * permissions);
};
 
FtpTest::ftpTest (const char * ipAddress, const char * username, const char
* password)
{
 PyObject *modname, *mod, *func, *mdict, *pArgs, *pValue;
 
 // Initialize the python interpreter
 Py_Initialize();
 
 Modname = PyString_FromString("ftplib");
 
 If (modname == NULL)
 {
  // Log an error
 }
 Else
 {
  Mod = PyImport_Import (modname);
 }
 
 If (mod)
 {
  Mdict = PyModule_GetDict (mod);
  Func = PyDict_GetItemString (mdict, "FTP");
  If (func)
  {
   Printf ("I am here -- 1\n");
  }
 
  Const char *arguments[] = {ipAddress, username, password};
 
  PArgs = PyTuple_New (3);
For (int I = 0; I < 3; ++I) 
  {
PValue = PyString_FromString(arguments[I]);
If (!pValue) 
   {
Py_DECREF(pArgs);
Py_DECREF(mod);
}
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, I, pValue);
}
 
  _FTP = PyObject_CallObject (func, pArgs);
 
  If (_FTP != NULL)
  {
   Printf ("I am here -- 2\n");
  }
 }
}
 
FtpTest::~ftpTest ()
{
 //Py_Finalize();
}
 
Int ftpTest::Close ()
{
 Return (1);
}
 
Int ftpTest::ChangeDir (const char * dirName)
{
 PyObject *t = PyObject_CallMethod (_FTP, "cwd", "(S)", dirName);
 Return (1);
}
 
Int ftpTest::DeleteFile (const char * fileName)
{
 PyObject *t = PyObject_CallMethod (_FTP, "delete", "(S)", fileName);
 Return (1);
}
 
Int ftpTest::PutFile (const char * fileName)
{
 PyObject * py_file = PyFile_FromString ((char *)fileName, "rb"); 
 Std::string S("STOR ");
 s += fileName;
 PyObject * t = PyObject_CallMethod (_FTP, "storlines", "(sO)", S.c_str(),
py_file);
 Return (1);
}
 
Int ftpTest::ChangePermissions (const char * fileName, const char *
permissions)
{
 Std::string S("SITE");
 s += " chmod ";
 s += permissions;
 s += " ";
 s += fileName;
 PyObject * t = PyObject_CallMethod (_FTP, "sendcmd", "(S)", S.c_str());
 Return (1);
}
 
Int ftpTest::GetFile (const char * fileName)
{
// TODO: Implement callback
#if 0
 PyObject *t = PyObject_CallMethod (_FTP, "retrlines", "(S)", "RETR ram.txt
);
#endif
 Return (1);
}
 
PyObject * c_function(char * data)
{
 // Process the data received in "data"
 Return (NULL);
}
 
Int ftpTest::DoesFileExist (const char * fileName)
{
 // Just get the list
 PyObject *t = PyObject_CallMethod (_FTP, "retrlines", "(sO)", "LIST",
c_function);
 If (t == NULL)
 {
  Printf ("I am here -- 4\n");
 }
 Return (1);
}
 
Int main ()
{
 FtpTest ftpClient("127.0.0.1", "xxx", "");
 FtpClient.DoesFileExist(NULL);
 Return (1);
}

>>> CODE END >
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spliting on ":"

2006-03-04 Thread Petr Jakes
> I think you're getting caught by the classic and/or trap in Python,
> trying to avoid using a simple if statement.

What do you mean by "the classic and/or trap"? Can you give an example
please?

Petr Jakes

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


Re: spliting on ":"

2006-03-04 Thread Cyril Bazin
Ok, ok, there was a mistake in the code. (Of course, it was done on prupose in order to verify if everybody is aware ;-)I don't know why it is preferable to compare an object to the object "None" using "is not".
"==" is, IMHO, more simple. Simple is better than complex. So I use "==". The correct program is:import urllib2for line in open("fileName.txt"):    addr, port  = urllib2.splitport
(line)
    print (port == None) and '' or portor import urllib2
for line in open("fileName.txt"):
    addr, port  = urllib2.splitport(line)

    if port == None:    print ''     else:    print port
On 3/4/06, Peter Hansen <[EMAIL PROTECTED]> wrote:
Cyril Bazin wrote:> Your file looks like a list of IP adresses.> You can use the urllib and urllib2 modules to parse IP adresses.>> import urllib2> for line in open("fileName.txt"):
> addr, port  = urllib2.splitport(line)> print (port != None) and '' or portIs this what you want to happen when port is None? >>> port = None >>> print (port != None) and '' or port
NoneI think you're getting caught by the classic and/or trap in Python,trying to avoid using a simple if statement.By the way, equality comparison with None is generally a bad idea aswell, so even if the above worked it should be (port is not None) rather
than (port != None).-Peter--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to except the unexpected?

2006-03-04 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> > approach. Basically this is reverse engineering the interface from the
> > source at the time of writing the app.
> 
> This is using the source as documentation, there is no law against
> that.

That's completely bogus.  Undocumented interfaces in the library
source are allowed to change between Python versions and across Python
implementations.  If you write your application according to the
documented interfaces in the Python manual, it should not break when
someone upgrades to the next Python release.  You should not have to
depend on undocumented aspects of the Python implementation which
change out of sync with the application.

> How things are and how things should be have always been 2 entirely
> different things. See early books by Robert J. Ringer for a more
> complete discussion.

That's like saying programs shouldn't have bugs, but they often do
anyway.  It doesn't mean the bugs are a good thing or that they
shouldn't be fixed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Papers on Dynamic Languages

2006-03-04 Thread Paul Boddie
Jay Parlar wrote:
>
> Anyway, I want to talk about things like typing disciplines (weak,
> strong, etc.),"class vs. prototype, JIT technologies in dynamic
> languages, interactive interpreters, etc.

There are a few classic papers on a number of these topics, but I'll
leave it to the papers mentioned below to provide references.

> I've got Brett Cannon's thesis already, but I'm looking for references
> to some more papers on these topics. A Python basis for any of the
> papers would be preferred, but anything will do.
>
> Any suggestions? This is my first real research paper in grad school,
> so I'm starting out from scratch here.

I'd have a look at the following Python-related papers:

Michael Salib's Starkiller paper (and presentation):
http://www.python.org/pycon/dc2004/papers/1/

Mark Dufour's ShedSkin paper:
http://kascade.org/optimizing_python.pdf

John Aycock's "Aggressive Type Inference" paper:
http://www.python.org/workshops/2000-01/proceedings/papers/aycock/aycock.html

I also provided a fair number of references in the following thread:

http://groups.google.co.uk/group/comp.lang.python/browse_thread/thread/cc98317bdf96efda

I hope this is of use!

Paul

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


Advice from distutils experts?

2006-03-04 Thread olsongt
I'm doing something a little wierd in one of my projects.  I'm
generating a C source file based on information extracted from python's
header files.  Although I can just generate the file and check the
result into source control, I'd rather have the file generated during
the install process instead of doing it manually.

So I'd like to:
+ have the file generated when a unix user runs setup.py install.
+ have the file generated when I create a windows binary
distribution.
+ not have the file generated when I create source distribution
.tgz's and .zip's.

I'd appreciate any pointers on the best way to hook into disutils to do
this.  And if the answer is "Your crazy, generate the file outside of
distutils." just let me know.

-Grant

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


Re: The old round off problem?

2006-03-04 Thread David Treadwell
On Mar 4, 2006, at 4:33 PM, Paul Rubin wrote:

> "sam" <[EMAIL PROTECTED]> writes:
>> Hello all, I am taking a class in scientific programming at the local
>> college. My problem is that the following difference produces  
>> round off
>> errors as the value of x increases. For x >= 19 the diference goes to
>> zero.I understand the problem, but am curious as to whether their
>> exists a solution.   [f(x)  = cosh^2(x) - sinh^2(x)  = 1]
>
> The usual way is to notice that the difference goes to zero because
> the lowest order terms of the Taylor series for cosh^2 and sinh^2 are
> equal and cancel each other out.  The solution is to write down the
> series for (cosh^2(x) - sinh^2(x)) and add up a few non-cancelled  
> terms.
> All these series should converge very fast.

Here's my analysis:

First, keep in mind that the range of values for a Taylor expansion  
of sinh() and cosh() is limited. Then...

Write down the series for (cosh^2(x) - sinh^2(x)), as Paul suggested.

c2 = taylor(cosh(x)^2,x,8)

s2 = taylor(sinh(x)^2,x,8)

The first method gives the expected answer:

eval(c2-s2) ==> 1

Write down the series for cosh(x), square that; write the series for  
sinh(x), square that and subtract.

Compare the two (I just did this in Eigenmath). Higher-order terms  
remain for the second method.. I don't know how many terms my cosh()  
and sinh() functions use, but if I evaluate (again, in Eigenmath)

The second method, which is more akin to what Python is doing (unless  
there is an explicit 'sinh**2(x)' function) is different.

c2 = (taylor(cosh(x),x,8))^2, which gives terms up to and including  
(x**8)**2 = x**16

s2 = (taylor(sinh(x),x,9))^2, which gives terms up to and including  
x**18, then subtract the two, the result is

eval(c2 - s2) ==> 1 - 1/1814400 * x**10 - ... higher terms.

This begs the question, "What is the algorithm used by my Python?"

And, the ever-important question, "Does it matter in my final  
result?" This is important, because I do not, in general, trust the  
result when subtracting two large numbers.

:--David T.


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


Re: spliting on ":"

2006-03-04 Thread Peter Hansen
Cyril Bazin wrote:
> Your file looks like a list of IP adresses.
> You can use the urllib and urllib2 modules to parse IP adresses.
> 
> import urllib2
> for line in open("fileName.txt"):
> addr, port  = urllib2.splitport(line)
> print (port != None) and '' or port

Is this what you want to happen when port is None?

 >>> port = None
 >>> print (port != None) and '' or port
None


I think you're getting caught by the classic and/or trap in Python, 
trying to avoid using a simple if statement.

By the way, equality comparison with None is generally a bad idea as 
well, so even if the above worked it should be (port is not None) rather 
than (port != None).

-Peter

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


Re: How to except the unexpected?

2006-03-04 Thread James Stroud
Rene Pijlman wrote:
> James Stroud:
> 
>>Which suggests that "try: except HTTPException:" will be specific enough 
>>as a catchall for this module.
>>
>>The following, then, should catch everything you mentioned except the 
>>socket timeout:
> 
> 
> Your conclusion may be (almost) right in this case. I just don't like this
> approach. Basically this is reverse engineering the interface from the
> source at the time of writing the app.

This is using the source as documentation, there is no law against that. 
It's better than waiting for a closed source software mogul to 
benevolently give you the API documentation, which may not be 100% 
accurate itself.

> Even if you get it right, it may
> fail next week when someone added an exception to a module.

Given how all of the exceptions raised by both modules are either (1) 
builtin or (2) defined in the module itself and given that all 
exceptions defined in these modules inheret from a single class, my 
money is on the fact that this approach should be forward compatible.

> 
>>But it seems to me that working with the internet as you are doing is 
>>fraught with peril anyway.
> 
> Why? It shouldn't be.
> 

How things are and how things should be have always been 2 entirely 
different things. See early books by Robert J. Ringer for a more 
complete discussion.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> > try:
> > process_things()
> > except Reraise:
> > raise
> > except:
> > log_error()
> >
> 
> Why catch an error only to re-raise it?
> 
> This falls under http://c2.com/cgi/wiki?YouReallyArentGonnaNeedThis

No, without the reraise, the bare "except:" clause would capture the
exception incorrectly and log it as an error.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The old round off problem?

2006-03-04 Thread Paul Rubin
"sam" <[EMAIL PROTECTED]> writes:
> Hello all, I am taking a class in scientific programming at the local
> college. My problem is that the following difference produces round off
> errors as the value of x increases. For x >= 19 the diference goes to
> zero.I understand the problem, but am curious as to whether their
> exists a solution.   [f(x)  = cosh^2(x) - sinh^2(x)  = 1]

The usual way is to notice that the difference goes to zero because
the lowest order terms of the Taylor series for cosh^2 and sinh^2 are
equal and cancel each other out.  The solution is to write down the
series for (cosh^2(x) - sinh^2(x)) and add up a few non-cancelled terms.
All these series should converge very fast.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: add an asynchronous exception class

2006-03-04 Thread Paul Rubin
"Christian Stapfer" <[EMAIL PROTECTED]> writes:
> I guess it means the following:
> 
> "Terminating exceptions" are exceptions that
> terminate the *thrower* of the exception.

Are you sure?  I didn't read it that way.  I'm not aware of there ever
having been a detailed proposal for resumable exceptions in Python,
though the gurus would know better than I do whether there's been one.

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


Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Paul Rubin
"Tuvas" <[EMAIL PROTECTED]> writes:
> I have made and recently posted a libary I made to do Modular
> Arithmetic and Prime numbers on my website  at
> http://www.geocities.com/brp13/Python/index.html . I am currently in a
> crypotology class, and am working on building a RSA public key
> cryptology system for a class project. I am building the librarys just
> to get the experience to do so.

I'm looking at 
  http://www.geocities.com/brp13/Python/prime3.html

You do something for x in range(10) but you don't use x in the loop.

I'll guess you actually intended to pick some random number n and find
the closest prime p >= n.  That's not a good strategy: imagine you pick
a random number n in the range 1..50.  Let's say n is 14.  14 isn't
prime, so you check 15, 16, and 17.  17 is prime so you return p = 17.
You also return 17 if n is 15, 16, or 17.  So the chance of your
returning p = 17 is 4/50.

What is your chance of returning p = 19?  It means n has to be 18 or
19, so the chance is only 2/50.  That's not good--you want all primes
to be equally likely.

Anyway, the simplest approach is:

1) get random numbers by reading characters from os.urandom() and
converting them to integers.  Don't use randint which makes no attempt
at cryptographic security.

2) For each random integer (you can set the low bit to make sure it is
odd), test against some small prime divisors p (say the primes up to
1000) as a fast way to throw away some composites.  If n%p == 0 for
any p, throw away n and go back to step 1.

3) If you get an n with no small divisors, do the (slow) Miller-Rabin
test.  If it passes, you're done; if it fails, go back to step 1.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Alex Martelli
James Stroud <[EMAIL PROTECTED]> wrote:

> > Reraise = (LookupError, ArithmeticError, AssertionError) # And then some
> > 
> > try:
> > process_things()
> > except Reraise:
> > raise
> > except:
> > log_error()
> > 
> 
> Why catch an error only to re-raise it?

To avoid the following handler[s] -- a pretty common idiom.


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


Open source reliability study

2006-03-04 Thread bearophileHUGS
They have used a lot of time and money to find bugs in Python too:
http://www.theregister.co.uk/2006/03/03/open_source_safety_report/print.html

0.32 defects per 1,000 lines of code in LAMP, it says.
I hope they will show such Python bugs, so Python developers can try to
remove them. From the bottom of the article:

>Coverity said it would now engage with open source developers to improve code, 
>and identify potential reasons for why some projects have more bugs than 
>others.<

Bye,
bearophile

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


Re: How to except the unexpected?

2006-03-04 Thread James Stroud
Rene Pijlman wrote:
> Steven D'Aprano:
> 
>>ExpectedErrors = (URLError, IOError)
>>ErrorsThatCantHappen =
>>
>>try:
>>   process_things()
>>except ExpectedErrors:
>>   recover_from_error_gracefully()
>>except ErrorsThatCantHappen:
>>   print "Congratulations! You have found a program bug!"
>>   print "For a $327.68 reward, please send the following " \
>>   "traceback to Professor Donald Knuth."
>>   raise
>>except:
>>   print "An unexpected error occurred."
>>   print "This probably means the Internet is broken."
>>   print "If the bug still occurs after fixing the Internet, " \
>>   "it may be a program bug."
>>   log_error()
>>   sys.exit()
> 
> 
> Yes, I think I'll do something like this. Perhaps combined with Peter's
> advice to not micromanage, like so:
> 
> Reraise = (LookupError, ArithmeticError, AssertionError) # And then some
> 
> try:
> process_things()
> except Reraise:
> raise
> except:
> log_error()
> 

Why catch an error only to re-raise it?

This falls under http://c2.com/cgi/wiki?YouReallyArentGonnaNeedThis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python advocacy in scientific computation

2006-03-04 Thread Terry Hancock
On Sat, 4 Mar 2006 14:23:10 -0500
David Treadwell <[EMAIL PROTECTED]> wrote:
> On Mar 4, 2006, at 5:55 AM, Dennis Lee Bieber wrote:
> > On Fri, 3 Mar 2006 22:05:19 -0500, David Treadwell
> > <[EMAIL PROTECTED]> declaimed the following
> > in comp.lang.python:
> >> 3. I demand a general-purpose toolkit, not a
> >gold-plated screwdriver. >
> >
> > Would a gold-plated sonic screwdriver work? 
> > {Let's see how many
> > catch that reference}
> >
> 
> Google makes this game too easy, but it's to Who you
> refer. How about   _this_ reference: "What we all need is
> a left-handed monkey wrench."   

You know, it just occured to me that you sent me on a quest
to get a "left-handed monkey wrench", and like a fool, I
went.  Of course, I found not one, but many...

In fact, this expression has so many echoes on the
web, it would be difficult to ascertain where it actually
came from (the derivation is obvious, of course, but who
first coined the expression?).

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: how to record how long i use the intenet

2006-03-04 Thread Gerard Flanagan

[EMAIL PROTECTED] wrote:
> use python
> use ADSL
> use windows XP
> i want to record the time when i get on the internet and off the
> internet
> into a txt file
> HOW?


http://en.wikipedia.org/wiki/Water_clock


HTH

Gerard

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


Re: Easy immutability in python?

2006-03-04 Thread Alex Martelli
Terry Hancock <[EMAIL PROTECTED]> wrote:
   ...
> I also am not trying to alter the Python language. I am
> trying to figure out how to most easily fix __setattr__ etc
> to act immutably, *using* the existing features.
> 
> I can already do what I want with some 25-30 lines of code
> repeated each time I need it, but I think it's dumb that
> it's that complicated.

If you need many immutable classes, inject __setattr__ etc into them
(via metaclass or otherwise).


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


Re: Easy immutability in python?

2006-03-04 Thread jess . austin
I guess we think a bit differently, and we think about different
problems.  When I hear, "immutable container", I think "tuple".  When I
hear, "my own class that is an immutable container", I think, "subclass
tuple, and probably override __new__ because otherwise tuple would be
good enough as is".

I'm not sure how this relates to the clp thread that you cite.  I
didn't read the whole thing, but I didn't find it to be a flamewar so
much as a typical clp contest of tedium, which failed to devolve into a
flamewar simply due to the maturity of the interlocutors.  To
summarize: first post is a use case, second post is an implementation
of that use case, and subsequent posts alternate between "that's not
how I want to do it" and "please provide a more specific use case for
which the provided implementation is not acceptable".

good luck,
Jess

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


Re: spliting on ":"

2006-03-04 Thread Cyril Bazin
Your file looks like a list of IP adresses. You can use the urllib and urllib2 modules to parse IP adresses.import urllib2for line in open("fileName.txt"):    addr, port  = urllib2.splitport(line)
    print (port != None) and '' or portCyril
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Easy immutability in python?

2006-03-04 Thread Terry Hancock
On 4 Mar 2006 10:14:56 -0800
[EMAIL PROTECTED] wrote:
> Since this is a container that needs to be "immutable,
> like a tuple", why not just inherit from tuple?  You'll
> need to override the __new__ method, rather than the
> __init__, since tuples are immutable:
> 
> class a(tuple):
> def __new__(cls, t):
> return tuple.__new__(cls, t)

The reason this is undesireable, is because in the typical
use-case, I want to have TWO kinds of objects, one mutable,
and one immutable. Just like tuple / list. I would prefer
not to have to implement them completely separately.  So
far, it's usually simpler to implement the mutable type
first -- the need for immutability semantics usually arises
after you have a mutable version. 

But undoing mutability apparently is like making a sieve
watertight -- it would've been easier to design a ladle and
then put holes in it, than to design a sieve and then stop
up the holes.

In fact, my particular case wants to subclass Set and
ImmutableSet -- their contents, though, are also immutables
in principle.  In fact the elements are similar to "int" or
"str", but I don't want to subclass those, because I don't
want them to have math methods or string methods.

I've considered several different approaches to this. One is
to create a "BaseVocabulary" as an abstract class, from
which the mutable and immutable types are drawn, and then
mix it in with Set and ImmutableSet:

class BaseVocabulary(object):
def __init__(self, values):
self._data = values
# (or something like that)
# other functionality

class Vocabulary(Set, BaseVocabulary):
# stuff appropriate for the "open" vocabulary
pass

class Enumeration(ImmutableSet, BaseVocabulary):
# stuff appropriate for the "closed" enumeration
pass

This is bad, both aesthetically and practically.
Aesthetically, because "abstract classes stink of Java" and
pragmatically because the __init__ from BaseVocabulary
will generally not work for the immutable case.

So I either have to rewrite it special, or go back in
time and fix the original, knowing that I'm going to want
an immutable variant.

Again with the aesthetics, it's just ugly that I can't
mutate an object in its __init__ and then make it immutable
after I'm done setting it up. The approach with __new__ and
using the superclass's __setattr__ to set values is nasty
boilerplate-rich cruft which forces me to go back and
completely re-implement the same functionality in a
completely different way, just because of something that
seems like a simple conceptual change (i.e. "don't overwrite
or extend this thing -- make a new one if you need a
change").

I even tried defining __setattr__ at the end of the
__init__, but that doesn't seem to work (or I'm doing it
wrongly).

Right now I'm leaning towards making a class "Immutable"
with all the mutator methods raising NotImplementedError,
and then subclass from this so that it overrides the
necessary methods. It's still going to mess with me, though,
because it will not allow the __init__ to work as planned,
and I'll have to go back and redesign the base class to work
with or without immutability.

Alternatively, I could just decide to change my practice and
implement ALL objects on the assumption that they will be
immutable, and add *mutability* after-the-fact. But that
seems like extraordinarily bad practice, since mutability is
usually the better default.

I'm going to dig through the sets module code to see how it
does this, but what little I've seen gives me a bad feeling
that this simple idea is hard to implement simply in Python
-- and that strikes me as a "wart", yes.

So, I'm wondering if there is a simple way after all.

1) Is there an idiom for this that I just don't know?

2) Have recent changes to the language made it easier?
   (__new__ for example, is apparently new, or at least
   newly documented -- but as I say, I'm not sure it's
   the most practical solution for this problem).

3) Is there a "remarkably clever" way that I can tack
   on, even if it isn't exactly simple?

and only in the unlikely event that answers 1-3 are all
"no", would I ask:

4) And as a last resort, if it really is hard, why?
   Shouldn't a simple idea to express in English be easy to
   express in Python? If it's really impossibly difficult,
   maybe Python should provide a means to implement it.

Cheers,
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


XP rich text cut-n-paste

2006-03-04 Thread Paddy
Hi,
Is their a colourized editor/shell that allows you to cut and paste the
colourized text?

Idle, SPE, Eclipse, and pythonwin all seem to nicely colourize both
command line input as well as editor windows but when I cut and paste
(in this case, into OpenOffice Writer), even the paste-special menu
just allows the pasting of un-adorned text.

i have a work-around: gvim coourizes and allows export as html, but it
is long-winded.

Thanks in advance, Paddy.

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


Papers on Dynamic Languages

2006-03-04 Thread Jay Parlar
For one of my grad school classes, I'm writing a paper on "Dynamic 
Languages". What a wonderfully vague topic (but at least it'll let me 
write about Python).

Anyway, I want to talk about things like typing disciplines (weak, 
strong, etc.),"class vs. prototype, JIT technologies in dynamic 
languages, interactive interpreters, etc.

I've got Brett Cannon's thesis already, but I'm looking for references 
to some more papers on these topics. A Python basis for any of the 
papers would be preferred, but anything will do.

Any suggestions? This is my first real research paper in grad school, 
so I'm starting out from scratch here.

Jay P.

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


how to record how long i use the intenet

2006-03-04 Thread b53444
use python
use ADSL
use windows XP
i want to record the time when i get on the internet and off the
internet
into a txt file
HOW?

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


Re: Python advocacy in scientific computation

2006-03-04 Thread David Treadwell
On Mar 4, 2006, at 5:55 AM, Dennis Lee Bieber wrote:


> On Fri, 3 Mar 2006 22:05:19 -0500, David Treadwell
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
>
>
>> My ability to think  of data structures was stunted BECAUSE of
>> Fortran and BASIC. It's very difficult for me to give up my bottom-up
>> programming style, even though I write better, clearer and more
>> useful code when I write top-down.
>>
>>

IIRC, during 1984, my senior year, BYTE magazine had a cover story on  
OOP. (OH, how I loved the cover art back in the day!) My impression  
after reading the article: WTF is that for? Every class I had which  
needed programming, be it CS or chemical engineering, taught it in a  
very linear, bottom-up fashion. First you read inputs, then do Foo,  
then do Bar, then do (fill in your favorite third-level word).

It was even worse in the chemistry department. No chem major (other  
than myself, as I also was a chem eng major) had _any_ computer  
courses beyond the required Fortran 101. It was a struggle to get any  
chemistry student to do anything that required using LINPAC,  
Mathematical Recipes code or a plotting program.

This level of absurdity reached its apex during grad skewl when I  
wrote a monolithic 30-page program in MS QuickBasic for Mac to  
simulate NMR spectra. No one else was ever able to understand how to  
use the program.

Even worse, that 30-page program disappeared the day Mac System 7.0  
was installed. The byte-compiled basic code became unreadable because  
System 7 permanently broke QuickBasic.

The last program I wrote for anyone else's use was written in VBA/ 
Excel. I hated every minute of it, but the request was made because  
everyone has Excel, and nobody wanted to install Python. VBA has at  
least 3 API's running simultaneously (Excel, VBA-classic and VBA- 
pseudoOOP). Now that I know Py2App, that dragon has been slain.

Which brings me to my last point: Why be beholden to the graces of a  
single-source supplier of a language or OS? Proprietary systems will  
always become either (a) extinct or (b) so crammed with legacy code  
they become unreliable.

I still don't get OOP completely, but Python has helped a great deal.


>   FORTRAN was quite amenable to "top-down" design (which was barely
> taught during my senior year: 1980; and I'm a CS major -- you don't  
> want
> to see the text used for the "systems analysis" class; I don't recall
> ever seeing a "requirement document" created in the entire text...)
>
>   I've done lots of FORTRAN stuff where the main program was
> interchangeable...
>
>   program main
>   ...
>   call Initialize()
>   call Process()
>   call CleanUp()
>   stop
>   end
>

Sure. It seems logical now. But remember, I learned WatFiv Fortran,  
which came before even Fortran 77. I saw my first Fortran 95 code  
about two years ago. It took me a while to realize that what I was  
looking at _was_ Fortran!


>> 3. I demand a general-purpose toolkit, not a gold-plated screwdriver.
>>
>
>   Would a gold-plated sonic screwdriver work?  {Let's see how many
> catch that reference}
>

Google makes this game too easy, but it's to Who you refer. How about  
_this_ reference: "What we all need is a left-handed monkey wrench."  


:--David

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


Re: Easy immutability in python?

2006-03-04 Thread Terry Hancock
Whoops I forgot to list the reference.
Also, I just finished reading the old thread, so I see some
damage-control may be needed.

On Sat, 4 Mar 2006 11:52:59 -0600
Terry Hancock <[EMAIL PROTECTED]> wrote:
> [1]
> http://news.hping.org/comp.lang.python.archive/28916.html

And more specifically, I'm referring to Alex Martelli's
reply:

http://news.hping.org/comp.lang.python.archive/28966.html

[Vain attempt to co-opt a flame-war follows]

And having seen that that discussion largely devolved into a
rant about why "you shouldn't do that", can we PLEASE
restrict this thread to the *how*?

My use case is quite similar to Ben's enumeration type. In
both cases, assigning attributes to the objects is
NONSENSICAL and possibly UNWISE.  Any attempt to do so is
almost certainly a bug in your code if you are using my
module -- and it happens to be one I want to make sure I
catch.  It is also true that the average person using my
code is not a blackbelt pythoneer, but rather a scripter who
needs/wants training wheels whenever it is practical to
provide them.

If you are REALLY sure you want mutability, you can always
subclass it.

If you think that code that handles prime numbers by marking
integer objects like so:

101.prime = True

is "just fine", and are not bothered that 101 is
mysteriously unclassified sometime after you've marked it
(because 100+1 is 101 == False), then we are not going to
see eye-to-eye, so let's not argue about it.

I also am not trying to alter the Python language. I am
trying to figure out how to most easily fix __setattr__ etc
to act immutably, *using* the existing features.

I can already do what I want with some 25-30 lines of code
repeated each time I need it, but I think it's dumb that
it's that complicated.

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: generators shared among threads

2006-03-04 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:

> hi,
> 
> This seems like a difficult question to answer through testing, so I'm
> hoping that someone will just know...  Suppose I have the following
> generator, g:
> 
> def f()
> i = 0
> while True:
> yield i
> i += 1
> g=f()
> 
> If I pass g around to various threads and I want them to always be
> yielded a unique value, will I have a race condition?  That is, is it

Yes, you will.

> before resuming the first thread?  If so, would I get different
> behavior if I just set g like:
> 
> g=itertools.count()

I believe that in the current implementation you'd get "lucky", but
there is no guarantee that such luck would persist across even a minor
bugfix in the implementation.  Don't do it.
 
> If both of these idioms will give me a race condition, how might I go
> about preventing such?  I thought about using threading.Lock, but I'm
> sure that I don't want to put a lock around the yield statement.

Queue.Queue is often the best way to organize cooperation among threads.
Make a Queue.Queue with a reasonably small maximum size, a single
dedicated thread that puts successive items of itertools.count onto it
(implicitly blocking and waiting when the queue gets full), and any
other thread can call get on the queue and obtain a unique item
(implicitly waiting a little bit if the queue ever gets empty, until the
dedicated thread waits and fills the queue again).  [[Alternatively you
could subclass Queue and override the hook-method _get, which always
gets called in a properly locked and thus serialized condition; but that
may be considered a reasonably advanced task, since such subclassing
isn't documented in the reference library, only in Queue's sources]].


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


Re: PyQt issue

2006-03-04 Thread Damjan
> Because you wrote curentText - note the missing t.

:)

You mean the missing 'r'

:)

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


Is there a WSGI sollutions repository somewhere

2006-03-04 Thread Damjan
It seems that WSGI support starts to flourish is there some document or
a web site that tracks what's out there, some place to pick and choose
WSGI components?

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


The old round off problem?

2006-03-04 Thread sam
Hello all, I am taking a class in scientific programming at the local
college. My problem is that the following difference produces round off
errors as the value of x increases. For x >= 19 the diference goes to
zero.I understand the problem, but am curious as to whether their
exists a solution. I have tried various graphing programs,and they all
exihibit this problem.

thanks in advance Sam Schulenburg
f(x)  = cosh^2(x) - sinh^2(x)  = 1

>>> from math import *
>>> for x in range(20):
print "x= %2d  Sinh^2(x) = %20.3f f(x) = %2.10f
"%(x,pow(cosh(x),2),pow(cosh(x),2)- pow(sinh(x),2))


x=  0  Sinh^2(x) =1.000 f(x) = 1.00
x=  1  Sinh^2(x) =2.381 f(x) = 1.00
x=  2  Sinh^2(x) =   14.154 f(x) = 1.00
x=  3  Sinh^2(x) =  101.358 f(x) = 1.00
x=  4  Sinh^2(x) =  745.740 f(x) = 1.00
x=  5  Sinh^2(x) = 5507.116 f(x) = 1.00
x=  6  Sinh^2(x) =40689.198 f(x) = 1.00
x=  7  Sinh^2(x) =   300651.571 f(x) = 0.99
x=  8  Sinh^2(x) =  2221528.130 f(x) = 1.00
x=  9  Sinh^2(x) = 16414992.784 f(x) = 1.37
x= 10  Sinh^2(x) =121291299.352 f(x) = 1.000298
x= 11  Sinh^2(x) =896228212.033 f(x) = 0.998808
x= 12  Sinh^2(x) =   6622280532.961 f(x) = 1.019073
x= 13  Sinh^2(x) =  48932402357.710 f(x) = 0.923706
x= 14  Sinh^2(x) = 361564266073.369 f(x) = 0.389648
x= 15  Sinh^2(x) =2671618645381.616 f(x) = 1.00
x= 16  Sinh^2(x) =   19740740045670.668 f(x) = 0.9921875000
x= 17  Sinh^2(x) =  145865435631864.219 f(x) = 1.00
x= 18  Sinh^2(x) = 1077807886778799.250 f(x) = 1.00
x= 19  Sinh^2(x) = 7963982939278438.000 f(x) = 0.00 
>>>

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


Re: do design patterns still apply with Python?

2006-03-04 Thread jess . austin
msoulier wrote:

> I find that DP junkies don't tend to keep things simple.

+1 QOTW.  There's something about these "political" threads that seems
to bring out the best quotes.  b^)

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


Re: How to except the unexpected?

2006-03-04 Thread Bruno Desthuilliers
Rene Pijlman a écrit :
> Jorge Godoy:
> 
>>Rene Pijlman:
>>
>>>my app was surprised by an
>>>httplib.InvalidURL since I hadn't noticed this could be raised by
>>>robotparser (this is undocumented).
>>
>>It isn't undocumented in my module.  From 'pydoc httplib':
> 
> 
> That's cheating: pydoc is reading the source :-)

Yes, and that's the Right Thing(tm) to do. Source code don't lie. Source 
  code don't get out of sync. So source code *is* the best documentation 
(or at least the most accurate).

> What I meant was, I'm calling robotparser, and there's no mention of
> exceptions on http://docs.python.org/lib/module-robotparser.html
> 
That's why reading the source is better. CQFD !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


generators shared among threads

2006-03-04 Thread jess . austin
hi,

This seems like a difficult question to answer through testing, so I'm
hoping that someone will just know...  Suppose I have the following
generator, g:

def f()
i = 0
while True:
yield i
i += 1
g=f()

If I pass g around to various threads and I want them to always be
yielded a unique value, will I have a race condition?  That is, is it
possible that the cpython interpreter would interrupt one thread after
the increment and before the yield, and then resume another thread to
yield the first thread's value, or increment the stored i, or both,
before resuming the first thread?  If so, would I get different
behavior if I just set g like:

g=itertools.count()

If both of these idioms will give me a race condition, how might I go
about preventing such?  I thought about using threading.Lock, but I'm
sure that I don't want to put a lock around the yield statement.

thanks,
Jess

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


Re: Easy immutability in python?

2006-03-04 Thread jess . austin
To be clear, in this simple example I gave you don't have to override
anything.  However, if you want to process the values you place in the
container in some way before turning on immutability (which I assume
you must want to do because otherwise why not just use a tuple to begin
with?), then that processing should take place in a.__new__.

cheers,
Jess

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


license preamble template

2006-03-04 Thread Xah Lee
I noticed, that in just about all emacs programs on the web (elisp
code), it comes with this template text as its preamble:

;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation; either version 2, or (at
;; your option) any later version.

;; This program is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;; General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program; see the file COPYING.  If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

Concerned parties and the FSF foundation, please remove the middle
section of this template. That section is mainly for lawyers, for
programers to protect themselves in the context of modern society's law
system. Legally speaking, that section is redundant because it is in
the GNU General Public License itself. The effect of that section in a
license summary is fueling the habit and sanction of irresponsible
programing we see all around us.

In place of that section, i'd propose replacing it with the following
gist:

«This program is distributed in the hope that it will be useful. The
author(s) has responsibly produced it, and will take reasonable
responsibilities with regards to the program's intended purpose and
workability. For legal aspects of WARRANTY, please see the GNU General
Public License for more details.»

Regarding these issues, please read:

Responsible Software Licensing
http://xahlee.org/UnixResource_dir/writ/responsible_license.html

Responsible Software Licensing & the Free Software Foundation
http://xahlee.org/UnixResource_dir/writ/responsible_license_FSF.html

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

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

Re: How to except the unexpected?

2006-03-04 Thread Roman Susi
Rene Pijlman wrote:
> Paul Rubin :
> 
>>We have to get Knuth using Python.
> 
> 
> Perhaps a MIX emulator and running TeXDoctest on his books will convince
> him..

Or maybe Python written for MIX...


-Roman

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


Re: Easy immutability in python?

2006-03-04 Thread jess . austin
Since this is a container that needs to be "immutable, like a tuple",
why not just inherit from tuple?  You'll need to override the __new__
method, rather than the __init__, since tuples are immutable:

class a(tuple):
def __new__(cls, t):
return tuple.__new__(cls, t)

cheers,
Jess

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


Re: Write a GUI for a python script?

2006-03-04 Thread Peter Decker
On 3/4/06, Bill Maxwell <[EMAIL PROTECTED]> wrote:

> Dabo does look really nice, but seems like it has a ways to go yet.
>
> I downloaded it a couple of weeks ago, and the very first thing I wanted
> to do doesn't seem to be supported.  I tried to create a simple
> application with a Notebook control inside a frame.  The Notebook
> control doesn't appear to be supported yet.
>
> Is that right, or am I just not looking in the right places?

It's fully supported. Their generic term for these paged controls is a
'pageframe', so a wx.Notebook is their dPageFrame class; wx.Listbook
is their dPageList class; wx.Choicebook is their dPageSelect, and they
also have a page control with no tabs called (gasp!) dPageFrameNoTabs.
One thing that they've done is pick names for classes and properties
that are the most common for all toolkits instead of blindly following
the wx names.

All of these classes have the same interface, and respond to the same
events. IOW, they've unified these different classes so that they have
a single API, making working with them much easier.

--

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re-posting: web.py, incomplete

2006-03-04 Thread _wolf
ok, that does it! [EMAIL PROTECTED] a lot!

sorry first of all for my adding to the confusion when i jumped to
comment on that ``-u`` option thing---of course, **no -u option** means
**buffered**, positively, so there is buffering and buffering problems,
**with -u option** there is **no buffer**, so also no buffering
problems at that point. these add-option-to-switch-off things do get
confusing sometimes.

ok, so the ``#!/usr/local/bin/python -u`` does work. as noted on
http://www.imladris.com/Scripts/PythonForWindows.html: "Trying to run
python cgi scripts in the (default) buffered mode will either result in
a complete lack of return value from your cgi script (manifesting as a
blank html page) or a "premature end of script headers" error." funny
you don't get to see a lot of ``-u`` shebang lines these days tho. as
the document goes on to explain, there is a way to put ::

SetEnv PYTHONUNBUFFERED 1

into your apache ``httpd.conf``. this works for me! great!

now, thinking about this problem it strikes me it has never bitten me
before, where it should have. is there something special about the way
web.py cgi apps work that make this thing pop up? also, in theory,
since apache itself (as of v1.3) does no buffering of cgi output, then
when apache calls a cgi process, and that process happily buffers at
its own descretion, and then finalizes and terminates, then should the
remaining buffer not be output and sent to apache---as happens with a
script run from the command line? you do get to see all the output in
that case, at long last upon process termination, right? i'm wondering.

_wolf

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


Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Tuvas
Okay, the bug in my code has been fixed, it should work alot better
now... I thought I had tested the power function, but I appearently
wasn't even close... But now it works just fine.

I guess you are right, I will have to work on a better system to be
cryptologically secure. But, at least I have a start. Thanks for the
help!

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


Re: Python advocacy in scientific computation

2006-03-04 Thread Brian Blais
sturlamolden wrote:
> 
> Typically a scientist need to:
> 
> 1. do a lot of experiments
> 
> 2. analyse the data from experiments
> 
> 3. run a simulation now and then
> 

unless you are a theorist!  in that case, I would order this list backwards.


> 
> 1. Time is money. Time is the only thing that a scientist cannot afford
> to lose. Licensing fees for Matlab is not an issue. If we can spend
> $1,000,000 on specialised equipment we can pay whatever Mathworks or
> Lahey charges as well. However, time spent programming are an issue.
> (As are time time spend learning a new language.)
> 

Another person stated that they don't have infinite funds, as implied here.  I 
would
add that, in addition to one's own research, professors must also teach and 
advise.
I find it very helpful to be able to say to a student, "go download this, and 
here is
the code I wrote for the work I do".  The price is often an impediment for 
getting 
students into research.  Often there are site licenses, but they don't work off 
campus.


> 2. We don't need fancy GUIs. GUI coding is a waste of time we don't
> have. We don't care if Python have fancy GUI frameworks or not.
> 

again, for sharing ideas, GUIs are *necessary*.  If you work with people who do 
less 
programming than you, then you need to make an interface to your code that they 
can 
understand.  it doesn't have to be fancy, just functional.

> 3. We do need fancy data plotting and graphing. We do need fancy
> plotting and graphing that are easy to use - as in Matlab or S-PLUS.
> 

here, I've found python to be good, but not great.  matplotlib (pylab) is a 
really 
great thing, but is not as straightforward as plotting in Matlab.  Either, you 
have a 
window which locks the process until you close it, or you do interactive mode, 
but 
the window results disappear if any other window is put on top (like your 
shell), and 
has to be manually redrawn.  This makes it far less convenient to deal with in 
interactive mode.

> 4. Anything that has to do with website development or enterprise class
> production quality control are crap that we don't care about.
> 

I think it can be pitched as an alternative to shell-scripts, which is a nice 
economy 
of concepts: the language you use for your scientific work, you can also use 
for your 
OS work, and your tinkering.


> 7. "My simulation is running to slowly" is the number ONE complaint.
> Speed of excecution is an issue, regardless of what computer science
> folks try to tell you. That is why we spend disproportionate amount of
> time learning to vectorize Matlab code.
> 

here, I would plug Pyrex like crazy.  to me the Python/Pyrex combination is the 
biggest selling point for me to convert my scientific matlab code to Python. 
Learning a new API is a drag, and I've found that SWIG is not particularly 
intuitive 
(although convenient, if you have a lot of libraries already written).  Pyrex 
seems 
to get the best of all possible worlds: seamless use of python objects, and the 
ability to do C-loops for speed, with no API.  Making extensions this way is a 
real joy.


> Now please go ahead and tell me how Python can help me become a better
> scientist. And try to steer clear of the computer science buzzwords
> that don't mean anyting to me.
> 


I have been using Matlab for nearly 10 years.  My claim to no-fame is the 
neural 
network simulator Plasticity (http://web.bryant.edu/~bblais/plasticity) which 
has 
taken me years to write.  I have some complaints about Matlab, but it has been 
a 
useful tool.  Some of my complaints are as follows:

1) Cost.  I find that the marketing model for Matlab is annoying.  They 
nickle-and-dime you, with the base package (educational pricing) at $500 per 
machine/operating system/user and then between $200-$500 *per* "toolbox", which 
adds 
up really quick.   I can't even buy 1 license for a dual boot, to have Matlab 
run on 
a Linux partition and a Windows partition.

The cost impacts my use of Matlab in the classroom, and with research students.

2) License Manager.  The license manager for Matlab is the most inconvenient 
program 
I have ever dealt with.  It is incredibly sensitive to the license file, and it 
nearly impossible to debug.  This has made Matlab one of the hardest programs 
to 
install, for me.  The issue that impacts my productivity is the following: the 
license key is tied to the network card, on eth0.  Thus, if I upgrade my 
laptop, I 
need to contact Mathworks for an updated license key.  Also, occasionally, my 
operating system decides to name my wireless card eth0, and my wired card eth1. 
Nothing else is affected by this, but then I can't run Matlab!

3) Upgrade Version Hell.  *Every* time Matlab has upgraded, my program has 
broken. 
Usually something small, but still it is a real pain in the butt.  Also, I have 
to 
pay full price for the upgrade, or pay some fee continuously whether there is 
an 
upgrade or not.

I have only been using Python for about 2 months, 

Re: spliting on ":"

2006-03-04 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> hi
> 
> i have a file with
> 
> xxx.xxx.xxx.xxx:yyy
> xxx.xxx.xxx.xxx:yyy
> xxx.xxx.xxx.xxx:yyy
> xxx.xxx.xxx.xxx
> xxx.xxx.xxx.xxx
> xxx.xxx.xxx.xxx:yyy
> 
> i wanna split on ":" and get all the "yyy" and print the whole line out
> so i did
> 
> print line.split(":")[-1]
> 
> but line 4 and 5 are not printed as there is no ":" to split. It should
> print a "blank" at least.
> how to print out lines 4 and 5 ?
> eg output is
> 
> yyy
> yyy
> yyy
> 
> 
> yyy

That's not what I get:

In [2]: data='''xxx.xxx.xxx.xxx:yyy
...: xxx.xxx.xxx.xxx:yyy
...: xxx.xxx.xxx.xxx:yyy
...: xxx.xxx.xxx.xxx
...: xxx.xxx.xxx.xxx
...: xxx.xxx.xxx.xxx:yyy'''.splitlines()

In [3]: for line in data:
...: print line.split(':')[-1]
...:
...:
yyy
yyy
yyy
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
yyy

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


Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Tuvas
Well, the RSA element's never going to encrypt more than a small, 1
block system except under rare occasions, the primary encryption will
be AES128. Thanks for the help though!

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


Re: Python advocacy in scientific computation

2006-03-04 Thread Michael Tobis
There is a range of folks doing scientific programming. Not all of them
are described correctly by your summary, but many are. The article is
aimed not at them, but rather at institutions that develop engineered
Fortran models using multipuurpose teams and formal methods. I
appreciate your comments, because I see that there should be another
article aimed at desktop programmers.

One of the things python addresses best is the division of labor, where
the subtle concepts are available to those who need them and hidden
from those who don't need them. From what I understand of your work
(and what I have seen of the work of two other neuroscientists,
actually) Python would be a good choice for you.

That said, the level of computational skill in many scientists is
alarming. Why do we expect to spend six semesters learning mathematics
and expect to pick up computing "on the side"? It baffles me.  Frankly,
saying "I don't need version control" sounds to me no less foolish than
 saying "I don't need logarithms". (Perhaps you don't but someday soon
you will.)

"Speed of excecution is an issue, regardless of what computer science
folks try to tell you." strikes me as nothing short of hallucinatory.
No informed person says that speed is never an issue, and a great deal
of effort is spent on  speed. Where do you suppose your Fortran
compiler came from in the first place?

For someone without legacy code to worry about, fussing with Fortran
for single-user one-off codes strikes me as a weak choice. If you are
hitting Matlab's performance or memory limits, you should take the time
to learn something about computation, not because you are idle, but
because you are busy. Or if you prefer, because your competitors will
be learning how to be more productive while you put all your efforts
into coping with crude tools.

The peculiar lack of communication between computer scientists and
application scientists is real; but I believe the fault is not all on
one side. The fact that you have a PhD does not prove that you know
everything you need to know, and I strongly recommend you reconsider
this attitude. For one thing, you misjudged which side of the divide I
started on.

Michael Tobis
(While I dislike credentialism on usenet, I will reply in kind. I hold
a Ph.D. in geophysical fluid dynamics.)

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


Easy immutability in python?

2006-03-04 Thread Terry Hancock
Is there an *easy* way to make an object immutable in
python?  Or perhaps I should say "one obvious way to do it"?
Oughtn't there to be one?

I've found a thread on how to do this[1], which essentially
says something like "redefine __setattr__, __delattr__,
__hash__, __eq__, __setitem__, delitem__ ... and probably
some other stuff too".

[1]

Yet, what you have to do is pretty mechanical (e.g. all the
mutators have to raise NotImplementedError and the hashes
and comparisons seem like they have obvious defaults).

Given that I have some kind of container, like an overloaded
list, and I just say "oh, I need that to be immutable, like
a tuple" -- it would be nice to just be able to declare it
so.  I just want this for QA purposes -- I have a pretty
complex system, and I want the programmer to be warned when
he accidentally tries to change an immutable enumeration or
redefine a symbol.

I know a (hard and error-prone) way to do it, but I'm
thinking there must be a "smart" way to do it.

Is there some way to do that with, e.g. decorators?

(I haven't really figured out why I should want decorators,
is this a use case?).

Or maybe I should make an "Immutable" class, and just
inherit from it last so it overloads everything else with
the null interfaces?

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Alex Martelli
Tuvas <[EMAIL PROTECTED]> wrote:
   ...
> to make sure. For simpler than going to the website, I used the ranint

I assume you mean random.randint here.

> function to pick a random prime number, then ran it through the miller
> rabin primality test. It's a probabalistic test, which means it isn't
> full proof, but there's still less than 1 in a million of giving a

Miller-Rabin is not the problem -- rather, random.randint might be... it
makes no claims to be cryptographically strong, in either the current
Mersenne implementation or the previous Wichman-Hill one. Could you
maybe use /dev/random or the like?  Cfr
 for an introduction to the
subject.  (For speed, you may want to look into gmpy.sf.net, but that's
quite a separate issue from the strength of your random numbers).


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


Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Tuvas
I have discoved that the mod function isn't quite right in dealing with
powers, but, I'll have it fixed shortly.

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


Re: Python advocacy in scientific computation

2006-03-04 Thread Alex Martelli
Terry Hancock <[EMAIL PROTECTED]> wrote:

> In fact, if I had one complaint about Python, it was the
> "with a suitable array of add-ons" caveat. The proprietary
> alternative had all of that rolled into one package (abeit
> it glopped into one massive and arcane namespace), whereas
> there was no "Python Data Language" or whatever that
> would include all that in one named package that everyone
> could recognize (I suppose SciPy is trying to achieve that).

I believe the Enthought distribution of Python (for Windows, with a Mac
version planned) is trying to move exactly in that direction, by
packaging up everything and a half (while of course leaving a reasonable
assignment of namespaces from the pieces it's packaging!-). However,
maintaining such a distro, and making it available for a wider variety
of platforms, are heavy, continuing tasks -- unless either firms, such
as Enthought, or volunteers, commit to such tasks, they won't "just
happen".


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


Re: add an asynchronous exception class

2006-03-04 Thread Christian Stapfer
"Paul Rubin"  wrote in message 
news:[EMAIL PROTECTED]
> "Fredrik Lundh" <[EMAIL PROTECTED]> writes:
>> PEP 348 addresses this by moving special exceptions out of the
>> Exception hierarchy:
>>
>> http://www.python.org/peps/pep-0348.html
>
> I see that suggestion was rejected (it needed changing the semantics
> of "except:").  Also, PEP 348 was rejected and is a huge, complex
> reorganization of the whole exception system.  This is cited:
>
>  http://mail.python.org/pipermail/python-dev/2005-August/055423.html
>
> but it talks about distinguishing terminating from non-terminating
> exceptions, whatever that means.  (Won't any uncaught exception like
> ValueError terminate the program)?

I guess it means the following:

"Terminating exceptions" are exceptions that
terminate the *thrower* of the exception.
"Non-terminating exceptions" are exceptions
that might allow the thrower to resume
(provided the catcher does *not* decide
to unwind the thrower's stack frame - and
possibly some other frames as well...).
So non-terminating exceptions allow the
thrower to offer the catcher a choice
between terminating the thrower or having
him try harder (until he possibly throws
yet another, but maybe this time terminating
exception that does not allow the catcher to
ask for resumption of the throwing code).

  So what's terminated (or not terminated)
here is not the program but merely the
code that throws an exception.
  VAX/VMS had such a non-terminating exception
handling mechanism, for example.

Regards,
Christian


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


Re: Write a GUI for a python script?

2006-03-04 Thread Bill Maxwell
On Fri, 3 Mar 2006 07:19:34 -0500, "Peter Decker" <[EMAIL PROTECTED]>
wrote:

>I started with wxPython and struggled with it for a long time. I was
>able to get the job done, but using it never seemed natural. Then I
>found the Dabo project, whose ui module wraps wxPython into a much
>more Pythonic, consistent interface. Since then I've been able to
>create GUIs without much effort at all. I highly recommend Dabo if you
>are thinking about wxPython.

Dabo does look really nice, but seems like it has a ways to go yet.

I downloaded it a couple of weeks ago, and the very first thing I wanted
to do doesn't seem to be supported.  I tried to create a simple
application with a Notebook control inside a frame.  The Notebook
control doesn't appear to be supported yet.

Is that right, or am I just not looking in the right places?


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


Re: spliting on ":"

2006-03-04 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> print line.split(":")[-1]
> 
> but line 4 and 5 are not printed as there is no ":" to split. It should
> print a "blank" at least.
> how to print out lines 4 and 5 ?
> eg output is
> 
> yyy
> yyy
> yyy
> 
> 
> yyy

if ":" in line:
   print line.split(":")[-1]
else:
   print

what's the problem?
-- 
http://mail.python.org/mailman/listinfo/python-list


spliting on ":"

2006-03-04 Thread s99999999s2003
hi

i have a file with

xxx.xxx.xxx.xxx:yyy
xxx.xxx.xxx.xxx:yyy
xxx.xxx.xxx.xxx:yyy
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx:yyy

i wanna split on ":" and get all the "yyy" and print the whole line out
so i did

print line.split(":")[-1]

but line 4 and 5 are not printed as there is no ":" to split. It should
print a "blank" at least.
how to print out lines 4 and 5 ?
eg output is

yyy
yyy
yyy


yyy

thanks

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


Re: Python advocacy in scientific computation

2006-03-04 Thread Terry Hancock
On 3 Mar 2006 17:33:31 -0800
"sturlamolden" <[EMAIL PROTECTED]> wrote:
> 1. Time is money. Time is the only thing that a scientist
> cannot afford to lose. Licensing fees for Matlab is not an
> issue. If we can spend $1,000,000 on specialised equipment
> we can pay whatever Mathworks or Lahey charges as well.
> However, time spent programming are an issue. (As are time
> time spend learning a new language.)

"that man speaks for himself!" ;-)

Seriously, this depends on the lab. If you're working for
a monster pharmaceutical corp or on a military contract on
"applied" science (meaning there is a definitely payback
expected), then you likely have money to burn. People
working in a academic or non-profit lab on "unsexy"/"pure"
science, likely don't.

Remember that site-licensing usually works on some kind of
"per seat" basis (even if you are lucky enough *not* to have
a "license server" that constantly tracks usage in order to
deny service if and when N+1 users try to use the system,
the fee the site fee is still based on the number
of expected users).  The last science facility I worked at
was in considerable debt to a proprietary scientific
software producer and struggling to pay the bills.  The
result was that they had fewer licenses than they wanted
and many people simply couldn't use the software when they
wanted.

I'm not sure what happened in the end, because I left for
unrelated reasons before all of that got sorted out, but
Python (with a suitable array of add-ons) was definitely on
the short-list of replacement software (and partly because I
was trying to sell people on it, of course).

In fact, if I had one complaint about Python, it was the
"with a suitable array of add-ons" caveat. The proprietary
alternative had all of that rolled into one package (abeit
it glopped into one massive and arcane namespace), whereas
there was no "Python Data Language" or whatever that
would include all that in one named package that everyone
could recognize (I suppose SciPy is trying to achieve that).

For similar reasons, Space Telescope Science Institute
decided to go full tilt into python development -- they
created "numarray" and "pyraf", and they are the ones paying
for the "chaco" development contract.

Which brings up another point -- whereas with proprietary
software (and stuff written using it, like the IDL astronomy
library) can leave you with an enormous investment in stuff
you can't use, free software development can often be just
as cheap, and you get to keep what you make.

At one point, I was seriously thinking about trying to write
some kind of translator to convert those IDL libs into
python libs (quixotic of me?).

So why rent when you can own?

Scientists certainly do understand all that bit about
"seeing further" because you're "standing on the shoulders
of giants".  With proprietary software, the giants keep
getting shot out from under you, which tends to make things
a bit harder to keep up with.

Cheers,
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: socket freezes

2006-03-04 Thread Luis P. Mendes
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Thank you all for your suggestions.



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

iD8DBQFECb5AHn4UHCY8rB8RAmeLAKCmSVfTvgQ94NPnJlD2QqdbMwVFXACdGFAh
8GL/9zxwXCYcmWxpyDweggE=
=9U0o
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Tuvas
I have made and recently posted a libary I made to do Modular
Arithmetic and Prime numbers on my website  at
http://www.geocities.com/brp13/Python/index.html . I am currently in a
crypotology class, and am working on building a RSA public key
cryptology system for a class project. I am building the librarys just
to get the experience to do so. However, I would ask if any of you know
of any gaping security holes that can easily be seen from my selection
of random prime numbers, ei, are they somehow predictable? Just wanting
to make sure. For simpler than going to the website, I used the ranint
function to pick a random prime number, then ran it through the miller
rabin primality test. It's a probabalistic test, which means it isn't
full proof, but there's still less than 1 in a million of giving a
false reading. Thanks! And if you should so want for some reason, feel
free to use it!

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


Re: do design patterns still apply with Python?

2006-03-04 Thread Bo Yang
Paul Novak :
> A lot of the complexity of design patterns in Java falls away in 
> Python, mainly because of the flexibility you get with dynamic typing. 
>
I agree with this very much !
In java or C++ or all such static typing and compiled languages , the 
type is fixed on
in the compile phrase , so for the flexible at the runtime , we often 
need to program to
interface . For example ,
we do in java :

implement I{...}
class A implement I{...}
class B implement I{...}

oprate(I var) // we can pass A's instance or B's instance here

and in C++ :

class Abstract{...}
class A : Abstract{...}
class B : Abstract{...}

oprate(Abstract var) // pass the A's instance or B's instance here

But in python , type is dynamic , and name is bind at runtime , so we 
can pass any variable as we want ! This feather make python not need for 
redundant class inherits
and interfaces which are the core of the GoF's design patterns I think !
> For a Pythonic Perspective on Patterns, "Python Programming Patterns" 
> by Thomas W. Christopher is definitely worth tracking down.  It looks 
> like it is out of print, but you can find used copies on Amazon.
>
> Regards,
>
> Paul.
>
>  
>
> This sounds like an article crying out to be written,
> "(Learning) Design Patterns with Python".
>
> Has it been written already?
>
> Cheers,
> Terry
>
>
> Bruce Eckel began writing "Thinking In Python" it was last updated
> in 2001.
>

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


Re: do design patterns still apply with Python?

2006-03-04 Thread Bo Yang
Paul Novak 写道:
> A lot of the complexity of design patterns in Java falls away in 
> Python, mainly because of the flexibility you get with dynamic typing.
>
I agree with this very much !
In java or C++ or all such static typing and compiled languages , the 
type is fixed on
in the compile phrase , so for the flexible at the runtime , we often 
need to program to
interface . For example ,
we do in java :

implement I{...}
class A implement I{...}
class B implement I{...}

oprate(I var) // we can pass A's instance or B's instance here

and in C++ :

class Abstract{...}
class A : Abstract{...}
class B : Abstract{...}

oprate(Abstract var) // pass the A's instance or B's instance here

But in python , type is dynamic , and name is bind at runtime , so we 
can pass any variable as we want ! This feather make python not need for 
redundant class inherits
and interfaces which are the core of the GoF's design patterns I think !

> For a Pythonic Perspective on Patterns, "Python Programming Patterns" 
> by Thomas W. Christopher is definitely worth tracking down. It looks 
> like it is out of print, but you can find used copies on Amazon.
>
> Regards,
>
> Paul.
>
>
> This sounds like an article crying out to be written,
> "(Learning) Design Patterns with Python".
>
> Has it been written already?
>
> Cheers,
> Terry
>
>
> Bruce Eckel began writing "Thinking In Python" it was last updated
> in 2001.
>

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

Re: How to except the unexpected?

2006-03-04 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Rene Pijlman <[EMAIL PROTECTED]> wrote:

> Roy Smith:
> >In theory, all exceptions which represent problems with the external 
> >environment (rather than programming mistakes) should derive from 
> >Exception, but not from StandardError.
> 
> Are you sure?
> 
> """
> The class hierarchy for built-in exceptions is:
> 
> Exception
>  +-- StandardError
>  |+-- KeyboardInterrupt
>  |+-- ImportError
>  |+-- EnvironmentError
>  ||+-- IOError
> """
> http://www.python.org/doc/current/lib/module-exceptions.html

Hmmm, OK, I missed EnvironmentError.  So, what you need to do is:

try:
   whatever()
except EnvironmentError:
   ...
except StandardError:
   ...
except Exception:
   ...

or something like that.

I do agree with you that there is some value in Java's "must catch or 
re-export all exceptions" semantics, and this would be one of those places 
where it would be useful.  In general, however, I've always found it to be 
a major pain in the butt, to the point where I sometimes just punt and 
declare all my methods to "throw Exception" (or whatever the correct syntax 
is).  Not to mention that with a dynamic language like Python, it's 
probably impossible to implement.

I think the real problem here is that the on-line docs are incomplete 
because they don't list all the exceptions that this module can raise.  The 
solution to that is to open a bug on sourceforge against the docs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-04 Thread Paul Novak
A lot of the complexity of design patterns in Java falls away
in Python, mainly because of the flexibility you get with dynamic
typing.  

For a Pythonic Perspective on Patterns, "Python Programming Patterns"
by Thomas W. Christopher is definitely worth tracking down.  It
looks like it is out of print, but you can find used copies on Amazon.

Regards,

Paul.

 


This sounds like an article crying out to be written,"(Learning) Design Patterns with Python".Has it been written already?
Cheers,TerryBruce Eckel began writing "Thinking In Python" it was last updated in 2001.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Win32api, pyHook, possibly win32com, not sure XD, thats why I'm posting

2006-03-04 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> Is there a way to hide a python instance from the Task Manager process
> list?

Try sony's rootkit. Or any other.

Diez

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


Re: Writing an OPC client with Python ?

2006-03-04 Thread F. GEIGER
About a year ago I dev'ed a host app in Python (2.3 at that time) to control 
a KUKA KR16 robot. Comm was over OPC. The OPC 2.0 server was inst'ed on the 
KRC2. What I was needed to do, was to install the appropriate (i.e. delivere 
together w/ the server) client software and to take Mark Hammonds COM Makepy 
utility to to create the wrapper. The rest of the story was fun, pure fun, 
as Python programming always is.

So, register the client software, fire up PythonWin, start the COM Makepy 
utility and wrap that DLL. If you are completely new to this stuff, it might 
help to look at all that from w/i MSVB 6.0 or something like that.

HTH
Franz GEIGER



"pierlau" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
> Hello,
>
> I use an OPC server for connection to DC Drive.
> I would like to write a small OPC client.
> I have the dll OPCDAAuto.dll which contains all class and method but I 
> wonder if its possible to instance in python the class that are in the dll 
> ?
>
> Thanks for your help .
>
> Pierre
>
>
> 


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


Re: Package organization: where to put 'common' modules?

2006-03-04 Thread Jorge Godoy
Kent Johnson <[EMAIL PROTECTED]> writes:

> What I do is run always from the base directory (violates your first
> requirement). I make a util package to hold commonly used code. Then B and D
> both use
>   from util import foo
>
> In Python 2.5 you will be able to say (in D, for example)
>   from ..util import foo
>
> http://www.python.org/peps/pep-0328.html

I do work a bit different here.  When two programs start sharing code, then I
convert this code into a "library", i.e., I make it a module, put it in
PYTHONPATH and then import it.  Probably more than two projects will use it if
two of them already are :-)


-- 
Jorge Godoy  <[EMAIL PROTECTED]>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >