def unify(u, v, s): # no check at the moment """ Find substitution so that u == v while satisfying s >>> from logpy.core import unify, var >>> x = var('x') >>> unify((1, x), (1, 2), {}) {~x: 2} """ u = walk(u, s) v = walk(v, s) if u == v: return s if isvar(u): return assoc(s, u, v) if isvar(v): return assoc(s, v, u) if isinstance(u, tuple) and isinstance(v, tuple): if len(u) != len(v): return False for uu, vv in zip(u, v): # avoiding recursion s = unify(uu, vv, s) if s is False: return False return s return False
def unify(u, v, s): # no check at the moment """ Find substitution so that u == v while satisfying s >>> from logpy.unification import unify, var >>> x = var('x') >>> unify((1, x), (1, 2), {}) {~x: 2} """ u = walk(u, s) v = walk(v, s) if u == v: return s if isvar(u): return assoc(s, u, v) if isvar(v): return assoc(s, v, u) types = (type(u), type(v)) if types in unify_dispatch: return unify_dispatch[types](u, v, s) if (hasattr(u, '_as_logpy') and not isinstance(u, type) and hasattr(v, '_as_logpy') and not isinstance(v, type)): return unify_seq(u._as_logpy(), v._as_logpy(), s) for (typu, typv), unify_fn in unify_isinstance_list: if isinstance(u, typu) and isinstance(v, typv): return unify_fn(u, v, s) for typ, fn in seq_registry: if isinstance(u, typ) and isinstance(v, typ): return unify_seq(fn(u), fn(v), s) else: return False
def unify(u, v, s): # no check at the moment """ Find substitution so that u == v while satisfying s >>> from logpy.unify import unify, var >>> x = var('x') >>> unify((1, x), (1, 2), {}) {~x: 2} """ u = walk(u, s) v = walk(v, s) if u == v: return s if isvar(u): return assoc(s, u, v) if isvar(v): return assoc(s, v, u) types = (type(u), type(v)) if types in unify_dispatch: return unify_dispatch[types](u, v, s) for (typu, typv), unify_fn in unify_isinstance_list: if isinstance(u, typu) and isinstance(v, typv): return unify_fn(u, v, s) for typ, fn in seq_registry: action = False if isinstance(u, typ): u = fn(u); action=True if isinstance(v, typ): v = fn(v); action=True if action: return unify(u, v, s) else: return False
def unify(u, v, s): # no check at the moment """ Find substitution so that u == v while satisfying s >>> from termpy.unification import unify, var >>> x = var('x') >>> unify((1, x), (1, 2), {}) {~x: 2} """ u = walk(u, s) v = walk(v, s) if u == v: return s elif isvar(u): return assoc(s, u, v) elif isvar(v): return assoc(s, v, u) types = (type(u), type(v)) if types in unify_dispatch: return unify_dispatch[types](u, v, s) elif not isleaf(u) and not isleaf(v): s = unify(op(u), op(v), s) if s is False: return s else: return unify(args(u), args(v), s) else: return False
def main(folder): transdict = {} # will be formatted as {jap: {translation: [(file, line, translation)*]}} util.walk(folder, testfile, transdict) fixlist = [] for i in transdict: if len(transdict[i]) > 1: # different translations keyname = min(min(k[0]+'_'+k[1] for k in transdict[i][j]) for j in transdict[i]) try: fixlist.append(( ('differences between:\n' + '\nand\n'.join( ', '.join( "file {} line {}".format(*k) for k in transdict[i][j] ) + '\n[[[{}]]]'.format(j.decode('utf-8')) for j in transdict[i] ) + '\n\n' ), keyname )) except UnicodeDecodeError: print("failed on", keyname, i) for j in transdict[i]: try: j.decode('utf-8') except: print(j, transdict[i][j]) raise with open('consistency.txt', 'w', encoding='utf-8') as g: g.write(''.join(i[0] for i in sorted(fixlist, key = lambda x: x[1]))) return transdict
def completedefault(self, *ignore): path = self.current ret = [] _, dirs, files = walk(self.up, path) ret.extend(dirs) ret.extend(files) return ret
def build_files(): try: kwargs = {'top': folderid, 'by_name': False} for path, root, dirs, files in util.walk(service, **kwargs): path = [ "".join([ c for c in dirname if c.isalpha() or c.isdigit() or c == ' ' ]).rstrip() for dirname in path ] for f in files: dest = os.path.join(destination, os.path.join(*path)) file_dest.append((service, f, dest, skip)) if file_dest != []: # First valid account found, break to prevent further searches return True except ValueError: # mimetype is not a folder dlfile = service.files().get(fileId=folderid, supportsAllDrives=True).execute() print( f"\nNot a valid folder ID. \nDownloading the file : {dlfile['name']}" ) # Only use a single process for downloading 1 file util.download(service, dlfile, destination, skip) sys.exit(0) except HttpError: print( f"{Fore.RED}File not found in account: {acc}{Style.RESET_ALL}") return False
def unify(u, v, s): # no check at the moment """ Find substitution so that u == v while satisfying s >>> from logpy.unify import unify, var >>> x = var('x') >>> unify((1, x), (1, 2), {}) {~x: 2} """ u = walk(u, s) v = walk(v, s) if u == v: return s if isvar(u): return assoc(s, u, v) if isvar(v): return assoc(s, v, u) types = (type(u), type(v)) if types in unify_dispatch: return unify_dispatch[types](u, v, s) else: return False
def iterate_targets(root): """Iterate over the targets generated based on root directory tree""" root = os.path.abspath(root) logging.info('sourcedir=%s', root) target_rules_filename = Settings.get('targets')['filename'] for path, files in util.walk(root): with util.pushd(os.path.join(root, path)): relpath = Path.clean(path.replace(root, '')) logging.info('Parsing folder: $sourcedir/%s', relpath) if not files: logging.debug('No files found') elif target_rules_filename in files: target_rules_filepath = os.path.join(path, target_rules_filename) target_rules = util.load_yaml_or_json(target_rules_filepath) for gyp_target in target_rules.get('targets', []): yield Target(relpath, files, gyp_target) else: yield Target(relpath, files)
def Gets(up, src, dst): err = False dst = os.path.join(dst, basename(src)) try: os.mkdir(dst) except: err = True if err: return err root, dirs, files = walk(up, src) for name in files: src_name = os.path.join(root, name) dst_name = os.path.join(dst, name) err = Get(up, src_name, dst_name) if err: return err for name in dirs: src_dir = os.path.join(root, name) err = Gets(up, src_dir, dst) if err: return err
def scan_cases(path): result = [] # 项目种类 project_kinds = util.safely_list_dir(path) for project_kind in project_kinds: projects = util.safely_list_dir(path, project_kind) # 遍历项目 for project in projects: versions = util.safely_list_dir(path, project_kind, project) # 遍历版本 for version in versions: pycharm_projects = util.safely_list_dir( path, project_kind, project, version) # 遍历pycharm工程 for pycharm_project in pycharm_projects: case_dir = util.join(path, project_kind, project, version, pycharm_project, 'src', 'cases') modules = util.safely_list_dir(case_dir) for m in modules: # 文件作为模块 if util.isfile(util.join(case_dir, m)): if util.suffix(m) == '.py': result.extend( parsePy2Dict(util.join(case_dir, m), util.join(path, project), 'cases', '', util.filename(m), [], None, version, pycharm_project, project_kind)) # 目录作为一级模块 else: # 在目录下的__init__.py里获取模块描述 module_desc = '' if util.isfile( util.join(case_dir, m, '__init__.py')): f = open(util.join(case_dir, m, '__init__.py')) p = ast.parse(f.read()).body module_desc = p[0].value.s if p else '' f.close() for root, dirs, files in util.walk( util.join(case_dir, m)): for file in files: if util.suffix(file) == '.py': modules = util.relative( util.join(root, file), case_dir)[0:-1] package = util.relative( util.join(root, file), util.dirname(case_dir))[0:-1] package = '.'.join(package) result.extend( parsePy2Dict( util.join(root, file), util.join(path, project), package, m, util.filename(file), modules, module_desc, version, pycharm_project, project_kind)) return result
# -*- coding: utf-8 -*- """ canteen: runscript ~~~~~~~~~~~~~~~~~~ accepts calls to ``canteen`` as a module. can be run with ``python -m canteen`` or ``python -m canteen/``, the latter assuming you have it installed right next to you. :author: Sam Gammon <*****@*****.**> :copyright: (c) Sam Gammon, 2014 :license: This software makes use of the MIT Open Source License. A copy of this license is included as ``LICENSE.md`` in the root of the project. """ # utils from util import walk from dispatch import run walk(), run()
# -*- coding: utf-8 -*- ''' canteen runscript ~~~~~~~~~~~~~~~~~ accepts calls to ``canteen`` as a module. can be run with ``python -m canteen`` or ``python -m canteen/``, the latter assuming you have it installed right next to you. :author: Sam Gammon <*****@*****.**> :copyright: (c) Keen IO, 2013 :license: This software makes use of the MIT Open Source License. A copy of this license is included as ``LICENSE.md`` in the root of the project. ''' # utils from util import walk from dispatch import run walk(), run()
def build_table(folder, tablefile): walk(folder, _scan_file) with open(tablefile, "w", encoding="utf-8") as outfile: for key, value in evis.ALIGNMENTS.items(): print(hex(key[1])[2:].zfill(2), hex(key[0])[2:].zfill(2), value, evis.COUNTS[key], file=outfile)
from util import walk # Part 1 class AccumulatingIntParser(object): def __init__(self): self.total = 0 def __call__(self, num_str): value = int(num_str) self.total += value return value acc1 = AccumulatingIntParser() decoder1 = json.JSONDecoder(parse_int=acc1) obj1 = decoder1.decode(open('input12.txt').read()) print('Part 1:', acc1.total) # Part 1, attempt 2 obj = json.load(open('input12.txt')) value = walk(obj, map_func=lambda x: sum(_ for _ in x.values() if isinstance(_, int)), seq_func=lambda x: sum(_ for _ in x if isinstance(_, int))) print('Part 1:', value) # Part 2 obj = json.load(open('input12.txt')) value = walk(obj, map_func=lambda x: 0 if "red" in x.values() else sum(_ for _ in x.values() if isinstance(_, int)), seq_func=lambda x: sum(_ for _ in x if isinstance(_, int))) print('Part 2:', value)