goodies.html
001| '''Goodies.
001|
001| A big collection of Goodies.
001|
001| Lambda functions:
001| KWARG (n,v,t,kw) - **kwargs extractor
001| typename (obj) - object's type name
001| makefilename (fpath,fname) - path.join(fpath,fname) if fpath else fname
001| isreallyafile (filename) - path.exists(filename) and path.isfile(filename)
001| roundup (ns,sep) - find upper bound of numbers and round up
001| rounddn (ns,sep) - find lower bound of numbers and round down
001| plural (n) - an "s" if n<>1, otherwise returns ""
001| list2str (list,delim) - combine a list: "item<delim>item<delim>item"
001| str2bytes (s) - given a hex string, return a list of bytes
001| distance (ds) - Pythagorean calculation over ds (list of numbers)
001| dot_product (a,b) - sum((a[i],b[i]))
001| comp (a,b) - replacement for cmp()
001| zstrFactory (prec) - return ZSTR() with user precision
001| estrFactory (prec) - return ESTR() with user precision
001| zstr (z) - return string of complex number (uses %.6f)
001| estr (z) - return string of complex number (uses %.6e)
001| svec (v) - return string for 3D vector
001| rot13 (ch) - ROT13 character
001| rots13 (s) - ROT13 string
001| TS () - timestamp (YYYYMMDD-hhmmss-SSSSSS)
001| UID () - a unique random-ish 64-bit number
001| UIDS () - a unique random-ish 16-digit hex string
001|
001| Functions:
001| reduce (func, list, init) - the original reduce function
001| interleave (*iters, fill='') - creates a single list
001| combine (*iters, fill='') - like ZIP but uses longest
001| powerset (iterable) - generate powerset of iterable
001|
001| divisions (start, stop, steps)
001| intervals (start, stop, interval, maxsteps)
001| marker (start, interval, steps)
001| integers (start, last)
001|
001| safediv (a, b) - safe divide; x/0 returns 0
001| safepercent (a, b) - safe percent (like safedivide but returns %)
001| str2int (str, dflt) - convert string to int (onerr: returns 0)
001| str2float (str, dflt) - convert string to float (onerr: returns 0.0)
001|
001| RandName (n) - random alpha string of length N
001| urlencode (url_text) - encode a string for a URL
001| urldecode (url_text) - decode an encoded URL
001| b64encode (cs) - Base64 Encode
001| b64decode (bs) - Base64 Decode (returns str)
001|
001| remove_quotes (s) - remove enclosing single- or double-quotes
001| add_commas (n) - insert commas into a number (return str)
001| triplets_right (s) - insert spaces every three chars from right
001| triplets_left (s) - insert spaces every three chars from left
001|
001| printlist (lst)
001| printobject (obj, showAll=False)
001|
001| stddev (data) - calculate standard deviation
001|
001| Decorators:
001| FunctionTimer (*,**) - time a function (uses FunctionTimes table)
001|
001| Classes:
001| NumberStats (iterable=None, init_value=None, window=10)
001|
001| '''
002|
003| from sys import stdout
004| from os import path
005| from time import time, perf_counter_ns
006| from datetime import datetime
007| from random import random,choice
008| from math import sqrt, fsum
009|
010|
011|
012| FunctionTimes = {'main':{}, 'subs':{}}
013|
014|
015| def FunctionTimer (channel='main'):
016| '''Decorator function for timing other functions.'''
017| if channel not in FunctionTimes:
018| FunctionTimes[channel] = {}
019|
020|
021| def function_decorator (function):
022| '''The actual decorator function.'''
023| func_name = function.__name__
024| if func_name not in FunctionTimes[channel]:
025| FunctionTimes[channel][func_name] = [0.0]
026|
027|
028| def function_wrapper (*args, **kwargs):
029| '''The timed function wrapper function.'''
030|
031| t0 = perf_counter_ns()
032| retv = function(*args, **kwargs)
033| t1 = perf_counter_ns() - t0
034| FunctionTimes[channel][func_name][0] += t1
035| FunctionTimes[channel][func_name].append(t1)
036|
037|
038| return retv
039|
040|
041| return function_wrapper
042|
043|
044| return function_decorator
045|
046| FunctionTimer.data = FunctionTimes
047|
048|
049|
050| class NumberStats:
051| '''List of numbers with tally functions.'''
052|
053| def __init__ (self, iterable=None, init_value=None, window=10):
054| self.window = [0]*window
055| self._total = 0 if init_value is None else init_value
056| self._count = 0 if init_value is None else 1
057| self._minimum = init_value
058| self._maximum = init_value
059|
060|
061| if init_value is not None:
062| self._rolling_window(init_value)
063|
064|
065| if iterable is not None:
066| self *= iterable
067|
068| @property
069| def total (self): return self._total
070|
071| @property
072| def count (self): return self._count
073|
074| @property
075| def minimum (self): return self._minimum
076|
077| @property
078| def maximum (self): return self._maximum
079|
080| @property
081| def average (self):
082| return (self._total/self._count) if self._count else 0
083|
084| @property
085| def rolling_average (self):
086| return sum(self.window)/len(self.window)
087|
088| def __repr__ (self):
089| return str(self._total)
090|
091| def __len__ (self):
092| return self._count
093|
094| def __iadd__ (self, value):
095| if isinstance(value, int) or isinstance(value, float):
096| self._total += value
097| self._count += 1
098| self._check_min_max(value)
099| self._rolling_window(value)
100| return self
101| raise ValueError(f'Not a number: "{value}"')
102|
103| def __imul__ (self, iterable):
104| for value in iterable:
105| if isinstance(value, int) or isinstance(value, float):
106| self._total += value
107| self._count += 1
108| self._check_min_max(value)
109| self._rolling_window(value)
110| continue
111| raise ValueError(f'Not a number: "{value}"')
112| return self
113|
114| def _rolling_window (self, value):
115| self.window.pop(0)
116| self.window.append(value)
117|
118| def _check_min_max (self, value):
119| if (self._minimum is None) or (value < self._minimum):
120| self._minimum = value
121| if (self._maximum is None) or (self._maximum < value):
122| self._maximum = value
123|
124|
125| def stddev (data, file=stdout):
126| '''Standard Deviation. Takes a list of Fraction objects [from fractions import Fraction].'''
127| if len(data) == 0:
128| return 0.0
129| count = len(data)
130| print(f'{count = }', file=file)
131| total = fsum(data)
132| print(f'{total = }', file=file)
133| mean = total / float(count)
134| print(f'max = {max(data)}', file=file)
135| print(f'avg = {mean}', file=file)
136| print(f'min = {min(data)}', file=file)
137| print(f'range = {max(data)-min(data)}', file=file)
138| diffs = [(float(d-mean)*float(d-mean)) for d in data]
139| difftot = fsum(diffs)
140| print(f'{difftot = }', file=file)
141| dmean = difftot / float(count)
142| print(f'{dmean = }', file=file)
143| stdv = sqrt(dmean)
144| print()
145| print(f'stddev = {stdv}', file=file)
146| print()
147| return stdv
148|
149|
150|
151| '''Return a keyword argument or a default if keyword not found.'''
152| KWARG = lambda name,dflt,typ,args: typ(args[name]) if name in args else dflt
153|
154|
155| '''Return an object's typename.'''
156| typename = lambda obj: type(obj).__name__
157|
158|
159| '''Join a path and filename in the usual way.'''
160| makefilename = lambda fp,fn: path.join(fp,fn) if fp else fn
161|
162|
163| '''path.exists(filename) and path.isfile(filename)'''
164| isreallyafile = lambda fn: True if (path.exists(fn) and path.isfile(fn)) else False
165|
166|
167| '''Find max/min of a list of numbers and round up or down.'''
168| roundup = lambda ns,sep: int(((max(ns)//sep)+1)*sep)
169| rounddn = lambda ns,sep: int(((min(ns)//sep)+0)*sep)
170|
171|
172| '''A 's' unless n=1.'''
173| plural = lambda n: '' if n == 1 else 's'
174|
175|
176| '''Given a list, return a nice string.'''
177| list2str = lambda xs,delim: delim.join(str(x) for x in xs)
178|
179|
180| '''Given a hex string, return a list of bytes values.'''
181| str2bytes = lambda xs:[int(xs[ix:ix+2],16) for ix in range(0,len(xs),2)]
182|
183|
184| '''Return a Pythagorean distance calculation on a vector of coordinates.'''
185| distance = lambda ds: sqrt(sum([float(d)*float(d) for d in ds]))
186|
187|
188| '''Return the dot product of two vectors.'''
189| dot_product = lambda a,b: sum([float(x)*float(y) for x,y in zip(a,b)])
190|
191|
192| '''Compare two numerical values.'''
193| comp = lambda a,b: ((b < a) - (a < b))
194|
195|
196| '''Pretty Print a complex number.'''
197| zstrFactory = lambda prec: lambda z:('(%+.*f, %+.*fi)' % (prec,z.real,prec,z.imag))
198| estrFactory = lambda prec: lambda z:('(%+.*e, %+.*ei)' % (prec,z.real,prec,z.imag))
199|
200| zstr = lambda z: ('(%+.6f, %+.6fi)' % (z.real,z.imag))
201| estr = lambda z: ('(%+.6e, %+.6ei)' % (z.real,z.imag))
202|
203| svec = lambda v:('<%+.3f,%+.3f,%+.3f>' % (v[0], v[1], v[2]))
204|
205|
206| '''ROT13 character function.'''
207| rot13 = lambda c:chr(ord(c)+13) if (ord('A') <= ord(c) <= ord('M')) or (ord('a') <= ord(c) <= ord('m')) else(chr(ord(c)-13) if (ord('N') <= ord(c) <= ord('Z')) or (ord('n') <= ord(c) <= ord('z')) else(chr(ord(c)+ 5) if (ord('0') <= ord(c) <= ord('4')) else(chr(ord(c)- 5) if (ord('5') <= ord(c) <= ord('9')) else c)))
208|
209|
210| '''ROT13 string function.'''
211| rots13 = lambda s: ''.join([rot13(c) for c in s])
212|
213|
214| '''Return a timestamp.'''
215| TS = lambda: datetime.now().strftime('%Y%m%d-%H%M%S-%f')
216|
217|
218| '''Return a unique random-ish 64-bit UID number.'''
219| UID = lambda: (int(1000*time()) * int((2**22)*random()))
220| UIDS = lambda: ('%016x' % UID())
221|
222|
223|
224| def reduce (function, iterable, initializer=None):
225| '''The original reduce function.'''
226| it = iter(iterable)
227| if initializer is None:
228| try:
229| initializer = next(it)
230| except StopIteration:
231| raise TypeError('Empty sequence with no initial value')
232| accum = initializer
233| for x in it:
234| accum = function(accum, x)
235| return accum
236|
237|
238| def interleave (*iterargs, only_all=False):
239| '''Alternates members of each list.'''
240| queues = [list(x) for x in iterargs]
241|
242|
243| while 0 < sum([len(q) for q in queues]):
244| if only_all:
245|
246| for que in queues:
247| if len(que) == 0:
248| return
249|
250| for que in queues:
251| if 0 < len(que):
252| yield que.pop(0)
253|
254|
255| def combine (*iterargs, fill=None):
256| '''Like ZIP but uses longest input.'''
257| its = [iter(a) for a in iterargs]
258| flags = [1]*len(its)
259| while True:
260| out = []
261| for ix,it in enumerate(its):
262| try:
263| v = next(it)
264| except StopIteration:
265| v = fill
266| flags[ix] = 0
267| finally:
268| out.append(v)
269| if sum(flags) == 0:
270| break
271| yield tuple(out)
272|
273|
274| def powerset (iterable) -> list:
275| '''Generate powerset of iterable.'''
276| from itertools import chain, combinations
277|
278| ii = list(iterable)
279| return list(chain.from_iterable(list(combinations(ii,r)) for r in range(len(ii)+1)))
280|
281|
282| def divisions (start, stop, divs):
283| '''From START to STOP in DIVS steps. (Returns divs+1 numbers.)'''
284| s0 = float(start)
285| s1 = float(stop)
286| sx = int(divs)
287| assert (s0 < s1)
288| assert (0 < sx)
289| interval = (s1 - s0) / float(sx)
290| for n in range(sx+1):
291| yield s0+(interval*n)
292|
293| def intervals (start, stop, interval=1, maxsteps=0):
294| '''From START to STOP by INTERVALs.'''
295| s0 = float(start)
296| s1 = float(stop)
297| si = float(interval)
298| assert (s0 < s1)
299| assert (0 < si)
300| sx = 0
301| while True:
302| yield s0
303| s0 += si
304| if s1 < s0:
305| return 0
306| sx += 1
307| if 0 < maxsteps < sx:
308| return sx
309|
310| def marker (start=0, interval=1, steps:int=0, dtype=float):
311| '''From START by INTERVALs for STEPS. Runs forever if STEPS not set.'''
312| s0 = dtype(start)
313| si = dtype(interval)
314| assert (dtype(0) < si)
315| assert (0 <= steps)
316| sx = 0
317| while True:
318| yield s0
319| s0 += si
320| sx += 1
321| if 0 < steps < sx:
322| return sx
323|
324|
325| def integers (start=0, last=None):
326| '''Spit out integers forever.'''
327| n = start
328| while True:
329| yield n
330| if last and (last <= n):
331| return n
332| n +=1
333|
334|
335| def safediv (a, b) -> float:
336| '''Division with exception trapping. Returns zero on exception.'''
337| try:
338| return float((float(a) / float(b)))
339| except:
340| return float(0)
341|
342| def safepercent (a, b) -> float:
343| '''Like SAFEDIV but times 100. Returns zero on exception.'''
344| try:
345| return float(float(100) * (float(a) / float(b)))
346| except:
347| return float(0)
348|
349|
350| def str2int (str_int, dflt=0) -> int:
351| '''Exception-free convert string to int.'''
352| try:
353| return int(str_int)
354| except:
355| return int(dflt)
356|
357| def str2float (str_float, dflt=0) -> float:
358| '''Exception-free convert string to float.'''
359| try:
360| return float(str_float)
361| except:
362| return float(dflt)
363|
364|
365| def RandName (n, charset='abcdefghijklmnopqrstuvwxyz') -> str:
366| '''Return a random alpha string of length N.'''
367| cs = [choice(charset) for _ in range(n)]
368| return ''.join(cs)
369|
370|
371| def urlencode (url:str) -> str:
372| '''Convert a plain string into a encoded URL.'''
373| from urllib.parse import quote_plus
374| return quote_plus(url)
375|
376| def urldecode (url:str) -> str:
377| '''Convert an encoded URL into a plain string.'''
378| from urllib.parse import unquote_plus
379| return unquote_plus(url)
380|
381|
382| def b64encode (cs:str) -> bytes:
383| '''Base64 Encode'''
384| from base64 import encodebytes
385| bs = bytes(cs, encoding='utf-8')
386| return encodebytes(bs)
387|
388| def b64decode (bs:bytes) -> str:
389| '''Base64 Decode'''
390| from base64 import decodebytes
391| return str(decodebytes(bs), encoding='utf-8')
392|
393|
394|
395| def remove_quotes (s):
396| '''Remove single- or double- quotes surrounding a string.'''
397|
398|
399| if s.startswith('"') and s.endswith('"'):
400| return s[1:-1]
401|
402|
403| if s.startswith("'") and s.endswith("'"):
404| return s[1:-1]
405|
406|
407| return s
408|
409|
410| def add_commas (n) -> str:
411| '''Insert commas into a number.'''
412| s = str(n)
413| a = []
414| for ix,c in enumerate(reversed(s)):
415| if (0 < ix) and (0 == (ix % 3)):
416| a.append(',')
417| a.append(c)
418| return ''.join(reversed(a))
419|
420|
421| def triplets_right (s:str, group=3, delimiter=' ') -> str:
422| '''Insert delimiter into a string every group characters (starting from right).'''
423| r = list(reversed(s))
424| t = [''.join(r[ix:ix+group]) for ix in range(0, len(r)+1, group)]
425| if len(t[-1]) == 0: t.pop()
426| u = delimiter.join(t)
427| return ''.join(reversed(u))
428|
429|
430| def triplets_left (s:str, group=3, delimiter=' ') -> str:
431| '''Insert delimiter into a string every group characters (starting from left).'''
432| t = [s[ix:ix+group] for ix in range(0, len(s)+1, group)]
433| return delimiter.join(t)
434|
435|
436|
437| def printlist (lst):
438| ''' Print any List object. '''
439| for ix, obj in enumerate(lst):
440| print('[%d] %s' % (1+ix, str(obj)))
441|
442|
443| def printobject (obj, showAll=False):
444| ''' Print Object Properties. '''
445| f = lambda s: showAll or (s[0:2] != '__')
446| props = [prop for prop in list(dir(obj)) if f(prop)]
447| for ix, prop in enumerate(props):
448| print('[%d] %s' % (1+ix, str(prop)))
449|
450|
451|
452| '''eof'''
453|