# -*- coding: iso-8859-7 -*-
import sys
class RecordedError(Exception):
pass
class Struct(object):
"Each instance of this class is like a C struct."
def __init__(self, name="<Unnamed>"):
"Just save the name."
self.__name = name
def __str__(self):
"Return the name of the structure."
return self.__name
def anal(self):
"Return an analytic list of all structure variables and their values as a string."
s = ["Structure %s at: %s" % (self.__name, object.__str__(self))]
for key,val in self.__dict__.iteritems():
if key.startswith("_Struct__"): continue # Avoid private variables
s.append("%s = %s" % (key, val))
return "\n".join(s)
class ThanStub:
"This class saves a function and its arguments for a later call."
def __init__(self, fun, *args, **kw):
"Save function and arguments."
self.args = args
self.kw = kw
# self.fun = weakref.proxy(fun)
self.fun = fun
def __call__(self, *args, **kw):
"Call the function with possible extra arguments."
if len(args) > 0: args = self.args+args
else: args = self.args
if len(kw) > 0: kw.update(self.kw)
else: kw = self.kw
return self.fun(*args, **kw)
class Null:
def __init__(self, *args, **kw): pass
def __getattr__(self, name): return self
############################################################################
############################################################################
#MODULE LEVEL ROUTINES
#============================================================================
def floate(a):
try: return float(a.replace(",", "."))
except ValueError: return None
def inte(a):
try: return int(a)
except ValueError: return None
def complexe(a):
try: return complex(a.replace(",", "."))
except ValueError: return None
#===========================================================================
def _inpGen(text, fun, other=()):
"Gets a text and validates it with fun; if text is in other it is valid and it is returned."
if sys.platform == "win32":
gc = gw2d
text = "".join([gc.get(c, c) for c in text])
while 1:
s = raw_input(text)
s1 = s.strip()
if s1 in other: return s1
try: return fun(s)
except ValueError: pass
print "Illegal value. Try again"
def inpFloat(text, other=()): return _inpGen(text, lambda t: float(t.replace(",",".")), other)
def inpComplex(text,other=()): return _inpGen(text, lambda t: complex(t.replace(",",".")), other)
def inpInt(text, other=()): return _inpGen(text, int, other)
def inpText(text, other=()): return _inpGen(text, ing, other)
#===========================================================================
def xfrangec(start, end, step=1):
"Implements float xrange - which includes start and end."
start = float(start); end = float(end); step = float(step)
a = start
if step > 0:
if start > end: return
while a < end:
yield a
a += step
else:
if start < end: return
while a > end:
yield a
a += step
yield end
def frangec(start, end, step=1):
"Implements float range - which includes start and end."
return [x for x in xfrangec(start, end, step)]
def xfrange(start, end, step=1):
"Implements float xrange."
start = float(start); end = float(end); step = float(step)
a = start
if step > 0:
if start > end: return
while a < end:
yield a
a += step
else:
if start < end: return
while a > end:
yield a
a += step
def frange(start, end, step=1):
"Implements float range - which includes start and end."
return [x for x in xfrange(start, end, step)]
def iterby2(iterable):
"""Returns pairs of consecutive elements of iterable (non exclusive).
For example: by2((1, 3, 7, -5)) returns:
(1,3) then (3,7) then (7,-5)
"""
it = iter(iterable)
val1 = it.next()
for val2 in it:
yield val1, val2
val1 = val2
def iterby3(iterable):
"""Returns triples of consecutive elements of iterable (non exclusive).
For example: by3((1, 3, 7, -5, 'a')) returns:
(1,3,7) then (3,7,-5) then (7,-5,'a')
"""
it = iter(iterable)
val1 = it.next()
val2 = it.next()
for val3 in it:
yield val1, val2, val3
val1 = val2
val2 = val3
#===========================================================================
def fnum(root):
"""Returns the last integer number in a string, or zero.
For example all of the following strings return the integer 123:
"123", "a123", "123b", "a123b", "55a123b", "c55da123b", "5_123"
If no digits are found the function returns None.
This function is very slow. Thus don't use fit for many
computations."""
for i in xrange(len(root)-1, -1, -1):
if root[i].isdigit(): break
else: return None
for j in xrange(i, -1, -1):
if not root[j].isdigit(): return int(root[j+1:i+1])
return int(root[:i+1])
def configFile(confname, appdir=".thancad"):
"Returns the path of confname, placing it into appdir."
from jorpath import path
if sys.platform == "win32": f1 = "$windir"
else: f1 = "~"
f = path(f1).expand()
if f == f1: f = f.getcwd() # expand failed; use current directory as homedir
f = f / appdir
if f.exists():
if not f.isdir(): return None, f+" is not a directory."
else:
try: f.mkdir()
except OSError, why: return None, why
return f / confname, ""
#===========================================================================
def dictInvert(a):
"Inverts a dictionary; values become keys and keys become values."
b = {}
for key,val in a.iteritems():
b[val] = key
return b
def isString(t):
"Check if argument is string-like object."
try: t+""
except: return False
else: return True
#===========================================================================
#GREEK handling routines
gcw = ""
gsw = ""
from grdos import *
gw2d = dict(zip(gcw, gcd))
gw2d.update(dict(zip(gsw, gsd)))
gd2w = dict(zip(gcd, gcw))
gd2w.update(dict(zip(gsd, gsw)))
del gcw, gsw, gcd, gsd
def grwin2dos(fr):
"Convert to DOS greek."
gc = gw2d
return "".join([gc.get(c, c) for c in fr])
def grdos2win(fr):
"Convert to Windows greek."
gc = gd2w
return "".join([gc.get(c, c) for c in fr])
def prg(fr):
"Print converting to DOS greek only if we run windows."
if sys.platform == "win32":
gc = gw2d
print "".join([gc.get(c, c) for c in fr])
else:
print fr
def prints(fr):
"Print without newline converting to DOS greek only if we run windows."
if sys.platform == "win32":
gc = gw2d
sys.stdout.write("".join([gc.get(c, c) for c in fr]))
else:
sys.stdout.write(fr)
def tog(fr):
"Convert to DOS greek only if we run windows."
if sys.platform == "win32":
gc = gw2d
return "".join([gc.get(c, c) for c in fr])
else:
return fr
def togi(fr):
"Convert DOS greek only to WINDOWS greek, onlyif we run windows."
if sys.platform == "win32":
gc = gd2w
return "".join([gc.get(c, c) for c in fr])
else:
return fr
def ing(fr):
"Convert to linux greek only if we read from DOS (we run windows)."
if sys.platform == "win32":
gc = gd2w
return "".join([gc.get(c, c) for c in fr])
else:
return fr
#===========================================================================
#Unicode handling routines
import codecs
def thanUnunicode(t):
"Convert unicode to string."
if not isinstance(t, unicode): return str(t)
return thanUnunicode1(t, "replace")[0]
def thanUnicode(t):
"Convert to unicode."
if isinstance(t, unicode): return t
return thanUnicode1(t, "replace")[0]
def thanSetEncoding(enc):
"Set new encoding."
ununi = codecs.getencoder(enc) # This will potentialy cause an exception without..
uni = codecs.getdecoder(enc) # .. changing current encoding
global thanEncoding, thanUnunicode1, thanUnicode1
thanEncoding = enc
thanUnunicode1 = ununi
thanUnicode1 = uni
def thanGetEncoding():
"Return current encoding."
return thanEncoding
thanSetEncoding("iso-8859-7")
############################################################################
############################################################################
#MODULE LEVEL ROUTINES - TEST CODE
#===========================================================================
#def testFrangec():
# print "frangec"
# print "10 , 0 :", frangec(10, 0)
# print " 0 ,10 , 2 :", frangec(0, 10, 2)
# print " 0 ,10 , 3 :", frangec(0, 10, 3)
# print " 0.1,10.99, 2.7:", frangec(0.1, 10.99, 2.7)
#
# print " 0 ,10 ,-1 :", frangec(0, 10, -1)
# print "10 , 0 ,-2 :", frangec(10, 0, -2)
# print "10 , 0 ,-3 :", frangec(10, 0, -3)
# print "10.99, 0.1,-2.7:", frangec(10.99, 0.1, -2.7)
# print "frange"
# print "10 , 0 :", frange(10, 0)
# print " 0 ,10 , 2 :", frange(0, 10, 2)
# print " 0 ,10 , 3 :", frange(0, 10, 3)
# print " 0.1,10.99, 2.7:", frange(0.1, 10.99, 2.7)
#
# print " 0 ,10 ,-1 :", frange(0, 10, -1)
# print "10 , 0 ,-2 :", frange(10, 0, -2)
# print "10 , 0 ,-3 :", frange(10, 0, -3)
# print "10.99, 0.1,-2.7:", frange(10.99, 0.1, -2.7)
#===========================================================================
#def testFnum():
# ex = ("123", "a123", "123b", "a123b", "55a123b", "c55da123b", "5_123", "aaa")
# for t in ex: print t, fnum(t)
############################################################################
############################################################################
#MODULE LEVEL CODE
#---Module initialisation (This code is executed only once)---------
#===========================================================================
#if __name__ == "__main__":
# testGon()
# testFrangec()
# testFnum()
# print complexe("10")
# print complexe("ff34")
# print complexe("10j")
# print complexe("5+10j")
# print complexe(20)
# print complexe(50.220)
|