Returns db value and branch in root->leaf order
191908
def _get(self, key: bytes) -> Tuple[bytes, Tuple[Hash32]]:
        
        validate_is_bytes(key)
        validate_length(key, self._key_size)
        branch = []

        target_bit = 1 << (self.depth - 1)
        path = to_int(key)
        node_hash = self.root_hash
        # Append the sibling node to the branch
        # Iterate on the parent
        for _ in range(self.depth):
            node = self.db[node_hash]
            left, right = node[:32], node[32:]
            if path & target_bit:
                branch.append(left)
                node_hash = right
            else:
                branch.append(right)
                node_hash = left
            target_bit >>= 1

        # Value is the last hash in the chain
        # NOTE: Didn't do exception here for testing purposes
        return self.db[node_hash], tuple(branch)
1237963
def node_val_dump(self):
        """"""
        self._flush_node_val()
        for (
                graph, node, key, branch, turn, tick, value
        ) in self.sql('node_val_dump'):
            yield (
                self.unpack(graph),
                self.unpack(node),
                self.unpack(key),
                branch,
                turn,
                tick,
                self.unpack(value)
            )
1313302
def get_tree(ident_hash, baked=False):
    """"""
    id, version = get_id_n_version(ident_hash)

    stmt = _get_sql('get-tree.sql')
    args = dict(id=id, version=version, baked=baked)

    with db_connect() as db_conn:
        with db_conn.cursor() as cursor:
            cursor.execute(stmt, args)
            try:
                tree = cursor.fetchone()[0]
            except TypeError:
                raise NotFound(ident_hash)
    if tree is None:
        raise NotFound(ident_hash)

    return tree
199339
def _query(_node_id, value=None, **kw):
    ""
    query_result = []
    try:
        query_result = db.execute(text(fetch_query_string('select_query_from_node.sql')), **kw).fetchall()
    except DatabaseError as err:
        current_app.logger.error("DatabaseError: %s, %s", err, kw)
        return value
    #current_app.logger.debug("queries kw: %s", kw)
    #current_app.logger.debug("queries value: %s", value)
    current_app.logger.debug("queries: %s", query_result)
    if query_result:
        values = []
        for query_name in [x['name'] for x in query_result]:
            if query_name:
                result = []
                try:
                    current_app.logger.debug("query_name: %s", query_name)
                    #current_app.logger.debug("kw: %s", kw)
                    # Query string can be insert or select here
                    #statement = text(fetch_query_string(query_name))
                    #params = [x.key for x in statement.params().get_children()]
                    #skw = {key: kw[key] for key in params}
                    #result = db.execute(statement, **skw)
                    result = db.execute(text(fetch_query_string(query_name)), **kw)
                    current_app.logger.debug("result query: %s", result.keys())
                except (DatabaseError, StatementError) as err:
                    current_app.logger.error("DatabaseError (%s) %s: %s", query_name, kw, err)
                if result and result.returns_rows:
                    result = result.fetchall()
                    #values.append(([[dict(zip(result.keys(), x)) for x in result]], result.keys()))
                    #values.append((result.fetchall(), result.keys()))
                    #current_app.logger.debug("fetchall: %s", values)
                    if len(result) == 0:
                        values.append(([], []))
                    else:
                        current_app.logger.debug("result: %s", result)
                        # There may be more results, but only interested in the
                        # first one. Use the older rowify method for now.
                        # TODO: use case for rowify?
                        values.append(rowify(result, [(x, None) for x in result[0].keys()]))
                        #current_app.logger.debug("fetchone: %s", values)
        value = values
    #current_app.logger.debug("value: %s", value)
    return value
230070
def complete_leaf_value(return_type: GraphQLLeafType, result: Any) -> Any:
        
        serialized_result = return_type.serialize(result)
        if is_invalid(serialized_result):
            raise TypeError(
                f"Expected a value of type '{inspect(return_type)}'"
                f" but received: {inspect(result)}"
            )
        return serialized_result
925676
def schema_root(self) -> "SchemaTreeNode":
        """"""
        sn = self
        while sn.parent:
            sn = sn.parent
        return sn
1278621
def leaf_list(cls, name, parent=None, interleave=None):
        """"""
        node = cls("_list_", parent, interleave=interleave)
        node.attr["name"] = name
        node.keys = None
        node.minEl = "0"
        node.maxEl = None
        node.occur = 3
        return node
1068970
function traverseLeaf(next, requireString, requireIndex) {
        var reqPath
          , reqDeps
          ;

        if ('.' === requireString[0]) {
          reqPath = url.resolve('/' + leaf.modulepath, requireString).substr(1); // strip leading '/'
        } else {
          // TODO handle absolute paths
          reqPath = requireString;
        }

        // check that we haven't visited this dependency tree already
        reqDeps = allDepsList[reqPath];
        if (reqDeps) {
          reqDeps.requiredAs[requireString] = true;
          leaf.dependencyList[requireIndex] = reqDeps;
          next();
          return;
        }

        getModuleTreeHelper(null, allDepsList, pkg, leaf, requireString, function (err, deps) {
          if (err) {
            callback(err);
            return;
          }

          leaf.dependencyList[requireIndex] = deps;
          next();
        });
      }
619109
def traverse_levelorder(self, leaves=True, internal=True):
        ''''''
        for node in self.root.traverse_levelorder(leaves=leaves, internal=internal):
            yield node
721964
def traverse_levelorder(self, leaves=True, internal=True):
        '''
        '''
        q = deque(); q.append(self)
        while len(q) != 0:
            n = q.popleft()
            if (leaves and n.is_leaf()) or (internal and not n.is_leaf()):
                yield n
            q.extend(n.children)
1241361
def from_db_value(self, value, expression, connection, context):
        ''''''
        if value is None:
            return value
        return self.parse_seconds(value)
1077233
function getTree(root, deps) {
  var tree;

  tree = {};

  populateItem(tree, root, deps);

  return tree;
}
686989
def tree(self):
        
        bs = self.model.branchScale
        for node in self._tree.find_clades():
            if node != self._tree.root:
                node.branch_length = self.t[self.name_to_nodeindex[node]] * bs
        return self._tree
456794
def value_leaf(self, data, schema, tree):
        
        key, value = data
        schema_key, schema_value = schema

        if hasattr(schema_value, '__validator_leaf__'):
            return schema_value(value, tree)
        enforce(value, schema_value, tree, 'value')
403859
def __embed_branch_recursive(u, dfs_data):
    """"""
    #print "\nu: {}\nadj: {}".format(u, dfs_data['adj'][u])

    #print 'Pre-inserts'
    #print "FG: {}".format(dfs_data['FG'])
    #print "LF: {}".format(dfs_data['LF'])
    #print "RF: {}".format(dfs_data['RF'])

    for v in dfs_data['adj'][u]:
        #print "\nu, v: {}, {}".format(u, v)
        #print "dfs_u, dfs_v: {}, {}".format(D(u, dfs_data), D(v, dfs_data))
        nonplanar = True
        if a(v, dfs_data) == u:
            #print 'Ancestor block entered:', u, v
            if b(v, dfs_data) == u:
                successful = __insert_branch(u, v, dfs_data)
                if not successful:
                    #print 'InsertBranch({}, {}) Failed'.format(u, v)
                    nonplanar = True
                    return nonplanar
            nonplanar = __embed_branch_recursive(v, dfs_data)
            if nonplanar:
                return nonplanar
        elif is_frond(u, v, dfs_data):
            #print 'Frond block entered:', u, v
            successful = __embed_frond(u, v, dfs_data)
            if not successful:
                #print 'EmbedFrond({}, {}) Failed'.format(u, v)
                nonplanar = True
                return nonplanar

            #print 'Post EmbedFrond'
            #print "FG: {}".format(dfs_data['FG'])
            #print "LF: {}".format(dfs_data['LF'])
            #print "RF: {}".format(dfs_data['RF'])
        else:
            # This block is totally valid, and there will be multiple cases when it gets hit.
            # We only want to do things if an edge is a tree edge (parent to child along the spine of the DFS tree),
            # or if it's a frond edge (an edge moving up the tree from lower along the spine).
            # Every non-tree edge will eventually get handled by the frond edge code as we recurse up the spine.
            pass
    #print "{}: Should be planar".format(u)

    #print 'Post-inserts'
    #print "FG: {}".format(dfs_data['FG'])
    #print "LF: {}".format(dfs_data['LF'])
    #print "RF: {}".format(dfs_data['RF'])

    nonplanar = False
    return nonplanar
197674
def initdb(self):
        """"""
        if hasattr(self, 'alchemist'):
            self.alchemist.meta.create_all(self.engine)
            if 'branch' not in self.globl:
                self.globl['branch'] = 'trunk'
            if 'rev' not in self.globl:
                self.globl['rev'] = 0
            return
        from sqlite3 import OperationalError
        cursor = self.connection.cursor()
        try:
            cursor.execute('SELECT * FROM global;')
        except OperationalError:
            cursor.execute(self.strings['create_global'])
        if 'branch' not in self.globl:
            self.globl['branch'] = 'trunk'
        if 'turn' not in self.globl:
            self.globl['turn'] = 0
        if 'tick' not in self.globl:
            self.globl['tick'] = 0
        for table in (
            'branches',
            'turns',
            'graphs',
            'graph_val',
            'nodes',
            'node_val',
            'edges',
            'edge_val',
            'plans',
            'plan_ticks'
        ):
            try:
                cursor.execute('SELECT * FROM ' + table + ';')
            except OperationalError:
                cursor.execute(self.strings['create_' + table])
956668
def _get(self, node_hash, keypath):
        
        # Empty trie
        if node_hash == BLANK_HASH:
            return None
        nodetype, left_child, right_child = parse_node(self.db[node_hash])
        # Key-value node descend
        if nodetype == LEAF_TYPE:
            if keypath:
                return None
            return right_child
        elif nodetype == KV_TYPE:
            # Keypath too short
            if not keypath:
                return None
            if keypath[:len(left_child)] == left_child:
                return self._get(right_child, keypath[len(left_child):])
            else:
                return None
        # Branch node descend
        elif nodetype == BRANCH_TYPE:
            # Keypath too short
            if not keypath:
                return None
            if keypath[:1] == BYTE_0:
                return self._get(left_child, keypath[1:])
            else:
                return self._get(right_child, keypath[1:])