Generates the recursive reduction tree. Used by mapReduce.
505554
def _recursiveReduce(mapFunc, reductionFunc, scan, *iterables):
    """"""
    if iterables:
        half = min(len(x) // 2 for x in iterables)
        data_left = [list(x)[:half] for x in iterables]
        data_right = [list(x)[half:] for x in iterables]
    else:
        data_left = data_right = [[]]

    # Submit the left and right parts of the reduction
    out_futures = [None, None]
    out_results = [None, None]
    for index, data in enumerate([data_left, data_right]):
        if any(len(x) <= 1 for x in data):
            out_results[index] = mapFunc(*list(zip(*data))[0])
        else:
            out_futures[index] = submit(
                _recursiveReduce,
                mapFunc,
                reductionFunc,
                scan,
                *data
            )

    # Wait for the results
    for index, future in enumerate(out_futures):
        if future:
            out_results[index] = future.result()

    # Apply a scan if needed
    if scan:
        last_results = copy.copy(out_results)
        if type(out_results[0]) is not list:
            out_results[0] = [out_results[0]]
        else:
            last_results[0] = out_results[0][-1]
        if type(out_results[1]) is list:
            out_results[0].extend(out_results[1][:-1])
            last_results[1] = out_results[1][-1]
        out_results[0].append(reductionFunc(*last_results))
        return out_results[0]

    return reductionFunc(*out_results)
1075924
function _recursiveDeps(graph, name, deps) {
  return Object.keys(deps).forEach((key) => {
    const dep = deps[key];
    if (PLUGIN.test(dep)) {
      return;
    }
    if (typeof dep === 'string') {
      if (!graph.hasNode(dep)) {
        graph.addNode(dep);
      }
      graph.addDependency(name, dep);
    } else if (typeof dep === 'object') {
      _recursiveDeps(graph, name, deps[key]);
    }
  });
}
663919
private Intermediate mapAndReduce(Context ctx) {
        /* Fetch each metric wildcard and add it to the to-be-processed list. */
        final List<Map.Entry<Tags, MetricValue>> matcher_tsvs = matchers_.stream()
                .flatMap(m -> m.filter(ctx))
                .map(named_entry -> SimpleMapEntry.create(named_entry.getKey().getTags(), named_entry.getValue()))
                .collect(Collectors.toList());
        /* Resolve each expression. */
        final Map<Boolean, List<TimeSeriesMetricDeltaSet>> expr_tsvs_map = exprs_.stream()
                .map(expr -> expr.apply(ctx))
                .collect(Collectors.partitioningBy(TimeSeriesMetricDeltaSet::isVector));
        final List<TimeSeriesMetricDeltaSet> expr_tsvs = expr_tsvs_map.getOrDefault(true, Collections.emptyList());
        final Optional<T> scalar = expr_tsvs_map.getOrDefault(false, Collections.emptyList())
                .stream()
                .map(tsv_set -> map_(tsv_set.asScalar().get()))
                .reduce(this::reducer_);

        /*
         * Reduce everything using the reducer (in the derived class).
         */
        return new Intermediate(scalar, unmodifiableMap(aggregation_.apply(
                matcher_tsvs.stream(), expr_tsvs.stream().flatMap(TimeSeriesMetricDeltaSet::streamAsMap),
                Map.Entry::getKey, Map.Entry::getKey,
                Map.Entry::getValue, Map.Entry::getValue)
                .entrySet().stream()
                .map(entry -> {
                    return entry.getValue().stream().map(this::map_)
                            .reduce(this::reducer_)
                            .map(v -> SimpleMapEntry.create(entry.getKey(), v));
                })
                .flatMap(opt -> opt.map(Stream::of).orElseGet(Stream::empty))
                .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()))));
    }
192649
synchronized void computeTrees() {
        boolean changed;
        try {
            createBuffers();
            do {
                switchBuffers();
                changed = computeOneLevel();
//System.out.println("Tree obj.   "+heap.idToOffsetMap.treeObj);
//if (changed) System.out.println("Next level  "+nextLevelSize);
            } while (changed);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        deleteBuffers();
//System.out.println("Done!");
    }
474248
def tree_to_gexf(tree:'BubbleTree') -> str:
    
    output_nodes, output_edges = '', ''

    def build_node(node:str) -> str:
        """Yield strings describing given node, recursively"""
        if tree.inclusions[node]:  # it's a powernode
            yield '<node id="{}" label="{}">'.format(node, node)
            yield '<nodes>'
            for sub in tree.inclusions[node]:
                yield from build_node(sub)
            yield '</nodes>'
            yield '</node>'
        else:  # it's a regular node
            yield '<node id="{}" label="{}"/>'.format(node, node)
        return

    # build full hierarchy from the roots
    output_nodes += '\n'.join('\n'.join(build_node(root)) for root in tree.roots)

    # # add the edges to the final graph
    for idx, (source, targets) in enumerate(tree.edges.items()):
        for target in targets:
            if source <= target:  # edges dict is complete. This avoid multiple edges.
                output_edges += '<edge id="{}" source="{}" target="{}" />\n'.format(idx, source, target)

    return GEXF_TEMPLATE.format(
        'directed' if tree.oriented else 'undirected',
        output_nodes,
        output_edges
    )
1056542
def get_tree(cls, parent=None):
        
        if parent:
            depth = parent.get_depth() + 1
            results = [parent]
        else:
            depth = 1
            results = []
        cls._get_tree_recursively(results, parent, depth)
        return results
310227
def _build_tree(self):
        
        if not self.nn_ready:
            self.kdtree   = scipy.spatial.cKDTree(self.data)
            self.nn_ready = True
440556
def _precompute(self, tree):
        
        d = {}
        for n in tree.preorder_internal_node_iter():
            d[n] = namedtuple('NodeDist', ['dist_from_root', 'edges_from_root'])
            if n.parent_node:
                d[n].dist_from_root = d[n.parent_node].dist_from_root + n.edge_length
                d[n].edges_from_root = d[n.parent_node].edges_from_root + 1
            else:
                d[n].dist_from_root = 0.0
                d[n].edges_from_root = 0
        return d
463956
def _flatten_subclass_tree(cls):
    
    subclasses = frozenset(cls.__subclasses__())
    children = frozenset(toolz.concat(map(_flatten_subclass_tree, subclasses)))
    return frozenset({cls}) | subclasses | children
519819
def descendants
      nodes = []
      children.each do |c|
        nodes << c
        nodes << c.descendants
      end
      nodes.flatten
    end
992350
def rebuild_tree(cls, session, tree_id):
        
        session.query(cls).filter_by(tree_id=tree_id)\
            .update({cls.left: 0, cls.right: 0, cls.level: 0})
        top = session.query(cls).filter_by(parent_id=None)\
            .filter_by(tree_id=tree_id).one()
        top.left = left = 1
        top.right = right = 2
        top.level = level = cls.get_default_level()

        def recursive(children, left, right, level):
            level = level + 1
            for i, node in enumerate(children):
                same_level_right = children[i - 1].right
                left = left + 1

                if i > 0:
                    left = left + 1
                if same_level_right:
                    left = same_level_right + 1

                right = left + 1
                node.left = left
                node.right = right
                parent = node.parent

                j = 0
                while parent:
                    parent.right = right + 1 + j
                    parent = parent.parent
                    j += 1

                node.level = level
                recursive(node.children, left, right, level)

        recursive(top.children, left, right, level)
1305529
private INode genDirStructure(String rootName, int maxDepth) {
    INode root = new INode(rootName);

    if (maxDepth>0) {
      maxDepth--;
      int minDepth = maxDepth*2/3;
      // Figure out the number of subdirectories to generate
      int numOfSubDirs = minWidth + r.nextInt(maxWidth-minWidth+1);
      // Expand the tree
      for (int i=0; i<numOfSubDirs; i++) {
        int childDepth = (maxDepth == 0)?0:
          (r.nextInt(maxDepth-minDepth+1)+minDepth);
        INode child = genDirStructure("dir"+i, childDepth);
        root.addChild(child);
      }
    }
    return root;
  }
1340108
public void simplify()
    {
        if (sourceNode != null)
        {
            mdagDataArray = new SimpleMDAGNode[transitionCount];
            createSimpleMDAGTransitionSet(sourceNode, mdagDataArray, 0);
            simplifiedSourceNode = new SimpleMDAGNode('\0', false, sourceNode.getOutgoingTransitionCount());

            //Mark the previous MDAG data structure and equivalenceClassMDAGNodeHashMap
            //for garbage collection since they are no longer needed.
            sourceNode = null;
            equivalenceClassMDAGNodeHashMap = null;
            /////
        }
    }
249611
private function generateTree($data, $total_depth, $current_depth = 1) {
        ksort($data);

        $table = [];

        foreach ($data as $key => $value) {
            $row = [];
            if ($current_depth > 1) {
                $row = array_merge($row, array_fill(0, ($current_depth - 1), ''));
            }

            $row[] = '<comment>' . $key . '</comment>';
            if (!is_array($value)) {
                $row[] = (is_bool($value)) ? (($value) ? 'true' : 'false') : $value;
            }

            // Pad the row out with empty columns equal to the total subtracting the current recursive depth.
            $empty_columns = ($total_depth - $current_depth);
            $empty_columns = array_fill(count($row) - 1, $empty_columns, '');
            $row = array_merge($row, $empty_columns);

            $table[] = $row;

            if (is_array($value)) {
                $table = array_merge($table, $this->generateTree($value, $total_depth, $current_depth + 1));
            }
        }

        return $table;
    }
1147510
def generate(ast_tree: ast.Tree, model_name: str, options: Dict[str, bool]=None) -> Model:
    
    if options is None:
        options = {}
    component_ref = ast.ComponentRef.from_string(model_name)
    ast_walker = GeneratorWalker()
    flat_tree = flatten(ast_tree, component_ref)
    component_ref_tuple = component_ref.to_tuple()
    casadi_gen = Generator(flat_tree, component_ref_tuple[-1], options)
    ast_walker.walk(casadi_gen, flat_tree)
    return casadi_gen.model
1282018
def _reduce_input(self, inputs, reducer, final=NotImplemented):
        
        for key, values in groupby(inputs, key=lambda x: self.internal_serialize(x[0])):
            for output in reducer(self.deserialize(key), (v[1] for v in values)):
                yield output
        if final != NotImplemented:
            for output in final():
                yield output
        self._flush_batch_incr_counter()
781650
private void buildCoverTree() {
        ArrayList<DistanceSet> pointSet = new ArrayList<>();
        ArrayList<DistanceSet> consumedSet = new ArrayList<>();

        E point = data[0];
        int idx = 0;
        double maxDist = -1;

        for (int i = 1; i < data.length; i++) {
            DistanceSet set = new DistanceSet(i);
            double dist = distance.d(point, data[i]);
            set.dist.add(dist);
            pointSet.add(set);
            if (dist > maxDist) {
                maxDist = dist;
            }
        }

        root = batchInsert(idx, getScale(maxDist), getScale(maxDist), pointSet, consumedSet);
    }