Re: how to append to a list twice?

2006-04-22 Thread Alex Martelli
Fredrik Lundh [EMAIL PROTECTED] wrote:

 Alex Martelli wrote:
 
   But of course that only does it once, and I don't want to have to copy
   and paste the append line. Perhaps there's a better way than this.
 
  def makeseries(N):
series = [N]
append = series.append
for tailer in xrange(N-1, -1, -1):
  append(tailer)
  append(tailer)
 
 But Now You've Violated The DRY Principle!!!

Just as with any other unrolled loop, yes -- loop unrolling is an
optimization which is based exactly on exchanging some textual
repetition for a tiny bit more speed.

Of course, optimizations can easily be premature, and in any case need
to be checked by measurement.  E.g., here are a few variations:

def makeseries_a(N):
  series = [N]
  append = series.append
  for tailer in xrange(N-1, -1, -1):
append(tailer)
append(tailer)
  return series

def makeseries_b(N):
  series = [N]
  append = series.append
  for tailer in xrange(N-1, -1, -1):
  for x in (1,2):
append(tailer)
  return series

def makeseries_c(N):
  series = [N]
  extend = series.extend
  for tailer in xrange(N-1, -1, -1):
extend((tailer,tailer))
  return series

def makeseries_d(N):
  series = [N]
  extend = series.extend
  for tailer in xrange(N-1, -1, -1):
extend((tailer,)*2)
  return series


And:

brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_a(100)'
1 loops, best of 3: 31.7 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_b(100)'
1 loops, best of 3: 57.4 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_c(100)'
1 loops, best of 3: 36.2 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_d(100)'
1 loops, best of 3: 54.4 usec per loop

So, it would seem that (at least among these few variations) I had
guessed right, this time -- the loop-unrolling is beneficial and append
is minutely better than extend. Of course, the yanking from the loopbody
of the boundmethod is also a key optimization here -- with unyanked
(more natural) versions [[i.e., calling series.append or series.extend
right in the loop body]] I measure:

brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_a(100)'
1 loops, best of 3: 57.3 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_b(100)'
1 loops, best of 3: 83.5 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_c(100)'
1 loops, best of 3: 48 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_d(100)'
1 loops, best of 3: 68.4 usec per loop


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


Re: Generate a sequence of random numbers that sum up to 1?

2006-04-22 Thread Alex Martelli
Anthony Liu [EMAIL PROTECTED] wrote:
   ...
 As a matter of fact, given that we have to specify the
 number of states for an HMM, I would like to create a
 specified number of random floating numbers whose sum
 is 1.0.

def forAL(N):
 N_randoms = [random.random() for x in xrange(N)]
 total = sum(N_randoms)
 return [x/total for x in N_randoms]


Does this do what you want?  Of course, the resulting numbers are not
independent, but then the constraints you pose would contradict that.


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


Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread ToddLMorgan
I'm just starting out with python, after having a long history with
Java. I was wondering if there were any resources or tips from anyone
out there in Python-land that can help me make the transition as
successfully as possible? Perhaps you've made the transition yourself
or just have experience with folks who have made the transition.

I'm looking for the common types of mistakes that say a Java/C# or
even C++ developer may commonly make. More examples like those
highlighted here http://dirtsimple.org/2004/12/python-is-not-java.html
would be particularly useful. I've already made the static class
method mistake, and been thoroughly confused by packages and
imports/froms and extremely frustrated with attempting to call super
constructors etc.  I'm getting the hang of passing around functions
(ala the command pattern), customising the operators and extending
inbuilt classes. All of these concepts I've done before so there
nothing really great and wonderful about using them in another
language. Some of the really powerful ideas of python (eg as suggested
in the link) about creating one function containing a template function
that can cater to all possible implementations sounds really cool and
alien to me at the same time. That's the sort of stuff I'm
interested in.

At this point in time I'd say my python code is more coding Java in
python than doing it in a pythonic way. Perhaps there some good/great
examples of Python scripts or projects that I could look at to get
inspired or learn pythonic implementation ideas? I just don't know of
any. Are there python specific equivalents to the common Patterns,
Anti-Patterns and Refactoring books that are so prevalent as
reccomended reading in C++ and Java? If so what?

Given the rising popularity of Python these days there has got to be a
few of you out there who've made the transition successfully and have
some pearls-of-wisdom to share that you'd wished you'd known about
earlier.

Thanks
 Todd

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


Re: Can you create an instance of a subclass with an existing instance of the base class?

2006-04-22 Thread Peter Otten
Sandra-24 wrote:

 Can you create an instance of a subclass using an existing instance of
 the base class?
 
 Such things would be impossible in some languages or very difficult in
 others. I wonder if this can be done in python, without copying the
 base class instance, which in my case is a very expensive object.

You can change the class of an instance by assigning to the __class__
attribute. The new class doesn't even need to be a subclass of the old:

 class A(object):
... def __init__(self, name):
... self.name = name
... def show(self): print self.name
...
 a = A(alpha)
 a.show()
alpha
 class B(object):
... def show(self): print self.name.upper()
...
 a.__class__ = B
 a.show()
ALPHA

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


Re: Generate a sequence of random numbers that sum up to 1?

2006-04-22 Thread Gerard Flanagan

Anthony Liu wrote:
 I am at my wit's end.

 I want to generate a certain number of random numbers.
  This is easy, I can repeatedly do uniform(0, 1) for
 example.

 But, I want the random numbers just generated sum up
 to 1 .

 I am not sure how to do this.  Any idea?  Thanks.


--
import random

def partition(start=0,stop=1,eps=5):
d = stop - start
vals = [ start + d * random.random() for _ in range(2*eps) ]
vals = [start] + vals + [stop]
vals.sort()
return vals

P = partition()

intervals = [ P[i:i+2] for i in range(len(P)-1) ]

deltas = [ x[1] - x[0] for x in intervals ]

print deltas

print sum(deltas)
---

Gerard

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


Re: Generate a sequence of random numbers that sum up to 1?

2006-04-22 Thread Gerard Flanagan

Gerard Flanagan wrote:
 Anthony Liu wrote:
  I am at my wit's end.
 
  I want to generate a certain number of random numbers.
   This is easy, I can repeatedly do uniform(0, 1) for
  example.
 
  But, I want the random numbers just generated sum up
  to 1 .
 
  I am not sure how to do this.  Any idea?  Thanks.
 

 --
 import random

 def partition(start=0,stop=1,eps=5):
 d = stop - start
 vals = [ start + d * random.random() for _ in range(2*eps) ]
 vals = [start] + vals + [stop]
 vals.sort()
 return vals

 P = partition()

 intervals = [ P[i:i+2] for i in range(len(P)-1) ]

 deltas = [ x[1] - x[0] for x in intervals ]

 print deltas

 print sum(deltas)
 ---


def partition(N=5):
vals = sorted( random.random() for _ in range(2*N) )
vals = [0] + vals + [1]
for j in range(2*N+1):
yield vals[j:j+2]

deltas = [ x[1]-x[0] for x in partition() ]

print deltas

print sum(deltas)


[0.10271966686994982, 0.13826576491042208, 0.064146913555132801,
0.11906452454467387, 0.10501198456091299, 0.011732423830768779,
0.11785369256442912, 0.065927165520102249, 0.098351305878176198,
0.077786747076205365, 0.099139810689226726]
1.0

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


Re: ANN: XMLObject

2006-04-22 Thread Nicolay A. Vasiliev
Hello!

I tried to use this class in my work. But I Can't understand the next.
I have an XML file, where I store an information by this way
First_NameWesley/First_Name
Last_NameHunter/Last_Name ie.

How can I get the value between First_Name and /First_Name?

Thanks in advance.


aum wrote:
 Hi folks,

 I've just released an XML object wrapper called XMLObject, which aims to
 do for XML file handling what SQLObject does for database access.

 XMLObject wraps XML files as Python objects, and lets you work with XML
 data more quickly and easily, and with code that's shorter and much more
 readable than the raw python XML APIs.

 It borrows some ideas from 'xml_objectify', but uses none of its code. In
 addition to 'xml_objectify', it lets you make changes within the document,
 and to save back to an XML file.

 http://www.freenet.org.nz/python/xmlobject

   

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


Re: Pythonesque interface.

2006-04-22 Thread bearophileHUGS
Gaz:
 Right now im trying to dl Jython (SF.net server down?), if it's
 language sintaxis is just like Python and allows to use numpy and PIL,
 im in! (i think :) )

I don't think you can do that, but you can create and show images
anyway (and maybe read the pointer position too).
Sorry for the OP, I have seen lot of people use it here, I'll avoid
such things in the future.

Bye,
bearophile

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


Re: proposed Python logo

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 Dennis Lee Bieber [EMAIL PROTECTED] wrote:

On Fri, 21 Apr 2006 16:13:53 -0700, Carl J. Van Arsdall
[EMAIL PROTECTED] declaimed the following in comp.lang.python:

 Lawrence D'Oliveiro wrote:
 
  Six words: copyright violation ... trademark violation.

 
 Six? 
 
 Looks more like 4 to me.

   Ah, but maybe it is self-referential...

At last, someone with the imagination I thought would be more common 
among Pythonistas. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 ToddLMorgan [EMAIL PROTECTED] wrote:

I'm looking for the common types of mistakes that say a Java/C# or
even C++ developer may commonly make.

Using subclassing when you don't have to. For instance, you might have a 
Java method which takes an argument of type java.io.OutputStream to 
which it writes. You might translate this to a Python method to which 
you are careful to only pass instances of subclasses of file objects. 
But in fact there is no necessity for this: you are free to pass any 
object which has appropriate members.

I suppose this is an instance of the more general rule: using OO when 
you don't have to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 ToddLMorgan [EMAIL PROTECTED] wrote:

Are there python specific equivalents to the common Patterns,
Anti-Patterns and Refactoring books that are so prevalent as
reccomended reading in C++ and Java?

I don't think they exist. Such books are targeted more towards 
development in a corporate environment, where every proposal has to go 
through multiple layers of management, and nothing is ever done by 
individuals working alone, always by teams working on separate parts 
of the project. And also where the end-users don't really get much say 
in how things are supposed to work. It's only in such a high-overhead, 
top-down, cover-your-ass environment that such books are looked on as 
being at all useful. Possibly on the grounds that nobody ever got fired 
for buying them.

I'd say languages like Python and Perl are the absolute antithesis of 
this sort of development culture.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Raising a specific OSError

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 David Hirschfield [EMAIL PROTECTED] wrote:

When I attempt to perform a file operation on a non-existent file, I get 
an OSError: [Errno 2], but what if I want to raise one of those myself?

raise OSError(2, No such file or directory)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: another question about buffers

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

databack = sockobj.recv(1028)
if databack:
   print 'caught a message %s bytes ' % len(databack)
else:
   print 'fail to recieve data from server'

the output in the terminal runs fine until it fails to get the
databack, it prints out the fail to receive from server bit.

Perhaps the string you are receiving back on the second recv is being 
interpreted as False.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: send cookie on request with urllib2

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] (John J. Lee) wrote:

No, scolded Yoda. Do, or do not. There is no try.

Convincing argument against exceptions, don't you think. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Define type of 'module' object that is imported

2006-04-22 Thread robert
Zachary Pincus wrote:

 Hi folks,
 
 I'm sure this has come up before, but the search terms I've been  using 
 are so non-specific that I can't get any traction on Google.
 
 Here's my question:
 I have written a subclass of ModuleType that handles lazy loading of  
 some slow resources. I would like a given module to be created as an  
 instance of that particular subclass on import, so that if I do:
 
 import foo
 type(foo)
 
 I get type 'myModule' instead of type 'module'.
 
 Is there any way to effect this? Something like __metaclass__ = ...  but 
 at the beginning of a module instead of at the beginning of a class?

Would be interesting to know about the motivation. Is foo just your own 
module or any module.

* you can replace __import__
* you can set sys.modules['foo']=mymod   (in sitecustomize.py ? )
* your module can be a class instance as well in newer pythons (2.2+?);
   = you can set sys.modules['foo']=Foo()   # Foo having properties ...
* simply import certain expensive modules only ad-hoc
* maybe you don't need it as module at all, but an instance. or you 
avoid pre-computing things in global namespace.
...


robert

---

PS:

In the Python standard lib there are some slow importing monsters. The 
worst is now urllib2 needing up to a second to import.
Thats because there is a questionable style of importing all kind of 
expensive stuff that _might_ be useful in advance as if we had C-style 
compiler #include-s. Yet Python allows 
best-amongst-most-programming-languages dynamic modularization of code 
by local/late imports. Most time you'll see, that the imported modules 
are anyway only needed in very few locations. the pychecker helps.

See rejected:
http://sourceforge.net/tracker/index.php?func=detailaid=1053150group_id=5470atid=305470

Meanwhile the cookielib is also amongst those urllib2 inhabitants - and 
its the slowest towards my profile runs. I've regular private patches on 
my production python installation to get apps (startup) fluid.

Maybe that rejected sf request should be re-opened, and a request put to 
optimize the python lib for late dynamic import's - at least in 
locations where (regardign a profiler inspection) it pays off well on 
low coding costs ?

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


Re: FOUNDIT (was Re: massive threading performance)

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 Paul Sijben [EMAIL PROTECTED] wrote:

I found that the problem was caused by the sending thread not giving
control back quickly enough to the receiving thread.

Also in going through the code I found an old self.s.setblocking(0)call
that was no longer relevant. Removing that solved my problem.

Something that took 20 seconds now takes just 1.

You might also find that it goes still faster if you forego threading 
and use a select.select loop.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Uniquifying a list?

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 Felipe Almeida Lessa [EMAIL PROTECTED] wrote:

list(set(x)) is the clear winner with almost O(1) performance.

Moral: in an interpreted language, use builtins as much as possible.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Any Python lullabies?

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 Ralf Muschall [EMAIL PROTECTED] wrote:

Christos Georgiou wrote:
 ... that I can sing to my newborn son (actually, born yesterday)?

...but the baby probably won't see the difference.

Boy, some people do take the born yesterday bit to heart. don't they. 
:)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a flattening operator?

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 gangesmaster [EMAIL PROTECTED] wrote:

as we all know, * (asterisk) can be used to inline or flatten a
tuple into an argument list, i.e.:

def f(a, b, c):
...
x = (1,2,3)
f(*x)

so... mainly for symmetry's sake, why not make a flattening operator
that also works outside the context of function calls?

def flatten(*a) :
return a
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread Anton Vredegoor
ToddLMorgan wrote:

 I'm just starting out with python, after having a long history with
 Java. I was wondering if there were any resources or tips from anyone
 out there in Python-land that can help me make the transition as
 successfully as possible? Perhaps you've made the transition yourself
 or just have experience with folks who have made the transition.

Some time ago I had to learn a bit of Java in order to be able to write 
some signed jython browser applets that I could use while working at a 
highly restricted public library computer. So I guess I was coming from 
the opposite direction :-) Anyway I wondered why (and how!) very small 
jython scripts could replace large blocks of java code.

Maybe looking at it from a jython perspective will be educational for 
you. I think it would be a lot of fun realizing how much java code can 
actually be 'automatically' generated or filled in by jython traversing 
its class system.

Also I'm hoping it would produce an opportunity for an advanced java 
coder to write some cool signed java applet in jython that would have 
the look and feel of idle.py for python but that would run from a 
webbrowser.

I know it can be done because I did write some experimental but still 
already very functional things like a jython console webbrowser applet, 
a websucker.py running from within a browser, and I hacked some other
jython editor-console (eclipse is good for such things) to add some 
functionality and do my own signing and library selection.

Don't ask for my code yet though, it's nowhere near presentable. Anyway, 
since then I found a job that gives me access to less locked down 
computers which is also fun.

Anton

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


Re: perspective on ruby

2006-04-22 Thread robert
Edward Elliott wrote:

 Alex Martelli wrote:
 
 While Mozart appears cool, I really think that a wider variety of
 languages would help -- some machine code (possibly abstract a la
 Mixal), C (a must, *SO* much is written in it!), at least one of C++, D,
 or ObjectiveC, either Scheme or Lisp, either *ML or Haskell, either
 Python or Ruby, and at least one OOP-only language such as Java, C#,
 Eiffel, or Smalltalk.  
 
 
 Yeah I agree that more is better.  The problem is using a new language 
 every couple courses without bogging down in implementation details. 
 Personally I'd just say Here's a book, learn it yourself.  It's what 
 they gotta do on the job anyway.

Yes - start them explore. I'd not want to be teached a specific 
_language_ in a course longer that one day. A language cannot be teached.
Who of the posters in this thread want themselves to be _teached_ more 
than one day on a language?

I've seen many graduates who know Java, C, this and that words and 
patterns, but hardly can write a loop and evolve things. Those, who can 
write loops are mostly self-educated and can do all things quickly in 
any language.

Isn't the fun, finding the right tools for certain purposes one-self?

The job of (CS) courses more to provide a map ( what fun to explore 
yourself ) and display extremes (ASM and Lisp) to prevent from 
identification ?

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


Re: Uniquifying a list?

2006-04-22 Thread bearophileHUGS
There is my version too:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438599

Bye,
bearophile

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


Re: how to append to a list twice?

2006-04-22 Thread Fredrik Lundh
Alex Martelli wrote:

  But Now You've Violated The DRY Principle!!!

 Just as with any other unrolled loop, yes -- loop unrolling is an
 optimization which is based exactly on exchanging some textual
 repetition for a tiny bit more speed.

I had hoped that the Unusual Capitalization would have been enough
to make up for the missing smiley...

(but note that the OP explicitly didn't want to copy and paste; given
that he wrote a newsgroup posting instead seems to indicate that his
programming editor isn't quite as good as the editor in his newsreader)

/F



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


Re: String To Dict Problem

2006-04-22 Thread Clodoaldo Pinto
Michael Spencer wrote:

 Alternatively, you could edit visitName to allow 'True' and any other
 identifiers you specify e.g. (untested):

  allowed = {True: True, False: False}
  def visitName(self,node, **kw):
   try:
  return self.allowed[node.name]
  except KeyError:
  raise Unsafe_Source_Error(Strings must be quoted,
   node.name, node)


Thank you both Michael and Felipe. The solutions work great!

Regards, Clodoaldo

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


repr() for Perl?

2006-04-22 Thread skip
Sorry to ask a Perl question here, but...  Does Perl have something like
Python's repr() function?  I want to print out a string and have CR print as
\r, LF as \n, etc.  I looked in the Perl/Python phrasebook:

http://wiki.python.org/moin/PerlPhrasebook

but saw nothing along those lines.

Thx,

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


Re: what has python added to programming languages? (lets be esoteric, shall we ;)

2006-04-22 Thread skip

Wildemar Are there any concepts that python has not borrowed, concepts
Wildemar that were not even inspired by other languages?

I'd say Guido's willingness to borrow heavily from the best ideas present in
other languages ranks right up there as one of its key concepts.

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


Re: repr() for Perl?

2006-04-22 Thread John J. Lee
[EMAIL PROTECTED] writes:

 Sorry to ask a Perl question here, but...  Does Perl have something like
 Python's repr() function?  I want to print out a string and have CR print as
 \r, LF as \n, etc.  I looked in the Perl/Python phrasebook:
 
 http://wiki.python.org/moin/PerlPhrasebook
 
 but saw nothing along those lines.

perldoc Data::Dumper

(but my Perl is rusty)


John

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


python's thread problem on Linux platform

2006-04-22 Thread devdoer
I found that  multi-threaded program(io-centralize )  runs very slowly
on linux while the same program   runs very quickly  on windows.If I
change the thread number to one ,the program runs quickly  on linux, in
fact the speed is quicker than the multi-threaded version .
It turns out   that python's multi-thread support on linux has some
problems.Any comments?

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


Re: repr() for Perl?

2006-04-22 Thread Mirco Wahab
Hi skip

 Sorry to ask a Perl question here, but...  Does Perl have something like
 Python's repr() function?  I want to print out a string and have CR print as
 \r, LF as \n, etc.  I looked in the Perl/Python phrasebook:

Have a look at this:

#  cmp_rep.pl --- #
#!/usr/bin/perl -w
use String::Escape qw(printable);

# - - - - the perl way - - - - -
$st = str\ting\n;
print In Perl:\n, printable($st);

# - - - - the python way - - - -
use Inline Python = 'PYEND';
st=str\ting\n;
print \nIn Python:\n, repr(st)
PYEND
# --- #

Should give almost the same results

Regards

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


howto py2exe/py2app for self updating application

2006-04-22 Thread SPE - Stani's Python Editor
Hi,

I'm creating a GUI program
with wxPython which will be distributed  for Mac and Windows. The
audience of the program is not technical at all (eg they've never
heard about Python yet ;-), so everything should go automatically. The
program should be able to update itself and to update its database
(collection of .txt files). These are two separated things and don't
happen simultaneously. I thought of the following:

- seperate the code which will be updated and zip it to use a zipimport
- zip the .txt files

These files can then be downloaded (urllib or so) and if the download
has completed succesfully, replace their old files. For the updated
python code it is necessary to restart the program for the database
not.

These questions arise:

++ How can I bundle a zipimport file with py2exe/py2app? Let say this
is the
folder layout of the program:
application.py
code.zip (contains main.py, ui.py, etc..) *
data.zip (contains .txt files) *
other files (preferably bundled but not necessary) such as the
wxPython libraries and whatever py2app will want to include

(* means should be remote updatable/synchronizable)

application.py is just a dummy file which calls code.main.main()

Should I declare code.zip as a data file or as a python package?

Of course it would be nice if someone be so kind to suggest a simple
setup.py recipee for this...

++ I have Python2.4, wxPython2.6.3, OS X 10.4 Will it run on other
versions of OS X? If not will a version compiled with py2app on OS X
10.3 run on
OS X 10.4 or do I need to provide a file for every OS X version?

++ Do I have to declare something special for py2app and wxPython?

Thanks in advance,

Stani

PS Please cc your answer to spe.stani.be IatI gmail.com

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


String formatting using dictionaries

2006-04-22 Thread Clodoaldo Pinto
I know how to format strings using a dictionary:

 d = {'list':[0, 1]}
 '%(list)s' % d
'[0, 1]'

Is it possible to reference an item in the list d['list']?:

 '%(list[0])s' % d
Traceback (most recent call last):
  File stdin, line 1, in ?
KeyError: 'list[0]'

Regards, Clodoaldo Pinto

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


Re: another question about buffers

2006-04-22 Thread nephish
i think it may be,
i am just doing a while 1: loop to just wait for whatever comes in.
thanks

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


Re: python's thread problem on Linux platform

2006-04-22 Thread Irmen de Jong
[EMAIL PROTECTED] wrote:
 I found that  multi-threaded program(io-centralize )  runs very slowly
 on linux while the same program   runs very quickly  on windows.If I
 change the thread number to one ,the program runs quickly  on linux, in
 fact the speed is quicker than the multi-threaded version .
 It turns out   that python's multi-thread support on linux has some
 problems.Any comments?
 

Yes. There is a bug in your code.

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


Re: String formatting using dictionaries

2006-04-22 Thread Peter Otten
Clodoaldo Pinto wrote:

 I know how to format strings using a dictionary:
 
 d = {'list':[0, 1]}
 '%(list)s' % d
 '[0, 1]'
 
 Is it possible to reference an item in the list d['list']?:
 
 '%(list[0])s' % d
 Traceback (most recent call last):
   File stdin, line 1, in ?
 KeyError: 'list[0]'

No, but you can provide a modified dictionary to get the effect:

 class Dict(dict):
... def __getitem__(self, key):
... if key in self:
... return super(Dict, self).__getitem__(key)
... return eval(key, self)
...
 d = Dict(list=[0, 1])
 %(list)s % d
'[0, 1]'
 %(list[0])s % d
'0'
 %(list[1]+42)s % d
'43'

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


Re: a flattening operator?

2006-04-22 Thread Michael Tobis
I think by regular expressions you mean expressions. regular
expressions are what you get from import re .

mt

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


Re: 有關於 Mining google web services : Building applications with the Google API這本書的範例

2006-04-22 Thread Sybren Stuvel
[EMAIL PROTECTED] enlightened us with:
 ?z?n?A
   ?O?o?A?e???b???s Mining Google Web Services
: Building Applications with
 the Google API[EMAIL PROTECTED] 6??Using SQL Server as a
 Database??
 ?M?B?A???q???w?g?w??SQL Server 2000
 sp4?A?b?d???{?A.net?X?{?F
 ?u?L?k?B?z?~???p: System.Data.SqlClient.SqlException: SQL
 Server
 [EMAIL PROTECTED]@?U?C?P???U??.
 Thank you.

It helps if you post in ASCII and English.

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


Re: Generate a sequence of random numbers that sum up to 1?

2006-04-22 Thread Gerard Flanagan
Gerard Flanagan wrote:
 Gerard Flanagan wrote:
  Anthony Liu wrote:
   I am at my wit's end.
  
   I want to generate a certain number of random numbers.
This is easy, I can repeatedly do uniform(0, 1) for
   example.
  
   But, I want the random numbers just generated sum up
   to 1 .
  
   I am not sure how to do this.  Any idea?  Thanks.
  
 
  --
  import random
 
  def partition(start=0,stop=1,eps=5):
  d = stop - start
  vals = [ start + d * random.random() for _ in range(2*eps) ]
  vals = [start] + vals + [stop]
  vals.sort()
  return vals
 
  P = partition()
 
  intervals = [ P[i:i+2] for i in range(len(P)-1) ]
 
  deltas = [ x[1] - x[0] for x in intervals ]
 
  print deltas
 
  print sum(deltas)
  ---
 

 def partition(N=5):
 vals = sorted( random.random() for _ in range(2*N) )
 vals = [0] + vals + [1]
 for j in range(2*N+1):
 yield vals[j:j+2]

 deltas = [ x[1]-x[0] for x in partition() ]

 print deltas

 print sum(deltas)


finally:

---
def distribution(N=2):
p = [0] + sorted( random.random() for _ in range(N-1) ) + [1]
for j in range(N):
yield p[j+1] - p[j]

spread = list(distribution(10))

print spread
print sum(spread)
---
Gerard

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


Re: 有關於 Mining google web services : Building applications with the Google API這本書的範例

2006-04-22 Thread pou
I have found the way to solve .
So long as alter and establish reading account number and password of
the database , finish. 
Thank you very mush.

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


Re: String formatting using dictionaries

2006-04-22 Thread Fredrik Lundh
Clodoaldo Pinto wrote:

 I know how to format strings using a dictionary:

  d = {'list':[0, 1]}
  '%(list)s' % d
 '[0, 1]'

 Is it possible to reference an item in the list d['list']?:

  '%(list[0])s' % d
 Traceback (most recent call last):
   File stdin, line 1, in ?
 KeyError: 'list[0]'

not directly, but you can wrap the dictionary in a custom mapper
class:

class mapper(dict):
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
k, i = key.split([)
i = int(i[:-1])
return dict.__getitem__(self, k)[i]

 d = {list: [0, 1]}
 d = mapper(d)
 '%(list)s' % d
[0, 1]
 '%(list[0])s' % d
0

/F



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


Jython/Python Programmers

2006-04-22 Thread Solar^
Greetings Group!
I'm trying to do a project for my CS class. I'm using this program
from Mark Guzdial Jython text:

def echoes(snd, delay, factor):
  sound1 = makeSound(snd)
  sndlen1 = getLength(sound1)
  sndlen2 = sndlen1 + (delay * factor)
  
  sound2 =decideLen(sound1, sndlen2) # this function return the length
# new sound canvas
  echoamp = 1.0   for echocount in range(1, factor + 1):
echoamp = echoamp * 0.6
for echoposition1 in range(1, sndlen1):
  echoposition2 = echoposition1 + (delay*echocount)
  value1 = getSampleValueAt(sound1, echoposition1) * echoamp
 #problem here# value2 = getSampleValueAt(sound2, echoposition2)
setSampleValueAt(sound2, echoposition2, value1 + value2)
  play(sound2)
  return(sound2)  

def decideLen(snd1, len1):
  srate1 = getSamplingRate(snd1)
  time1 = len1/srate1
  time1 =int( ceil(time1))
  snd2 = makeEmptySound(time1)
  return snd2

The problem I'm having is that this program will work for a sampling 
rate of 22050, but not for the higher quality 44000 rate.
I keep getting an array out of bounds message where I marked it on the
program. Can't seem to find out why. Too much of a NewBe programmer I
guess. Any one help?
Regards,
Solar^
-- 
http://mail.python.org/mailman/listinfo/python-list


need a thread to keep a socket connection alive?

2006-04-22 Thread nephish
hey there,

i have a script that waits for message packets from a data server over
a socket.
it goes a little like this:

while 1:
x+=1
databack = sockobj.recv(158)
if databack:

print 'caught a message %s bytes ' % len(databack)
if len(databack)  120:
message = databack[3:-3] #strip stx and enx
print '\n\n%s' % message
else:
   break
print 'end data ack'


it works fine for a while, but the server requires that i send a
heartbeat ping every 600 seconds or it will terminate the connection.

so i also need something like
while 1:
 sockobj.send(ping)
 ping_acknowlage = sockobj.recv(48)
 time.sleep(550)



should i do this with threads? i dont want to interrupt the listening
cycle to send a ping.

appreciate any tips on how would be the best way to pull this off.

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


Re: howto py2exe/py2app for self updating application

2006-04-22 Thread [EMAIL PROTECTED]
of course!
 your can be carefully if you do it.
but why you ask some here ? in http://www.python.org completly a module
for your problem 
look and try again!

[roRoNoaZoro]

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


Re: proposed Python logo

2006-04-22 Thread jarrells
Mike,

Excellent artwork!

I don't like reinventing the wheel so I propose we reuse someone else's
work.

I propose something like:

http://www.dvdweb.co.uk/reviewgfx/bompfc1.jpg

which symbolizes Python's ability to quickly implement many coding
ideas or:

http://www.phill.co.uk/comedy/python/python15.jpg

which symbolizes Python's ability to squash the competition for quick
coding or:

http://imagecache2.allposters.com/images/CMAG/939-009.jpg

which symbolizes Python's place as the pick of the litter.

They also symbolize the fact that coder's shouldn't take life too
seriously.

Happy coding!

Mike

Michael Tobis wrote:
 Is this the right room for an argument?

 http://geosci.uchicago.edu/~tobis/snake.png

 ok, so my execution is pretty crude, but you can at least see my idea.
 I trust you to imagine it professionally executed in cheerful colors.

 Advantages of proposed logo over existing logo
SNIP GOOD ARGUMENTS

 Much as it would be an ego-boost for me to have some version of this
 idea used for the language, I'm  almost as happy with repurposing the
 most excellent PyCon logo if that is OK with everyone involved. But imo
 we can't fully promote the power of Python with tadpoles.
 
 mt

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


Re: howto py2exe/py2app for self updating application

2006-04-22 Thread SPE - Stani's Python Editor
Can you be more specific? Which module do you mean at python.org?

Stani

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


problems when unpacking tuple ...

2006-04-22 Thread harold
Dear all,

Maybe I stared on the monitor for too long, because I cannot find the
bug ...
My script transition_filter.py starts with the following lines:

import sys

for line in sys.stdin :
try :
for a,b,c,d in line.split() :
pass

except ValueError , err :
print line.split()
raise err

The output (when given the data I want to parse) is:
['0.0','1','0.04','0']
Traceback (most recent call last):
  File transition_filter.py, line 10, in ?
raise err
ValueError: need more than 3 values to unpack

What is going wrong here? Why does python think that
I want to unpack the outcome of line.split() into three
values instead of four? I must be really tired, but I just
cannot see the problem. Any clues??

Thanks,

- harold -

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


Re: need a thread to keep a socket connection alive?

2006-04-22 Thread Rene Pijlman
[EMAIL PROTECTED]:
i have a script that waits for message packets from a data server over
a socket.

Using what network protocol?

it works fine for a while, but the server requires that i send a
heartbeat ping every 600 seconds or it will terminate the connection.
[...]
should i do this with threads? i dont want to interrupt the listening
cycle to send a ping.

If this is a TCP connection with a conversational protocol, you can't have
two threads reading bytes of the socket, without some sort of
coordination. When one thread parses the bytes it received, some bytes may
be part of the next message for the other thread.

You may be better off with asynchronous I/O and a state machine model.
http://squirl.nightmare.com/medusa/async_sockets.html
http://www.python.org/doc/lib/module-asyncore.html
http://twistedmatrix.com/projects/core/documentation/howto/clients.html

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problems when unpacking tuple ...

2006-04-22 Thread Tim Chase
 for a,b,c,d in line.split() :

[snip]
 
 The output (when given the data I want to parse) is:
 ['0.0','1','0.04','0']

You'll notice that you're not passing any parameters to 
split().  By default, it splits on whitespace, and your 
input doesn't have any whitespace in it.  Thus, you're 
actually only getting *one* (not three) elements back.  Try 
using split(,) instead.

-tkc




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


Re: problems when unpacking tuple ...

2006-04-22 Thread Rene Pijlman
harold:
The output (when given the data I want to parse) is:

If you'd told us that data, and told us what version of Python you're
using, we could have reproduced the problem to look into it.

ValueError: need more than 3 values to unpack

Why does python think that I want to unpack the outcome of 
line.split() into three values instead of four? 

That's not what it says. It says there are only 3 values in the outcome,
and it needs more (4 to be precise).

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problems when unpacking tuple ...

2006-04-22 Thread Gerard Flanagan

harold wrote:
 Dear all,

 Maybe I stared on the monitor for too long, because I cannot find the
 bug ...
 My script transition_filter.py starts with the following lines:

 import sys

 for line in sys.stdin :
 try :
 for a,b,c,d in line.split() :
 pass

 except ValueError , err :
 print line.split()
 raise err

 The output (when given the data I want to parse) is:
 ['0.0','1','0.04','0']
 Traceback (most recent call last):
   File transition_filter.py, line 10, in ?
 raise err
 ValueError: need more than 3 values to unpack

 What is going wrong here? Why does python think that
 I want to unpack the outcome of line.split() into three
 values instead of four? I must be really tired, but I just
 cannot see the problem. Any clues??


The 3 values are coming from the first element in the list '0.0' -
change it to '0' and you should get: ValueError: need more than 1 value
to unpack.
See? it's trying to get a,b,c,d from each element of the list not the
whole list.

Gerard

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


Re: problems when unpacking tuple ...

2006-04-22 Thread harold
Rene Pijlman schrieb:

 harold:
 The output (when given the data I want to parse) is:

 If you'd told us that data, and told us what version of Python you're
 using, we could have reproduced the problem to look into it.


Thank you for the answers and sorry that I did not provide more
information in the first place.
My data file is white space seperated data (space seperated data to be
precise) and I am
using python 2.4.2


As can be seen, the output of the print statement in the lines

except ValueError , err:
print line.split()
raise err

has exactly four values...


 ValueError: need more than 3 values to unpack
 
 Why does python think that I want to unpack the outcome of
 line.split() into three values instead of four?

 That's not what it says. It says there are only 3 values in the outcome,
 and it needs more (4 to be precise).


A similar error happens in an interpreter session, when typing
 for line in [1 2 3 4] :
...for a,b,c,d in line.split() :
...pass
...
Traceback (most recent call last):
  File stdin, line 2, in ?
ValueError: need more than 1 value tyo unpack

maybe this might help to track down the error.
Thanks!

- harold -

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


Re: problems when unpacking tuple ...

2006-04-22 Thread harold
Thank you Gerard.
This must be the problem. Now I can get it working.

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


Re: proposed Python logo

2006-04-22 Thread EP
Michael Yanowitz wrote:

   How about having something from Monty Python in the logo rather
than something snakelike. Python was named after Monty Python and not
the snake. Snakes also don't appear friendly to me.


I think the new logo, while professionally done (bravo!) is 
unmemmorable.  And why such fat snakes?  Snakes are not generally 
thought of as friendly (whereas Pythoin the langauge is); they are not 
even warm-blooded, and I've always thought the snake a misfit for the 
language... though the old snake was at least cute.

I think something along the flying sheep motif would be memorable - 
after all, many of us remember it from MP.

And something like that much better represents the change in thinking 
most programmers must undergo to embrace the language.  Help, I'm 
falling --- I can't find any braces!

To some extent Python is something completely different.

EP


calling it Python and then having a flying sheep as a logo - the 
apparent contradiction might be a good mental reset for those 
approaching the language.  just my two cents
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting using dictionaries

2006-04-22 Thread Clodoaldo Pinto
Thank you guys, you are great!

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


Re: problems when unpacking tuple ...

2006-04-22 Thread Felipe Almeida Lessa
Em Sáb, 2006-04-22 às 09:21 -0700, harold escreveu:
 for line in sys.stdin :
 try :
 for a,b,c,d in line.split() :
 pass
 
 except ValueError , err :
 print line.split()
 raise err 

Try this:

for a, b, c, d in sys.stdin:
 print a, b, c, d

-- 
Felipe.

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

Re: problems when unpacking tuple ...

2006-04-22 Thread Rene Pijlman
harold:
A similar error happens in an interpreter session, when typing
 for line in [1 2 3 4] :
...for a,b,c,d in line.split() :
...pass
...
Traceback (most recent call last):
  File stdin, line 2, in ?
ValueError: need more than 1 value tyo unpack

maybe this might help to track down the error.

Suppose the code was:

for x in line.split():

line.split() yields one list with 4 items. The loop will be performed 4
times, assigning one value of the list to x with every iteration. In your
code, x is a tuple with 4 elements: a,b,c,d. So with every iteration one
value is assigned to that tuple. Since the value is not a sequence of 4
items, this fails.

There's two sensible things you can do:

for line in [1 2 3 4]:
a,b,c,d = line.split()

for line in [1 2 3 4]:
for a in line.split():

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Define type of 'module' object that is imported

2006-04-22 Thread Zachary Pincus
 I would like a given module to be created as an
 instance of that particular subclass on import, so that if I do:

 import foo
 type(foo)

 I get type 'myModule' instead of type 'module'.

 Is there any way to effect this? Something like __metaclass__  
 = ...  but
 at the beginning of a module instead of at the beginning of a class?

 Would be interesting to know about the motivation. Is foo just your  
 own
 module or any module.

No, just one particular module that needs to do some slow things.
I'd like for a user to just be able to type
import foo
and have the foo module's type be some special type. None of the  
options below really allow this to happen with one step. It would be  
more like import lazyFoo; import foo.

What I'm doing now is in 'foo.py' performing surgery a la:
sys.modules[__name__] = MyModuleClass(...)
but that's ugly, and can break the reload mechanism, and causes some  
other troubles.
I would like to do:
sys.modules[__name__].__class__ = MyModuleClass
but that fails because the module is not a heap type or something.

I have also tried:
sys.modules[__name__].__getattribute__ = MethodType(myGetattr,  
sys.modules[__name__], ModuleType)
but the custom __getattribute__ never gets called.

Hmm, oh well.

Zach

 * you can replace __import__
 * you can set sys.modules['foo']=mymod   (in sitecustomize.py ? )
 * your module can be a class instance as well in newer pythons (2.2 
 +?);
= you can set sys.modules['foo']=Foo()   # Foo having  
 properties ...
 * simply import certain expensive modules only ad-hoc
 * maybe you don't need it as module at all, but an instance. or you
 avoid pre-computing things in global namespace.
 ...

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


Re: problems when unpacking tuple ...

2006-04-22 Thread Felipe Almeida Lessa
Em Sáb, 2006-04-22 às 14:25 -0300, Felipe Almeida Lessa escreveu:
 Em Sáb, 2006-04-22 às 09:21 -0700, harold escreveu:
  for line in sys.stdin :
  try :
  for a,b,c,d in line.split() :
  pass
  
  except ValueError , err :
  print line.split()
  raise err 
 
 Try this:
 
 for a, b, c, d in sys.stdin:
  print a, b, c, d
 

Forget that. It was stupid. You should try this instead:

for line in sys.stdin:
a, b, c, d = line.split()

-- 
Felipe.

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

Re: problems when unpacking tuple ...

2006-04-22 Thread Gerard Flanagan

harold wrote:
 Thank you Gerard.
 This must be the problem. Now I can get it working.

Good!  I got confused thinking about it too, but I think you just had
one loop too many.

for line in sys.stdin :
try :
a,b,c,d = line.split()

not:

for line in sys.stdin :
try :
for a,b,c,d in line.split() :
pass

Gerard

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


Re: send cookie on request with urllib2

2006-04-22 Thread itay_k
Thanks!

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


Re: perspective on ruby

2006-04-22 Thread Edward Elliott
robert wrote:
  Yes - start them explore. I'd not want to be teached a specific
  _language_ in a course longer that one day. A language cannot be teached.
  Who of the posters in this thread want themselves to be _teached_ more
  than one day on a language?
 
 Isn't the fun, finding the right tools for certain purposes one-self?

That holds for bright, motivated students.  The problem is the others. 
Some people are totally lost when you throw them a book and say learn 
this.   So the choices are:

1. Do it and watch the rank-and-file students abandon the major
2. Provide more language-specific instruction

Now places like Berkeley and MIT can afford to take route 1.  They already 
have a surplus of bright, motivated students.  But at many (most?) schools, 
route 2 is in the dept's best interest.  Number of majors affects prestige, 
influence, and at many state schools funding.  Telling the rank-and-file to 
shove off is shooting themselves in the foot, and ultimately hurts the good 
students as well with a lesser dept.  These depts are walking a tightrope 
as they try hard to maintain minimum standards.  It's not a binary choice 
really, it's a spectrum.

So while route 1 may be better for the profession as a whole, the current 
educational system has some pretty strong pressures for route 2.
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem calling math.cos()

2006-04-22 Thread Sambo
I have the following module:
---
import math

def ac_add_a_ph( amp1, ph1, amp2, ph2 ):

amp3 = 0.0 
ph3 = 0.0
ac1 = ( 0, 0j )
ac2 = ( 0, 0j )  
ac3 = ( 0, 0j )
ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( 
math.radians( ph1 ) ) )
ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 * math.sin( 
math.radians( ph2 ) ) )
ac3 = ac1 + ac2
amp3 = math.abs( ac3 )
ph3 = math.atan( ac3.imag / ac3.real )
return [amp3, ph3]  
--
when I import it (electronics) in python.exe in windows2000 and 
try to use it, it croaks.  ??? 

 import math
 import electronics
 print electronics.ac_add_a_ph( 10, 0 , 6 , 45 )
Traceback (most recent call last):
  File stdin, line 1, in ?
  File f:\devel\python\electronics.py, line 10, in ac_add_a_ph
ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( math
.radians( ph1 ) ) )
NameError: global name 'cos' is not defined



global?? huh?
what does abs stand for? why is that not absolute value? hmmm.
Hmm, complex numbers, cool I don't even have any idea where C 
stands on this. 

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


Re: repr() for Perl?

2006-04-22 Thread skip

 Does Perl have something like Python's repr() function?

John perldoc Data::Dumper

Thanks.  Just what the doctor ordered (after setting Useqq).

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


Re: repr() for Perl?

2006-04-22 Thread skip

 Does Perl have something like Python's repr() function? 

Mirco Have a look at this:

...

Thanks, I'm getting set up to try it just for the exercise.  I went with
John Lee's Data::Dumper suggestion simply because I already had it installed
and have neither String::Escape nor Inline::Python installed.

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


Re: Problem calling math.cos()

2006-04-22 Thread Roy Smith
In article [EMAIL PROTECTED], Sambo [EMAIL PROTECTED] 
wrote:

 I have the following module:
 ---
 import math
 
 def ac_add_a_ph( amp1, ph1, amp2, ph2 ):
 
 amp3 = 0.0 
 ph3 = 0.0
 ac1 = ( 0, 0j )
 ac2 = ( 0, 0j )  
 ac3 = ( 0, 0j )
 ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( 
 math.radians( ph1 ) ) )
 ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 * math.sin( 
 math.radians( ph2 ) ) )
 ac3 = ac1 + ac2
 amp3 = math.abs( ac3 )
 ph3 = math.atan( ac3.imag / ac3.real )
 return [amp3, ph3]  
 --
 when I import it (electronics) in python.exe in windows2000 and 
 try to use it, it croaks.  ??? 
 
  import math
  import electronics
  print electronics.ac_add_a_ph( 10, 0 , 6 , 45 )
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File f:\devel\python\electronics.py, line 10, in ac_add_a_ph
 ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( 
 math
 .radians( ph1 ) ) )
 NameError: global name 'cos' is not defined
 

That's not what I get when I run it (admittedly, not on windows).  I get:

 import math
 import electronics
 print electronics.ac_add_a_ph( 10, 0 , 6 , 45 )
Traceback (most recent call last):
  File stdin, line 1, in ?
  File electronics.py, line 13, in ac_add_a_ph
amp3 = math.abs( ac3 )
AttributeError: 'module' object has no attribute 'abs'
 

which is exactly what I expected, since abs (which is indeed absolute 
value) is a built-in function, not a part of the math module.  Are you sure 
the stack trace you posted matches the source code you posted?

By the way, when using math functions, I find it's usually easier to import 
them into my namespace by doing from math import *, then I can just use 
sin(), cos(), etc directly, instead of having to do math.sin() or 
math.cos().  Especially for common math functions, this makes your code a 
lot easier to read.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem calling math.cos()

2006-04-22 Thread Alex Martelli
Sambo [EMAIL PROTECTED] wrote:

 I have the following module:
 ---
 import math
 
 def ac_add_a_ph( amp1, ph1, amp2, ph2 ):
 
 amp3 = 0.0 
 ph3 = 0.0
 ac1 = ( 0, 0j )
 ac2 = ( 0, 0j )
 ac3 = ( 0, 0j )

You're defining ac1, ac2, ac3 as tuples, each with two items.  That's
silly: remove these three useless and confusing lines (the first two are
prety silly too).  No damage, but, avoidable extra confusion.

 ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * \
 math.sin( math.radians( ph1 ) ) )
 ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 * \
 math.sin( math.radians( ph2 ) ) )
 ac3 = ac1 + ac2
 amp3 = math.abs( ac3 )
 ph3 = math.atan( ac3.imag / ac3.real )
 return [amp3, ph3]  
 --
 when I import it (electronics) in python.exe in windows2000 and 
 try to use it, it croaks.  ??? 
 
  import math
  import electronics
  print electronics.ac_add_a_ph( 10, 0 , 6 , 45 )
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File f:\devel\python\electronics.py, line 10, in ac_add_a_ph
 ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * \
  math.sin( math
 .radians( ph1 ) ) )

[[some lines split to respect NNTP's constraint on 80-char lines]]

 NameError: global name 'cos' is not defined
 
 
 
 global?? huh?

Weird -- I can't reproduce this; it's the kind of symptom you get when
mistakenly using a comma instead of a dot, for example, but I don't see
that error in your code.

What I _do_ see is an AttributeError: 'module' object has no attribute
'abs' on the amp3 assignment -- of course, because that's indeed the
fact (abs is a builtin, not a member to module math).

Most likely, you got a bit confused and didn't copy-and-paste exactly
what was going on.


 what does abs stand for? why is that not absolute value? hmmm.

abs does stand for absolute-value.

 Hmm, complex numbers, cool I don't even have any idea where C 
 stands on this. 

C has no stand on complex numbers.


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


Re: Problem calling math.cos()

2006-04-22 Thread Robert Kern
Sambo wrote:
 I have the following module:
 ---
 import math
 
 def ac_add_a_ph( amp1, ph1, amp2, ph2 ):
 
 amp3 = 0.0 
 ph3 = 0.0
 ac1 = ( 0, 0j )
 ac2 = ( 0, 0j )  
 ac3 = ( 0, 0j )
 ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( 
 math.radians( ph1 ) ) )
 ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 * math.sin( 
 math.radians( ph2 ) ) )
 ac3 = ac1 + ac2
 amp3 = math.abs( ac3 )
 ph3 = math.atan( ac3.imag / ac3.real )
 return [amp3, ph3]  
 --
 when I import it (electronics) in python.exe in windows2000 and 
 try to use it, it croaks.  ??? 
 
import math
import electronics
print electronics.ac_add_a_ph( 10, 0 , 6 , 45 )
 
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File f:\devel\python\electronics.py, line 10, in ac_add_a_ph
 ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( 
 math
 .radians( ph1 ) ) )
 NameError: global name 'cos' is not defined
 
 global?? huh?

That's not what I get.

[~]$ cat electronics.py
import math

def ac_add_a_ph( amp1, ph1, amp2, ph2 ):

amp3 = 0.0
ph3 = 0.0
ac1 = ( 0, 0j )
ac2 = ( 0, 0j )
ac3 = ( 0, 0j )
ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin(
math.radians( ph1 ) ) )
ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 * math.sin(
math.radians( ph2 ) ) )
ac3 = ac1 + ac2
amp3 = math.abs( ac3 )
ph3 = math.atan( ac3.imag / ac3.real )
[~]$ python
Python 2.4.1 (#2, Mar 31 2005, 00:05:10)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin
Type help, copyright, credits or license for more information.
 import electronics
 electronics.ac_add_a_ph(10, 0, 6, 45)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File electronics.py, line 13, in ac_add_a_ph
amp3 = math.abs( ac3 )
AttributeError: 'module' object has no attribute 'abs'


 what does abs stand for? why is that not absolute value? hmmm.
 Hmm, complex numbers, cool I don't even have any idea where C 
 stands on this. 

Change math.abs() to abs(). It's a builtin function. Yes, it does compute the
absolute value. Fixing that:

 import electronics
 electronics.ac_add_a_ph(10, 0, 6, 45)
[14.861117513241918, 0.2895134725436232]


-- 
Robert Kern
[EMAIL PROTECTED]

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread Chris Lambacher

http://dirtsimple.org/2004/12/python-is-not-java.html
http://dirtsimple.org/2004/12/java-is-not-python-either.html
http://dirtsimple.org/2004/12/python-interfaces-are-not-java.html

This link seems to be down at the moment.
http://naeblis.cx/rtomayko/2004/12/15/the-static-method-thing

The above articles were really helped me understand the python way of doining
things.  In particular they mention language features that may be named the
same and do similar things, but would be used for totally different reasons in
the two languages.

I hope you find them as helpful as I did.

-Chris


On Sat, Apr 22, 2006 at 12:40:51AM -0700, ToddLMorgan wrote:
 I'm just starting out with python, after having a long history with
 Java. I was wondering if there were any resources or tips from anyone
 out there in Python-land that can help me make the transition as
 successfully as possible? Perhaps you've made the transition yourself
 or just have experience with folks who have made the transition.
 
 I'm looking for the common types of mistakes that say a Java/C# or
 even C++ developer may commonly make. More examples like those
 highlighted here http://dirtsimple.org/2004/12/python-is-not-java.html
 would be particularly useful. I've already made the static class
 method mistake, and been thoroughly confused by packages and
 imports/froms and extremely frustrated with attempting to call super
 constructors etc.  I'm getting the hang of passing around functions
 (ala the command pattern), customising the operators and extending
 inbuilt classes. All of these concepts I've done before so there
 nothing really great and wonderful about using them in another
 language. Some of the really powerful ideas of python (eg as suggested
 in the link) about creating one function containing a template function
 that can cater to all possible implementations sounds really cool and
 alien to me at the same time. That's the sort of stuff I'm
 interested in.
 
 At this point in time I'd say my python code is more coding Java in
 python than doing it in a pythonic way. Perhaps there some good/great
 examples of Python scripts or projects that I could look at to get
 inspired or learn pythonic implementation ideas? I just don't know of
 any. Are there python specific equivalents to the common Patterns,
 Anti-Patterns and Refactoring books that are so prevalent as
 reccomended reading in C++ and Java? If so what?
 
 Given the rising popularity of Python these days there has got to be a
 few of you out there who've made the transition successfully and have
 some pearls-of-wisdom to share that you'd wished you'd known about
 earlier.
 
 Thanks
  Todd
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem calling math.cos()

2006-04-22 Thread Felipe Almeida Lessa
Em Sáb, 2006-04-22 às 15:14 -0400, Sambo escreveu:
 when I import it (electronics) in python.exe in windows2000 and 
 try to use it, it croaks.  ??? 

$ python2.4
Python 2.4.3 (#2, Mar 30 2006, 21:52:26)
[GCC 4.0.3 (Debian 4.0.3-1)] on linux2
Type help, copyright, credits or license for more information.
 import math
 def ac_add_a_ph( amp1, ph1, amp2, ph2 ):
... amp3 = 0.0
... ph3 = 0.0
... ac1 = ( 0, 0j )
... ac2 = ( 0, 0j )
... ac3 = ( 0, 0j )
... ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 *
math.sin( math.radians( ph1 ) ) )
... ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 *
math.sin( math.radians( ph2 ) ) )
... ac3 = ac1 + ac2
... amp3 = math.abs( ac3 )
... ph3 = math.atan( ac3.imag / ac3.real )
... return [amp3, ph3]
...
 ac_add_a_ph(10, 0, 6, 45)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 10, in ac_add_a_ph
AttributeError: 'module' object has no attribute 'abs'
 abs
built-in function abs
 def ac_add_a_ph(amp1, ph1, amp2, ph2):
... ac1 = complex(amp1 * math.cos(math.radians(ph1)), amp1 *
math.sin(math.radians(ph1)))
... ac2 = complex(amp2 * math.cos(math.radians(ph2)), amp2 *
math.sin(math.radians(ph2)))
... ac3 = ac1 + ac2
... ph3 = math.atan(ac3.imag / ac3.real)
... return [abs(amp3), ph3]
...
 ac_add_a_ph(10, 0, 6, 45)
[14.86111751324192, 0.28951347254362308]




So:
---
import math

def polar(rho, theta, theta_in_radians=False)
Creates a complex number from its polar form.
# Avoid repeating yourself by creating different functions
if not theta_in_radians:
theta = math.radians(theta)
return complex(rho * math.cos(theta), rho * math.sin(theta))

def ac_add_a_ph(amp1, ph1, amp2, ph2):
Add two complexes together from their polar form.
# You don't have to initialize the variables with 0.0 and such.
ac3 = polar(amp1, ph1) + polar(amp2, ph2)
ph3 = math.atan(ac3.imag / ac3.real)
return (abs(ac3), ph3) # Use a tuple in this case
--



*But*, I encourage you using the complex numbers themselves instead of
converting to and from over and over.


HTH,

-- 
Felipe.

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

Re: Can you create an instance of a subclass with an existing instance of the base class?

2006-04-22 Thread Sandra-24
Now that is a clever little trick. I never would have guessed you can
assign to __class__, Python always surprises me in it's sheer
flexibility.

In this case it doesn't work.

TypeError: __class__ assignment: only for heap types

I suspect that's because this object begins its life in C code.

The technique of using the __class__.__subclasses__ also fails:

TypeError: cannot create 'B' instances

This seems more complex than I thought. Can one do this for an object
that beings it's life in C?

Thanks,
-Sandra

Peter Otten wrote:
 Sandra-24 wrote:

  Can you create an instance of a subclass using an existing instance of
  the base class?
 
  Such things would be impossible in some languages or very difficult in
  others. I wonder if this can be done in python, without copying the
  base class instance, which in my case is a very expensive object.

 You can change the class of an instance by assigning to the __class__
 attribute. The new class doesn't even need to be a subclass of the old:

  class A(object):
 ... def __init__(self, name):
 ... self.name = name
 ... def show(self): print self.name
 ...
  a = A(alpha)
  a.show()
 alpha
  class B(object):
 ... def show(self): print self.name.upper()
 ...
  a.__class__ = B
  a.show()
 ALPHA
 
 Peter

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


Re: Generate a sequence of random numbers that sum up to 1?

2006-04-22 Thread Anthony Liu
Thanks a lot, Alex and Gerard.

I am actually not very concerned about the
inter-dependency of the floating numbers generated
randomly.  They are good enough if they are subject to
the constraint of summing up to 1.  

It is simply not worth the time to get an HMM by
training it on a large corpus. My sole purpose is to
test the predicting power of an HMM, given a set of
parameter values. 

I will definitely try out your snippet and see if it
works.  Thanks a lot!

--- Alex Martelli [EMAIL PROTECTED] wrote:

 Anthony Liu [EMAIL PROTECTED] wrote:
...
  As a matter of fact, given that we have to specify
 the
  number of states for an HMM, I would like to
 create a
  specified number of random floating numbers whose
 sum
  is 1.0.
 
 def forAL(N):
  N_randoms = [random.random() for x in
 xrange(N)]
  total = sum(N_randoms)
  return [x/total for x in N_randoms]
 
 
 Does this do what you want?  Of course, the
 resulting numbers are not
 independent, but then the constraints you pose would
 contradict that.
 
 
 Alex
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 


__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem calling math.cos()

2006-04-22 Thread Tim Peters
[Robert Kern]
 ...
 ph3 = math.atan( ac3.imag / ac3.real )
 ...

Don't do that:  atan2 is the correct way to compute the angle, because
the signs of both inputs are needed to determine the correct quadrant.
 So do:

 ph3 = math.atan2(ac3.imag, ac3.real)

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


Re: quick surface plots

2006-04-22 Thread nich2o
Did you try mplot3D ?
http://www.scipy.org/Wiki/Cookbook/Matplotlib/mplot3D 

-- N

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


list example

2006-04-22 Thread PAolo
Hi,
I wrote this small example to illustrate the usage of lists:

even=[]
odd=[]

for i in range(1,10):
if i%2:
odd.append(i)
else:
even.append(i)

print odd: +str(odd)
print even: +str(even)

numbers=even
numbers.extend(odd)
print numbers:+str(numbers)
numbers.sort()
print sorted numbers:+str(numbers)


any comment, suggestion? Is there something not elegant?

Thnx
PAolo

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


Re: list example

2006-04-22 Thread Edward Elliott
No substantive problems.  The str() calls are unnecessary, print calls 
list.__str__ already.  You can replace the loop with list comprehensions or 
slices.  Same result, a bit more succinct.  See these pages for more:

http://docs.python.org/lib/typesseq.html
http://docs.python.org/tut/node7.html  (section 5.1.4)


PAolo wrote:
 Hi,
 I wrote this small example to illustrate the usage of lists:
 
 even=[]
 odd=[]
 
 for i in range(1,10):
 if i%2:
 odd.append(i)
 else:
 even.append(i)
 
 print odd: +str(odd)
 print even: +str(even)
 
 numbers=even
 numbers.extend(odd)
 print numbers:+str(numbers)
 numbers.sort()
 print sorted numbers:+str(numbers)
 
 
 any comment, suggestion? Is there something not elegant?
 
 Thnx
 PAolo
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Python on WinXP: 7 Minutes To Hello World!

2006-04-22 Thread BartlebyScrivener
I started a long email to a friend about how to get up and running on
Python, then I thought, why not make something I can post?

It's NOT a tutorial. Just a specific, narrow, quick installation guide
for Windows XP users.

Would love comments, but probably can't incorporate them until Monday,
because I have a long drive ahead of me.

Thanks for any help.

http://www.dooling.com/index.php/category/geekophilia

rpd

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


Re: Problem calling math.cos()

2006-04-22 Thread Roy Smith
In article [EMAIL PROTECTED],
 Tim Peters [EMAIL PROTECTED] wrote:

 [Robert Kern]
  ...
  ph3 = math.atan( ac3.imag / ac3.real )
  ...
 
 Don't do that:  atan2 is the correct way to compute the angle, because
 the signs of both inputs are needed to determine the correct quadrant.
  So do:
 
  ph3 = math.atan2(ac3.imag, ac3.real)
 
 instead.

I certainly agree about using atan2() instead of atan(), but I'm surprised 
there's not an easier way to get the phase of a complex, just like abs() 
gives you the modulus.  I can see why you wouldn't want to pollute the 
global namespace with another built-in just for this purpose, but surely a 
complex.phase property wouldn't hurt?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list example

2006-04-22 Thread Wojciech Muła
PAolo wrote:
 any comment, suggestion? Is there something not elegant?

Try this:

even = range(10)[0::2]
odd  = range(10)[1::2]

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


Re: Lamdba forms

2006-04-22 Thread Duncan Booth
Ant wrote:

 Fair enough. I've just found this as well, which implies that lambda
 isn't being killed off in 3.0:
 
 http://www.python.org/dev/peps/pep-3100/
 
 In particular:
 Lambdas will have to be parenthesized [23]
 

Also: http://www.python.org/doc/essays/ppt/accu2006/Py3kACCU.ppt
slide 14.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem calling math.cos()

2006-04-22 Thread Tim Peters
[Roy Smith]
 I certainly agree about using atan2() instead of atan(), but I'm surprised
 there's not an easier way to get the phase of a complex, just like abs()
 gives you the modulus.  I can see why you wouldn't want to pollute the
 global namespace with another built-in just for this purpose, but surely a
 complex.phase property wouldn't hurt?

Or method.  Does anyone care enough to do the work? is the real
question.  I don't :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


check whether a value is scalar

2006-04-22 Thread Eli
Hi,

I want to check whether a value is a scalar. A scalar can be:
- None (null)
- string
- number (integer, float)
- boolean
How can I validate a value is one of these types?

I care about the value only, and not its class methods.
An object is not a scalar, since it's not a simple value.
An array might be considered as scalar.
The issue is I want to keep a set of values to share among several
applications in different languages, and only scalar values can be
shared. Since objects are not the same in all languages, it's possible
to share only simple values.

-thanks

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


Re: Can my python script return a value to the c program executing it?

2006-04-22 Thread Philippe Martin
Like this ?


http://aspn.activestate.com/ASPN/Mail/Message/python-list/1304518


Philippe



vduber6er wrote:

 I have a C program that calls my python script by
 
 exec_pycode(code);
 
 code =  import CheckFasta\nCheckFasta.CheckFasta (\sampledata.txt\,
 %d)\n, PyNum);
 
 CheckFasta.py is my python script with a def CheckFasta in it that
 returns a string.
 
 Is there a way for my C code to get the return value from CheckFasta?
 
 Example:
 If CheckFasta returns hello world
 
 can I somehow do something like
 
 returnstring = exec_pycode(code);
 
 where returnstring will contain hello world after the line above?
 
 Thanks

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


Re: list example

2006-04-22 Thread bearophileHUGS
PAoloany comment, suggestion? Is there something not elegant?

Here you can see many little differences, some of them reflect just my
style, but some other of them are Python standard style guidelines:

even = []
odd = []

for i in xrange(1, 10):
if i % 2:
odd.append(i)
else:
even.append(i)

print Odd:, odd
print Even:, even

numbers = even + odd
print Numbers:, numbers
numbers.sort()
print Sorted numbers:, numbers


There are surely more compact versions of that, but compactness is
usually less important than clarity, expecially for someone that is
learning Python.
This is a more compact version (with the suggestion by Wojciech Mula,
modified in two ways):

even = range(1, 10)[1::2]
odd  = range(1, 10)[0::2]

print Odd:, odd
print Even:, even

numbers = even + odd
print Numbers:, numbers
print Sorted numbers:, sorted(numbers)


Bye,
bearophile

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


Re: problems when unpacking tuple ...

2006-04-22 Thread harold
Thanks for all your answer!
Of course, I wanted to assign the outcome of the split(),  not to
iterate
over them. Thinks are done so easy in python that, sometimes, one
does not even notice that one actually does them ;-)
Cheers,

- harold -

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


Re: check whether a value is scalar

2006-04-22 Thread Roy Smith
In article [EMAIL PROTECTED],
 Eli [EMAIL PROTECTED] wrote:

 Hi,
 
 I want to check whether a value is a scalar. A scalar can be:
 - None (null)
 - string
 - number (integer, float)
 - boolean
 How can I validate a value is one of these types?
 
 I care about the value only, and not its class methods.
 An object is not a scalar, since it's not a simple value.
 An array might be considered as scalar.
 The issue is I want to keep a set of values to share among several
 applications in different languages, and only scalar values can be
 shared. Since objects are not the same in all languages, it's possible
 to share only simple values.
 
 -thanks

I'm not sure what scalar means in this context.  You say an object is 
not a scalar, but you also assert that an integer is a scalar.  These are 
contradictory statements, since integers *are* objects:

 isinstance (1, object)
True

You say that numbers are scalars.  All nunmbers, or just integers and 
floats?  What about complex numbers?  What about long integers?

In any case, the way to check for a type is with isinstance(), as I did 
above).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: check whether a value is scalar

2006-04-22 Thread harold
would

isinstance(value,(type(None),str,int,float,bool))

be enough? This yields true if the type value is in the list of type
objects given as second argument, or a subtype of one of them. What,
however, do you mean with I care about the value only, and not its
class method?

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


Re: Problem calling math.cos()

2006-04-22 Thread Sambo
Roy Smith wrote:
 In article [EMAIL PROTECTED], Sambo [EMAIL PROTECTED] 
 wrote:
 
 
I have the following module:
---
import math

def ac_add_a_ph( amp1, ph1, amp2, ph2 ):

amp3 = 0.0 
ph3 = 0.0
ac1 = ( 0, 0j )
ac2 = ( 0, 0j )  
ac3 = ( 0, 0j )
ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( 
math.radians( ph1 ) ) )
ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 * math.sin( 
math.radians( ph2 ) ) )
ac3 = ac1 + ac2
amp3 = math.abs( ac3 )
ph3 = math.atan( ac3.imag / ac3.real )
return [amp3, ph3]  
--
when I import it (electronics) in python.exe in windows2000 and 
try to use it, it croaks.  ??? 


import math
import electronics
print electronics.ac_add_a_ph( 10, 0 , 6 , 45 )

Traceback (most recent call last):
  File stdin, line 1, in ?
  File f:\devel\python\electronics.py, line 10, in ac_add_a_ph
ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( 
math
.radians( ph1 ) ) )
NameError: global name 'cos' is not defined

 
 That's not what I get when I run it (admittedly, not on windows).  I get:
 
 
import math
import electronics
print electronics.ac_add_a_ph( 10, 0 , 6 , 45 )
 
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File electronics.py, line 13, in ac_add_a_ph
 amp3 = math.abs( ac3 )
 AttributeError: 'module' object has no attribute 'abs'
 
 
 which is exactly what I expected, since abs (which is indeed absolute 
 value) is a built-in function, not a part of the math module.  Are you sure 
 the stack trace you posted matches the source code you posted?
 
Well I took the abs( 'complex' ) from the python documentation (python24.chm)
section 3.1.1 
has the following comment after it '# sqrt(a.real**2 + a.imag**2)'

 By the way, when using math functions, I find it's usually easier to import 
 them into my namespace by doing from math import *, then I can just use 
 sin(), cos(), etc directly, instead of having to do math.sin() or 
 math.cos().  Especially for common math functions, this makes your code a 
 lot easier to read.

Ah, I thought I used to use module functions without the module name.

I think my problem is reimporting electronics(.py) after modifications.
Yes, now it complains about abs().
looks like enother reason to dump this w2000 installation just so I can 
install python from scratch and use idle. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem calling math.cos()

2006-04-22 Thread Robert Kern
Tim Peters wrote:
 [Robert Kern]
 
...
ph3 = math.atan( ac3.imag / ac3.real )
...
 
 Don't do that:  atan2 is the correct way to compute the angle, because
 the signs of both inputs are needed to determine the correct quadrant.
  So do:
 
  ph3 = math.atan2(ac3.imag, ac3.real)
 
 instead.

Hey, I just copied his code to show that it gave a different error than the one
he said. I didn't bother to fix it.  :-)

-- 
Robert Kern
[EMAIL PROTECTED]

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread Ant
Take a look at the newgroup archives over the last week or two - there
seem to have been a glut of people coming from Java to Python and
asking the same sort of questions. There were some links to a bunch of
Python 'gotcha' pages which will be useful.

For my part, I came from Java to Python, and found that it was useful
to do a load of small  scripts in the simplest way possible, or in as
many different ways possible. For example, trying a script involving
creating a new iterable object from a list using for loops, list
comprehensions, generators or functional built-ins (such as map()). The
clearest method usually seems to be considered the most pythonic.

A couple of sites to practice against are:
http://www.pythonchallenge.com/
http://mathschallenge.net/

They give a good set of problems which will work various aspects of
Python that aren't familiar to Java guys, and also break the mindset
that everything has to be done in classes.

I'm still making the transition of course ;-)

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


Performance of Python 2.3 and 2.4

2006-04-22 Thread Michal Kwiatkowski
Hi!

I was just wondering...

Python 2.3.5 (#2, Mar  6 2006, 10:12:24)
[GCC 4.0.3 20060304 (prerelease) (Debian 4.0.2-10)] on linux2
Type help, copyright, credits or license for more information.
 import timeit
 a = timeit.Timer('2**1')
 b = timeit.Timer('112233445566778899 * 112233445566778899')
 a.timeit(1)
5.3986599445343018
 b.timeit()
0.59309601783752441

Python 2.4.2 (#2, Nov 20 2005, 17:04:48)
[GCC 4.0.3 2005 (prerelease) (Debian 4.0.2-4)] on linux2
Type help, copyright, credits or license for more information.
 import timeit
 a = timeit.Timer('2**1')
 b = timeit.Timer('112233445566778899 * 112233445566778899')
 a.timeit(1)
13.129707813262939
 b.timeit()
0.72854804992675781

Why long numbers operations are slower in 2.4?

mk
-- 
 . o . http://joker.linuxstuff.pl  
 . . o   It's easier to get forgiveness for being wrong
 o o o   than forgiveness for being right.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: another question about buffers

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

i think it may be,

Moral: don't use arbitrary values as booleans.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can you create an instance of a subclass with an existing instance of the base class?

2006-04-22 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 Sandra-24 [EMAIL PROTECTED] wrote:

Now that is a clever little trick. I never would have guessed you can
assign to __class__, Python always surprises me in it's sheer
flexibility.

That's because you're still thinking in OO terms.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need a thread to keep a socket connection alive?

2006-04-22 Thread nephish
thanks for the info, i will likely use the first link you posted with
the async module just to get it going, but i want to learn more about
twisted for later. there is even an O'Reilly book on it i see.
thanks for the tips,
sk

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


Re: Performance of Python 2.3 and 2.4

2006-04-22 Thread Tim Peters
[Michal Kwiatkowski]
 I was just wondering...

 Python 2.3.5 (#2, Mar  6 2006, 10:12:24)
 [GCC 4.0.3 20060304 (prerelease) (Debian 4.0.2-10)] on linux2
 Type help, copyright, credits or license for more information.
  import timeit
  a = timeit.Timer('2**1')
  b = timeit.Timer('112233445566778899 * 112233445566778899')
  a.timeit(1)
 5.3986599445343018
  b.timeit()
 0.59309601783752441

 Python 2.4.2 (#2, Nov 20 2005, 17:04:48)
 [GCC 4.0.3 2005 (prerelease) (Debian 4.0.2-4)] on linux2
 Type help, copyright, credits or license for more information.
  import timeit
  a = timeit.Timer('2**1')
  b = timeit.Timer('112233445566778899 * 112233445566778899')
  a.timeit(1)
 13.129707813262939
  b.timeit()
 0.72854804992675781

 Why long numbers operations are slower in 2.4?

In general, they're not.  Here on Windows, with those specific examples:


$ type ls.py
import timeit
a = timeit.Timer('2**1')
b = timeit.Timer('112233445566778899 * 112233445566778899')
print a.timeit(1)
print b.timeit()

$ \python23\python ls.py
6.96490123499
0.266523717213

$ \python24\python ls.py
6.81509407621
0.204446820019


So 2.4 is faster on those specific examples here.  Some of that's
probably due to code changes, and the rest to that the released
Windows 2.3.5 and 2.4.3 were compiled with different versions of MS's
C compiler, and VC 7.1 happened to do better optimization of the
relevant C code than VC 6.0.

I note that your Pythons were compiled with different (pre)releases of
gcc, so if you want to pursue this the first thing to do is compile
both Pythons with the same gcc.  The effectiveness of the platform C's
optimization matters a lot here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problems when unpacking tuple ...

2006-04-22 Thread John Machin
On 23/04/2006 2:21 AM, harold wrote:
 Dear all,
 
 Maybe I stared on the monitor for too long, because I cannot find the
 bug ...

You already have your answer, but below are clues on how to solve such 
problems much faster by yourself.

 My script transition_filter.py starts with the following lines:
 
 import sys
 
 for line in sys.stdin :
 try :
 for a,b,c,d in line.split() :
 pass
 
 except ValueError , err :
 print line.split()
 raise err
 
 The output (when given the data I want to parse) is:
 ['0.0','1','0.04','0']

I doubt it. Much more likely is
['0.0', '1', '0.04', '0']
It doesn't matter in this case, but you should really get into the
habit of copy/pasting *EXACTLY* what is there, not re-typing what you 
think is there.

 Traceback (most recent call last):
   File transition_filter.py, line 10, in ?
 raise err
 ValueError: need more than 3 values to unpack
 
 What is going wrong here? Why does python think that
 I want to unpack the outcome of line.split() into three
 values instead of four? I must be really tired, but I just
 cannot see the problem. Any clues??
 

Clues:
1. Use the print statement to show what you have.
2. Use the built-in repr() function to show *unambiguously* what you 
have -- very important when you get into Unicode and encoding/decoding 
problems; what you see after print foo is not necessarily what 
somebody using a different locale/codepage will see.
3. In some cases (not this one), it is also helpful to print the type() 
of the data item.

Example:

C:\junktype harold.py
import sys

def harold1():
 for line in sys.stdin :
 try :
 for a,b,c,d in line.split() :
 pass

 except ValueError , err :
 print line.split()
 raise err

def harold2():
 for line in sys.stdin:
 print line =, repr(line)
 split_result = line.split()
 print split result =, repr(split_result)
 for x in split_result:
 print about to try to unpack the sequence, repr(x), into 
4 items

 a, b, c, d = x

harold2()

C:\junkharold.py
0.0 1 0.04 0
a b c d e f
^Z
line = '0.0 1 0.04 0\n'
split result = ['0.0', '1', '0.04', '0']
about to try to unpack the sequence '0.0' into 4 items
Traceback (most recent call last):
   File C:\junk\harold.py, line 22, in ?
 harold2()
   File C:\junk\harold.py, line 20, in harold2
 a, b, c, d = x
ValueError: need more than 3 values to unpack

=

Coding style: Not inventing and using your own dialect makes two-way 
communication much easier in any language (computer or human). Consider 
reading and following http://www.python.org/dev/peps/pep-0008/

Hope this helps,
John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: howto py2exe/py2app for self updating application

2006-04-22 Thread Tony Meyer
 I'm creating a GUI program
 with wxPython which will be distributed  for Mac and Windows.
[...]
 The program should be able to update itself
[...]

By default, py2exe puts all the .pyc files used in a zip file.  The  
simplest way to do this it let py2exe do what it normally does.  Code  
all of the .py files as you would when running from source (i.e.  
you'll never explicitly use zipimport).

To update, you then:

   1. Download the new .pyc files.
   2. Expand (use ZipFile) the existing py2exe zip.
   3. Replace the old .pyc files with the new ones.
   4. Rezip (use ZipFile) the .pyc files.
   5. Replace the old py2xe zip with the one containing the new files.
   6. Restart the program.

This works (I use a more sophisticated version of this) well with  
py2exe.  I haven't used py2app at all, but if it works much like  
py2exe, then all of the above still applies (certainly the steps are  
platform-agnostic).

=Tony.Meyer

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


Re: Application Generators

2006-04-22 Thread rajeev . tandon
Hi walterbyrd,

I had also gone through this search earlier, but unfortunately the app
generators generate a lot of code, and more imp is that inspite of
this, they are not very close to what you really need. I had been
evaluating these from time to time. Appgini is good but mostly from an
academic view point, you can better learn from its mechanism.

Secondly, the kind of app you have in mind, is better hand coded. I
recently came accross a similar project, which was eventually done by
handcoding.

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


Re: Performance of Python 2.3 and 2.4

2006-04-22 Thread Felipe Almeida Lessa
Em Dom, 2006-04-23 às 00:20 +0200, Michal Kwiatkowski escreveu:
 Hi!
 
 I was just wondering...

Probably there is another factor involved:

$ python2.3
Python 2.3.5 (#2, Mar  6 2006, 10:12:24)
[GCC 4.0.3 20060304 (prerelease) (Debian 4.0.2-10)] on linux2
Type help, copyright, credits or license for more information.
 import timeit
 timeit.Timer('2**1').timeit(1)
4.6463479995727539
 timeit.Timer('112233445566778899 * 112233445566778899').timeit()
0.44853687286376953


$ python2.4
Python 2.4.3 (#2, Mar 30 2006, 21:52:26)
[GCC 4.0.3 (Debian 4.0.3-1)] on linux2
Type help, copyright, credits or license for more information.
 import timeit
 timeit.Timer('2**1').timeit(1)
4.9987671375274658
 timeit.Timer('112233445566778899 * 112233445566778899').timeit()
0.36968302726745605

-- 
Felipe.

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

Re: check whether a value is scalar

2006-04-22 Thread Eli
Python treats integers as objects, but as I mentioned that I do care
about the value only, and not its object methods. I mean that it's not
possible to share objects among application in different programming
languages, but it's possible to share the scalar values among them.
Strings, booleans, integeres, floats, null are types that most
programming languages use. Arrays are also commonly used, but each
programming language defines and uses it differently, so it's more
problematic to treat it as scalar (for example python uses dictionaries
while other langs uses regular arrays only).

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


Custom data type in a matrix.

2006-04-22 Thread Gaz
Hi guys. I've been lookig for this in the numpy pdf manual, in this
group and on google, but i could not get an answer...

Is there a way to create a custom data type (eg: Name: string(30), Age:
int(2), married: boolean, etc) and then use that custom data in a
matrix? Actually, this is a two question question :P

Im doing a simple hex based game and i need a way to store every hex
property (color, owner,x, y, etc) in a matrix's cell, representing
each cell a hex.

Thank you.

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


Re: Custom data type in a matrix.

2006-04-22 Thread Robert Kern
Gaz wrote:
 Hi guys. I've been lookig for this in the numpy pdf manual, in this
 group and on google, but i could not get an answer...

You will probably want to look or ask on the numpy list, too.

  https://lists.sourceforge.net/lists/listinfo/numpy-discussion

 Is there a way to create a custom data type (eg: Name: string(30), Age:
 int(2), married: boolean, etc) and then use that custom data in a
 matrix? Actually, this is a two question question :P

Yes. Use record arrays. They are discussed in section 8.5 of the _The Guide to
NumPy_ if you have the book. There is another example of using record arrays on
the SciPy wiki (although it is less focused on combining different data types
than it is named column access):

  http://www.scipy.org/RecordArrays

Here is an example:

In [18]: from numpy import *

In [19]: rec.fromrecords([['Robert', 25, False], ['Thomas', 53, True]],
names='name,age,married', formats=['S30', int, bool])
Out[19]:
recarray([('Robert', 25, False), ('Thomas', 53, True)],
  dtype=[('name', '|S30'), ('age', 'i4'), ('married', '|b1')])

In [21]: Out[19].name
Out[21]:
chararray([Robert, Thomas],
  dtype='|S30')

In [22]: Out[19].age
Out[22]: array([25, 53])

In [23]: Out[19].married
Out[23]: array([False, True], dtype=bool)

You can also use object arrays if you need to implement classes and not just
dumb, basic types:

In [33]: class Hex(dict):
   : def __init__(self, **kwds):
   : dict.__init__(self, **kwds)
   : self.__dict__ = self
   :
   :

In [34]: field = array([Hex(color=(0,0,0), owner='Player1', x=10, y=20,
etc='Black hex owned by Player1'),
   :Hex(color=(1,1,1), owner='Player2', x=10, y=21,
etc='White hex owned by Player2')], dtype=object)

In [35]:

In [35]: field
Out[35]: array([{'y': 20, 'etc': 'Black hex owned by Player1', 'color': (0, 0,
0), 'owner': 'Player1', 'x': 10}, {'y': 21, 'etc': 'White hex owned by Player2',
'color': (1, 1, 1), 'owner': 'Player2', 'x': 10}], dtype=object)

-- 
Robert Kern
[EMAIL PROTECTED]

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


  1   2   >