Walk the directory tree under root up till reaching max_depth.
    With max_depth=None (default), do not limit depth.
965826
def _depth_limited_walk(top, max_depth=None):
    '''
    
    '''
    for root, dirs, files in salt.utils.path.os_walk(top):
        if max_depth is not None:
            rel_depth = root.count(os.path.sep) - top.count(os.path.sep)
            if rel_depth >= max_depth:
                del dirs[:]
        yield (six.text_type(root), list(dirs), list(files))
779693
def _root(self):
        
        _n = self
        while _n.parent:
            _n = _n.parent
        return _n
100052
private TreeNodeVisitor walkCorruptedPath(TreeLearner model, DataPoint dp, int j, Random rand)
    {
        TreeNodeVisitor curNode = model.getTreeNodeVisitor();
        while(!curNode.isLeaf())
        {
            int path = curNode.getPath(dp);
            int numChild = curNode.childrenCount();
            if(curNode.featuresUsed().contains(j))//corrupt the feature!
            {
                //this gets us a random OTHER path, wont be the same b/c we would need to wrap around 1 farther
                path = (path + rand.nextInt(numChild)) % numChild;
            }
            
            if(curNode.isPathDisabled(path))
                break;
            else
                curNode = curNode.getChild(path);
        }
        return curNode;
    }
502921
def walklevel(path, depth = -1, **kwargs):
        
        # if depth is negative, just walk
        if depth < 0:
            for root, dirs, files in os.walk(path, **kwargs):
                yield root, dirs, files

        # path.count works because is a file has a "/" it will show up in the list
        # as a ":"
        path    = path.rstrip(os.path.sep)
        num_sep = path.count(os.path.sep)
        for root, dirs, files in os.walk(path, **kwargs):
            yield root, dirs, files
            num_sep_this = root.count(os.path.sep)
            if num_sep + depth <= num_sep_this:
                del dirs[:]
876358
def walk(self,depth=0,fsNode=None) :
        """"""
        if not fsNode :
            fsNode = FSNode(self.init_path,self.init_path,0)
            
        if fsNode.isdir() :
            if self.check_dir(fsNode) :
                if self.check_return(fsNode) :
                    yield fsNode                
                for n in fsNode.children() :
                    if n.islink() :
                        # currently we don't follow links
                        continue
                    for n2 in self.walk(depth+1,n) :
                        if self.check_return(n2) :
                            yield n2
        else :
            if self.check_file(fsNode) :
                if self.check_return(fsNode) :
                    yield fsNode
        raise StopIteration
422227
def _walk(self) -> None:
        
        # Buffer of NTs to expand, previous actions
        incomplete_paths = [([str(type_)], [f"{START_SYMBOL} -> {type_}"]) for type_ in
                            self._world.get_valid_starting_types()]

        self._completed_paths = []
        actions = self._world.get_valid_actions()
        # Keeps track of `MultiMatchNamedBasicTypes` to substitute them with appropriate types.
        multi_match_substitutions = self._world.get_multi_match_mapping()
        # Overview: We keep track of the buffer of non-terminals to expand, and the action history
        # for each incomplete path. At every iteration in the while loop below, we iterate over all
        # incomplete paths, expand one non-terminal from the buffer in a depth-first fashion, get
        # all possible next actions triggered by that non-terminal and add to the paths. Then, we
        # check the expanded paths, to see if they are 1) complete, in which case they are
        # added to completed_paths, 2) longer than max_path_length, in which case they are
        # discarded, or 3) neither, in which case they are used to form the incomplete_paths for the
        # next iteration of this while loop.
        # While the non-terminal expansion is done in a depth-first fashion, note that the search over
        # the action space itself is breadth-first.
        while incomplete_paths:
            next_paths = []
            for nonterminal_buffer, history in incomplete_paths:
                # Taking the last non-terminal added to the buffer. We're going depth-first.
                nonterminal = nonterminal_buffer.pop()
                next_actions = []
                if nonterminal in multi_match_substitutions:
                    for current_nonterminal in [nonterminal] + multi_match_substitutions[nonterminal]:
                        if current_nonterminal in actions:
                            next_actions.extend(actions[current_nonterminal])
                elif nonterminal not in actions:
                    # This happens when the nonterminal corresponds to a type that does not exist in
                    # the context. For example, in the variable free variant of the WikiTables
                    # world, there are nonterminals for specific column types (like date). Say we
                    # produced a path containing "filter_date_greater" already, and we do not have
                    # an columns of type "date", then this condition would be triggered. We should
                    # just discard those paths.
                    continue
                else:
                    next_actions.extend(actions[nonterminal])
                # Iterating over all possible next actions.
                for action in next_actions:
                    new_history = history + [action]
                    new_nonterminal_buffer = nonterminal_buffer[:]
                    # Since we expand the last action added to the buffer, the left child should be
                    # added after the right child.
                    for right_side_part in reversed(self._get_right_side_parts(action)):
                        if types.is_nonterminal(right_side_part):
                            new_nonterminal_buffer.append(right_side_part)
                    next_paths.append((new_nonterminal_buffer, new_history))
            incomplete_paths = []
            for nonterminal_buffer, path in next_paths:
                # An empty buffer means that we've completed this path.
                if not nonterminal_buffer:
                    # Indexing completed paths by the nonterminals they contain.
                    next_path_index = len(self._completed_paths)
                    for action in path:
                        for value in self._get_right_side_parts(action):
                            if not types.is_nonterminal(value):
                                self._terminal_path_index[action].add(next_path_index)
                    self._completed_paths.append(path)
                # We're adding to incomplete_paths for the next iteration, only those paths that are
                # shorter than the max_path_length. The remaining paths will be discarded.
                elif len(path) <= self._max_path_length:
                    incomplete_paths.append((nonterminal_buffer, path))
1246441
def _walk_depth(
        self,
        fs,  # type: FS
        path,  # type: Text
        namespaces=None,  # type: Optional[Collection[Text]]
    ):
        # type: (...) -> Iterator[Tuple[Text, Optional[Info]]]
        
        # No recursion!

        _combine = combine
        _scan = self._scan
        _calculate_depth = self._calculate_depth
        _check_open_dir = self._check_open_dir
        _check_scan_dir = self._check_scan_dir
        _check_file = self.check_file
        depth = _calculate_depth(path)

        stack = [
            (path, _scan(fs, path, namespaces=namespaces), None)
        ]  # type: List[Tuple[Text, Iterator[Info], Optional[Tuple[Text, Info]]]]

        push = stack.append

        while stack:
            dir_path, iter_files, parent = stack[-1]
            info = next(iter_files, None)
            if info is None:
                if parent is not None:
                    yield parent
                yield dir_path, None
                del stack[-1]
            elif info.is_dir:
                _depth = _calculate_depth(dir_path) - depth + 1
                if _check_open_dir(fs, dir_path, info):
                    if _check_scan_dir(fs, dir_path, info, _depth):
                        _path = _combine(dir_path, info.name)
                        push(
                            (
                                _path,
                                _scan(fs, _path, namespaces=namespaces),
                                (dir_path, info),
                            )
                        )
                    else:
                        yield dir_path, info
            else:
                if _check_file(fs, info):
                    yield dir_path, info
494301
def walk_paths(self,
                   base: Optional[pathlib.PurePath] = pathlib.PurePath()) \
            -> Iterator[pathlib.PurePath]:
        
        raise NotImplementedError()
237223
def longest_consecutive(root):
    
    if root is None:
        return 0
    max_len = 0
    dfs(root, 0, root.val, max_len)
    return max_len
1040992
def nextparent(self, parent, depth):
        '''
        
        '''
        if depth > 1:  # can't jump to parent of root node!
            pdir = os.path.dirname(self.name)
            line = 0
            for c, d in parent.traverse():
                if line > parent.curline and c.name.startswith(pdir):
                    parent.curline += 1
                line += 1
        else:  # otherwise just skip to next directory
            line = -1  # skip hidden parent node
            for c, d in parent.traverse():
                if line > parent.curline:
                    parent.curline += 1
                    if os.path.isdir(c.name) and c.name in parent.children[0:]:
                        break
                line += 1
415569
def pushd(path, mkdir=True, cleanup=False):
    
    cwd = os.getcwd()
    exists = osp.exists(path)
    if mkdir and not exists:
        os.makedirs(path)
    os.chdir(path)
    try:
        yield path
    finally:
        os.chdir(cwd)
        if not exists and cleanup:
            # NB: should we be checking for rmtree.avoids_symlink_attacks ?
            shutil.rmtree(path)
643763
def depth(self):
        
        return len(self.path.rstrip(os.sep).split(os.sep))
604219
def do_tree(self, path, max_depth, level, full_path, include_stat):
        
        try:
            children = self.get_children(path)
        except (NoNodeError, NoAuthError):
            children = []

        for child in children:
            cpath = os.path.join(path, child) if full_path else child
            if include_stat:
                yield cpath, level, self.stat(os.path.join(path, child))
            else:
                yield cpath, level

            if max_depth == 0 or level + 1 < max_depth:
                cpath = os.path.join(path, child)
                for rchild_rlevel_rstat in self.do_tree(cpath, max_depth, level + 1, full_path, include_stat):
                    yield rchild_rlevel_rstat
922795
def increment(self):
        
        # Increment position from the deepest place of the tree first.
        for index in reversed(range(self.depth)):
            self.indexes[index] += 1
            # We haven't reached the end of board, no need to adjust upper
            # level.
            if self.indexes[index] < self.range_size:
                break
            # We've reached the end of board. Reset current level and increment
            # the upper level.
            self.indexes[index] = 0

        # Now that we incremented our indexes, we need to deduplicate positions
        # shering the same UIDs, by aligning piece's indexes to their parents.
        # This works thanks to the sort performed on self.pieces
        # initialization. See #7.
        for i in range(self.depth - 1):
            if (self.pieces[i] == self.pieces[i + 1]) and (
                    self.indexes[i] > self.indexes[i + 1]):
                self.indexes[i + 1] = self.indexes[i]
12617
def _traverse_tree(tree, path):
        """"""
        path_steps = (step for step in path.split('.') if step != '')
        # Special handling for first step, because the first step isn't under 'objects'
        first_step = path_steps.next()
        subtree = tree[first_step]

        for step in path_steps:
            subtree = subtree['children'][step]
        return subtree
1148909
public void traverse(Object root) {
    // Reset the state
    visited.clear();
    toVisit.clear();

    if (root == null) return;

    addIfNotVisited(root, root.getClass());
    start();
  }
535733
def min_depth(self, root):
    
    if root is None:
        return 0
    if root.left is not None or root.right is not None:
        return max(self.minDepth(root.left), self.minDepth(root.right))+1
    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1