Re: comparing two lists and returning position

2007-06-25 Thread Charles Sanders
hiro wrote:
 bare in mind that I have a little over 10 million objects in my list
 (l2) and l1 contains around 4 thousand
 objects.. (i have enough ram in my computer so memory is not a
 problem)

Glad to see you solved the problem with the trailing space.

Just one minor point, I did say

  or probably less efficiently ...

As far as i know, my suggestion's running time is
proportional to len(l1)*len(l2), which gets quite
big for your case where l1 and l2 are large lists.

If I understand how python dictionaries work, Paul Rubin's
suggestion

  from itertools import izip, count
  pos = map(dict(izip(l2, count())).__getitem__, l1)

or the (I think) approximately equivalent

from itertools import izip, count
d = dict(izip(l2,count()))
pos = [ d[i] for i in l1 ]

or the more memory intensive

d = dict(zip(l2,range(len(l2
pos = [ d[i] for i in l1 ]

should all take take running time proportional to
(len(l1)+len(l2))*log(len(l2))

For len(l1)=4,000 and len(l2)=10,000,000
Paul's suggestion is likely to take
about 1/100th of the time to run, ie
be about 100 times as fast. I was trying
to point out a somewhat clearer and simpler
(but slower) alternative.

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


Re: comparing two lists and returning position

2007-06-21 Thread Charles Sanders
Paul Rubin wrote:
 
 from itertools import izip
 pos = map(dict(izip(l2, count())).__getitem__, l1)

or probably less efficiently ...

  l1 = [ 'abc', 'ghi', 'mno' ]
  l2 = [ 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqr']
  pos = [ l2.index(i) for i in l1 ]
  print pos
[0, 2, 4]

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


Re: ctypes: error passing a list of str to a fortran dll

2007-06-04 Thread Charles Sanders
luis wrote:
 I'm using ctypes to call a fortran dll from python. I have no problems
 passing integer and double arryas, but I have an error with str arrys.
 For example:
[snip]

I do not know about Microsoft Fortran compilers (your mention
of dll indicates you are probably using MS), nor much about
Python, but the C equivalent of a given Fortran call is operating
system and compiler dependent. You should consult the Fortran
compiler manual for the compiler used to create the DLL.

Despite this, many (but not all) C to Fortran interfaces have
the following characteristics

+ C name is Fortran name in lower case
+ Fortran REAL, DOUBLE PRECISION, INTEGER etc parameters
  are pointers to the parameter in C, ie float*, etc
+ Fortran REAL etc arrays are pointers in C (same as
  C arrays decay to pointers).
+ Fortran CHARACTER and CHARACTER arrays are passed as TWO
  parameters, one a pointer to the start of the variable
  or array, and the other the length as an integer, not
  a pointer. The length parameters follow all other
  parameters, in order of the character variables/arrays.

Variations I have seen (all on Unix) include using upper case
instead of lower, prepending (or postpending) an underscore (or
other character(s)) to the subroutine or function name, and
using special character descriptors (packing address and
length into one word) for character variables. There are
almost certainly more variations that I have not seen.

For example, given a FORTRAN declaration

SUBROUTINE X( CV, RV, CA, N )
CHARACTER*(*) CV
REAL  RV
CHARACTER*(*) CA(*)
INTEGER   N

The C equivalent is likely to be

void x( char *pcv, float *prv, char *pca, int *pn,
int lv, int la)

Where lv will hold the length  of cv and la the length of
each element of ca (required to be the same for all elements
of the array). Fortran uses fixed length character strings,
padded with blanks.

Given the error message

  ValueError: Procedure probably called with not enough
  arguments (4 bytes missing)

I suspect that your Fortran compiler is one of the many which
do this, and the missing 4 bytes are the integer length of
each element of the character array.

Also, I noticed you seem to be passing an array of character
pointers rather than an array of characters. It is doubtful that
Fortran can handle this. You will probably have to pad the strings
to a maximal length with spaces, concatanate then into one big
string, and pass this by reference together with their padded
length. Your Fortran may (but probably won't) have extensions
that allow you to pass an array of character pointers.


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


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-30 Thread Charles Sanders
Dave Hansen wrote:
 
 The date is about right (actually, a little early: ASR-33, 1965; C,
 about 1970), but you can't program C on an ASR-33.  Keywords are all
 lower case, and always have been.  IF is a syntax error...
 

But the Unix terminal drivers of the day for
upper case only terminals translated to lower case and
you had to enter \A to get an upper case A, and so on.

Still hangs around in the stty options iuclc,
-iuclc, olcuc and -olcuc - You can make an x-term window
look like an old upper case only terminal.

I don't know if any still do it, but old unices
used to detect on logon if you typed your user name and
password in all caps and then turned on the iuclc and
olcuc options, assuming that the reason for the all caps
was a upper case only terminal - great fun if you hit caps
lock by accident.


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


Re: installing cx_Oracle.

2007-05-24 Thread Charles Sanders
Doug Phillips wrote:
 It also works the other way around, at least on the non-empty 
 set of systems that contains my workstation. export simply 
 marks the variable name for automatic export to the 
 environment of subsequent commands. The value at that time 
 doesn't matter. What matters is the value that the name has 
 at the time the command is run:
[snip]
 Just tried on a FreeBSD 6.1 development box with stock /bin/sh and it
 works there too...

As far as I know, it has been like this since the introduction
of the Bourne shell in (according to a web search) 1979.

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


Re: Regexes: How to handle escaped characters

2007-05-18 Thread Charles Sanders
Torsten Bronger wrote:
 Hallöchen!
[...]

 Example string: uHollo, escaped positions: [4].  Thus, the
 second o is escaped and must not be found be the regexp
 searches.

 Instead of re.search, I call the function guarded_search(pattern,
 text, offset) which takes care of escaped caracters.  Thus, while

 
 Tschö,
 Torsten.

I'm still pretty much a beginner, and I am not sure
of the exact requirements, but the following seems to work
for at least simple cases when overlapping matches are not
considered.

def guarded_search( pattern, text, exclude ):
   return [ m for m in re.finditer(pattern,text)
 if not [ e for e in exclude if m.start() = e  m.end() ] ]

txt = axbycz
exc = [ 3 ]  # y
pat = [xyz]
mtch = guarded_search(pat,txt,exc)
print Guarded search text='%s' excluding %s % ( txt,exc )
for m in mtch:
   print m.group(), 'at', m.start()

txt = Hollo
exc = [ 4 ]  # Final o
pat = o$
mtch = guarded_search(pat,txt,exc)
print Guarded search text='%s' excluding %s %s matches % 
(txt,exc,len(mtch))
for m in mtch:
   print m.group(), 'at', m.start()

Guarded search text='axbycz' excluding [3] 2 matches
x at 1
z at 5
Guarded search text='Hollo' excluding [4] 0 matches


Simply finds all the (non-overlapping) matches and rejects any
that include one of the excluded columns (the y in the first
case and the final o in the second).

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


Re: preferred windows text editor?

2007-05-10 Thread Charles Sanders
Ant wrote:
 
 What method of executing code snippets in a Python shell do other Vim
 users use? Other than just copy/paste?
 

Not vim, but good old vi so should work in vim

1. Mark the start of the fragment, for exampls ms (to mark
with label s). Labels a through z are available.
2. Move to the end of the fragment.
3. :'s,.w !python to send the fragment to the python
interpreter

Worked for me when I tried it a few minutes ago. I had never
bothered before - just copied/pasted.

Obviously, you can also mark the end, move to the start and
do something like :.,'ew !python  or mark both the start and
the end, or use line numbers, or labels plus offsets, or
searches, eg :/def/;+5w !python to search forward to the
next occurrence of def and send that line plus the next
five to the interpreter. Whatever works for you. The abbreviate
and map commands can be used to reduce the typing if you are
fanatical.


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


Re: interesting exercise

2007-05-09 Thread Charles Sanders
Michael Tobis wrote:
 Here is the bloated mess I came up with. I did see that it had to be
 recursive, and was proud of myself for getting it pretty much on the
 first try, but the thing still reeks of my sorry old fortran-addled
 mentality.

Recursion is not necessary, but is much, much clearer.

Here is one non-recursive version from another aging
fortran programmer. I agree it is less clear than most
of the recursive alternatives. No checks for sorted
input etc, these are left as an exercise for the reader.

def permute( s, n ):
   def _perm( m, n ):
 ilist = [0]*n
 while True:
   yield ilist
   i = n-1
   while i = 0 and ilist[i]=m-1: i = i - 1
   if i = 0:
 ilist = ilist[0:i] + [ilist[i]+1] + [0]*(n-i-1)
   else:
 return

   return [ ''.join([s[i] for i in ilist])
 for ilist in _perm(len(s),n) ]

print permute('abc',2) = , permute('abc',2)
print len(permute('13579',3)) = , len(permute('13579',3))

permute('abc',2) =  ['aa', 'ab', 'ac', 'ba', 'bb', 'bc',
'ca', 'cb', 'cc']
len(permute('13579',3)) =  125

or even this monstrosity ...

def permute2( s, n ):
   return [ ''.join([ s[int(i/len(s)**j)%len(s)]
 for j in range(n-1,-1,-1)])
   for i in range(len(s)**n) ]

print permute2('abc',2) =, permute2('abc',2)
print len(permute2('13579',3)) =, len(permute2('13579',3))

permute2('abc',2) = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc',
  'ca', 'cb', 'cc']
len(permute2('13579',3)) = 125


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


Re: Multiple regex match idiom

2007-05-09 Thread Charles Sanders
Hrvoje Niksic wrote:
 I often have the need to match multiple regexes against a single
 string, typically a line of input, like this:
 
 if (matchobj = re1.match(line)):
   ... re1 matched; do something with matchobj ...
 elif (matchobj = re2.match(line)):
   ... re2 matched; do something with matchobj ...
 elif (matchobj = re3.match(line)):
 
[snip]
 
 There are ways to work around the problem, for example by writing a
 utility predicate that passes the match object as a side effect, but
 that feels somewhat non-standard.  I'd like to know if there is a
 Python idiom that I'm missing.  What would be the Pythonic way to
 write the above code?

Only just learning Python, but to me this seems better.
Completely untested.

re_list = [ re1, re2, re3, ... ]
for re in re_list:
   matchob = re.match(line)
   if matchob:
 
 break

Of course this only works it the do something is the same
for all matches. If not, maybe a function for each case,
something like

re1 = re.compile()
def fn1( s, m ):
   
re2 = 
def fn2( s, m ):
   

re_list = [ (re1, fn1), (re2, fn2), ... ]

for (r,f) in re_list:
   matchob = r.match(line)
   if matchob:
 f( line, matchob )
 break
 f(line,m)

Probably better ways than this exist.


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


Re: interesting exercise

2007-05-09 Thread Charles Sanders
[EMAIL PROTECTED] wrote:
 On May 9, 1:13 am, Charles Sanders [EMAIL PROTECTED]
 wrote:
[snip]
 or even this monstrosity ...

 def permute2( s, n ):
return [ ''.join([ s[int(i/len(s)**j)%len(s)]
  for j in range(n-1,-1,-1)])
for i in range(len(s)**n) ]

 print permute2('abc',2) =, permute2('abc',2)
 print len(permute2('13579',3)) =, len(permute2('13579',3))

 permute2('abc',2) = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc',
   'ca', 'cb', 'cc']
 len(permute2('13579',3)) = 125

 Charles
 
 Could you explain, this one, actually?  Don't forget StopIteration.
 

As Michael said, simple counting in base n with the
string as the digits. No attempt at clarity or efficiency (I
did say it was a monstrosity).

Also, as a python beginner I didn't know about divmod,
and have no idea what you (castironpi) mean by Don't forget
StopIteration.


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


Re: 4 quadrant atan

2007-05-03 Thread Charles Sanders
Roel Schroeven wrote:
 
 I might be wrong of course, but can't you just use atan2? Only problem 
 is that it returns negative angles for quadrants 3 and 4, but that is 
 easily solved. In Python:
 
 from math import atan2, pi, fmod
 def vectorAngle(x, y):
 return fmod(atan2(y, x) + 2*pi, 2*pi)
 
 No conditionals in sight.
 

Yes, but there will be some conditionals for special
cases in the implementation of atan2().

I am pretty sure that in Python (and Perl) atan2() is
the C atan2() from the C math library, also often used by
Fortran.

This is normally written in assembler for the individual
architecture by the hardware vendor or compiler writer, is usually
heavily optimized, carefully handles all the corner cases, and
often carries extra precision to ensure accuracy.

If I recall correctly P. J. Plauger's book on the C
standard library (The Standard C Library) includes a C version
of atan2(), which is probably pretty typical of the algorithms
used when there is no hardware support for trigonometric functions.

As I remember it, atan2 (and atan) in Plauger's book
use a ratio of polynomials to approximate atan(x) over a
limited range, (such as -1.0 ... +1.0 or 0.0 ... sqrt(2)-1)
and formulae (assuming I have remembered high school
trigonometry correctly) such as atan(x) = pi/2 - atan(1/x)
and atan(x) = pi/4 - atan((1-x)/(1+x)) [derived from tan(pi/4-x)
= (1-x)/(1+x)] to extend the range.

There is an obvious trade off between the complexity
of the approximating polynomials (and the range they cover
with acceptable accuracy), and the number of cases needed to
extend the range to all valid inputs. For example, if the
polynomials cover -1.0 ... +1.0 (atan() values of -pi/4
to +pi/4) then there are at least 5 cases to consider
(atan() ranges -pi ... -3pi/4, -3pi/4 ... -pi/4, -pi/4
... +pi4, +pi/4 ... +3pi/4, +3pi/4 ... +pi), while if the
approximations only cover 0.0 ... sqrt(2)-1 (atan() values
from 0.0 to pi/8) then there are at least 16 cases. NaNs
and infinities would add additional cases, as may the need
to preserve accuracy near zero.


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


Re: Lazy evaluation: overloading the assignment operator?

2007-05-02 Thread Charles Sanders
Diez B. Roggisch wrote:
 I fail to see where laziness has anything to do with this.
  In C++, this problem can be remedied with the so called
  temporary base class idiom.

I have seen this referred to as lazy evaluation in C++,
so I suspect that Diez and Sturia are using Lazy evaluation
in different contexts with different meaning.

 But this has nothing to do with laziness, which does not
  reduce the amount of code to execute, but instead defers the
  point of execution of that code.

But that is precisely what Sturia is suggesting, defer
(for a few nanoseconds) the evaluation of the multiplications
and addition until the assignment occurs. Admittedly a big
difference to the lazy evaluation implied by python's yield
statement, but still a version of lazy evaluation and (at
least sometimes) referred to as such in a C++ context.

I am a python newbie (about one month) but I think
some of what Sturia wants could be achieved by partially
following what is usually done in C++ to achieve what he
wants. It would involve a replacement array class (possibly
derived from NumPy's arrays) and a proxy class.

+ Addition, multiplication, etc of arrays and proxy
  arrays does not return the result array, but returns
  a proxy which stores the arguments and the
  operation.

+ Array indexing of the proxy objects results in
  the indexing methods of the arguments being
  called and the operation being carried out and
  returned. In C++ this is normally very efficient
  as the operations are all defined inline and
  expanded by the compiler.

+ If necessary, define an additional method to evaluate
  the entire array and return it.

I think this would allow code like (if the new array type is
XArray)

a = Xarray(...)
b = Xarray(...)
c = Xarray(...)
d = Xarray(...)

y = a*b+c*d   # Returns a proxy object

x = y[4]  # Computes x = a[4]*b[4] + c[4]*d[4]

v = y.eval()  # Evaluates all elements, returning Xarray

z = ((a+b)*(c+d)).eval()  # Also evaluates all elements

Whether it would be any faster is doubtful, but it would eliminate
the temporaries.

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


Re: scaling

2007-05-01 Thread Charles Sanders
Gabriel Genellina wrote:
[snip]
 if xminvalue: yield 0
 elif xmaxvalue: yield top
 else: yield (x-minvalue)*top/(maxvalue-minvalue)
[snip]

Personally, I find

yield min(top,max(0,(x-minvalue)*top/(maxvalue-minvalue)))
or
scaled_value = (x-minvalue)*top/(maxvalue-minvalue)
yield min(top,max(0,scaled_value))

clearer, but I am aware that others disagree with this.


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


Re: Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread Charles Sanders
Grant Edwards wrote:
 Assuming the python interpreter free()s the memory, my
 understanding is that on Unixes the memory is returned to the
 pool used by malloc(), but is not returned to the OS since
 there isn't a practical way to ensure that the memory at the
 end of the data segment is not used.

http://www.dent.med.uni-muenchen.de/~wmglo/malloc-slides.html

  Large chunks are allocated via mmap(). The threshold is set
  through the environment variable MALLOC_MMAP_THRESHOLD_.
  The maximum number of chunks allocated in this way is limited
  through MALLOC_MMAP_MAX_.

I think these large chunks are returned to the OS when
freed.

  Trimming occurs when the size of the top chunk exceeds
  MALLOC_TRIM_THRESHOLD_.

I think this means that memory for small chunks
is returned to the OS if the free space at the top of the
heap exceeds the threshold.

 Asking on the gnu libc mailing list would probably provide a
 more authoritative answer.  I'd wager that they even know what
 other non-Gnu libc implementations do.

Agreed, they would be authoritative for GNU libc.

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


Re: Strange terminal behavior after quitting Tkinter application

2007-04-24 Thread Charles Sanders
Chris wrote:
 ... Quitting by typing 'sys.exit()' in the interpreter
 also works fine. Only quitting via the GUI seems to cause the
 problem.

As previously stated, I know nothing about Tkinter,
but it definitely looks like there is some cleanup being skipped
on a GUI exit that is in fact being run on exit via ^D and
sys.exit from the terminal.

If I remember correctly, the low level details of how
this sort of thing is usually handled on unix like systems is
for the application to
- Do an ioctl TCGETA system call to get the current
  settings, and save them somewhere.
- Do an ioctl TCSETA system call to change the settings.
- Arrange, via signal handlers, atexit, or other means
  for a cleanup routine to be called on exit.
- The cleanup routine does an ioctl TCSETA call with
  the saved settings.
(all this would typically involve C calls)

I believe that in your case this last cleanup is being omitted
on exit via the GUI.

  For the moment, including the line 'os.system(stty sane)'
  before sys.exit() is the solution I'll use.

If that is satisfactory, well and good. However, there
is a possibility that you may lose some settings that you would
prefer to keep. The terminal settings have been trashed, and
stty sane has restored a minimally workable set, but some
settings may not be what you expect.

If you are on a unix like system (eg Linux), and can wrap
your Tkinter application in a shell script, you should be able to 
save/restore the settings outside of Tkinter and python, ie

#! /bin/sh
saved_settings=`stty -g` i# Note backquotes, save current settings
python Tkinter-application.py # Or whatever
stty $saved_settings   i# Restore settings

Doing the save within the Tkinter application, with
(for example)  os.system(stty -g  saved_settings) and
os.system(stty `cat saved_settings`) may not work as
the setting may have been changed by Tkinter before you get
a chance to save them - I just do not know.

Just in case, I did a google search. I am not familiar
with TKinter, but a couple of articles out there imply
that rather than calling sys.exit you should be calling a
TkInter routine root.destroy. I am not sure if root is a
variable for the main window (ie you call the destroy method
on the main window) or if it has some special Tkinter meaning. 
Presumably this routine cleans things up before calling sys.exit
or an equivalent.

Charles

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


Re: Compare regular expressions

2007-04-19 Thread Charles Sanders
Thomas Dybdahl Ahle wrote:
 Hi, I'm writing a program with a large data stream to which modules can 
 connect using regular expressions.
 
 Now I'd like to not have to test all expressions every time I get a line, 
 as most of the time, one of them having a match means none of the others 
 can have so.

Not what you want, and would be a LOT of work, but if I
remember correctly (from university more than 20 years ago)
there is an algorithm that could be adapted to return a list
of all the regular expressions that match a string.

I thing the base algorithms were documented in Aho and Ullman
(The Dragon book if I remember correctly). There was one
for converting a regular expression into a Non-deterministic
Finite-state Automaton, and another for converting the NFA
to a Deterministic Finite-state Automaton. The book mentioned
that this also handles multiple regular expressions which can
be treated as the sub-expressions combined using the or operator.
Other, newer books on compiler design would probably contain
similar information in their sections on lexical analysis.

The algorithm given (if my memory is correct) only handled the
case where a true/false match/no-match result was required, but
mentioned how to generalise it to return which of several
expressions separated by or operators was matched. I think
an additional generalisation to return a set of matches rather
than one would be relatively straight-forward.

I believe these algorithms are the basis of lex/flex and
similar utilities, as well as the regular expression handling
of many languages.

Of course, I would like to emphasise that all this is based on
memory of university courses more than 20 years ago, so the
details could be wrong.

Charles


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


Re: Strange terminal behavior after quitting Tkinter application

2007-04-18 Thread Charles Sanders
Chris wrote:
 
 But does anyone know why the Tkinter program is doing this to the
 terminal in the first place? I don't want to have to tell users of my
 program that they must recover their terminal's sanity each time after
 running my program.
 

I don't know about Tkinter, but my guess would be that
it has to change the terminal settings to do what it does, and
you are quitting without restoring the settings.

Is there some Tkinter clean up that you have omitted ?

Have you ensured that the clean up runs on both normal
exit and abnormal exit (eg ^C) ?

For example, the curses library (in C) requires an
endwin() call before exit to restore settings. If this
is omitted, a stty sane is needed to set the terminal to
a semi-sensible default. On Unix and similar systems, signal
handlers are normally installed to ensure (as far as possible)
that the cleanup occurs if the process is killed. This also
applies to vi and similar programs that take total control of
the terminal.


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


Re: strange behaviour sys.argv

2007-04-17 Thread Charles Sanders
schnupfy wrote:
 
 ok, thanks for the answers. I try to hand over the 3rd part (the long
 trap) as one cmd argument. I will ask in a shell ng. Thanks again.
 
 Cheers

Should be as simple as removing the backslashes

/root/mk/services.py $HOST $SEVERITY $TRAP

should pass TRAP as a single arg

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


Re: strange behaviour sys.argv

2007-04-16 Thread Charles Sanders
Michael Hoffman wrote:
 schnupfy wrote:
 
 I am not used to python and I am wondering about this thing:
 
 This is not a Python question. It is a question about how to use bash.
 
[snip]

Michael is correct, it is a bash thing, nothing to do with python.
bash (and other *nix like shells) generally break arguments on
white space. Quoting (both single and double) overrides this with
(slightly) different rules for different shells.

  /root/mk/services.py 192.168.1.101 critical 192.168.1.101
  192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2-
  MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2-
  SMI::enterprises.789.0.2cfCannotTakeover == 1 priority == critical
  SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101 SNMP-COMMUNITY-
  MIB::snmpTrapCommunity.0 public

Assuming this has been folded and actually is one long
line (which the output confirms), you have passed the python
script seven arguments

'192.168.1.101'  (blank seperated)
'critical'   (also blank seperated)
a string extending from just after the first double quote to
just before the second, ie starting with '192.168.1.101' and
ending with '789.0.2', with the immediately following (no
white space) unquoted text 'fCannotTakeover' appended
'==' (blank seperated)
'priority
'=='
a string starting with critical, with the quoted string from
'SNMP-COMMUNITY' to 'Community.0 ' (including the blank), the
unquoted string 'public', and the null quoted string  all
appended.

  TRAP='192.168.1.101 192.168.1.101 SNMPv2-MIB::sysUpTime.0
  14:13:02:57.06 SNMPv2-MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.
  789.0.13 SNMPv2-SMI::enterprises.789.0.2cfCannotTakeover == 1
  priority == critical SNMP-COMMUNITY-MIB::snmpTrapAddress.0
  192.168.1.101 SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 public'
  HOST=$(echo $TRAP | awk '{print $1}')
  SEVERITY='critical'
  /root/mk/services.py $HOST $SEVERITY \$TRAP\

Here, the variables are expanded, and then split into
arguments on white space unless quoted. The backslashes protect
the double quotes so they are treated as normal characters, so
the $TRAP variable is also split into arguments on white space.
Quotes resulting from the substitution of $TRAP are also protected
(ie are treated as ordinary characters).

The result is

'192.168.1.101   (From $HOST)
'critical'(From $SEVERITY)
'192.168.1.101'  (Leading '' from \, rest from
   $TRAP, blank seperated)
'192.168.1.101'   (from $TRAP, blank seperated)
'SNMPv2-MIB::sysUpTime.0'
and so on for the rest of the $TARP string, splitting it at
white space. The last part of $TRAP, 'public', has a double
quote appended from the \.

Python is giving exactly what the shell has given it in both cases.

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


Re: Problem with algorithm

2007-04-13 Thread Charles Sanders
Paul Rubin wrote:
[snip]
 
 def a(n):
 if n==0:
 yield ''
 return
 for c in s:
 for r in a(n-1):
 yield c+r
 
 print list(a(3))

Of course, obvious in retrospect, recursion instead of iteration.
I have yet to completely wean myself off Fortran style thinking.

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


Re: Problem with algorithm

2007-04-12 Thread Charles Sanders
[EMAIL PROTECTED] wrote:
 On Apr 12, 10:16�pm, Jia Lu [EMAIL PROTECTED] wrote:
 Hi all.
 �I want to create a large list like:

  ~ 

 Is there any good algorithm to do this?
 
 Sure.
 test = '01'
 
 for m in test:
 for n in test:
 for o in test:
  for p in test:
 print m+n+o+p
[snip]

Forgive any silly mistakes I have made (I've been teaching
myself python for about 1 week) but there is a moderately
well known algorithm for this that extends to arbitrary
lengths of both the list of alternatives and the length
of the required output, and avoids deeply nested loops.
I know that it is no better for small and constant output
lengths, but for longer lengths or if the output length
can vary it should be better. There is a similar algorithm
if duplicates are not allowed (ie abcd ... wxyz).

My attempt at a python translation of the algorithm:

def m_from_n ( v, m ):
   
   Print all combinations of m things from v[0] ... v[n-1],
   duplicates OK. Yields a list.
   
   x = [0] * m
   while True:
 yield [ v[i] for i in x ]
 i = m - 1
 while i=0 and x[i]==len(v)-1:
   x[i] = 0
   i = i - 1
 if i = 0:
   x[i] = x[i] + 1
 else:
   return

for y in m_from_n( xyz, 2 ):
   print ''.join(y)

xx
xy
xz
yx
yy
yz
zx
zy
zz

for y in m_from_n( [0,1], 3 ):
   print y

[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]

for y in m_from_n( abcdefghijklmnopqrstuvwxyz, 4 ):
   print ''.join(y)

should more or less do what you want.

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

How to tell easy_install that a package is already installed

2007-03-21 Thread Charles Sanders
I  am not sure if this is the right forum to ask this. If it is not,
could someone pleas point me to a more appropriate newsgroup.

I am attempting to install dap.plugins.netcdf using easy_install
on HP-UX 11. As a user, I do not have access to root so have
followed the easy_install recommendation to set up a virtual
python, as described at

http://peak.telecommunity.com/DevCenter/EasyInstall#creating-a-virtual-python

and this is mostly working well. One of the dependencies, numpy
is already installed, but easy_install does not detect this, and
tries to install numpy, which fails with many compilation errors.
(numerous pointer type mismatches, undeclared functions like
rintf that do not exist on HP, ...) I could try to install numpy
myself from the tar.gz file, but this seems pointless since it is
already installed.

Is there any way to tell easy_install that numpy is installed, while
still installing any other dependencies ?

Would the best option be to just use the --no-deps option and see if
it works ?


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