def parseOutput(content): """Convert the nested paranthesis output from pdflatex to a tree structure.""" root = anytree.AnyNode(content='', filename='', warnings=[]) node = root for char in content: if char == '(': node = anytree.AnyNode(parent=node, content='', filename='', warnings=[]) elif char == ')': node = node.parent else: node.content += str(char) return root
def forced_mate_in_n(board: chess.Board, color_getting_checkmated, num_moves) -> bool: """ for each legal move that `color_getting_checkmated` has, there exists a legal move for the opposing player such that after the following move is played, then `forced_mate_in_n(color_getting_checkmated, num_moves - 1)` is true. that is to say: given alternating color moves at each level in the move tree, every move taken by `color_getting_checkmated` has at least one child move (i.e. a move by the opponent) that results in `forced_mate_in_n(color_getting_checkmated, num_moves - 1)`, recurse down the tree culminating in a checkmate at the end of each path TODO: complete this """ root = anytree.AnyNode(id='root') if num_moves == 1: for mv in board.generate_legal_moves(): new_board = board.copy() new_board.push(mv) if new_board.is_checkmate(): return True return False else: for mv in board.generate_legal_moves(): new_board = board.copy() new_board.push(mv) return forced_mate_in_n(board, color_getting_checkmated, num_moves - 1)
def storage_node(self, name, path, parent, attr=None): '''create a new node representing a storage''' path = os.path.abspath(path) free = psutil.disk_usage(path).free total = psutil.disk_usage(path).total epoch = int(time.time()) return anytree.AnyNode(name=name, type=self.TYPE_STORAGE, free=free, total=total, parent=parent, attr=attr, ts=epoch)
def _node(self, name, type, relpath, parent, size=None, md5=None): ''' generic node creation ''' return anytree.AnyNode(name=name, type=type, relpath=relpath, parent=parent, size=size, md5=md5)
def archive_node(self, name, path, parent, archive): return anytree.AnyNode(name=name, type=self.TYPE_ARC, relpath=path, parent=parent, size=0, md5=None, archive=archive)
def __read_hierarchy(node, parent=None): # Cast an ``anytree.AnyNode`` (after first level of recursion) to dict. attributes = dict(node) children = attributes.pop("Subcategory", []) node = anytree.AnyNode(parent=parent, **attributes) for child in children: __read_hierarchy(child, parent=node) return node
def generate_wcs_diagram(conversation_username: str = None, conversation_password: str = None, version: str = None, workspace: str = None) -> str: """ generates a compact, text represation of a WCS instance. ex: root ├── welcome ├── 1 (jumps to: 3) ├── 2 │ ├── 2_1 │ └── 2_2 ├── 3 │ ├── 3_1 │ ├── 3_2 │ └── 3_3 └── Anything else parameters: conversation_username: WCS instance username conversation_password: WCS instance password version: WCS API version workspace: WCS instance workspace returns: projection: a string representation of the WCS workspace """ export = get_and_backup_workspace(username=conversation_username, password=conversation_password, version=version, workspace=workspace, export_path=None) # build tree roots root = anytree.AnyNode(id=None, title=None, desc='root') # build our trees _build_tree(export['dialog_nodes'], root) # for rendering, let's update the desc fields with titles of the jump nodes_with_jumps = anytree.search.findall(root, filter_=_get_nodes_with_jump) # update the descriptions for node in nodes_with_jumps: dest = _get_all_matches(root, node.node['next_step']['dialog_node']) if len(dest) == 1: node.desc = node.desc + ' (jumps to: {})'.format(dest[0].desc) # projected rendering of tree projected = anytree.RenderTree( root, childiter=_sort_child_nodes).by_attr(attrname='desc') return projected
def update_metanode(self, meta): '''create or update meta node information''' epoch = int(time.time()) if not meta: attr = {} attr['created'] = epoch attr['created_version'] = VERSION meta = anytree.AnyNode(name=self.METANAME, type=self.TYPE_META, attr=attr) meta.attr['access'] = epoch meta.attr['access_version'] = VERSION return meta
def configure_loads(self) -> None: """ Configura la carga de todos los elementos del circuito """ # Conectamos la carga nula a cada elemento de salida for leave in self.tree.leaves: null_load_node = anytree.AnyNode(device=null_load()) leave.children = [null_load_node] # Recorremos todos los nodos (salvo las cargas nulas) y # seteamos el dispositivo que los carga for node in anytree.PreOrderIter(self.tree, \ filter_=lambda node: not node.is_leaf): node.device.set_connected_devices([child.device for child in node.children])
def create_tree(root_json, root_node): con_name = root_json['name'] if con_name is None: con_name = 'container' if con_name in ['__i3', 'topdock', 'bottomdock']: return None else: this_node = at.AnyNode(id=con_name, parent=root_node, con_id=root_json['id'], workspace=False, container=False) if con_name == 'container': this_node.container = True for a_node in root_json['nodes']: create_tree(a_node, this_node)
def new_top_node(self): '''create a new top node''' return anytree.AnyNode(name=self.TOPNAME, type=self.TYPE_TOP)
'''Call dmenu with a list of options.''' cmd = subprocess.Popen(program, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = cmd.communicate('\n'.join(options).encode('utf-8')) return stdout.decode('utf-8').strip('\n') # Get I3 tree proc_out = subprocess.run(['swaymsg', '-t', 'get_tree'], stdout=subprocess.PIPE) i3tree = json.loads(proc_out.stdout.decode('utf-8')) # Create tree from the i3 tree output root = at.AnyNode(id='r') create_tree(i3tree, root) root = root.children[0] # Identify the workspaces for display in root.children: for wk in display.children[0].children: wk.workspace = True # Get the current workspace proc_out = subprocess.run(['swaymsg', '-t', 'get_workspaces'], stdout=subprocess.PIPE) wkList = json.loads(proc_out.stdout.decode('utf-8')) focWkName = nf.getFocusedWK(wkList) # Change the tree such that the workspaces are children to the root # while ignoring the current workspace
def copy_dialog_branch( root_node: str = '', target_node: str = 'root', target_insert_as: str = 'child', source_username: str = '', source_password: str = '', source_workspace: str = '', target_username: str = '', target_password: str = '', target_workspace: str = '', version: str = '', target_backup_file: str = _DEFAULT_BACKUP_FILE) -> \ Tuple[anytree.AnyNode, str]: """ Copy a dialog branch (and any jumps) to a target workspace at `target_node` using `target_insert_as` strategy (child, last_child, or sibling). Writes a backup of the target workspace to `target_backup_file` Root | |--Target Node | | | |<-(insert as child) | | | |--Existing Node | | | |<-(insert as last_child) | | | |--"true" node | |<-(insert as sibling) | ... parameters: root_node: ID or title of the root node in source target_node: ID or title of the root node in target target_insert_as: Default 'child'. Location of branch insertion, with respect to the target node. valid options ['child', 'last_child' or 'sibling'] source_username: Username for source WCS instance source_password: Password for source WCS instance source_workspace: Workspace ID for source WCS instance target_username: Username for target WCS instance target_password: Password for target WCS instance target_workspace: Workspace ID for target WCS instance version: WCS API version target_backup_file: write a backup of target workspace to this file returns: target_nodes: the root node of the projected target tree projected: a string representation of the projected tree """ #validate that values are provided args = locals() for key in [ 'root_node', 'target_node', 'target_insert_as', 'source_username', 'source_password', 'source_workspace', 'target_username', 'target_password', 'target_workspace', 'version', 'target_backup_file' ]: if args[key] is '': raise ValueError("Argument '{}' requires a value".format(key)) # can't copy the entire root if root_node == 'root' or root_node is None: raise ValueError("""Root node cannot be the source root. Import the workspace instead.""") # need a valid insert type target_insert_as = target_insert_as.lower() if target_insert_as not in ['child', 'last_child', 'sibling']: raise ValueError("""'target_insert_as is required to be one of 'child', 'last_child', or 'sibling'""") # build backup file if not specified # otherwise just call it the POSIX timestamp if target_backup_file == _DEFAULT_BACKUP_FILE: target_backup_file = _DEFAULT_BACKUP_FILE.format( str(datetime.now().timestamp())) # set root references to None for consistency if target_node == 'root': target_node = None # we will need to walk up the trees tree_walker = anytree.walker.Walker() # get export of workspaces source_export = get_and_backup_workspace(username=source_username, password=source_password, version=version, workspace=source_workspace, export_path=target_backup_file) target_export = get_and_backup_workspace(username=target_username, password=target_password, version=version, workspace=target_workspace, export_path=None) # build tree roots source_nodes = anytree.AnyNode(id=None, title=None, desc='root') target_nodes = anytree.AnyNode(id=None, title=None, desc='root') # build our trees _build_tree(source_export['dialog_nodes'], source_nodes) _build_tree(target_export['dialog_nodes'], target_nodes) # we only have one value for these branches source_branch = _get_branch_node(source_nodes, root_node, 'source') target_branch = _get_branch_node(target_nodes, target_node, 'target') # we need to have ensure branches in order to insert if source_branch is None: raise RuntimeError('No matching root node found in source') if target_branch is None: raise RuntimeError('No target node found in target') # insert a copy of the source branch into the target tree _insert_into_target_tree(source_branch, target_branch, target_nodes, target_insert_as) # check for any jumps, these will need to be accounted for nodes_with_jumps = anytree.search.findall(source_branch, filter_=_get_nodes_with_jump) # this is the set of nodes that jumped to to_jump_to = [x.node['next_step']['dialog_node'] \ for x in nodes_with_jumps] # make sure that we have a valid destination for the jump # if not, we will insert at the first common ancestor for jump_id in to_jump_to: # destination exists, move on jump_node = anytree.search.findall( target_nodes, filter_=_get_matcher_function(jump_id)) if jump_node: continue # we need to find the common ancestor source_branch = _get_branch_node(source_nodes, jump_id, 'source') if source_branch is None: raise RuntimeError('No matching jump node found in source') ancestors, _, _ = tree_walker.walk(source_branch, source_nodes) # assume we need to insert at the root (the last ancestor as we walk # up the tree) common_ancestor = ancestors[-1] for node in ancestors: # otherwise, if we have found a common ancestor, we can insert at # that point if _get_branch_node(target_nodes, node.id, 'target') is not None: common_ancestor = node continue # set our insert point target_branch = target_nodes if common_ancestor.parent.id is not None: target_branch = _get_branch_node(target_nodes, common_ancestor.id, 'target') # insert the jump to information # will always be done as last child _insert_into_target_tree(common_ancestor, target_branch, target_nodes, 'last_child') # find any new jumps nodes_with_jumps = anytree.search.findall(common_ancestor, filter_=_get_nodes_with_jump) # add these new jumps to be checked for node in nodes_with_jumps: to_jump_to.append(node.node['next_step']['dialog_node']) # for rendering, let's update the desc fields with titles of the jump nodes_with_jumps = anytree.search.findall(target_nodes, filter_=_get_nodes_with_jump) # update the descriptions for node in nodes_with_jumps: dest = _get_all_matches(target_nodes, node.node['next_step']['dialog_node']) if len(dest) == 1: node.desc = node.desc + ' (jumps to: {})'.format(dest[0].desc) # go ahead and update the workspace _update_workspace( target_username, target_password, target_workspace, [x.node for x in LevelOrderIter(target_nodes) \ if x.id is not None]) print('dialog update complete') # projected rendering of tree projected = anytree.RenderTree( target_nodes, childiter=_sort_child_nodes).by_attr(attrname='desc') return target_nodes, projected
def verify_user(session, action, param_dict): """ 检查账号密码 """ if action == "by_username": username = param_dict["username"] password = param_dict["password"] #query_result = session.query(User).filter(User.mobilephonenumber == mobilephone_number,User.password == password).first() query_result = session.query(User).filter( User.username == username, User.password == password).first() if query_result: uid = query_result.id username = query_result.username realname = query_result.realname status = query_result.status if status: query = session.query( UserRole, RolePermission, Permission).filter( UserRole.uid == uid, UserRole.rid == RolePermission.rid, RolePermission.pid == Permission.id).order_by() root = anytree.AnyNode(name="root") id2dict = {} rid_set = set() pid_set = set() permission_dict_list = [] exporter = anytree.exporter.JsonExporter(indent=2, sort_keys=True) for v in query: #print([v.UserRole.rid,v.RolePermission.pid,v.Permission.id,v.Permission.fatherpid,v.Permission.name]) rid_set.add(v.UserRole.rid) if not v.Permission.id in pid_set: pid_set.add(v.Permission.id) permission_dict_list.append({ "id": v.Permission.id, "name": v.Permission.name, "fatherpid": v.Permission.fatherpid }) for v in permission_dict_list: if v["fatherpid"] == -1: id2dict[v["id"]] = anytree.AnyNode(id=v["id"], name=v["name"], parent=root) #二层结构的特别写法 for v in permission_dict_list: if v["fatherpid"] != -1: id2dict[v["id"]] = anytree.AnyNode( id=v["id"], name=v["name"], parent=id2dict[v["fatherpid"]]) return { "data": json.loads(exporter.export(root)), "username": username, "uid": uid, "rid_set": rid_set, "realname": realname } else: raise ValueError("等待用户审核") else: raise ValueError("用户名密码错误")