def process(input, output): if format() == 'xml': o = xmltodict.parse(input.read()) elif format() == 'yaml': o = yaml.load(input) else: o = json.load(input) if ascii(): tr = LeftAligned() else: tr = LeftAligned(draw=BoxStyle(gfx=BOX_LIGHT, horiz_len=1)) output.write(tr(treeFix(o)))
def individual(self, individual, depth=1): """Format an individual.""" """ tree = { 'asciitree': OD([ ('sometimes', {'you': {}}), ('just', {'want': OD([ ('to', {}), ('draw', {}), ])}), ('trees', {}), ('in', { 'your': { 'terminal': {} } }) ]) } """ tree = {'me': OD('')} tr = LeftAligned() return tr(tree)
async def do_tree(self, dn = None, level = 1): """Prints a tree from the given DN (if not set, the top) and with a given depth (default: 1)""" try: await self.do_ldapinfo(False) if level is None: level = 1 level = int(level) if dn is not None: try: int(dn) except: pass else: level = int(dn) dn = None if dn is None: await self.do_ldapinfo(False) dn = self.connection._tree logging.debug('Tree on %s' % dn) tree_data = await self.connection.get_tree_plot(dn, level) tr = LeftAligned() print(tr(tree_data)) except: traceback.print_exc()
def show(self, what): print self.data_refining if len(what) == 0 or 'Plain' in what: scaffold_nodes = self.data_refining['scaffolding'] for scaffold_node, ports in scaffold_nodes.items(): print(Fore.BLUE + "--- scaffold_node: %s" % (scaffold_node)) print(Style.RESET_ALL) for p_id, ctx in ports.items(): print self.service_fmt % (ctx["srv"]['@name'], p_id) for key in ['connected', 'disjoined']: print CohesionTermCb.append_str( key, " ".join(ctx[key])) print "\n" # JSON if 'Json' in what: print 'JSON \n' print json.dumps(self.data_refining) # maybe deep copy if data reused if 'Tree' in what: # TREE Construer.traverse(self.data_refining, TermTreeConvCb()) tr = LeftAligned(draw=BoxStyle(gfx=BOX_HEAVY)) print(tr(self.data_refining))
def __unicode__(self): drawer = LeftAligned( traverse=TreeTraversal(), draw=BoxStyle(gfx=self.unicode_kwargs, **self.text_kwargs), ) root = self.node_cls(self.group, level=self.level) return drawer(root)
def tree(data): if not LeftAligned: print("asciitree not installed!") sys.exit(-1) tr = LeftAligned() tree = {"/": {}} def _put_into_dict(root, resource): resource = resource component = resource.split("/")[0] if not component: return if not component in root.keys(): root[component] = {} resource = "/".join(resource.split("/")[1:]) _put_into_dict(root[component], resource=resource) for entry in data: (resource, code, ext, response_size) = (entry[3], entry[5], entry[4], entry[6]) if code in response_codes: if ext: resource = resource + ext _put_into_dict(tree["/"], resource) print(tr(tree))
def print_diff(common_paths): comm_path_str = common_paths_to_str(common_paths) common_paths = common_paths_from_str(comm_path_str) untracked_files = {k: v for k, v in common_paths.items() if not v['synid']} remote_files = { k: v for k, v in common_paths.items() if not v['local_md5'] } mismatch_files = { k: v for k, v in common_paths.items() if ((None not in [v['local_md5'], v['remote_md5']]) & (len(set([v['local_md5'], v['remote_md5']]))) > 1) } d = { 'Untracked files:': untracked_files, 'Remote files:': remote_files, 'Mismatched_files:': mismatch_files } for k, v in d.items(): head_str = k + ' ' + str(len(v)) + ' file(s).' print(head_str) if len(v) > 0: tr = LeftAligned(draw=BoxStyle(gfx=BOX_LIGHT, horiz_len=1)) tree = paths_to_tree(v) print(' ' + tr(tree).replace('\n', '\n ')) print() print()
def delete(name, dry_run, verbose): """Delete a collection.""" collection = Collection.query.filter_by(name=name).one() if verbose: tr = LeftAligned(traverse=AttributeTraversal()) click.secho(tr(collection), fg='red') db.session.delete(collection)
def display_class_tree(classes, top_class=None): """ Display the list of classes as a left justified tree in ascii to the click.echo output Parameters: classes (list of :class:`~pywbem.CIMClass`) top_class (:term: `string`) The top level class to display or None if the display is from root. """ # build dictionary of classname : superclassname cn_supercn = {cl.classname: cl.superclass for cl in classes} # if top_class is none, create artifical root if top_class is None: for cn in cn_supercn: if not cn_supercn[cn]: cn_supercn[cn] = 'root' top_class = 'root' # Hack to build the class to subclass dictionary from the # superclass to class dictionary cn_subcn = NocaseDict() # pylint: disable=bad-continuation, expression-not-assigned [ cn_subcn.setdefault(v, []).append(k) for (k, v) in six.iteritems(cn_supercn) ] # noqa: F841 tree = build_tree(cn_subcn, top_class) tr = LeftAligned() click.echo(tr(tree))
def tree(): if not LeftAligned: print("asciitree not installed!") sys.exit(-1) tr = LeftAligned() tree = {'/': {}} def _put_into_dict(root, resource): resource = resource.decode('UTF-8', 'replace') component = resource.split('/')[0] if not component: return if not component in root.keys(): root[component] = {} resource = "/".join(resource.split('/')[1:]) _put_into_dict(root[component], resource=resource) for entry in data: (resource, code, ext, response_size) = (entry[3], entry[5], entry[4], entry[6]) if banned_extensions and is_banned(resource): continue if unbanned_extensions and not is_ubanned(resource): continue if size_filter and size_is_banned(response_size): continue if code in response_codes: if ext: resource = resource + ext _put_into_dict(tree['/'], resource) print(tr(tree))
def __init__(self, max_depth=10, max_nodes=50, percentage=False, horiz_len=1, indent=2, style="BOX_ASCII"): """Create a tree object from JSON Data Keyword Arguments: max_depth {int} -- how deep into the branches the tree is supposed to be displayed (default: {10}) max_nodes {int} -- how many items a single node is allowed to have (default: {50}) percentage {bool} -- show percentage of total next to the numbers (default: {False}) horiz_len {int} -- see documentation of asciitree (default: {1}) indent {int} -- see documentation of asciitree (default: {2}) style {str} -- possibilites are ['BOX_ASCII', 'BOX_DOUBLE', 'BOX_BLANK', 'BOX_HEAVY', 'BOX_LIGHT'] ; for details see documenation of asciitree (default: {"BOX_ASCII"}) The documentation of asciitree can be found here: https://pythonhosted.org/asciitree/ """ self.percentage = percentage self.max_nodes = max_nodes self.max_depth = max_depth self.list_placeholder = "[LIST]" self.n = 0 self.tree = cdict() self.count_tree = OrderedDict() _style = getattr(drawing, style) self.viewer = LeftAligned(draw=drawing.BoxStyle( gfx=_style, horiz_len=horiz_len, indent=indent)) self._append_dots = []
def quadtree_str(): d = OrderedDict() d['root::{}'.format(str( NBodySimulator.root_node))] = NBodySimulator.root_node.make_dict() tr = LeftAligned() max_depth = max([n.depth for n in NBodySimulator.nodes.values()]) return 'Quad Tree ({} total nodes, {} levels deep):\n'.format( len(NBodySimulator.nodes), max_depth + 1) + tr(d)
def path(name): """Print path to root.""" try: coll = Collection.query.filter(Collection.name == name).one() tr = LeftAligned( traverse=CollTraversalPathToRoot(coll.path_to_root().all())) click.echo(tr(coll)) except NoResultFound: raise click.UsageError('Collection {0} not found'.format(name))
def process(self, input, output=sys.stdout): if type(input) in self.collections: o = input elif isinstance(input, IOBase) or isinstance(input, StringIO): input = input.read() if type(input) in [str]: if self.format == 'xml': o = xmltodict.parse(input) elif self.format == 'yaml': o = yaml.load(input) else: # == 'json' o = json.loads(input) if self.ascii: tr = LeftAligned() else: tr = LeftAligned( draw=BoxStyle(label_space=0, gfx=BOX_LIGHT, horiz_len=1)) output.write(tr(self.treeFix(o)))
def __repr__(self): if self.is_leaf: return f"{self.value}" else: tr = LeftAligned(draw=BoxStyle(gfx=BOX_DOUBLE, horiz_len=1)) out_final = {} out_final[self.name] = self.to_dict() return tr(out_final)
def __bytes__(self): drawer = LeftAligned(traverse=TreeTraversal(), draw=BoxStyle(gfx=self.bytes_kwargs, **self.text_kwargs)) root = TreeNode(self.group, level=self.level) result = drawer(root) # Unicode characters slip in on Python 3. # So we need to straighten that out first. result = result.encode() return result
def dependency_graph(self, package_name): """ takes package_name and outputs its dependencies and their own dependencies plus an asciitree of this arrangement. :param package_name: :return: dictionary of dictionaries with dependencies of package name """ sub_tr = {package_name: self.sub_graph(package_name)} tree = sub_tr for node in sub_tr[package_name]: tree[package_name][node] = self.sub_graph(node) box_tr = LeftAligned(draw=BoxStyle(gfx=BOX_DOUBLE, horiz_len=1)) return box_tr(tree)
def tree(names): """Show the tree of the collection(s) specified.""" # query query = Collection.query if names: query = query.filter(Collection.name.in_(names)) else: query = query.filter(Collection.level == 1) # print tree tr = LeftAligned(traverse=AttributeTraversal()) for coll in query.all(): click.secho(tr(coll))
def get_answer(db_name, query): output = t2sql.process(query, db_name) translatable = output['translatable'] sql_query = output['sql_query'] confusion_span = output['confuse_span'] replacement_span = output['replace_span'] answer = [ 'Translatable: {}'.format(translatable), 'Confusion span: {}'.format(confusion_span), 'Replacement span: {}'.format(replacement_span), LeftAligned()(schemas[db_name].printable) ] answer = "\n\n".join(answer) return answer, sql_query, translatable
def cli(gh, repos): """ Show a tree of forks """ if not repos: repos = [gh.repository()] repos = [r.get() for r in repos] traverser = ForkTraversal(gh, repos) tree = LeftAligned(draw=BoxStyle(gfx=BOX_LIGHT), traverse=traverser) first = True for r in repos: if r["full_name"] not in traverser.seen: if first: first = False else: click.echo() click.echo(tree(r))
def draw(self, depth=None, hidden=False): """Print an ASCII-fied visual of the tree. Parameters ---------- depth : int, optional Maximum directory depth to display. ``None`` indicates no limit. hidden : bool If True, show hidden files and directories. """ if not self.exists: raise OSError("Tree doesn't exist in the filesystem") tree = OrderedDict() rootdir = self.abspath.rstrip(os.sep) start = rootdir.rfind(os.sep) + 1 for path, dirs, files in scandir.walk(rootdir): # sort files and directories so they show up in output sorted dirs.sort() files.sort() folders = ["{}/".format(x) for x in path[start:].split(os.sep)] parent = reduce(dict.get, folders[:-1], tree) # depth handling if depth and len(folders) == depth + 1: parent[folders[-1]] = {} continue elif depth and len(folders) > depth + 1: continue # filter out hidden files and directories, if desired if not hidden: outfiles = [file for file in files if file[0] != os.extsep] hidden_dirs = [d for d in dirs if d[0] == os.extsep] for d in hidden_dirs: dirs.remove(d) else: outfiles = files subdir = OrderedDict.fromkeys(outfiles, {}) parent[folders[-1]] = subdir tr = LeftAligned() print(tr(tree))
def printFeatureTreeOfBundle( feature, bundleString ) : # First seache bundle in feature bundles=searchBundleVersions(feature, bundleString) root=OD() bundlesRoot=OD() root['b: ' + bundleString]=bundlesRoot if ( len ( bundles ) == 0 ) : bundleRoot=OD() bundlesRoot["Not found"]={} else : for bundle in bundles : featuresOfBundle=searchFeatureOfBundle(feature, bundle) bundleRoot=OD() bundlesRoot['b: ' + bundle.toStr(ver=True)]=bundleRoot loadParentTree( bundleRoot, featuresOfBundle ) tr = LeftAligned(draw=BoxStyle(gfx=BOX_LIGHT, label_space=0, indent=0)) print(tr(root))
def create_tree(table: dict, root: str, mark: str, f_pid: str = "pid", f_id: str = "id", f_label: str = "item", f_ctime: str = "ctime", v_none: str = "null") -> str: """ Creates the ascii checkpoint tree. Args: table: List of checkpoints as a table. root: Root label of the tree. mark: Current snapshot name. Mark the element with an '*' f_pid: Field of the table that contains the parent id of the node. f_id: Field of the table that contains the id of the node. f_label: Field with the label of the node. f_ctime: Field with the timestamp creation date. v_none: Value to be used for empty fields. Returns: A string containing the tree of snapshots """ items = [(c[f_pid], c[f_id]) for c in table] tree = {root: OD()} inserted = [] while [x[1] for x in items if x[1] not in inserted]: for parent, item in items: if parent == v_none: parent = root inserts = walk(tree, parent, item) inserted.extend(list(inserts)) tr = LeftAligned() tr_tree = tr(tree) for cell in table: if cell[f_label] == mark: cell[f_label] = "{}*".format(cell[f_label]) tr_tree = tr_tree.replace( cell[f_id], "{} ({})".format(cell[f_label], convert_dt(cell[f_ctime]))) return tr_tree
def formatted_tree(params, folder): def tree_node(node): name = node.name sfs = [params.folder_cache[sfuid] for sfuid in node.subfolders] if len(sfs) == 0: return name, {} sfs.sort(key=lambda f: f.name.lower(), reverse=False) tns = [tree_node(sf) for sf in sfs] return name, OD(tns) t = tree_node(folder) tree = {t[0]: t[1]} tr = LeftAligned() print(tr(tree)) print('')
def show_tree(hdf5_file): tree = {hdf5_file: OrderedDict()} f = h5py.File(hdf5_file, 'r') for k, v in f.items(): tree[hdf5_file][k] = OrderedDict() for k2, v2 in v.items(): tree[hdf5_file][k][f'{k2} -> {v2.shape} {v2.dtype}'] = OrderedDict() chrs = dict( UP_AND_RIGHT=u"\u2514", HORIZONTAL=u"\u2500", VERTICAL=u"\u2502", VERTICAL_AND_RIGHT=u"\u251C" ) tr = LeftAligned(draw=BoxStyle(gfx = chrs, horiz_len=1)) print(tr(tree))
def render_split_tree(tree, root=None, uuid_len=4): """ Render the given split tree as ascii text. Requires the 'asciitree' module (conda install -c conda-forge asciitree) Args: tree: nx.DiGraph with 'uuid' annotations (as returned by extract_split_tree()) root: Node to use as the root of the tree for display purposes. If None, root will be searched for. uuid_len: How many characters of the uuid to print for each node in the tree. Set to 0 to disable UUID display. Returns: str Example: >>> events = fetch_supervoxel_splits(('emdata3:8900', '52f9', 'segmentation')) >>> tree = extract_split_tree(events, 677527463) >>> print(render_split_tree(tree)) 677527463 (<unknown>) +-- 5813042205 (25dc) +-- 5813042206 (25dc) +-- 5813042207 (25dc) +-- 5813042208 (25dc) """ root = root or find_root(tree, next(iter(tree.nodes()))) def abbreviate_uuid(n): uuid = tree.node[n]['uuid'] if uuid != '<unknown>': uuid = uuid[:uuid_len] return f"{n} ({uuid})" if uuid_len == 0: d = tree_to_dict(tree, root) else: d = tree_to_dict(tree, root, abbreviate_uuid) from asciitree import LeftAligned return LeftAligned()(d)
def __init__(self, *args): self.function = { "register": self.register, "login": self.login, "logout": self.logout, "whoami": self.whoami, "create-board": self.create_board, "create-post": self.create_post, "list-board": self.list_board, "list-post": self.list_post, "read": self.read, "delete-post": self.delete_post, "update-post": self.update_post, "comment": self.comment, "subscribe": self.subscribe, "unsubscribe": self.unsubscribe, "list-sub": self.list_sub } self.tree_format = LeftAligned() super().__init__(*args)
def get_printable(self, level=0): try: from asciitree import LeftAligned from collections import OrderedDict as OD from asciitree.drawing import BoxStyle, BOX_DOUBLE, BOX_ASCII def get_ascii_tree(node): if node.is_leaf(): return str(node.sym), {} return str(node.sym), OD(map(get_ascii_tree, node.childs)) tree = {str(self.sym): get_ascii_tree(self)[1]} tr = LeftAligned(draw=BoxStyle(gfx=BOX_ASCII, indent=0)) return str(tr(tree)) except Exception as e: print(e.args) if self.is_leaf(): return " " * level + str(self.sym) + '\n' pp = " " * level + str(self.sym) + '\n' for child in self.childs: pp += child.get_printable(level+1) return pp
def print_children(obj): def build_tree(obj): def process_child(child): c = getattr(obj, child) if isinstance(c, Mapping): return child, OrderedDict((k + ': ' + v.name, build_tree(v)) for k, v in sorted(c.items())) elif isinstance(c, Iterable): return child, OrderedDict((str(i) + ': ' + v.name, build_tree(v)) for i, v in enumerate(c)) else: return child + ': ' + c.name, build_tree(c) return OrderedDict(process_child(child) for child in sorted(RuleTable.get_children(obj))) try: from asciitree import LeftAligned print(LeftAligned()({obj.name: build_tree(obj)})) except ImportError: from pprint import pprint pprint({obj.name: build_tree(obj)})
def show_configuration(sub_menu: Optional[str] = None): """ display the current configuration or a sub menu if provided """ tr = LeftAligned(draw=BoxStyle(gfx=BOX_DOUBLE, horiz_len=1)) out_final = {} if sub_menu is None: out_final["CONFIG"] = _to_dict(threeML_config) else: assert sub_menu in threeML_config, "not a valild topic" out_final[sub_menu] = _to_dict(threeML_config[sub_menu]) print(tr(out_final))