GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Python-CodeBase-Tools/MPSSBaseTools.py at master · MPSystemsServices/Python-CodeBase-Tools Expand file tree/ Copy pathMPSSBaseTools.pyMore file actions 2782 lines (2485 loc) · 101 KB / Copy pathMPSSBaseTools.pyFile metadata and controls2782 lines (2485 loc) · 101 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 # Copyright (C) 2010-2018 by M-P Systems Services, Inc., # PMB 136, 1631 NE Broadway, Portland, OR 97232. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General # Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <https://www.gnu.org/licenses/> """ MPSS Basic Utility functions, many copied over from VFP MPSSLib.PRG, some based on VFP functions or commands Created Nov. 8, 2010. JSH. """ # 8/30/2011 JMc added FSacquire, thispath, getconfig # 10/06/2011 JMc added get # 10/26/2011 JSH mod to getconfig parameters. # 03/18/2012 JSH added MPlocal_except_handler # 08/12/2012 JSH added named parm to HexToString. # 11/15/2012 JMc 1) fixed WEEK() so it would work. 2) added sanitizeHtml() # 3/29/2016 JMc Added NamedTuple (with defaults) # 10/15/2018 JSH Modified for Python 3.x compatibility from __future__ import print_function import collections import random import os import fnmatch import traceback import time import datetime from dateutil import parser import sys import math import glob import re import json import pywintypes import calendar import shutil from win32com.server.exception import COMException import win32con import win32api from functools import wraps import tempfile if sys.version_info[0] <= 2: _ver3x = False from BeautifulSoup import BeautifulSoup, Comment import _winreg as xWinReg else: _ver3x = True from bs4 import BeautifulSoup, Comment import winreg as xWinReg try: from validate import Validator except ImportError: Validator = False print('### Unable to import configobj. Please easy_install configobj') gcNonPrintables = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11" + \ "\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F" gxNonPrintables = dict() for c in gcNonPrintables: gxNonPrintables[ord(c)] = None gxDateRangeTypes = {"LMONTH": "Previous Month", "LWEEK": "Previous Week", "LQUARTER": "Previous Quarter", "LYEAR": "Previous Year", "YTD": "Year to Date", "MTD": "Month to Date", "QTD": "Quarter to Date", "DATERANGE": "Custom Date Range"} gbIsRandomized = False gcLastErrorMessage = "" cMonths = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC" gxMonthList = cMonths.split(",") gxConversionFactors = {"LB2KG": 0.453592, "KG2LB": 2.20462, "CM2IN": 0.3937008, "IN2CM": 2.54, "IN2MT": 0.0254, "FT2MT": 0.3048, "MT2FT": 3.28084, "CF2CM": 0.0283168, "MT2IN": 39.3701, "CM2CF": 35.3147, "IN2FT": 0.083333, "FT2IN": 12.0, "MT2CM": 100.0, "CM2MT": 0.010, "LB2LB": 1.0, "KG2KG": 1.0, "CM2CM": 1.0, "IN2IN": 1.0, "FT2FT": 1.0, "MT2MT": 1.0, "CF2CF": 1.0} gxHTMLCodes = { ">": ">", "<": "<", "&": "&", '"': """, "\\": "\", "/": "/", "~": "˜", "^": "ˆ"} gxHTMLSimpleCodes = { ">": ">", "<": "<", "&": "&", '"': """, "\\": "\"} # MIME Types per http://filext.com/faq/office_mime_types.php gxMIMEtypes = {"DOC": "application/msword", "DOT": "application/msword", "DOCX": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "DOTX": "application/vnd.openxmlformats-officedocument.wordprocessingml.template", "DOCM": "application/vnd.ms-word.document.macroEnabled.12", "DOTM": "application/vnd.ms-word.template.macroEnabled.12", "XLS": "application/vnd.ms-excel", "XLT": "application/vnd.ms-excel", "XLA": "application/vnd.ms-excel", "XLSX": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "XLTX": "application/vnd.openxmlformats-officedocument.spreadsheetml.template", "XLSM": "application/vnd.ms-excel.sheet.macroEnabled.12", "XLTM": "application/vnd.ms-excel.template.macroEnabled.12", "XLAM": "application/vnd.ms-excel.addin.macroEnabled.12", "XLSB": "application/vnd.ms-excel.sheet.binary.macroEnabled.12", "PPT": "application/vnd.ms-powerpoint", "POT": "application/vnd.ms-powerpoint", "PPS": "application/vnd.ms-powerpoint", "PPA": "application/vnd.ms-powerpoint", "PPTX": "application/vnd.openxmlformats-officedocument.presentationml.presentation", "POTX": "application/vnd.openxmlformats-officedocument.presentationml.template", "PPSX": "application/vnd.openxmlformats-officedocument.presentationml.slideshow", "PPAM": "application/vnd.ms-powerpoint.addin.macroEnabled.12", "PPTM": "application/vnd.ms-powerpoint.presentation.macroEnabled.12", "POTM": "application/vnd.ms-powerpoint.template.macroEnabled.12", "PPSM": "application/vnd.ms-powerpoint.slideshow.macroEnabled.12", "TXT": "text/plain", "XML": "text/xml", "PDF": "application/pdf", "CSV": "application/vnd.ms_excel", "RFQ": "text/xml"} # More constants used by functions below. Evaluate just once when this module is loaded. allChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" passChars = "ABCDEFHJKLMNPQRSTUVWXYZ23456789" gcErrorFilePath = "c:\\temp" ############### # this copy&pasted from configtool. Remove when getconfig in websession.py and purgeCmd.py use configtools ############### if Validator: from configobj import ConfigObj, flatten_errors vdt = Validator() def error_list(self, copy=False): """ Validate using vdt :copy: option to copy all defaults into current object :return: None if missing, False if verified, string of errors if not validated """ if not self.configspec: return errors = list() ok = self.validate(vdt, copy=copy) # converts to correct type ( integer, list) if ok is not True: if not ok: errors.append('no value present') for (section_list, key, _) in flatten_errors(self, ok): if key is not None: errors.append(' ## The "%s" key in the section "%s" failed validation' % (key, ', '.join(section_list))) else: errors.append(' ## The following section was missing:%s ' % ', '.join(section_list)) return errors return False def add(self, other): """ allow ConfigObj + ConfigObj structure to create new configs :param other: Other ConfigObj item :return: new (unless error, then old) """ if not other: return self new = ConfigObj(self,configspec=self.configspec) custom = ConfigObj(other) # allows either filename or dict new.merge( custom) errors = self.errors() if errors: print('###### %s in the below folder failed validation, ignored. #####' % other) for e in errors: print(e) return self return new ConfigObj.__add__ = add ConfigObj.errors = error_list if _ver3x: def bytes2str(xbytes): """ Transforms an ASCII byte string into unicode :param xbytes: :return: """ return None else: def bytes2str(xbytes): return xbytes ########################################################################################## # Cleans up HTML to get rid of possible dangerous codes or disruptive codes when we are # importing HTML into a formated text entry screen in a browser. def sanitizeHtml(value): rjs = r'[\s]*(&#x.{1,7})?'.join(list('javascript:')) rvb = r'[\s]*(&#x.{1,7})?'.join(list('vbscript:')) re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE) validTags = 'p i strong b u a h1 h2 h3 h4 h5 h6 blockquote br ul ol li span sup sub '\ 'strike div font hr'.split() validAttrs = 'href src width height style align face size color'.split() soup = BeautifulSoup(value) for comment in soup.findAll(text=lambda text: isinstance(text, Comment)): # Get rid of comments comment.extract() newoutput = soup.renderContents() while 1: # this will filter out tags in the text attempting to bypass normal filters oldoutput = newoutput soup = BeautifulSoup(newoutput) for tag in soup.findAll(True): if tag.name not in validTags: tag.hidden = True attrs = tag.attrs tag.attrs = [] for attr, val in attrs: if attr in validAttrs: val = re_scripts.sub('', val) # Remove scripts (vbs & js) tag.attrs.append((attr, val)) newoutput = soup.renderContents() if oldoutput == newoutput: break return soup.renderContents().decode('utf-8').encode('ascii', 'xmlcharrefreplace') def findAllFiles(cDirPath, cSkel="", cExcl=""): """ Finds all files matching the standard OS file wildcard pattern in cSkel and returns them in a list of fully qualified path names. :param cDirPath: :param cSkel: Include '?' or '*' to match multiple file names. Do NOT include the path, just the file name. :param cExcl: Reverse of cSkel -- exclude files with matching this wild-card file-name string. :return: List of matching files or None on error. List may be empty if there aren't any files there. """ if not os.path.exists(cDirPath): return None xRet = list() xGen = os.walk(cDirPath) for xG in xGen: cPath = xG[0] for cF in xG[2]: if cExcl: if fnmatch.fnmatch(cF, cExcl): continue if cSkel: if not fnmatch.fnmatch(cF, cSkel): continue xRet.append(os.path.join(cPath, cF)) return xRet def getTempFileName(ext="tmp"): """ Returns a fully qualified path name for a temporary file that can be used as needed. The file will NOT be created. That is the responsibility of the calling program. It will NOT be deleted automatically either. :param ext: Pass an extension if that will be important, otherwise the extension .TMP will be used :return: The file name, or "" on error """ cFileName = "" cPath = tempfile.gettempdir() cBase = strRand(10) + "." + ext if cPath: cFileName = os.path.join(cPath, cBase) return cFileName def FSacquire(name, isdir=True, root=False, starting=None): '''Find a directory or file here or higher in the directory structure. Returns file/folder name or an empty string isdir: Must be a folder if True(default), otherwise must be a file root: Allow it to be found at the root of the drive (default=False) starting: specify starting directory explicitly # added JMc 9/12/12 ''' # JMc 8/30/2011 if isdir: test = os.path.isdir else: test = os.path.isfile fn = '' testpath = starting and os.path.abspath(starting) or os.getcwd() # print "IN FSACQUIRE:", testpath while True: testname = os.path.join(testpath, name) testpath, lastdir = os.path.split(testpath) atroot = not bool(lastdir) if not root and atroot: # print "FOUND AT ROOT: BAD lastdir=", lastdir, "testpath=", testpath break # found at root not allowed # print "TESTING FOR: ", testname if test(testname): fn = testname break if atroot: break return fn def isDigits(lpcStr, bAllowSpace=False): """ examines every character in lpcStr and returns True if all are in the range from 0 to 9, else False :param lpcStr: String to test :param bAllowSpace: pass True if a ' ' char is OK. :return: See above """ cValid = "0123456789" if bAllowSpace: cValid += " " for c in lpcStr: if c not in cValid: return False return True def convertUnits(cConvCode="", nFromNumber=0.0): """ Converts the nFromNumber (converted to float if necessary) into the specified output value with units conversion: :param cConvCode: Specifies the from and to units: LB2KG = Pounds to Kilograms: specify nFromNumber in pounds. KG2LB = Kilograms to Pounds: specify nFromNumber in kilograms CM2IN = Centimeters to Inches: specify nFromNumber in centimeters IN2CM = Inches to Centimeters: specify nFromNumber in inches IN2MT = Inches to Meters: specify from Number in inches FT2MT = Feet to Meters: specify nFromNumber in Feet MT2FT = Meters to Feet: specify nFromNumber in Meters CF2CM = Cubic Feet to Cubic Meters: specify nFromNumber in Cubic Feet CM2CF = Cubic Meters to Cubic Feet: specify nFromNumber in Cubic Meters MT2IN = Meters to Inches: specify nFromNumber in Meters IN2FT = Inches to Feet: specify nFromNumber in Inches FT2IN = Feet to Inches: specify nFromNumber in Feet MT2CM = Meters to Centimeters: specify nFromNumber in Meters CM2MT = Centimeters to Meters: specify nFromNumber in Centimeters Identities are also supported: CM2CM, IN2IN, FT2FT, CF2CF, MT2MT, LB2LB, KT2KG :param nFromNumber: The value you are converting FROM, see above. :return: the converted value or None on error. """ global gxConversionFactors nFactor = gxConversionFactors.get(cConvCode, None) if nFactor is None: return None else: return nFromNumber * nFactor def IsValidNumber(lpcStr, bForceInt=False): """ Pass any string that purports to be a representation of a number (like a value passed back by a web page form). Returns a float or an int consisting of the numeric value (or None if the value is not a valid number). A non-string value will trigger an error, except for None, which returns None as of Oct. 10, 2013. """ lnReturn = 0 if lpcStr is None: lnReturn = None else: if lpcStr == "": lnReturn = 0 else: if "." in lpcStr: # Assume they want a floating point value... try: lnReturn = float(lpcStr) except: lnReturn = None if bForceInt and lnReturn is not None: lnReturn = int(lnReturn) else: try: lnReturn = int(lpcStr) except: lnReturn = None return lnReturn def deleteByAge(cSkel, nDays): """ Pass a file name skeleton (fully qualified path name) which may or may not match some files in the specified directory. Any matching files older than nDays in age will be deleted. Uses glob() for the file matching so ? and * are recognized in the skeleton. Returns the number of files deleted. Does not raise an error if no matching files are found, just returns 0. """ lnReturn = 0 xFiles = glob.glob(cSkel) dToday = datetime.date.today() dTest = dToday - datetime.timedelta(days=nDays) cPath, cFile = os.path.split(cSkel) if len(xFiles) > 0: for cF in xFiles: dDate = datetime.date.fromtimestamp(os.stat(cF).st_mtime) if dDate < dTest: try: os.remove(cF) lnReturn += 1 except: pass # Nothing to be done return lnReturn def isDateBetween(tTest, tFrom, tTo): """ Simple test of whether a datetime or date value tTest is between the datetime or date values of tFrom and tTo, inclusive. """ if isinstance(tTest, datetime.date): tTest = datetime.datetime(tTest.year, tTest.month, tTest.day) if isinstance(tFrom, datetime.date): tFrom = datetime.datetime(tFrom.year, tFrom.month, tFrom.day) if isinstance(tTo, datetime.date): tTo = datetime.datetime(tTo.year, tTo.month, tTo.day) dDiff1 = tTest - tFrom dDiff2 = tTo - tTest nDiff1 = dDiff1.days nDiff2 = dDiff2.days bReturn = True if nDiff1 < 0: bReturn = False if nDiff2 < 0: bReturn = False return bReturn def CTOD(cDateString, cPattern="mm/dd/yy"): """ Pass a simple date string, and this returns a Python datetime.date() value representing the string. This is like the VFP CTOD() function. The difference is that in VFP, the way the date is parsed is based on the setting of SET DATE TO, which has values like mdy or dmy, etc. In this version, if you are starting with a non-US type date string, you'll need to pass the cPattern value where mm == the month number, yy = the year number, and dd = the day number separated by delimiters (required). Changed 08/26/2015 by addition of accepting the Evos/MPSS standard codes for dates: MDY, MDYY, DMY, DMYY, DMMY, and YYMD See FormatDateString() for details on their meaning. JSH. """ global gxMonthList cDateString = cDateString.strip() cPattern = cPattern.strip() if len(cPattern) == 3 or len(cPattern) == 4: if cPattern == "MDY": cPattern = "mm-dd-yy" elif cPattern == "MDYY": cPattern = "mm-dd-yyyy" elif cPattern == "DMY": cPattern = "dd-mm-yy" elif cPattern == "DMYY": cPattern = "dd-mm-yyyy" elif cPattern == "DMMY": cPattern = "dd-mmm-yyyy" else: cPattern = "INVALID" cDateString = cDateString.replace("/", "-") cDateString = cDateString.replace("\\", "-") cDateString = cDateString.replace(".", "-") cDateString = cDateString.replace(" ", "-") cPattern = cPattern.replace("/", "-") cPattern = cPattern.replace("\\", "-") cPattern = cPattern.replace(".", "-") cPattern = cPattern.upper() if RIGHT(cPattern, 3) == "-YY": # handle the case where the pattern specifies a 2-digit year # but the actual date string has a 4-digit year cTestYear = RIGHT(cDateString, 4) try: nTestYear = int(cTestYear) except: nTestYear = 0 if isBetween(nTestYear, 1800, 2500): cPattern += "YY" # Add yy to support 4-digit year. nPatLen = len(cPattern) cDateString = cDateString[0: nPatLen] # trim off any possible time info fields. cDelim = "-" if cDelim not in cDateString: return None # Invalid format if cDelim not in cPattern: return None # also invalid xPat = cPattern.split(cDelim) xParts = cDateString.split(cDelim) if len(xPat) != 3: return None # also invalid if len(xParts) != 3: return None # also invalid nYear = 0 nMonth = 0 nDay = 0 for kk in range(0, 3): cPat = xPat[kk].upper() cElem = xParts[kk] cElem = cElem.strip() if cElem == "": return None # Any empty spot in the date string results in a null date. if cPat == "MMM": try: nMonth = gxMonthList.index(cElem.upper()) except: nMonth = -1 nMonth += 1 # 0 if an error occurred. elif "M" in cPat: nMonth = int(cElem) elif "Y" in cPat: nYear = int(cElem) if cPat == "YY" and nYear < 100: nYear += 2000 # Added this to correct the 2-digit year stuff. JSH. 09/25/2015. elif "D" in cPat: nDay = int(cElem) if (nYear == 0) or (nMonth == 0) or (nDay == 0): return None # Again not valid return datetime.date(nYear, nMonth, nDay) def cleanUnicodeString(cSource): """ Applies transformations to strings where it may be possible to have higher-order unicode values embedded in a standard ascii or UTF8 string. :param cSource: Source string to be transformed. Must be a string or a error will be triggered. :return: Clean-up string, or None on error condition NOTE: May not work reliably when utf-16 source is passed or 2 or 3 byte unicode characters are embedded in a UTF-8 string. """ if isstr(cSource): # Added this 01/03/2013. JSH. if isinstance(cSource, unicode): cSource = cSource.encode("utf-8", "replace") else: cSource = unicode(cSource, "utf-8", "replace") cReturn = cSource.encode("ascii", "replace") cReturn = cReturn.replace(u"\x93", u'"') cReturn = cReturn.replace(u"\x94", u'"') else: raise ValueError("Must be a string") return cReturn def toAscii(cSrc): """ Brute force removal of non-ascii characters from a string. Returns a standard string, NOT unicode. :param cSrc: :return: standard ascii string. Always works, regardless of the input string, but will lose all upper range special characters. New 10/07/2016. JSH. """ xList = list() for i, c in enumerate(cSrc): if ord(c) <= 128: xList.append(str(c)) else: xList.append("") return "".join(xList) def rawReplace(cSource, cOld, cNew, bMakeAscii=False): xList = list() for i, c in enumerate(cSource): if bMakeAscii: if ord(c) > 128: cNew = "" if c == cOld: xList.append(str(cNew)) else: xList.append(c) return "".join(xList) def safeHTMLcoding(lcSource, bFixNewLines=False, bSimple=False): """ Replaces unsafe characters in a text string with their HTML codes to allow strings to be embedded more easily in javascript variables passed from the page engine. Fixed this function 04/20/2017. JSH. """ cRet = toAscii(lcSource) xDict = gxHTMLSimpleCodes if bSimple else gxHTMLCodes for cChar, cCode in xDict.items(): cTemp1 = cChar cTemp2 = cCode cRet = rawReplace(cRet, cTemp1, cTemp2, True) if bFixNewLines: cRet = cRet.replace("\r\n", "<br>") # Convert the DOS EOL markers cRet = cRet.replace("\n", "<br>") # If UNIX EOL markers are left, convert them. return cRet def TTOD(tTheDT): """ Like the VFP TTOD() function, converts a datetime type value to a date type value. """ tReturn = None try: tReturn = datetime.date(tTheDT.year, tTheDT.month, tTheDT.day) except: tReturn = None return tReturn def DTOT(dTheDate): """ Quick conversion utility to convert a Python datetime.date() object to a datetime.datetime() object, like the corresponding VFP DTOT() function. Returns the datetime value or None on error """ tReturn = None try: tReturn = datetime.datetime(dTheDate.year, dTheDate.month, dTheDate.day, 0, 0, 0, 0) except: tReturn = None # all we can do return tReturn def fDiv(nDividend, nDivisor): """ In Python 2.x the division of two integers results in an integer result. If instead you want a floating result with the appropriate fractional part, you have to convert one of the values to float first. This function simplifies that process and in addition protects against divide by zero errors. In DBZ situations, it returns 0.0. Always returns a float value. """ if nDivisor == 0: return 0.0 return float(nDividend) / float(nDivisor) def CTOTX(cDateStr="", cDateFmat=None): """ Addresses some of the shortcomings of CTOT for parsing datetimes in the form of 08/01/2018 10:30AM which CTOT struggles with. Uses the Python dateutil object to do the parsing :param cDateStr: In one of many possible formats. dateutil parser is clever about this :param cDateFmat: MDY, MDYY, YYDM, YYMD, DMY, DMYY, YDM, YMD :return: datetime.datetime object or None on error Added 03/01/2018. JSH. """ if not cDateStr or not isstr(cDateStr): return None if not cDateFmat: cDateFmat = "MDY" # US standard as default. bDayFirst = False bYearFirst = False tRet = None if cDateFmat[0: 1] == "Y": bYearFirst = True if "DM" in cDateFmat: bDayFirst = True try: tRet = parser.parse(cDateStr, dayfirst=bDayFirst, yearfirst=bYearFirst) except: tRet = None return tRet def CTOT(cDateStr, cDateFmat=None): """ The reverse of the TTOC() function below. It auto-detects which of the datetime formats (not including the one which is "time only") has been passed, and interprets it accordingly. If it doesn't recognize the format, or the date/time is otherwise not valid, returns None, otherwise returns a datetime.datetime value. 08/21/2014 - Added a parser for MercuryGate XML date/time values of the form: 08/21/2014 10:23 """ if not isstr(cDateStr): return None cDateStr = cDateStr.upper() tDateTime = None cYr = "" cMo = "" cSe = "" cHr = "" cMi = "" cMo = "" cDa = "" cFrac = "" cDate = "" cTime = "" nHr = 0 cPM = "" if ("T" in cDateStr) and ("-" in cDateStr) and (":" in cDateStr): # Type 3 x = cDateStr.split("T") if len(x) == 2: cDate, cTime = x x = cDate.split("-") if len(x) == 3: cYr, cMo, cDa = x x = cTime.split(":") if len(x) == 3: cHr, cMi, cSe = x try: tDateTime = datetime.datetime(int(cYr), int(cMo), int(cDa), int(cHr), int(cMi), int(cSe)) except: tDateTime = None elif (" " in cDateStr) and ("/" in cDateStr) and (("P" in cDateStr) or ("A" in cDateStr)): # Type 0 x = cDateStr.split(" ") if len(x) == 3: cDate, cTime, cPM = x cDate = cDate.replace("-", "/") cDate = cDate.replace(".", "/") x = cDate.split("/") if len(x) == 3: cMo, cDa, cYr = x if len(cYr) == 2: if cYr.isdigit(): if int(cYr) > 55: cYr = "19" + cYr else: cYr = "20" + cYr x = cTime.split(":") if len(x) == 3: cHr, cMi, cSe = x nHr = 0 if cHr.isdigit(): nHr = int(cHr) if ("P" in cPM) and (nHr < 12): nHr = nHr + 12 elif ("A" in cPM) and (nHr == 12): nHr = 0 try: tDateTime = datetime.datetime(int(cYr), int(cMo), int(cDa), nHr, int(cMi), int(cSe)) except: tDateTime = None elif (len(cDateStr) == 16) and (":" in cDateStr) and ("/" in cDateStr) and (" " in cDateStr): # MercuryGate XML date/time representation x = cDateStr.split(" ") if len(x) == 2: cDate, cTime = x if cDate: x = cDate.split("/") if len(x) == 3: cMo, cDa, cYr = x if cTime: x = cTime.split(":") if len(x) == 2: cHr, cMi = x cSe = "0" try: tDateTime = datetime.datetime(int(cYr), int(cMo), int(cDa), int(cHr), int(cMi), int(cSe)) except: tDateTime = None elif (len(cDateStr) == 20) and (":" in cDateStr): # Type 9 cYr = cDateStr[0:4] cMo = cDateStr[4:6] cDa = cDateStr[6:8] cTime = cDateStr[8:] x = cTime.split(":") if len(x) == 4: cHr, cMi, cSe, cFrac = x try: tDateTime = datetime.datetime(int(cYr), int(cMo), int(cDa), int(cHr), int(cMi), int(cSe)) except: tDateTime = None elif (len(cDateStr) == 14) and cDateStr.isdigit(): # Type 1 cYr = cDateStr[0:4] cMo = cDateStr[4:6] cDa = cDateStr[6:8] cHr = cDateStr[8:10] cMi = cDateStr[10:12] cSe = cDateStr[12:] try: tDateTime = datetime.datetime(int(cYr), int(cMo), int(cDa), int(cHr), int(cMi), int(cSe)) except: tDateTime = None elif (len(cDateStr) == 26) and (":" in cDateStr) and (" " in cDateStr) and ("." in cDateStr) and ("-" in cDateStr): # Native Python str() of datetime.datetime x = cDateStr.split(" ") if len(x) == 2: cDate, cTime = x x = cDate.split("-") if len(x) == 3: cYr, cMo, cDa = x x = cTime.split(":") if len(x) == 3: cHr, cMi, cSe = x x = cSe.split(".") if len(x) == 2: cSe, cFrac = x try: tDateTime = datetime.datetime(int(cYr), int(cMo), int(cDa), int(cHr), int(cMi), int(cSe), int(cFrac)) except: tDateTime = None else: tDateTime = None # Default return nothing. return tDateTime def TTOC(tDateTime, nHow=0): """ Pass a datetime value and an optional value of nHow and this creates a text string representation of the value in the same exact way as the VFP TTOC() functions. This simplifies the creation of values to seek for when datetime values are included in VFP table indexes. - nHow = 0: yields MM/DD/YY HH:MM:SS xM (where xM is either AM or PM) - nHow = 1: yields YYYYMMDDHHMMSS with no punctuation. This will match a VFP index value like: UPPER(LOGIN_ID) + TTOC(MYDATETIME, 1) - nHow = 2: Time only in form HH:MM:SS xM per the above. - nHow = 3: yields YYYY-MM-DDTHH:MM:SS (where time is expressed in 24 hour clock time) - used in some XML formats. - nHow = 4: yields YYYY_MM_DD_HH_MM_SS, which can be used in file names and read more easily than nHow = 1. - nHow = 9: yields YYYYMMDDHH:MM:SS:000 (the format needed by the CodeBaseTools seek() method when passing JUST the datetime value. This is a format which is NOT supported by the VFP TTOC() function. - nHow set to any other number returns the built-in Python str() representation of a datetime.datetime type: YYYY-MM-DD HH:MM:SS.SSSSSS where the number of seconds is represented to 6 decimal places. For human readable date/time strings see FormatDateTimeString() """ if not isinstance(tDateTime, datetime.datetime): lcReturn = "" elif nHow == 0: lcReturn = tDateTime.strftime("%m/%d/%y %I:%M:%S %p").replace(".", "") elif nHow == 1: lcReturn = tDateTime.strftime("%Y%m%d%H%M%S") elif nHow == 2: lcReturn = tDateTime.strftime("%I:%M:%S %p").replace(".", "") # Just the time portion elif nHow == 3: lcReturn = tDateTime.strftime("%Y-%m-%dT%H:%M:%S") elif nHow == 4: lcReturn = tDateTime.strftime("%Y_%m_%d_%H_%M_%S") elif nHow == 9: lcReturn = tDateTime.strftime("%Y%m%d%H:%M:%S:000") else: lcReturn = str(tDateTime) return lcReturn ###################################################################### ## # get - generic object keyed access with default ## ###################################################################### def get(obj, key, df=None): try: r = obj[key] except: r = df return r ###################################################################### ## # NamedTuple - create a named tuple with defaults. ## ###################################################################### # noinspection PyProtectedMember class NamedTuple(object): def __init__(self, tupleClassName, tupleFieldnames, **defaults): """ :param tupleClassName: namedtuple parameter :param tupleFieldnames: namedtuple parameter :param defaults: one or more default field assignments I.E. age=0 :returns: a namedtuple *template* instance with defaults example: > tmpl = NamedTuple('test', 'name state age', state='WA') > me = tmpl(name='Bob', age=99) test(name='Bob', state='WA', age=99) NOTE: Once you have created the actual named tuple from this template, you can convert it to an ordered dict and back again to the same kind of named tuple. This makes the code for altering multiple elements much more straightforward: > meD = me._asdict() # the above meD is an ordered dict. # to create a copy of tmpl with no changes, do > me2 = tmpl(**meD) # Now me2 is an identical namedtuple. You could have changed some of the values in the meD ordered # dict if you needed to. """ emptyTuple = collections.namedtuple(tupleClassName, tupleFieldnames) setDict = dict() for field in emptyTuple._fields: setDict[field] = defaults.setdefault(field, "") self.namedTuple = emptyTuple(**setDict) def __call__(self, **fields): """ create named tuple from this template. All missing fields will use their default values """ return self.namedTuple._replace(**fields) ###################################################################### ## # Bunch - generic object to store "things". Access by dict or attribute ## ###################################################################### class Bunch(dict): """ A Dictionary Object that can be accessed via attributes """ def __getattr__(self, key): # noinspection PyTypeChecker return self.get(key, '') def __setattr__(self, key, value): self.__setitem__(key, value) def thispath(name): """ returns full path name of the file 'name' in the same folder as the calling program """ myPath = os.path.abspath(sys.argv[0] if __name__ == '__main__' else __file__) ret = os.path.join(os.path.split(myPath)[0], name) return ret def getconfig( name=None, cspecFile='default.conf' ): """ return a default configobj or pass a different name to read that file Added the cspecFile parm so as to be able to override default.conf. This really needs a .cspec type file for the validation anyway. JSH 10/26/2011. """ if not ConfigObj: return # cannot use if not imported if name: return ConfigObj(name) name = 'app.conf' # Note: if app.conf doesn't exist - you MUST run calling program from the app directory # the first time so it is created in the correct folder # If it does exist anywhere up the directory structure, it will be found fullname = FSacquire(name, isdir=False) or name appdir = os.path.split(fullname)[0] or '.' config = ConfigObj(fullname, configspec=thispath(cspecFile), interpolation='template', # allows use of $name inside CONF file indent_type=' ', ) vdt = Validator() isNewfile = not bool(config) config['appdir'] = appdir # Added pgmdir to allow that to be templated in the conf file too. JSH. 10/26/2011 pgmdir = os.path.split(__file__)[0] config['pgmdir'] = pgmdir xkeys = config.keys() results = config.validate(vdt, copy=True) if not results: print('###### %s failed validation. #####' % fullname) for (section_list, key, _) in flatten_errors(config, results): if key is not None: print('The "%s" key in the section "%s" failed validation' % (key, ', '.join(section_list))) else: print('The following section was missing:%s ' % ', '.join(section_list)) if set(config.keys()) - set(xkeys): # this happens if a new section or attribute is added to the default.conf print('%s config file "%s"' % (('Update','Write new')[isNewfile], fullname)) # don't write appdir to saved CONF del config['appdir'] config.write() config['appdir'] = appdir return config def getrandomseed(nSize=4): """ Returns a seed that can be used by any randomizer, which is not dependant on the system clock. Use if you think your processes may run concurrently and get the same seed for random() from the clock. """ cRandStr = os.urandom(nSize) cRandStr = str(cRandStr) nSeed = 0 for j in range(0, nSize): nVal = ord(cRandStr[j]) if nVal > 1: nVal -= 1 nSeed += (255**j) * nVal return nSeed def strRand(StrLength, isPassword=0): |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |