Re: number generator

2007-03-14 Thread Steven D'Aprano
On Tue, 13 Mar 2007 20:42:17 -0700, [EMAIL PROTECTED] wrote:

 It should be possible to enumerate all sets of five numbers which sum
 to 50 and randomly select one of them.

Of course it's possible. It's also a very inefficient way of doing so. For
five numbers between 1 and 50, there are 50**5 = 312,500,000 possible sets
to enumerate. Do you really think it is a good idea to generate over three
hundred and twelve million lists, just to return one?

The sole advantage of this method is that it will give the most random
result, with the least amount of bias possible. But it isn't clear that
the much more efficient fence-post method is any less random.

See also the Subset Sum Problem:
http://en.wikipedia.org/wiki/Subset_sum_problem



-- 
Steven D'Aprano 

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


Re: number generator

2007-03-14 Thread Paul Rubin
Steven D'Aprano [EMAIL PROTECTED] writes:
  It should be possible to enumerate all sets of five numbers which sum
  to 50 and randomly select one of them.
 
 Of course it's possible. It's also a very inefficient way of doing so. For
 five numbers between 1 and 50, there are 50**5 = 312,500,000 possible sets
 to enumerate. 

No there are only 2611 such sets and generating them takes about 0.5
seconds on my laptop.  I posted the code for this elsewhere in the thread.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: number generator

2007-03-14 Thread Hendrik van Rooyen
Duncan Smith [EMAIL PROTECTED] wrote:


 Yes, if the generating processes yield numbers from different
 probability mass functions.  You could simply look at the likelihood
 ratio.  Otherwise, the likelihood ratio will be 1.
 
 I was thinking about the same random number generator being used in the two 
disparate ways.

- Hendrik

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


Re: number generator

2007-03-14 Thread Hendrik van Rooyen
Steven D'Aprano [EMAIL PROTECTED] wrote:

 Easy-peasey. Just collate the individual numbers from the lists, and graph
 their frequencies. You will get quite different distributions. Both are
 random, but in different ways.
 
8  code -

Thanks - I think too complex - was thinking about means and std devs and stuff
for each column, and chi squared tests of significance...

: - )

- Hendrik




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


Re: number generator

2007-03-14 Thread Hendrik van Rooyen

Gabriel Genellina [EMAIL PROTECTED] wrote:

You can't have two different sets with four equal numbers - it's not a
very difficult thing, it's impossible to distinguish because they're
identical!
Given 4 numbers in the set, the 5th is uniquely determined. By example:
12, 3, 10, 18 *must* end with 7. The 5th number is not random. Any
randomness analysis should include only the first 4 numbers (or any other
set of 4).
In other words, there are only 4 degrees of freedom. In the fence analogy,
you only have to choose where to place 4 poles; the 5th is fixed at the
end.

Yes - the requirement of 5 random numbers is in a sense in conflict
with the requirement of that add up to 50 - because for the fifth number,
given that you have chosen the other 4, you have to get lucky and
choose the right one if you are doing it randomly...

What my question was about was whether some sort of cluster
analysis applied to the results of repeated application of two algorithms
would reveal the way in which the numbers were chosen - the first one being
choose five numbers, see if they add up to 50, repeat if not, repeat till say
1000 samples generated, and the second being choose four numbers,
see if they add to less than 50, repeat if not, else make the fifth the
difference
between the sum and 50, repeat till 1000 instances generated...

Intuitively, the second one will run a LOT faster, all other things being equal,
and I was simply wondering if one could tell the difference afterwards -
in the first case all the numbers clearly come from the same population,
while in the second case four of them do, and the fifth could possibly
be from a different population, as it was forced to make up the difference.

So I am not so very sure that the set of fifth numbers of the second run
would actually be indistinguishable from that of the first.

- Hendrik




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


Re: number generator

2007-03-14 Thread Steven D'Aprano
On Tue, 13 Mar 2007 23:08:38 -0800, Paul Rubin wrote:

 Steven D'Aprano [EMAIL PROTECTED] writes:
  It should be possible to enumerate all sets of five numbers which sum
  to 50 and randomly select one of them.
 
 Of course it's possible. It's also a very inefficient way of doing so. For
 five numbers between 1 and 50, there are 50**5 = 312,500,000 possible sets
 to enumerate. 
 
 No there are only 2611 such sets and generating them takes about 0.5
 seconds on my laptop.  I posted the code for this elsewhere in the thread.

If you generate all the possible sets of five numbers between 1 and 50,
there are 50**5 of them, not 2611.

Naturally you don't have to store them all, and if you read what I wrote,
you'll see I never suggested that you have to store them all. That would
be silly. Of course you would use a generator.

Now that I've seen your _partition() function, I'm quite impressed. It is
still brute-force, but it avoids generating all 50**5 non-unique lists. By
my count, it only has to throw away 11,294 lists to generate the 2611
unique lists it returns.

And it is quite fast too: approximately 0.12 seconds on my PC.
Unfortunately, it doesn't scale. 

unique_partitions(60, 6) takes 0.8 seconds; unique_partitions(80, 8)
takes about 25 seconds; unique_partitions(80, 10) takes about 80 seconds,
and unique_partitions(81, 10) takes over 90 seconds.

So yes, your partition algorithm does avoid creating the millions of lists
which don't sum to 50, and that's a good thing. But it still brute-forces
thousands or millions of lists when only one is needed.

(E.g. unique_partitions(80, 10) returns 533,975 unique lists.
_partitions(80, 10) gives 3,233,568 non-unique lists.)



-- 
Steven D'Aprano 

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


Re: number generator

2007-03-14 Thread Steven D'Aprano
On Wed, 14 Mar 2007 19:25:46 +1100, Steven D'Aprano wrote:

 Now that I've seen your _partition() function, I'm quite impressed. It is
 still brute-force, but it avoids generating all 50**5 non-unique lists. By
 my count, it only has to throw away 11,294 lists to generate the 2611
 unique lists it returns.

Ignore that count. I don't know where I got 11,294 from, the correct
figure is 10,358.

Oh, I seem to have found a bug in the _partitions() function. I believe it
is missing some of the partitions.

 list(_partitions(25, 24))
[(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2)]
 list(_partitions(25, 25))
[]


-- 
Steven D'Aprano 

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


Mocking OpenOffice in python?

2007-03-14 Thread PaoloB
Hi everyone,

during our development, we need to write some unit tests that interact
with OpenOffice through pyUno.

Is there anyone who has got any experience on it? As OpenOffice is
quite a large beast, and interaction is rather complex, I would like
to know if there is someone who is willing to share experience (and,
possibly, code).

Ciao

PaoloB

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


Re: number generator

2007-03-14 Thread Raymond Hettinger
 To make the solutions equi-probable, a simple approach is to
 recursively enumerate all possibilities and then choose one of them
 with random.choice().

Since people are posting their solutions now (originally only hints
were provided for the homework problem), here's mine:

def genpool(n, m):
if n == 1:
yield [m]
else:
for i in xrange(1, m):
for rest in genpool(n-1, m-i):
yield rest + [i]

import random
print random.choice(list(genpool(n=4, m=20)))

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


Re: How to capture environment state after running a shell script.

2007-03-14 Thread Gerard Flanagan
On Mar 13, 7:54 pm, [EMAIL PROTECTED] wrote:
 On Mar 13, 5:57 am, Gerard Flanagan [EMAIL PROTECTED] wrote:

  Hello,

  I have a third party shell script which updates multiple environment
  values, and I want to investigate (and ultimately capture to python)
  the environment state after the script has run.

 First close the input so that the (sub) process
 knows to terminate and flush the output.  Then,
 you can read from the output:

 import subprocess
 import popen2

 p = subprocess.Popen([/bin/sh], stdin=subprocess.PIPE,
 stdout=subprocess.PIPE)

 p.stdin.write(env -i FOO=BAR\n)
 p.stdin.close()
 status = p.wait()
 ret = p.stdout.readlines()
 p.stdout.close()


 print ret


Perfect! Works a charm. Thanks for helping me out.

Gerard


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


Re: using python to visit web sites and print the web sites image to files

2007-03-14 Thread imx
On 3月14日, 上午5时44分, [EMAIL PROTECTED] [EMAIL PROTECTED]
wrote:
  The reason I want to do simulation but not just crawling is : we have
  to check many web pages' front page to see whether it conform to our
  visual standard, e.g, it should put a search box on the top part of
  the page. It's tedious for human work. So I want to 'crawl and save
  the visual presentation of the web site automatically', and check
  these image files later with human eyes.

  -Xiong

 Hi Xiong,

 I have been working on a program to do something very similar to
 generate thumbnails of websites.

 The code is in IronPython (which may put you off!) and would need
 modified or scripted with pywinauto to deal with multiple images.

 Let me know if it is of use to you and I will upload it.

 Cheers,
 Davy

Cool, but does it mean that I will need .net to run the code?

Xiong

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

Re: how to detect change of list of instances

2007-03-14 Thread Bruno Desthuilliers
manstey a écrit :
 Thanks.
 
 All I want to know is whether the newlist, as a list of instances, is
 modified. I thought equality was the way to go, but is there a simpler
 way? How can I monitor the state of newlist and set a flag if it is
 changed in anyway?

thinking-out-loud
Override the mutators - or just wrap them in a decorator. But I don't 
know if it's simpler. And FWIW, it won't catch modifications of 
contained objects - only modifications of the list itself. So you'd also 
need to wrap contained objects in an object that would itself detect all 
changes and notify the container. Err... Looks like equality is the way 
to go.
/thinking-out-loud
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Setting Up SOAPpy for Python v2.5 on Windows?

2007-03-14 Thread Simon Brunning
On 13 Mar 2007 11:53:24 -0700, Steve [EMAIL PROTECTED] wrote:
 What are the required version of the SOAPpy, PyXML, fpconst that are
 needed to run under the Python 2.5 environment on Windows?

SOAPpy doesn't install under Python 2.5 as-is. You'll need to add
source code encodings on all the source files in all the files before
setup.py will run. (See PEP 263.).

You can get fpconst 0.7.2 from the cheese shop, and PyXML from
Sourceforge. I believe the latest versions of these packages work
fine.

Do be aware, though, that SOAPpy is unmaintained, so you might want to
look at other SOAP handling packages like ZSI or elementsoap. Unless,
that is, you need functionality that only SOAPpy provides, in which
case you are stuck with it.

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning
MSN: small_values
-- 
http://mail.python.org/mailman/listinfo/python-list


how to catch system errors in python

2007-03-14 Thread Manpreet Singh Khurana
Hi,
I am using paramiko 1.5.3 with python 2.4 and pycrypto 1.9
 I need to know if it is possible to catch sysytem level error, like
disk space full or cpu usage indication etc.

Any help would be appriciated.

Regards,

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


Re: help developing an editor to view openoffice files.

2007-03-14 Thread krishnakant Mane
On 14/03/07, Paul Hummer [EMAIL PROTECTED] wrote:

 I actually just read this in the O'Reilly book Python Cookbook, so I
 know this answer off the top of my head.  OpenOffice files are merely
 zip files with well documented XML inside.  Use the builtin zip module
 to open them, and then it's just XML parsing.  As far as the editor,
 you'll have to familiarize yourself with the XML data from the
 documentation, and it sounds like that's quite a project.

it is indeed a huge project but I need to get started.
I know that it is xml inside a zipped archive.  but reading the
documents is one thing and rendering them is another.
just in case we can convert it to html and then render it in some kind
of a html browser or html text area and then when user makes changes
to the document, we can save it back to odt.  but for that we need
both way conversion.


 Just out of curiosity, why not just download OpenOffice?

I wished I could use it out of the box.
but the problem is that open office does not provide any accessibility
on windows and on linux the work is going on.
regards.
Krishnakant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Swig Problem string

2007-03-14 Thread Amitabh Saikia
Hi

  I have created a simple function called  'addTheString(string str,
string appstr)' and the intension
  is to append the 'appstr' to 'str' and use 'str'.

  I tried swigging this method. My swigtest.i file is okay as I think
I have added both
 - stl.i at top
 - std_string.i

   However, I am running into the problem. I get error messages as follows

   -- error --
  TypeError: argument number 1: a 'std::string' is expected,
   -- end error --

  I tried the mailing list solution posted by Mr. Chiang, but its not
helping me.
  Could you please help me out.

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


Re: number generator

2007-03-14 Thread Hendrik van Rooyen
 Steven D'Aprano [EMAIL PROTECTED] wrote:

 
 Consider the distance between each paid of consecutive poles. The sum of
 the distances must add up to the distance from the first to the last, and
 if there are two fixed poles plus five in between, there are five
 distances.

No there are six distances - the fifth pole has to fit in the same hole as the 
last fixed one for there to be five.

- Hendrik

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


Re: Mocking OpenOffice in python?

2007-03-14 Thread M�ta-MCI
Hi!


Under windows, I drive OOo, from Python, via COM/OLE-automation.

It's run OK, but some bugs, in the OOo-COM-Python, had stop my 
devloppements...

However, this way is usable (only on Win, ok?)



@-salutations
-- 
Michel Claveau


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


Re: Iterating across a filtered list

2007-03-14 Thread Bruno Desthuilliers
Paul Rubin a écrit :
 Bruno Desthuilliers [EMAIL PROTECTED] writes:
(snip)
 Python has had functions as first class objects and
 (quite-limited-but) anonymous functions, map(), filter() and reduce()
 as builtin funcs at least since 1.5.2 (quite some years ago).
 
 True, though no iterators so you couldn't easily use those functions
 on lazily-evaluated streams like you can now.

Obviously. But what I meant is that Python may not be *so* historically 
imperative !-)

FWIW, I first learned FP concepts with Python.

  Iterators like that are a new Python feature
 List comps are not that new (2.0 or 2.1 ?):
 print \n.join([contact for name, contact in contacts.items() \
   if search.match(name)])
 
 Well you could do it that way but it allocates the entire filtered
 list in memory.

Of course. But then nothing prevents you from using a genexp instead of 
the list comp - same final result, and the syntax is quite close:

print \n.join(contact for name, contact in contacts.items() \
  if search.match(name))

So the fact that genexps are still a bit new is not a problem here 
IMHO - this programming style is not new in Python.

 It's usually safest to create and consume them in the same
 place, e.g. creating some sequence and passing it through map, filter, etc.
 Safest ? Why so ?
 
 Just that things can get confusing if you're consuming the iterator in
 more than one place.

Indeed. But that's not what we have here. And FWIW, in programming, lots 
of things tends to be confusing at first.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating across a filtered list

2007-03-14 Thread Bruno Desthuilliers
Arnaud Delobelle a écrit :
 On Mar 13, 8:53 pm, Bruno Desthuilliers
 [EMAIL PROTECTED] wrote:
 Paul Rubin a écrit :
 
 [snip]
 
  Iterators like that are a new Python feature
 List comps are not that new (2.0 or 2.1 ?):
 print \n.join([contact for name, contact in contacts.items() \
   if search.match(name)])
 
 You can write this, but:
* it is difficult to argue that it is more readable than Paul's (or
 my)  'imperative' version;

I personnaly find it more readable. To me, it tells what, not how.

* it has no obvious performance benefit,

No.

 and they have
 some annoying characteristics, like the way they mutate when you touch
 them.
 While sequences are iterables, all iterables are not sequences. Know
 what you use, and you'll be fine.
 
 ...And know when to use for statements :)

Don't worry, I still use them when appropriate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python/C++ wrapper

2007-03-14 Thread Szabolcs Nagy
 - A c++ program receives a 2D-matrix from python as input and gives a
 2D-matrix as output back to python.

pyogre uses swig

ogre is a 3d realtime rendering engine written in c++ so there are
many matrix manipulation there and also pyogre does not modify the
original code

cgkit is a computer graphics toolkit written in c++ for python and it
uses boost-python and it uses matrices as well

if you want matrix manipulations in python then you may want to look
into numpy c api

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


Re: number generator

2007-03-14 Thread Raymond Hettinger
[Alex Martelli]
   map([random.randrange(5) for i in xrange(45)].count, xrange(5))

 i.e., this gives 5 integers (each between 0 and 45 included) summing to
 45 -- add 1 to each of them to get the desired result.

This is a really nice approach.  Besides being fast, it is not too
hard to see that it is correct.

FWIW, here's a variant with a count using the new defaultdict:

n, m = 5, 45
bag = collections.defaultdict(int)
for i in xrange(m):
bag[random.randrange(n)] += 1
ans = [bag[k] for k in range(n)]

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


Re: python/C++ wrapper

2007-03-14 Thread Roman Yakovenko
On 14 Mar 2007 02:38:32 -0700, Szabolcs Nagy [EMAIL PROTECTED] wrote:
  - A c++ program receives a 2D-matrix from python as input and gives a
  2D-matrix as output back to python.

 pyogre uses swig

Well, pyogre has few problems with maintenance, and new bindings to
Ogre engine was
created using Boost.Python( http://www.ogre3d.org/wiki/index.php/PyOgre )

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: number generator

2007-03-14 Thread Anton Vredegoor
Raymond Hettinger wrote:

 Since people are posting their solutions now (originally only hints
 were provided for the homework problem), here's mine:

Homework problem? Do you have some information from the OP that I can't 
find in this thread? Anyway, I consider the 'homework' idea and the 
associated self concept that turns people into -for example- 
backstabbing computer scientists who never release their code as the 
root of all evil in the educational system. Why should I uphold a moral 
code that I don't agree with? To me people posting homework problems are 
like refugees which I will help if I can.

 def genpool(n, m):
 if n == 1:
 yield [m]
 else:
 for i in xrange(1, m):
 for rest in genpool(n-1, m-i):
 yield rest + [i]
 
 import random
 print random.choice(list(genpool(n=4, m=20)))

OK back to the *computer* code. Great function! And it's ideally suited 
for memoization too. Too bad this memoizor doesn't accept keyword 
arguments, but for the rest it works fine and greatly speeds it up.

import random

def memoize(fn):
  cache = {}
  def proxy(*args):
  try: return cache[args]
  except KeyError: return cache.setdefault(args, fn(*args))
  return proxy

@memoize
def genpool(n, m):
 if n == 1:
 yield [m]
 else:
 for i in xrange(1, m):
 for rest in genpool(n-1, m-i):
 yield rest + [i]

def test():
 print random.choice(list(genpool(5,50)))

if __name__=='__main__':
 test()

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


Attribute monitoring in a class

2007-03-14 Thread Joel Andres Granados
Hi list:

I have googled quite a bit on this matter and I can't seem to find what 
I need (I think Im just looking where I'm not suppose to :).  I'm 
working with code that is not of my authorship and there is a class 
attribute that is changes by directly referencing it (object.attr = 
value) instead of using a getter/setter (object.setAttr(Value) ) 
function.  The thing is that I have no idea when the change occurs and I 
would REALLY like to find out.
So here comes my question .
Is there a function construct inside a python class that is 
automatically called when an attr is changed
Like for example

/class Class:
def __init__();
   self.attr = whatever

def __attrChangeFunction__():
   print It has changed

obj = Class()
obj.attr = other whatever

*Output:*
It has changed

/
Thanks for the help.
Regards/
/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python/C++ wrapper

2007-03-14 Thread Szabolcs Nagy

 Well, pyogre has few problems with maintenance, and new bindings to
 Ogre engine was
 created using Boost.Python( http://www.ogre3d.org/wiki/index.php/PyOgre )

oh
last time i played with pyogre they made a transition from boost to
swig :)
so they are back again at boost
(the problem with boost was the slow recompilation time with all the
gccxml parsing and a few other problems which maybe got resolved)

 --
 Roman Yakovenko
 C++ Python language binding
 http://www.language-binding.net/

thanks for the info this py++ looks promising

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


Re: Attribute monitoring in a class

2007-03-14 Thread Simon Brunning
On 3/14/07, Joel Andres Granados [EMAIL PROTECTED] wrote:
 I have googled quite a bit on this matter and I can't seem to find what
 I need (I think Im just looking where I'm not suppose to :).  I'm
 working with code that is not of my authorship and there is a class
 attribute that is changes by directly referencing it (object.attr =
 value) instead of using a getter/setter (object.setAttr(Value) )
 function.  The thing is that I have no idea when the change occurs and I
 would REALLY like to find out.
 So here comes my question .
 Is there a function construct inside a python class that is
 automatically called when an attr is changed

You want __setttr__(). See http://docs.python.org/ref/attribute-access.html.

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning
MSN: small_values
-- 
http://mail.python.org/mailman/listinfo/python-list


Passing a FILE* from Python into a MinGW/SWIG module

2007-03-14 Thread John Pye
Hi all

I understand that I can't hope to pass a FILE* from the Windows
version of Python into a SWIG module that I've built using MinGW gcc/g+
+, because apparently the FILE* structure are different and
incompatible.

Is there an official workaround for this? Presumably I need to
implement a mingw-compatible version of all the 'file' class in
Python, eg

import mingw
import myswigmodule

F1 = mingw.file(newfile.txt,rw)
F1.write(somestuff)
F1.seek(0)
F2 = mingw.tmpfile()
myswigmodule.dosomething(F1,F2)
F2.seek(0)
print F2.read()

Has anyone done this? Is there a better way that doesn't require users
of my module to adapt? Do I have to use the dreaded MSVS to compile my
SWIG module?

Cheers
JP

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


Re: python/C++ wrapper

2007-03-14 Thread John Pye
Check out this example from NumPy. This would be the way sanctioned by
the scipy community, as you benefit from a large library of matrix
routines that you can use to prepare/postprocess the data.

http://www.scipy.org/Cookbook/SWIG_and_NumPy


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


Re: Attribute monitoring in a class

2007-03-14 Thread Bruno Desthuilliers
Joel Andres Granados a écrit :
 Hi list:
 
 I have googled quite a bit on this matter and I can't seem to find what 
 I need (I think Im just looking where I'm not suppose to :).  I'm 
 working with code that is not of my authorship and there is a class 
 attribute that is changes by directly referencing it (object.attr = 
 value) instead of using a getter/setter (object.setAttr(Value) ) 

Which is the right thing to do in Python (I mean : *not* using 
Java-style getters/setters).

 function.  The thing is that I have no idea when the change occurs and I 
 would REALLY like to find out.
 So here comes my question .
 Is there a function construct inside a python class that is 
 automatically called when an attr is changed

yes : object.__setattr__(self, name, value)

# example:
class Class(object):
def __init__();
   self.attr = whatever

def __setattr__(self, name, value):
   object.__setattr__(self, name, value)
   if name == 'attr':
   print It has changed
   # you can also print the call frame,
   # or set a 'hard' breakpoint here...

obj = Class()
obj.attr = other whatever

*Output:*
It has changed


Or you might turn attr into a property:

class Class(object):
def __init__();
   self.attr = whatever

@apply
def attr():
def fset(self, value):
self._attr = value
print It has changed
def fget(self):
return self._attr
return property(**locals())

But unless you have other needs than simple tracing/debugging, it's 
probably overkill.

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


Re: Attribute monitoring in a class

2007-03-14 Thread Laurent Pointal
Joel Andres Granados a écrit :
 Hi list:
 
 I have googled quite a bit on this matter and I can't seem to find what
 I need (I think Im just looking where I'm not suppose to :).  I'm
 working with code that is not of my authorship and there is a class
 attribute that is changes by directly referencing it (object.attr =
 value) instead of using a getter/setter (object.setAttr(Value) )
 function.  The thing is that I have no idea when the change occurs and I
 would REALLY like to find out.
 So here comes my question .
 Is there a function construct inside a python class that is
 automatically called when an attr is changed
 Like for example
 
 /class Class:
def __init__();
   self.attr = whatever
 
def __attrChangeFunction__():
   print It has changed

Use a property. Extract from Python 2.3 docs:

property(   [fget[, fset[, fdel[, doc)
Return a property attribute for new-style classes (classes that
derive from object).

fget is a function for getting an attribute value, likewise fset is
a function for setting, and fdel a function for del'ing, an attribute.
Typical use is to define a managed attribute x:

class C(object):
def getx(self): return self.__x
def setx(self, value): self.__x = value
def delx(self): del self.__x
x = property(getx, setx, delx, I'm the 'x' property.)

New in version 2.2.


 obj = Class()
 obj.attr = other whatever
 
 *Output:*
 It has changed
 
 /
 Thanks for the help.
 Regards/
 /

A+

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


Quick Filter Dictionary

2007-03-14 Thread abcd
Hi,
   I have a dictionary which may contain various keys/values, however,
it will always contain 'name' and 'age' keys.

   This dictionary is kept inside a class, such as

class Person:
def __init__(self, name, age):
self.data = {'name' : name, 'age' : age}

def getData(self, includeNameAge=False):
if includeNameAge: return self.data
tmp = shallow or deep copy of 'data'
del tmp['name']
del tmp['age']
return tmp

   The getdata method should return the data stored for the
person, however, it should be able to return the data excluding the
'name' and 'age'.  Any suggestions on how to best implement this?
Keep in mind this sample code is meant to be an example, I realize
that a person would probably always want the name and age returned.

thanks

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


Re: Quick Filter Dictionary

2007-03-14 Thread abcd
On Mar 14, 7:29 am, abcd [EMAIL PROTECTED] wrote:
 Hi,
I have a dictionary which may contain various keys/values, however,
 it will always contain 'name' and 'age' keys.

This dictionary is kept inside a class, such as

 class Person:
 def __init__(self, name, age):
 self.data = {'name' : name, 'age' : age}

 def getData(self, includeNameAge=False):
 if includeNameAge: return self.data
 tmp = shallow or deep copy of 'data'
 del tmp['name']
 del tmp['age']
 return tmp

The getdata method should return the data stored for the
 person, however, it should be able to return the data excluding the
 'name' and 'age'.  Any suggestions on how to best implement this?
 Keep in mind this sample code is meant to be an example, I realize
 that a person would probably always want the name and age returned.

 thanks


I guess one solution might be

def getData(self, includeNameAge=False):
if includeNameAge: return self.data
return dict(filter(lambda item: item[0] not in ('name', 'age'),
self.data.items()))

any other suggestions, improvements?

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


Re: number generator

2007-03-14 Thread cesco
 Since people are posting their solutions now (originally only hints
 were provided for the homework problem), here's mine:

Well, I never really said it was a homework problem. Sure there are
more implications to my question that I had first imagined and I'm
really happy I could get so many insights but the question did
originate from a real problem I was facing in my research.

Thanks to everyone for the wonderful thread so far
Francesco

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


mod_python demo

2007-03-14 Thread Jan Danielsson
Hello all,

   I have written a web-based voting system (add question, add possible
answers to that question, and let users vote) in python. It uses:

   - mod_python
   - postgreql (through psycopg2)

   It includes basic session and user management.

   It's a very simple system, and the session/user management is highly
reusable.

   The point of writing it was just as a small exercise I made for
myself. But now that I'm done with it, I wouldn't mind sharing it with
people wanting to get started with mod_python, but wants to have some
working code to use as a base (or merely look at for ideas).

   Is there any Python/web community site anywhere which allows users to
upload template code for others to use?

   Note: I am a Python newbie, so there are probably lots of
improvements to be done, if anyone cares enough).

-- 
Kind regards,
Jan Danielsson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem I have with a while loop/boolean/or

2007-03-14 Thread Steve Holden
Scott David Daniels wrote:
 Bart Willems wrote:
 ...
 I always try to stay away from 'negative' operators if possible, to 
 improve readability:

 while True:
hint = raw_input('\nAre you stuck? y/n: ').lower()
if hint = 'y' or hint = 'n':
   break
else:
   print 'Please answer yes or no'
 
 And if you really want to see what is going wrong, replace that last by:
  print 'Please answer yes or no (not %r):' % hint
 
Better still, use

   Please answer y or n

since those are the values you are testing for ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


execfile locks file forever if there are any syntax errors - is it python bug?

2007-03-14 Thread Slawomir Nowaczyk
Hello,

When I execfile a file which contains a syntax error, the file becomes
locked and stays this way all the way until I exit the interpreter (I am
unable to delete it, for example). I have tried but failed to find any
way to unlock the file... Is this a bug in Python?

Is there *any* way to unlock the file? It is annoying for me because I
often execfile various temporary files and it is a nuisance not to be
able to delete them.

I have tested with Python 2.5 on Windows... do other versions of Python
behave this way as well?

-- 
 Best wishes,
   Slawomir Nowaczyk
 ( [EMAIL PROTECTED] )

I didn't fight my way to the top of the food chain to be a vegetarian.

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


Re: Quick Filter Dictionary

2007-03-14 Thread Bruno Desthuilliers
abcd a écrit :
 On Mar 14, 7:29 am, abcd [EMAIL PROTECTED] wrote:
 Hi,
I have a dictionary which may contain various keys/values, however,
 it will always contain 'name' and 'age' keys.

This dictionary is kept inside a class, such as

 class Person:

Do yourself a favor : use new-style classes:
class Person(object):

 def __init__(self, name, age):
 self.data = {'name' : name, 'age' : age}

You may improve this part with kwargs:

  def __init__(self, name, age, **kw):
  kw.update(name=name, age=age)
  self.data = kw

Also, and FWIW, object attributes are stored in self.___dict__. Do you 
have a compelling reason to use yet another 'data' dict ?

 def getData(self, includeNameAge=False):
 if includeNameAge: return self.data
 tmp = shallow or deep copy of 'data'
tmp = self.data.copy()
 del tmp['name']
 del tmp['age']
 return tmp

The problem with this implementation (as well as for the other below) is 
that in the first case you return a reference to the data dict itself, 
while in the second case you return a new dict.

p = Person('bibi', 42, foo='bar')
data = p.getData(True)
data['baaz'] = 'quux'
del data['name']
print p.data

p = Person('bibi', 42, foo='bar')
p.getData()
data['baaz'] = 'quux'
del data['foo']
print p.data

Better to *always* return a copy IMHO.
-- 
http://mail.python.org/mailman/listinfo/python-list


Grep Equivalent for Python

2007-03-14 Thread tereglow
Hello all,

I come from a shell/perl background and have just to learn python.  To
start with, I'm trying to obtain system information from a Linux
server using the /proc FS.  For example, in order to obtain the amount
of physical memory on the server, I would do the following in shell:

grep ^MemTotal /proc/meminfo | awk '{print $2}'

That would get me the exact number that I need.  Now, I'm trying to do
this in python.  Here is where I have gotten so far:

memFile = open('/proc/meminfo')
for line in memFile.readlines():
print re.search('MemTotal', line)
memFile.close()

I guess what I'm trying to logically do is... read through the file
line by line, grab the pattern I want and assign that to a variable.
The above doesn't really work, it comes back with something like
_sre.SRE_Match object at 0xb7f9d6b0 when a match is found.

Any help with this would be greatly appreciated.
Tom

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


Re: Quick Filter Dictionary

2007-03-14 Thread Steve Holden
abcd wrote:
 On Mar 14, 7:29 am, abcd [EMAIL PROTECTED] wrote:
 Hi,
I have a dictionary which may contain various keys/values, however,
 it will always contain 'name' and 'age' keys.

This dictionary is kept inside a class, such as

 class Person:
 def __init__(self, name, age):
 self.data = {'name' : name, 'age' : age}

 def getData(self, includeNameAge=False):
 if includeNameAge: return self.data
 tmp = shallow or deep copy of 'data'
 del tmp['name']
 del tmp['age']
 return tmp

The getdata method should return the data stored for the
 person, however, it should be able to return the data excluding the
 'name' and 'age'.  Any suggestions on how to best implement this?
 Keep in mind this sample code is meant to be an example, I realize
 that a person would probably always want the name and age returned.

 thanks
 
 
 I guess one solution might be
 
 def getData(self, includeNameAge=False):
 if includeNameAge: return self.data
 return dict(filter(lambda item: item[0] not in ('name', 'age'),
 self.data.items()))
 
 any other suggestions, improvements?
 
You might find

 return dict((x,y) for (x, y) in self.data.iteritems()
 if x not in ('name', 'age'))

easier to understand. Or you might not ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


IronPython and COM Interface

2007-03-14 Thread Divya
Hello,

I'm new to IronPython and COM so please bear with me.

I have a COM interface provided to me. I need to implement this
interface and pass it to a method as a way of implementing
'callbacks'.

However it appears that the methods of my interface object are never
called.

As a alternative, I implemented the interface in C# and then extended
the C# class in IronPython. However, on running the code, methods of
my C# class rather than the IronPython class are being called.

Can anyone advise? Is this possible in IronPython?

The code is listed below.

Regards,
Divya

---

import time

import clr
clr.AddReference('Interop.MBTCOMLib.dll')
clr.AddReference('Interop.MBTORDERSLib.dll')
clr.AddReference('Interop.MBTQUOTELib.dll')

import MBTCOMLib
import MBTORDERSLib
import MBTQUOTELib

demo_user='user'
demo_pass='pass'
demo_host=9

class MBEvents(MBTQUOTELib.IMbtQuotesNotify):
def __init__(self):
MBTQUOTELib.IMbtQuotesNotify.__init__(self)

def OnLevel2Data(data):
print 'OnLevel2Data'

def OnOptionsData(self, data):
print 'OnOptionsData'

def OnQuoteData(self, data):
print 'OnQuoteData'

def OnTSData(self, data):
print 'OnTSData'

class MB:
def __init__(self):
self.conn = MBTCOMLib.MbtComMgrClass()
#self.conn.EnableSplash(False)
self.orders = self.conn.OrderClient
self.quotes = self.conn.Quotes
self.events = MBEvents()

def login(self, host=demo_host, user=demo_user, passwd=demo_pass):
self.conn.DoLogin(host, user, passwd, '')
print self.quotes.RemoteAddress, self.quotes.RemotePort
self.quotes.AdviseSymbol(self.events, 'EUR/USD', 1|2|3|4)

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


Re: Grep Equivalent for Python

2007-03-14 Thread Steve Holden
tereglow wrote:
 Hello all,
 
 I come from a shell/perl background and have just to learn python.  To
 start with, I'm trying to obtain system information from a Linux
 server using the /proc FS.  For example, in order to obtain the amount
 of physical memory on the server, I would do the following in shell:
 
 grep ^MemTotal /proc/meminfo | awk '{print $2}'
 
 That would get me the exact number that I need.  Now, I'm trying to do
 this in python.  Here is where I have gotten so far:
 
 memFile = open('/proc/meminfo')
 for line in memFile.readlines():
 print re.search('MemTotal', line)
 memFile.close()
 
 I guess what I'm trying to logically do is... read through the file
 line by line, grab the pattern I want and assign that to a variable.
 The above doesn't really work, it comes back with something like
 _sre.SRE_Match object at 0xb7f9d6b0 when a match is found.
 
 Any help with this would be greatly appreciated.
 Tom
 
Regular expressions aren't really needed here. Untested code follows:

for line in open('/proc/meminfo').readlines:
 if line.startswith(Memtotal:):
 name, amt, unit = line.split()
 print name, amt, unit
 break

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: i can`t get python working on the command line (linux)

2007-03-14 Thread Facundo Batista
Mark wrote:


 and i`ve put it in tel.py (just the same as in the sample) than chmod
 it to 777 (just to make sure it isn`t a permission issue) and than i
 run it with: ./tel.py
 now this is the error that i get:

 Traceback (most recent call last):
   File ./tel.py, line 12, in module
 for line in open(argv[1], 'r').readlines():
 IndexError: list index out of range

Your Python is installed fine.

The problem is that you're accesing argv[1], which would be the first
argument after the program in the command line, and you're executing
your program without any parameters.

All you need to do is read the error message, they help, ;)

Try executing your program with something like

  ./tel.py myfile.txt

where, of course, myfile.txt is some file you have around...

Regards,

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


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


logging and wx.Timer

2007-03-14 Thread hg
Hi,

I read that logging was thread safe ... but can I use it under a GUI timer ?

Thanks,

hg

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


Re: Attribute monitoring in a class

2007-03-14 Thread Joel Andres Granados
Bruno Desthuilliers wrote:
 Joel Andres Granados a écrit :
   
 Hi list:

 I have googled quite a bit on this matter and I can't seem to find what 
 I need (I think Im just looking where I'm not suppose to :).  I'm 
 working with code that is not of my authorship and there is a class 
 attribute that is changes by directly referencing it (object.attr = 
 value) instead of using a getter/setter (object.setAttr(Value) ) 
 

 Which is the right thing to do in Python (I mean : *not* using 
 Java-style getters/setters).

   
 function.  The thing is that I have no idea when the change occurs and I 
 would REALLY like to find out.
 So here comes my question .
 Is there a function construct inside a python class that is 
 automatically called when an attr is changed
 

 yes : object.__setattr__(self, name, value)

 # example:
 class Class(object):
 def __init__();
self.attr = whatever

 def __setattr__(self, name, value):
object.__setattr__(self, name, value)
if name == 'attr':
print It has changed
# you can also print the call frame,
# or set a 'hard' breakpoint here...

 obj = Class()
 obj.attr = other whatever

 *Output:*
 It has changed

   

I used this ^^^ one.  Thank for the help.
Works like a charm.
Regards

 Or you might turn attr into a property:

 class Class(object):
 def __init__();
self.attr = whatever

 @apply
 def attr():
 def fset(self, value):
 self._attr = value
 print It has changed
 def fget(self):
 return self._attr
 return property(**locals())

 But unless you have other needs than simple tracing/debugging, it's 
 probably overkill.

 HTH
   

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


Re: Grep Equivalent for Python

2007-03-14 Thread Paul Boddie
On 14 Mar, 13:37, tereglow [EMAIL PROTECTED] wrote:
 Hello all,

 I come from a shell/perl background and have just to learn python.

Welcome aboard!

  To start with, I'm trying to obtain system information from a Linux
 server using the /proc FS.  For example, in order to obtain the amount
 of physical memory on the server, I would do the following in shell:

 grep ^MemTotal /proc/meminfo | awk '{print $2}'

 That would get me the exact number that I need.  Now, I'm trying to do
 this in python.  Here is where I have gotten so far:

 memFile = open('/proc/meminfo')
 for line in memFile.readlines():
 print re.search('MemTotal', line)

You could even use the regular expression '^MemTotal' as seen in your
original, or use the match function instead of search. However...

 memFile.close()

 I guess what I'm trying to logically do is... read through the file
 line by line, grab the pattern I want and assign that to a variable.
 The above doesn't really work, it comes back with something like
 _sre.SRE_Match object at 0xb7f9d6b0 when a match is found.

This is because re.search and re.match (and other things) return match
objects if the regular expression has been found in the provided
string. See this page in the library documentation:

http://docs.python.org/lib/match-objects.html

 Any help with this would be greatly appreciated.

The easiest modification to your code is to replace the print
statement with this:

match = re.search('MemTotal', line)
if match is not None:
print match.group()

You can simplify this using various idioms, I imagine, but what you
have to do is to test for a match, then to print the text that
matched. The group method lets you get the whole matching text (if
you don't provide any arguments), or individual groups (applicable
when you start putting groups in your regular expressions).

Paul

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


Re: execfile locks file forever if there are any syntax errors - is it python bug?

2007-03-14 Thread skip

Slawomir When I execfile a file which contains a syntax error, the file
Slawomir becomes locked and stays this way all the way until I exit the
Slawomir interpreter (I am unable to delete it, for example). I have
Slawomir tried but failed to find any way to unlock the file... Is this
Slawomir a bug in Python?

Kinda seems like it might be.  Please file a bug report on SourceForge.

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


Re: Grep Equivalent for Python

2007-03-14 Thread Laurent Pointal
Steve Holden a écrit :
 Regular expressions aren't really needed here. Untested code follows:
 
 for line in open('/proc/meminfo').readlines:
for line in open('/proc/meminfo').readlines():

 if line.startswith(Memtotal:):
 name, amt, unit = line.split()
 print name, amt, unit
 break
 
 regards
  Steve
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mocking OpenOffice in python?

2007-03-14 Thread Carsten Haese
On Wed, 2007-03-14 at 01:39 -0700, PaoloB wrote:
 Hi everyone,
 
 during our development, we need to write some unit tests that interact
 with OpenOffice through pyUno.
 
 Is there anyone who has got any experience on it? As OpenOffice is
 quite a large beast, and interaction is rather complex, I would like
 to know if there is someone who is willing to share experience (and,
 possibly, code).

I have some experience with pyuno, but your question is very open-ended.
It would be helpful if you asked specific questions or gave more
background on what kind of interaction you're trying to achieve.

The generic answer to your request for code examples is that there's a
tutorial with example code at
http://udk.openoffice.org/python/python-bridge.html, and then there's
the API documentation at
http://api.openoffice.org/DevelopersGuide/DevelopersGuide.html.

-Carsten


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


Re: IronPython and COM Interface

2007-03-14 Thread Larry Bates
Divya wrote:
 Hello,
 
 I'm new to IronPython and COM so please bear with me.
 
 I have a COM interface provided to me. I need to implement this
 interface and pass it to a method as a way of implementing
 'callbacks'.
 
 However it appears that the methods of my interface object are never
 called.
 
 As a alternative, I implemented the interface in C# and then extended
 the C# class in IronPython. However, on running the code, methods of
 my C# class rather than the IronPython class are being called.
 
 Can anyone advise? Is this possible in IronPython?
 
 The code is listed below.
 
 Regards,
 Divya
 
 ---
 
 import time
 
 import clr
 clr.AddReference('Interop.MBTCOMLib.dll')
 clr.AddReference('Interop.MBTORDERSLib.dll')
 clr.AddReference('Interop.MBTQUOTELib.dll')
 
 import MBTCOMLib
 import MBTORDERSLib
 import MBTQUOTELib
 
 demo_user='user'
 demo_pass='pass'
 demo_host=9
 
 class MBEvents(MBTQUOTELib.IMbtQuotesNotify):
   def __init__(self):
   MBTQUOTELib.IMbtQuotesNotify.__init__(self)
 
   def OnLevel2Data(data):
   print 'OnLevel2Data'
 
   def OnOptionsData(self, data):
   print 'OnOptionsData'
 
   def OnQuoteData(self, data):
   print 'OnQuoteData'
 
   def OnTSData(self, data):
   print 'OnTSData'
 
 class MB:
   def __init__(self):
   self.conn = MBTCOMLib.MbtComMgrClass()
   #self.conn.EnableSplash(False)
   self.orders = self.conn.OrderClient
   self.quotes = self.conn.Quotes
   self.events = MBEvents()
 
   def login(self, host=demo_host, user=demo_user, passwd=demo_pass):
   self.conn.DoLogin(host, user, passwd, '')
   print self.quotes.RemoteAddress, self.quotes.RemotePort
   self.quotes.AdviseSymbol(self.events, 'EUR/USD', 1|2|3|4)
 

It may not help but I was struggling with the COM-callback issue
yesterday and found that this works in regular python:

import win32com.server.util

def callback:
_public_methods_=['progress']
def progress(self, total, number):
print completed %i of %i % (number, total)

#
# Get instance of callback class
#
cb=callback()
#
# Wrap the callback class to turn it into an IDispatch (COM) object
# so I can pass it to my COM object.
#
idCallback=win32com.server.util.wrap(cb)
#
# Call the COM interface and pass it the callback function
#
r=oC.WSset_callback(idCallback)

In my case the COM object was also written in Python so to get
to the python object I do following:

def WSset_callback(idCallback)
self.callback=win32com.client.Dispatch(idCallback)

Now I can call .progress method of callback class from the COM
object.

self.callback.progress(total, number)

Hope this helps in some way.

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


Re: Grep Equivalent for Python

2007-03-14 Thread BJörn Lindqvist
 I come from a shell/perl background and have just to learn python.  To
 start with, I'm trying to obtain system information from a Linux
 server using the /proc FS.  For example, in order to obtain the amount
 of physical memory on the server, I would do the following in shell:

 grep ^MemTotal /proc/meminfo | awk '{print $2}'

 That would get me the exact number that I need.  Now, I'm trying to do
 this in python.  Here is where I have gotten so far:

 memFile = open('/proc/meminfo')
 for line in memFile.readlines():
 print re.search('MemTotal', line)
 memFile.close()

import sys
sys.stdout.write(L.split()[1] + '\n' for L in open('/proc/meminfo') if
L.startswith('MemTotal'))

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mocking OpenOffice in python?

2007-03-14 Thread Shane Geiger
My take was that this is an effort to manipulate these files without the 
need for Open Office, so I replied as follows:


Open Office files (.ods and perhaps .odt) are just zipped or gzipped.  
Unpack that and then you are dealing with manipulating regular text 
files--probably HTML. 



Carsten Haese wrote:

On Wed, 2007-03-14 at 01:39 -0700, PaoloB wrote:
  

Hi everyone,

during our development, we need to write some unit tests that interact
with OpenOffice through pyUno.

Is there anyone who has got any experience on it? As OpenOffice is
quite a large beast, and interaction is rather complex, I would like
to know if there is someone who is willing to share experience (and,
possibly, code).



I have some experience with pyuno, but your question is very open-ended.
It would be helpful if you asked specific questions or gave more
background on what kind of interaction you're trying to achieve.

The generic answer to your request for code examples is that there's a
tutorial with example code at
http://udk.openoffice.org/python/python-bridge.html, and then there's
the API documentation at
http://api.openoffice.org/DevelopersGuide/DevelopersGuide.html.

-Carsten


  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

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

Re: number generator

2007-03-14 Thread Duncan Smith
Duncan Smith wrote:
 greg wrote:
 
Gabriel Genellina wrote:


The 5th number is not random.


More precisely, the fifth number is not *independent*
of the others. You can't have five independent random
numbers that sum to 50; only four independent numbers
plus a dependent one.

-- 
Greg
 
 
 In the interests of precision, that should probably read are
 constrained to sum to 50; it's quite possible to generate a sequence of
 independent random variates that just happen to sum to 50 (as I'm sure
 you know).
 
 A fairly efficient way of generating random multinomial variates (which
 would satisfy the OP's problem)

[snip]

That is, the OP's original problem (without the positivity constraint
added in a later post).

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


Re: Mocking OpenOffice in python?

2007-03-14 Thread PaoloB
On 14 Mar, 14:48, Carsten Haese [EMAIL PROTECTED] wrote:
 On Wed, 2007-03-14 at 01:39 -0700, PaoloB wrote:
  Hi everyone,

  during our development, we need to write some unit tests that interact
  with OpenOffice through pyUno.

  Is there anyone who has got any experience on it? As OpenOffice is
  quite a large beast, and interaction is rather complex, I would like
  to know if there is someone who is willing to share experience (and,
  possibly, code).

 I have some experience with pyuno, but your question is very open-ended.
 It would be helpful if you asked specific questions or gave more
 background on what kind of interaction you're trying to achieve.

 The generic answer to your request for code examples is that there's a
 tutorial with example code 
 athttp://udk.openoffice.org/python/python-bridge.html, and then there's
 the API documentation 
 athttp://api.openoffice.org/DevelopersGuide/DevelopersGuide.html.

 -Carsten

Hi Carsten,

basically, our project (PAFlow) is an application for producing
documents in public administrations.

We create templates using OpenOffice, that are filled automatically
using data from the application itself.

Now, interacting with OpenOffice is slow, and our tests get a lot of
time to be executed automatically.

We are trying to mock OpenOffice, so that we can run our tests without
using a true OpenOffice for our tests, except when we express test the
filling of data and production of document.

Ciao

PaoloB


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


Re: number generator

2007-03-14 Thread Alex Martelli
Raymond Hettinger [EMAIL PROTECTED] wrote:

 [Alex Martelli]
map([random.randrange(5) for i in xrange(45)].count, xrange(5))
 
  i.e., this gives 5 integers (each between 0 and 45 included) summing to
  45 -- add 1 to each of them to get the desired result.
 
 This is a really nice approach.  Besides being fast, it is not too
 hard to see that it is correct.
 
 FWIW, here's a variant with a count using the new defaultdict:
 
 n, m = 5, 45
 bag = collections.defaultdict(int)
 for i in xrange(m):
 bag[random.randrange(n)] += 1
 ans = [bag[k] for k in range(n)]

Neat -- and you can use 1+bag[k] in the LC to adjust the results if
needed, of course.


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


Re: Mocking OpenOffice in python?

2007-03-14 Thread PaoloB
On 14 Mar, 14:52, Shane Geiger [EMAIL PROTECTED] wrote:
 My take was that this is an effort to manipulate these files without the
 need for Open Office, so I replied as follows:

 Open Office files (.ods and perhaps .odt) are just zipped or gzipped.
 Unpack that and then you are dealing with manipulating regular text
 files--probably HTML.

No.

What I was trying was to build a fake OpenOffice server, so that we
could interact with a fake OpenOffice during our unit test. As
OpenOffice is quite slow, this could improve the performance of our
unit tests.

However, your suggestion is interesting.

Ciao

PaoloB

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


Re: using python to visit web sites and print the web sites image to files

2007-03-14 Thread [EMAIL PROTECTED]
On Mar 14, 9:02 am, imx [EMAIL PROTECTED] wrote:
 Cool, but does it mean that I will need .net to run the code?

Yep - runtime is free though as is IronPython. For my program the
license is BSD.

Cheers,
Davy

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


Re: number generator

2007-03-14 Thread Duncan Smith
Hendrik van Rooyen wrote:
 Duncan Smith [EMAIL PROTECTED] wrote:
 
 
 
Yes, if the generating processes yield numbers from different
probability mass functions.  You could simply look at the likelihood
ratio.  Otherwise, the likelihood ratio will be 1.

 
  I was thinking about the same random number generator being used in the two 
 disparate ways.
 
 - Hendrik
 

The code I posted for multinomial variates repeatedly generates
independent Poissons until the total is less than, or equal to, the
desired total.  Then the total is made up by repeatedly sampling from a
discrete distribution (multinomial with n==1).  If you replace the
second stage by just increasing a single count by the necessary amount,
then the two mass functions are clearly different.  I'm not sure that
I'd count this as two approaches using the same random number generator.

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


RE: Mocking OpenOffice in python?

2007-03-14 Thread Sells, Fred
I currently use Java to generate a 150 page PDF from about 50 .odt files,
including replacing occurrances of about 10 place-holder phrases from data
in our system.  I do not use the OOo database/mailmerge features, just UNO.
This process takes about 20 seconds on my 2 year old XP laptop and about 10
seconds on our Linux doc server.

So the key problem may be your approach to generating the OO being to slow,
rather than needing a way to speed up testing.

I use a std java property file/url to define the search/replace pairs and to
contol insert of the conditional documents.

FWIW the internal .odt is XML once it is unzipped.

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
Behalf Of PaoloB
Sent: Wednesday, March 14, 2007 9:11 AM
To: python-list@python.org
Subject: Re: Mocking OpenOffice in python?


On 14 Mar, 14:48, Carsten Haese [EMAIL PROTECTED] wrote:
 On Wed, 2007-03-14 at 01:39 -0700, PaoloB wrote:
  Hi everyone,

  during our development, we need to write some unit tests that interact
  with OpenOffice through pyUno.

  Is there anyone who has got any experience on it? As OpenOffice is
  quite a large beast, and interaction is rather complex, I would like
  to know if there is someone who is willing to share experience (and,
  possibly, code).

 I have some experience with pyuno, but your question is very open-ended.
 It would be helpful if you asked specific questions or gave more
 background on what kind of interaction you're trying to achieve.

 The generic answer to your request for code examples is that there's a
 tutorial with example code
athttp://udk.openoffice.org/python/python-bridge.html, and then there's
 the API documentation
athttp://api.openoffice.org/DevelopersGuide/DevelopersGuide.html.

 -Carsten

Hi Carsten,

basically, our project (PAFlow) is an application for producing
documents in public administrations.

We create templates using OpenOffice, that are filled automatically
using data from the application itself.

Now, interacting with OpenOffice is slow, and our tests get a lot of
time to be executed automatically.

We are trying to mock OpenOffice, so that we can run our tests without
using a true OpenOffice for our tests, except when we express test the
filling of data and production of document.

Ciao

PaoloB


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


Re: Questions on migrating from Numeric/Scipy to Numpy

2007-03-14 Thread vj
What should I be using to replace Numeric/arrayobject.h:

numpy/arrayobject.h

or

numpy/oldnumeric.h

Thanks,

VJ

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


Re: Problem I have with a while loop/boolean/or

2007-03-14 Thread [EMAIL PROTECTED]
On Mar 13, 5:34 pm, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 Hi all.

 I have a problem with some code :(

 ---

 hint = raw_input(\nAre you stuck? y/n: )
 hint = hint.lower()

 while (hint != 'n') or (hint != 'y'):
 hint = raw_input(Please specify a valid choice: )


I'd even make it a little more bullet-proof by using lower()

while hint.lower() not in ('y','n'):
  stuff

That way if the user types in 'Y' on 'N' it will still work.  I've
even gone further on occasion

while hint.lower()[0] not in ('y','n'):
  stuff

so if they type 'Yes' or 'No' you're still good.

--greg

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


Re: most complete xml package for Python?

2007-03-14 Thread Stefan Behnel
metaperl wrote:
 Without even checking them all out, I'm thinking the Amara XML Toolkit
 must be the most feature-packed.

Please check out lxml before you post FUD like this.

http://codespeak.net/lxml/

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


dict.items() vs dict.iteritems and similar questions

2007-03-14 Thread Drew
When is it appropriate to use dict.items() vs dict.iteritems. Both
seem to work for something like:

for key,val in mydict.items():
  print key,val

for key,val in mydict.iteritems():
  print key,val

Also, when is it appropriate to use range() vs xrange(). From my
understanding, xrange() essentially gives you an iterator across a
range, so it should be used when iterating. Should you only use
range() when want to physically store the range as a list?

Thanks,
Drew

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


Re: number generator

2007-03-14 Thread Shane Geiger
Raymond:   It looks to me as if you are trying to turn a generator into 
a list in the final line.  That doesn't work.




Raymond Hettinger wrote:

To make the solutions equi-probable, a simple approach is to
recursively enumerate all possibilities and then choose one of them
with random.choice().



Since people are posting their solutions now (originally only hints
were provided for the homework problem), here's mine:

def genpool(n, m):
if n == 1:
yield [m]
else:
for i in xrange(1, m):
for rest in genpool(n-1, m-i):
yield rest + [i]

import random
print random.choice(list(genpool(n=4, m=20)))

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

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

Re: dict.items() vs dict.iteritems and similar questions

2007-03-14 Thread Laurent Pointal
Drew a écrit :
 When is it appropriate to use dict.items() vs dict.iteritems. Both
 seem to work for something like:
 
 for key,val in mydict.items():
   print key,val
 
 for key,val in mydict.iteritems():
   print key,val
 
 Also, when is it appropriate to use range() vs xrange(). From my
 understanding, xrange() essentially gives you an iterator across a
 range, so it should be used when iterating. Should you only use
 range() when want to physically store the range as a list?

iteritems and xrange only provide values when requested.
items and range build complete list when called.

Both work, you may prefer xrange/iteritems for iteration on large
collections, you may prefer range/items when processing of the result
value explicitly need a list (ex. calculate its length) or when you are
going to manipulate the original container in the loop.

A+

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


getting user id (from an arbitrary sys user)

2007-03-14 Thread Gerardo Herzig
hi all. What i need to know is if there is some function like 
os.getuid(), but taking an argument (the username, off course), so i can 
do getuid('myuser')

Thanks you dudes!

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


Re: httplib/socket problems reading 404 Not Found response

2007-03-14 Thread Patrick Altman
On Mar 13, 3:16 pm, Gabriel Genellina [EMAIL PROTECTED]
wrote:
 En Tue, 13 Mar 2007 10:38:24 -0300, Patrick Altman [EMAIL PROTECTED]
 escribió:

  Yes, it's a known problem. See this message with a
  self-response:http://mail.python.org/pipermail/python-list/2006-March/375087.html
  Are there plans to include this fix in the standard Python libraries
  or must I make the modifications myself (I'm running Python 2.5)?

 Submit a bug report, if not already 
 done.http://sourceforge.net/tracker/?group_id=5470

 --
 Gabriel Genellina

Bug already exists at:
https://sourceforge.net/tracker/index.php?func=detailaid=1486335group_id=5470atid=105470

In the meantime, I implemented a work around for my specific case in
the Amazon S3 library in that I implemented a head() method but am
actually just requesting a GET operation with a very small byte
range.  This is essentially yielding all the same header data that I
need (md5 hash in the ETag if the file exists, 404 Not Found if it
doesn't).

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


Re: dict.items() vs dict.iteritems and similar questions

2007-03-14 Thread Drew
On Mar 14, 11:44 am, Laurent Pointal [EMAIL PROTECTED] wrote:
 Both work, you may prefer xrange/iteritems for iteration on large
 collections, you may prefer range/items when processing of the result
 value explicitly need a list (ex. calculate its length) or when you are
 going to manipulate the original container in the loop.

 A+

 Laurent.

Laurent -

Extremely helpful, exactly what I was looking for.

Thanks,
Drew

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


Re: number generator

2007-03-14 Thread Paul Rubin
Steven D'Aprano [EMAIL PROTECTED] writes:
 If you generate all the possible sets of five numbers between 1 and 50,
 there are 50**5 of them, not 2611.

Yes, the idea is generate only the sets that add up to 50.

 unique_partitions(60, 6) takes 0.8 seconds; unique_partitions(80, 8)
 takes about 25 seconds; unique_partitions(80, 10) takes about 80 seconds,
 and unique_partitions(81, 10) takes over 90 seconds.

Hmm, interesting.  Maybe some more optimization is possible.

 (E.g. unique_partitions(80, 10) returns 533,975 unique lists.
 _partitions(80, 10) gives 3,233,568 non-unique lists.)

Well that's just 6x inflation due to duplicates, so I dunno what
else can be done for exhaustive enumeration.  Maybe another approach
to generating the k'th partition is possible.  I'll try to think about
this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: number generator

2007-03-14 Thread Paul Rubin
Raymond Hettinger [EMAIL PROTECTED] writes:
 Since people are posting their solutions now (originally only hints
 were provided for the homework problem), here's mine:
 
 def genpool(n, m):
 if n == 1:
 yield [m]
 else:
 for i in xrange(1, m):
 for rest in genpool(n-1, m-i):
 yield rest + [i]
 
 import random
 print random.choice(list(genpool(n=4, m=20)))

This generates a lot of the partitions more than once, with
possibly unequal probability.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Communicating with a DLL under Linux

2007-03-14 Thread Mikael Olofsson
Thanks for all the responces, both on and off list.

So, I should forget about the DLL, and if I intend to connect the thing 
to a Linux computer, I'll have to develop the code myself for 
communicating with it over USB. Fair enough. I might even try that.

I've done some surfing since yesterday. Why do I always do that after 
asking stupid questions in public? It turns out that a Nicolas Sutre has 
already ported the thing to Linux:

http://linuxk8055.free.fr/

Velleman links to his solution from their product page

http://www.velleman.be/ot/en/product/view/?id=351346

which might mean something. Nicolas solution is only 250 lines of C 
code. It #includes a usb.h, so I guess a lot of its functionality is 
hidden there. It seems structured enough, so I might be able to find 
some inspiration there.

I guess I have some reading to do before I can decide if I shall do this.

Anyway, thanks once again for the responces.

Not completely in dispair...
/MiO
-- 
http://mail.python.org/mailman/listinfo/python-list


Q: Cteni unicode retezcu ze souboru UTF-8 s BOM?

2007-03-14 Thread Petr Prikryl
Ahoj všeci,

Tak nějak prakticky poprvé se dostávám k tomu, 
jak přečíst unicode řetězce ze souboru, který
je uložen ve formátu UTF-8 se signaturou
na začátku (BOM). Nějak se mi nedaří.

Mám takovýto soubor.txt v UTF-8 s BOM
=
První řádek.
Druhý řádek.
Třetí řádek.
Příšerně žluťoučký kůň úpěl ďábelské ódy.
=

... a pustím skript
=
import codecs
f = codecs.open('soubor.txt', 'r', 'utf-8')
for line in f:
print repr(line)
print line[1:]
f.close()
=

Výsledek vypadá takto
=
C:\tmppython a.py
u'\ufeffPrvn\xed \u0159\xe1dek.\r\n'
První řádek.

u'Druh\xfd \u0159\xe1dek.\r\n'
ruhý řádek.

u'T\u0159et\xed \u0159\xe1dek.\r\n'
řetí řádek.

u'P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 
\xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy.\r\n'
říšerně žluťoučký kůň úpěl ďábelské ódy.
=

Všimněte si, že na prvním řádku je \ufeff, což je Byte Order Mark, 
který se tam vůbec nemá objevit. Jeví se mi to jako chyba. 
Na všech řádcích záměrně nevypisuji printem první znak, 
protože u toho prvního řádku to krachne (což je pochopitelné).
Řešil někdo něco podobného? Musí se BOM ukousávat ve vlastní režii?

Díky, 
  pepr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Grep Equivalent for Python

2007-03-14 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Laurent Pointal wrote:

 Steve Holden a écrit :
 Regular expressions aren't really needed here. Untested code follows:
 
 for line in open('/proc/meminfo').readlines:
 for line in open('/proc/meminfo').readlines():
for line in open('/proc/meminfo'):

 if line.startswith(Memtotal:):
 name, amt, unit = line.split()
 print name, amt, unit
 break

Of course it's cleaner to assign the file object to a name and close the
file explicitly after the loop.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: most complete xml package for Python?

2007-03-14 Thread Paul Boddie
On 14 Mar, 16:15, Stefan Behnel [EMAIL PROTECTED] wrote:
 metaperl wrote:
  Without even checking them all out, I'm thinking the Amara XML Toolkit
  must be the most feature-packed.

 Please check out lxml before you post FUD like this.

 http://codespeak.net/lxml/

Calm down, Stefan! The inquirer must have got the impression of
Amara's superiority from somewhere; all you need to do is to discover
which resource gave that impression and balance the situation out. In
any case, it's an opinion: there's no fear involved, and the only
uncertainty and doubt are in the inquirer's mind, which I suppose is
why they posted the inquiry.

Paul

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


print and softspace in python

2007-03-14 Thread Phoe6
print and softspace in python
In python, whenever you use print statement it will append a
newline by default. If you don't want newline to be appended, you got
use a comma at the end (print 10,)
When, you have a list of characters and want them to be printed
together a string using a for loop, there was observation that no
matter what there was space coming between the characters. No split
or  join methods helped.
list1=['a','b','c']
for e in list1:
   print e,
a b c
# Without whitespace it will look like.
print abc
abc

The language reference says that print is designed to output a space
before any object. And some search goes to find and that is controlled
by softspace attribute of sys.stdout.
Way to print without leading space is using sys.stdout.write()

import sys
for e in list1:
  sys.stdout.write(e)
abc

Reference manual says:
A space is written before each object is (converted and) written,
unless the output system believes it is positioned at the beginning of
a line. This is the case (1) when no characters have yet been written
to standard output, (2) when the last character written to standard
output is \n, or (3) when the last write operation on standard
output was not a print statement. (In some cases it may be functional
to write an empty string to standard output for this reason.)

Question to c.l.p
Am Not getting the last part as how you will write  a empty string and
use print  not appending  blank space in a single line. Am not getting
the (In some cases... ) part of the reference manual section. Please
help.

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


Re: Setting Up SOAPpy for Python v2.5 on Windows?

2007-03-14 Thread Steve
All,

Thanks for the suggestions!

I think that I will move forward with elementsoap instead of soappy...

Steve

On Mar 13, 11:53 am, Steve [EMAIL PROTECTED] wrote:
 Hi All,

 What are the required version of the SOAPpy, PyXML, fpconst that are
 needed to run under the Python 2.5 environment on Windows?

 Locations for the downloads?

 Thanks!

 Steve


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


Re: number generator

2007-03-14 Thread Anton Vredegoor
Paul Rubin wrote:

 def genpool(n, m):
 if n == 1:
 yield [m]
 else:
 for i in xrange(1, m):
 for rest in genpool(n-1, m-i):
 yield rest + [i]

 import random
 print random.choice(list(genpool(n=4, m=20)))
 
 This generates a lot of the partitions more than once, with
 possibly unequal probability.

Well, I just noticed that with my memoization function it produces too 
little :-(

But I hope you notice that this function doesn't create only partitions 
but all possible outcomes?

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


Re: number generator

2007-03-14 Thread Paul Rubin
Steven D'Aprano [EMAIL PROTECTED] writes:
  list(_partitions(25, 24))
 [(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2)]
  list(_partitions(25, 25))
 []

Hmm.  I'll look into this later if I get a chance.  Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


(beginners) howto ascribe _all_ fields of parent class to child class?

2007-03-14 Thread dmitrey
Hi all,
I'm rewriting some code from other language  to Python; can anyone
explain me which way is the simpliest:
I have
class C1():
def __init__(self):
 self.a = 5

class C2(C1):
def __init__(self):
 self.b = 8

c = C2()
print c.b#prints 8
print c.a#prints error, because field a is absent

so how can I wrote the code that I'll got all class C1 fields (not
only funcs)

Thank you in advance,
Dmitrey

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


Re: Grep Equivalent for Python

2007-03-14 Thread tereglow
On Mar 14, 11:57 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 In [EMAIL PROTECTED], Laurent Pointal wrote:

  Steve Holden a écrit :
  Regular expressions aren't really needed here. Untested code follows:

  for line in open('/proc/meminfo').readlines:
  for line in open('/proc/meminfo').readlines():

 for line in open('/proc/meminfo'):

  if line.startswith(Memtotal:):
  name, amt, unit = line.split()
  print name, amt, unit
  break

 Of course it's cleaner to assign the file object to a name and close the
 file explicitly after the loop.

 Ciao,
 Marc 'BlackJack' Rintsch

Thanks all for the help with this, am learning a lot; really
appreciate it.
Tom

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


Re: logging and wx.Timer

2007-03-14 Thread Jordan
On Mar 14, 1:52 am, hg [EMAIL PROTECTED] wrote:
 Hi,

 I read that logging was thread safe ... but can I use it under a GUI timer ?

 Thanks,

 hg

That was barely enough information to be worthy of a reply.  Need more
than that.  What do you mean under a gui timer? What gui? What type of
usage? More info = more (and better) help.  Cheers.

JT

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


Re: most complete xml package for Python?

2007-03-14 Thread Steve Holden
Paul Boddie wrote:
 On 14 Mar, 16:15, Stefan Behnel [EMAIL PROTECTED] wrote:
 metaperl wrote:
 Without even checking them all out, I'm thinking the Amara XML Toolkit
 must be the most feature-packed.
 Please check out lxml before you post FUD like this.

 http://codespeak.net/lxml/
 
 Calm down, Stefan! The inquirer must have got the impression of
 Amara's superiority from somewhere; all you need to do is to discover
 which resource gave that impression and balance the situation out. In
 any case, it's an opinion: there's no fear involved, and the only
 uncertainty and doubt are in the inquirer's mind, which I suppose is
 why they posted the inquiry.
 
Although the phrase without even checking them all out hardly lends 
credence to the OP's assertion of Amara's superiority, and does tend to 
support a hypothesis involving some ulterior motive (or would if less 
ingenuously done).

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: (beginners) howto ascribe _all_ fields of parent class to child class?

2007-03-14 Thread Diez B. Roggisch
dmitrey schrieb:
 Hi all,
 I'm rewriting some code from other language  to Python; can anyone
 explain me which way is the simpliest:
 I have
 class C1():
 def __init__(self):
  self.a = 5
 
 class C2(C1):
 def __init__(self):
  self.b = 8
 
 c = C2()
 print c.b#prints 8
 print c.a#prints error, because field a is absent
 
 so how can I wrote the code that I'll got all class C1 fields (not
 only funcs)

You need to call the super classes __init__-method. There are several 
ways to do so, in your case

class C2(C1):
 def __init__(self):
 C1.__init__(self)
 self.b = 8

should do the trick.

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


Re: dict.items() vs dict.iteritems and similar questions

2007-03-14 Thread Shane Geiger
# Just by looking at the output, it seems pretty obvious that xrange 
would be more memory effcient for large ranges:


print With range():,range(100,200)
print
print With xrange():,xrange(100,200)

d = {1:2,2:3,3:4}
d.items()
d.iteritems()

#  I have been curious to use Pysizer (which requires patching Python) 
to demonstrate the difference.




Drew wrote:

When is it appropriate to use dict.items() vs dict.iteritems. Both
seem to work for something like:

for key,val in mydict.items():
  print key,val

for key,val in mydict.iteritems():
  print key,val

Also, when is it appropriate to use range() vs xrange(). From my
understanding, xrange() essentially gives you an iterator across a
range, so it should be used when iterating. Should you only use
range() when want to physically store the range as a list?

Thanks,
Drew

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

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

Re: (beginners) howto ascribe _all_ fields of parent class to child class?

2007-03-14 Thread Steve Holden
dmitrey wrote:
 Hi all,
 I'm rewriting some code from other language  to Python; can anyone
 explain me which way is the simpliest:
 I have
 class C1():
 def __init__(self):
  self.a = 5
 
 class C2(C1):
 def __init__(self):
  self.b = 8
 
 c = C2()
 print c.b#prints 8
 print c.a#prints error, because field a is absent
 
 so how can I wrote the code that I'll got all class C1 fields (not
 only funcs)
 
 Thank you in advance,
 Dmitrey
 

The only problem here is that your subclass doesn't call the __init__ 
method of the superclass. Rewrite your C2 definition to read

class C2(C1):
 def __init__(self):
  C1.__init__(self)
  self.b = 8

and you should find your example works as you want.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Python equivalents to MATLAB str2func, func2str, ischar, isfunc?

2007-03-14 Thread dmitrey
I can't find these via web serch

thank you in advance,
Dmitrey

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


Re: Python equivalents to MATLAB str2func, func2str, ischar, isfunc?

2007-03-14 Thread Alexander Schmolck
dmitrey [EMAIL PROTECTED] writes:

 I can't find these via web serch
 
 thank you in advance,
 Dmitrey


str2func: getattr(some_module, 'f')
func2str: f.__name__
ischar: isinstance(x, basestring) and len(x) == 1
isfunc: callable(x) # is most likely to be what you want

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


Re: dict.items() vs dict.iteritems and similar questions

2007-03-14 Thread Leif K-Brooks
Laurent Pointal wrote:
 Both work, you may prefer xrange/iteritems for iteration on large
 collections, you may prefer range/items when processing of the result
 value explicitly need a list (ex. calculate its length) or when you are
 going to manipulate the original container in the loop.

xrange actually supports len():

   len(xrange(10))
  10
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: number generator

2007-03-14 Thread Anton Vredegoor
Anton Vredegoor wrote:

 def memoize(fn):
   cache = {}
   def proxy(*args):
   try: return cache[args]
   except KeyError: return cache.setdefault(args, fn(*args))
   return proxy

Sorry this doesn't work in this case. This works:

def memoize(fn):
  cache = {}
  def proxy(*args):
  try: return cache[args]
  except KeyError: return cache.setdefault(args, list(fn(*args)))
  return proxy

But then we lose all speed advantages from memoizing so
it's no good either.

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


Re: Python equivalents to MATLAB str2func, func2str, ischar, isfunc?

2007-03-14 Thread Travis Oliphant
dmitrey wrote:
 I can't find these via web serch


You won't find exact equivalents.  But, the same functionality is 
available.  Perhaps you would like to show us what you are trying to do 
in Python.

Python's eval has some similarity with str2func

Python's repr() or str() has some similarity with func2str

ischar(A)  is similiar to isinstance(A, str)

isfunc  is similiar to callable

-Travis

P.S.  (if you are using NumPy, then there are other possibilities as well.

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


Re: Python equivalents to MATLAB str2func, func2str, ischar, isfunc?

2007-03-14 Thread dmitrey
Thank you
(however in MATLAB ischar is the same as isstr)
but what if I don't know the name of module?
I.e. I have

def myfunc(param): ...
#where param can be both funcName or a function, and I want to obtain
both name and func, something like
if isinstance(param, basestring):
   func, funcName = something, param
else: func, funcName = param, param.__name__
what should I type instead of something?

D.



On Mar 14, 7:06 pm, Alexander Schmolck [EMAIL PROTECTED] wrote:
 dmitrey [EMAIL PROTECTED] writes:
  I can't find these via web serch

  thank you in advance,
  Dmitrey

 str2func: getattr(some_module, 'f')
 func2str: f.__name__
 ischar: isinstance(x, basestring) and len(x) == 1
 isfunc: callable(x) # is most likely to be what you want

 'as


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


Fwd: Server-side script takes way too long to launch

2007-03-14 Thread Teresa Hardy

Thanks Jeff for all the great advice on where to look next, including help
with mailman. (I fell off the list and am using this reply to figure out
why!) Just switched to gmail and still learning it too.

And thanks for being so kind in the code review. Fundamentally, I had too
many imported modules in the original code so I partitioned it to run more
efficiently. The data from the machine up at school on the subset of code
was closer to yours. You have definitely put me back on track.
Thanks,
Teresa


-- Forwarded message --
From: Jeff McNeil [EMAIL PROTECTED]
Date: Mar 13, 2007 12:33 PM
Subject: Re: Server-side script takes way too long to launch
To: Teresa Hardy [EMAIL PROTECTED]

Can you send the program? It's hard to try and follow through without...
With the additional socket library calls, that could contribute.

On 3/13/07, Teresa Hardy [EMAIL PROTECTED] wrote:


Josh, someone mentioned mod_python to me and I wasn't sure if it was the
right/best solution for accelerating python. I'll chase that one down.

Jeff, If I read this right, the browser isn't showing the launched swf for
a good 7 seconds on top of the initial latency...some of which is expected.
There is something else going on with a socket class running without being
called. Restart doesn't seem to help. But the discussion is helping me
through some code that might be contributing to the problem. I am going to
make some more test runs with a subset of the code. In the meantime there
might be something more obvious to an expert in what I am sending.

I like to quote Michael Crighton from his Airframes book...it is always a
compounding series of events that causes a crash.

Any advice greatly appreciated!

Access log from Apache...
 127.0.0.1 - - [13/Mar/2007:11:33:06 -0700] GET
/cgi-bin/finalcode.py?usae HTTP/1.1 200 231
127.0.0.1 - - [13/Mar/2007:11:33:07 -0700] GET /favicon.ico HTTP/1.1 200
3262
192.168.1.51 - - [13/Mar/2007:11:33:17 -0700] GET /choosetemplate.swf
HTTP/1.1 200 250695 ---
192.168.1.51 - - [13/Mar/2007:11:33:17 -0700] GET /favicon.ico HTTP/1.1
200 3262
127.0.0.1 - - [13/Mar/2007:11:30:09 -0700] GET /cgi-bin/finalcode.py?usae
HTTP/1.1 200 231
127.0.0.1 - - [13/Mar/2007:11:33:21 -0700] GET /cgi-bin/xmlmaker.py?swf1
HTTP/1.1 200 132

My run log inside Python...
start Tue Mar 13 11:30:10 2007 Tue Mar 13 11:30:10 2007
inside distractor Tue Mar 13 11:30:10 2007
---
after display1.join Tue Mar 13 11:30:10 2007
Socket in msg init
in main program theme before bridge... Tue Mar 13 11:30:10 2007
Connection received from: 192.168.1.51
Socket out msg swf1
Connection terminated Tue Mar 13 11:33:21 2007
in main program theme... swf1 Tue Mar 13 11:33:21 2007


On 3/13/07, Jeff McNeil [EMAIL PROTECTED] wrote:

 But even if the server was loading Python on each hit, which it will for
 CGI, it shouldn't take a count to 13, especially on localhost. That to me
 is an indication of a further problem.  Does it take that long to load with
 each hit, or just the first following a server restart?  What do log
 timestamps say from initial hit until last-byte from your Python script?

 Might want to validate your Apache configuration and have a look at
 httpd.apache.org.  Sounds to me like DNS lookups are enabled or
 something of the sort.

 Thanks,

 Jeff


 On 3/13/07, Josh Bloom  [EMAIL PROTECTED]  wrote:
 
  Teresa, when you call a python script this way, the server needs to
  load the python interpreter for each call.
 
  If you need faster execution you should look into having a server
  process running already. Something like mod_python for apache or CherryPy
  will help you speed this up.
 
  -Josh
 
 
  On 3/13/07, Teresa Hardy  [EMAIL PROTECTED] wrote:
 
   I have a webpage calling a python script, using Apache
   serverhttp://localhost/cgi-bin/mycode.py?dmn
   I am using Firefox, WindowsXP Python 2.4
  
   I can count to 13 from the time I click to the time the browser
   finds the path.
  
   The python runs okay when I finally get to it. In the first step it
   just launches a Flash file. I benchmarked the time thru the python code 
and
   it isn't the slow part. It's the launch. Forgive me if I am not explaining
   this well. I am pretty much teaching myself...fumbling thru the process.
  
   Any suggestions on how to speed up the first step?
  
   Thanks,
   Teresa
  
  
  
  
  
  
  
   --
   http://mail.python.org/mailman/listinfo/python-list
  
 
 
  --
  http://mail.python.org/mailman/listinfo/python-list
 


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



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

Re: print and softspace in python

2007-03-14 Thread Stargaming
Phoe6 schrieb:
 print and softspace in python
 In python, whenever you use print statement it will append a
 newline by default. If you don't want newline to be appended, you got
 use a comma at the end (print 10,)
 When, you have a list of characters and want them to be printed
 together a string using a for loop, there was observation that no
 matter what there was space coming between the characters. No split
 or  join methods helped.

Huh?
  x = ['h', 'i', '!']
  print ''.join(x)
hi!

I don't see any problem there. In the most cases you could also build up 
a string accumulatedly.


list1=['a','b','c']
for e in list1:
 
print e,
 a b c
 
# Without whitespace it will look like.
print abc
 
 abc
 
 The language reference says that print is designed to output a space
 before any object. And some search goes to find and that is controlled
 by softspace attribute of sys.stdout.
 Way to print without leading space is using sys.stdout.write()
 
Note: This attribute is not used to control the print statement, but to 
allow the implementation of print to keep track of its internal state.
 
import sys
for e in list1:
 
   sys.stdout.write(e)
 abc
 
 Reference manual says:
 A space is written before each object is (converted and) written,
 unless the output system believes it is positioned at the beginning of
 a line. This is the case (1) when no characters have yet been written
 to standard output, (2) when the last character written to standard
 output is \n, or (3) when the last write operation on standard
 output was not a print statement. (In some cases it may be functional
 to write an empty string to standard output for this reason.)
 
 Question to c.l.p
 Am Not getting the last part as how you will write  a empty string and
 use print  not appending  blank space in a single line. 
I'd guess they think about print ,;print moo (print a blank string, 
do not skip line, print another one) to preserve the softspace. As far 
as I get your problem, you don't really have to think about it.
 Am not getting
 the (In some cases... ) part of the reference manual section. Please
 help.
 

Use the join-idiom correctly.

HTH,
Stargaming
-- 
http://mail.python.org/mailman/listinfo/python-list


Constructor of object

2007-03-14 Thread inline
Hello!
I want to assign self to object of parent class in constructor, like

def my_func():
...
return ParentClass()

class MyClass (ParentClass):
def __init__(self):
self = my_func()

but it not work, because object not initialized. What i can do?

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


Re: Grep Equivalent for Python

2007-03-14 Thread tereglow
Okay,

It is now working as follows:

memFile = open('/proc/meminfo')
for line in memFile.readlines():
if line.startswith(MemTotal):
memStr = line.split()
memTotal = memStr[1]
memFile.close()
print Memory:  + memTotal + kB

I'm learning the whole try, finally exception stuff so will add that
in as well.  Now, I'm trying to figure out the CPU speed.  In shell,
I'd do:

grep ^cpu MHz /proc/cpuinfo | awk '{print $4}' | head -1

The head -1 is added because if the server has 2 or more processors,
2 or more lines will result, and I only need data from the first
line.  So, now I'm looking for the equivalent to head (or tail in
Python.  Is this a case where I'll need to break down and use the re
module?  No need to give me the answer, a hint in the right direction
would be great though.

Thanks again,
Tom

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


Re: Constructor of object

2007-03-14 Thread Sylvain Defresne
inline wrote:
 Hello!
 I want to assign self to object of parent class in constructor, like
 
 def my_func():
 ...
 return ParentClass()
 
 class MyClass (ParentClass):
 def __init__(self):
 self = my_func()
 
 but it not work, because object not initialized. What i can do?
 

You want to override the __new__ function.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting user id (from an arbitrary sys user)

2007-03-14 Thread Thinker
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Gerardo Herzig wrote:
 hi all. What i need to know is if there is some function like
 os.getuid(), but taking an argument (the username, off course), so i can
 do getuid('myuser')

 Thanks you dudes!

 Gerardo
Please refer http://docs.python.org/lib/module-pwd.html for pwd module.

- --
Thinker Li - [EMAIL PROTECTED] [EMAIL PROTECTED]
http://heaven.branda.to/~thinker/GinGin_CGI.py
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (FreeBSD)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFF+Dfv1LDUVnWfY8gRAkfkAKDydeZwxvb1tK+Ms5xE9xWfetNtLACg5xi3
yAJvjodjdL20vU32MVZsLDk=
=iRUm
-END PGP SIGNATURE-

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

Python Oracle

2007-03-14 Thread Facundo Batista
Hi! I need to connect to Oracle.

I found this binding,

  http://www.zope.org/Members/matt/dco2

that is the recommended in the Python page.

But that page seems a bit confuse to me. In the upper right corner says
that the last release is PreRelease 1, from 2001-11-15.

At the bottom, however, it says that 1.3 beta was released 2003-02-10,
and is a development version (the last stable is 1.2, from 2002-10-02),
four and a half years ago.

The question is: is this connector the recommended one? it's aged
because it's stable and no more changes are necessary, or it just dead?
Works Ok?

Thank you!! Regards,

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


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


Re: Python Oracle

2007-03-14 Thread Josh Bloom

I would suggest using cx_Oracle as I have had good experience with it.
http://www.cxtools.net/default.aspx?nav=cxorlb

-Josh

On 3/14/07, Facundo Batista [EMAIL PROTECTED] wrote:


Hi! I need to connect to Oracle.

I found this binding,

  http://www.zope.org/Members/matt/dco2

that is the recommended in the Python page.

But that page seems a bit confuse to me. In the upper right corner says
that the last release is PreRelease 1, from 2001-11-15.

At the bottom, however, it says that 1.3 beta was released 2003-02-10,
and is a development version (the last stable is 1.2, from 2002-10-02),
four and a half years ago.

The question is: is this connector the recommended one? it's aged
because it's stable and no more changes are necessary, or it just dead?
Works Ok?

Thank you!! Regards,

--
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


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

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

Re: Constructor of object

2007-03-14 Thread Thinker
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

inline wrote:
 Hello! I want to assign self to object of parent class in
 constructor, like

 def my_func(): ... return ParentClass()

 class MyClass (ParentClass): def __init__(self): self = my_func()

 but it not work, because object not initialized. What i can do?

Do you want to call constructor of super-class to initialize the object?
If it is true, you have following options.

In old style class:
class MyClass(ParentClass):
def __init__(self):
ParentClass.__init__(self)

In new style class:
class MyClass(ParentClass):
def __init__(self):
super(MyClass).__init__(self)

Or
class MyClass(ParentClass):
def __init__(self):
super(MyClass, self).__init__()

- --
Thinker Li - [EMAIL PROTECTED] [EMAIL PROTECTED]
http://heaven.branda.to/~thinker/GinGin_CGI.py
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (FreeBSD)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFF+Dls1LDUVnWfY8gRAvDaAKDVmX8LmuWUdJ4eVil7l//rjCQZLQCg8dO8
Y77CL1ikmtdl6S3HD04GWiA=
=mvSe
-END PGP SIGNATURE-

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

  1   2   3   >