Determine the spacing of the current node depending on the number
       of the leaves of the tree
195481
def _spacingx(node, max_dims, xoffset, xspace):
    '''
    '''
    x_spacing = _n_terminations(node) * xspace

    if x_spacing > max_dims[0]:
        max_dims[0] = x_spacing

    return xoffset - x_spacing / 2.
356485
function() {
    var n; // iterates over tree elements

    // Initialize the trees.
    for(n = 0; n < zip_L_CODES;  n++) zip_dyn_ltree[n].fc = 0;
    for(n = 0; n < zip_D_CODES;  n++) zip_dyn_dtree[n].fc = 0;
    for(n = 0; n < zip_BL_CODES; n++) zip_bl_tree[n].fc = 0;

    zip_dyn_ltree[zip_END_BLOCK].fc = 1;
    zip_opt_len = zip_static_len = 0;
    zip_last_lit = zip_last_dist = zip_last_flags = 0;
    zip_flags = 0;
    zip_flag_bit = 1;
}
720761
def condense(self):
        ''''''
        self.resolve_polytomies(); labels_below = dict(); longest_leaf_dist = dict()
        for node in self.traverse_postorder():
            if node.is_leaf():
                labels_below[node] = [node.label]; longest_leaf_dist[node] = None
            else:
                labels_below[node] = set()
                for c in node.children:
                    labels_below[node].update(labels_below[c])
                    d = longest_leaf_dist[c]
                    if c.edge_length is not None:
                        if d is None:
                            d = 0
                        d += c.edge_length
                    if node not in longest_leaf_dist or longest_leaf_dist[node] is None or (d is not None and d > longest_leaf_dist[node]):
                        longest_leaf_dist[node] = d
        nodes = deque(); nodes.append(self.root)
        while len(nodes) != 0:
            node = nodes.pop()
            if node.is_leaf():
                continue
            if len(labels_below[node]) == 1:
                node.label = labels_below[node].pop(); node.children = list()
                if longest_leaf_dist[node] is not None:
                    if node.edge_length is None:
                        node.edge_length = 0
                    node.edge_length += longest_leaf_dist[node]
            else:
                nodes.extend(node.children)
198174
def _generate_dendro(self, current_section, spacing, offsets):
        '''
        '''
        max_dims = self._max_dims
        start_x = _spacingx(current_section, max_dims, offsets[0], spacing[0])

        for child in current_section.children:

            segments = child.points

            # number of leaves in child
            terminations = _n_terminations(child)

            # segement lengths
            seg_lengths = np.linalg.norm(np.subtract(segments[:-1, COLS.XYZ],
                                                     segments[1:, COLS.XYZ]), axis=1)

            # segment radii
            radii = np.vstack((segments[:-1, COLS.R], segments[1:, COLS.R])).T \
                if self._show_diameters else np.zeros((seg_lengths.shape[0], 2))

            y_offset = offsets[1]
            for i, slen in enumerate(seg_lengths):

                # offset update for the vertical segments
                new_offsets = _update_offsets(start_x, spacing, terminations,
                                              (offsets[0], y_offset), slen)

                # segments are drawn vertically, thus only y_offset changes from init offsets
                self._rectangles[self._n] = _vertical_segment((offsets[0], y_offset),
                                                              new_offsets, spacing, radii[i, :])
                self._n += 1
                y_offset = new_offsets[1]

            if y_offset + spacing[1] * 2 + sum(seg_lengths) > max_dims[1]:
                max_dims[1] = y_offset + spacing[1] * 2. + sum(seg_lengths)

            self._max_dims = max_dims
            # recursive call to self.
            self._generate_dendro(child, spacing, new_offsets)

            # update the starting position for the next child
            start_x += terminations * spacing[0]

            # write the horizontal lines only for bifurcations, where the are actual horizontal
            # lines and not zero ones
            if offsets[0] != new_offsets[0]:

                # horizontal segment. Thickness is either 0 if show_diameters is false
                # or 1. if show_diameters is true
                self._rectangles[self._n] = _horizontal_segment(offsets, new_offsets, spacing, 0.)
                self._n += 1
374781
function measureText (nodes, parentNode) {
  let width = 0
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i]
    width += measure(node.textContent, node.nodeType === 1 ? node : parentNode)
  }
  return width
}
611236
function findChildContainingNode(root, node) {
  const parentNode = node.parentNode;
  return parentNode === root ?
    node :
    findChildContainingNode(root, parentNode);
}
801181
private void adjustTree(IndexTreePath<E> subtree) {
    final Logging log = getLogger();
    if(log.isDebugging()) {
      log.debugFine("Adjust tree " + subtree + "\n");
    }

    // get the root of the subtree
    int nodeIndex = subtree.getIndex();
    N node = getNode(subtree.getEntry());

    // overflow in node; split the node
    if(hasOverflow(node)) {
      // do the split
      Assignments<E> assignments = settings.splitStrategy.split(this, node);
      final N newNode = node.isLeaf() ? createNewLeafNode() : createNewDirectoryNode();

      List<E> entries1 = new ArrayList<>(assignments.getFirstAssignments().size());
      List<E> entries2 = new ArrayList<>(assignments.getSecondAssignments().size());
      // Store final parent distances:
      for(DistanceEntry<E> ent : assignments.getFirstAssignments()) {
        final E e = ent.getEntry();
        e.setParentDistance(ent.getDistance());
        entries1.add(e);
      }
      for(DistanceEntry<E> ent : assignments.getSecondAssignments()) {
        final E e = ent.getEntry();
        e.setParentDistance(ent.getDistance());
        entries2.add(e);
      }
      node.splitTo(newNode, entries1, entries2);

      // write changes to file
      writeNode(node);
      writeNode(newNode);

      if(log.isDebuggingFine()) {
        log.debugFine(new StringBuilder(1000)//
            .append("Split Node ").append(node.getPageID()).append(" (").append(this.getClass()).append(')').append(FormatUtil.NEWLINE)//
            .append("      newNode ").append(newNode.getPageID()).append(FormatUtil.NEWLINE)//
            .append("      firstPromoted ").append(assignments.getFirstRoutingObject()).append(FormatUtil.NEWLINE)//
            .append("      firstAssignments(").append(node.getPageID()).append(") ").append(assignments.getFirstAssignments()).append(FormatUtil.NEWLINE)//
            .append("      firstCR ").append(assignments.computeFirstCover(node.isLeaf())).append(FormatUtil.NEWLINE)//
            .append("      secondPromoted ").append(assignments.getSecondRoutingObject()).append(FormatUtil.NEWLINE)//
            .append("      secondAssignments(").append(newNode.getPageID()).append(") ").append(assignments.getSecondAssignments()).append(FormatUtil.NEWLINE)//
            .append("      secondCR ").append(assignments.computeSecondCover(node.isLeaf())).append(FormatUtil.NEWLINE));
      }

      // if root was split: create a new root that points the two split nodes
      if(isRoot(node)) {
        // FIXME: stimmen die parentDistance der Kinder in node & splitNode?
        IndexTreePath<E> newRootPath = createNewRoot(node, newNode, assignments.getFirstRoutingObject(), assignments.getSecondRoutingObject());
        adjustTree(newRootPath);
      }
      // node is not root
      else {
        // get the parent and add the new split node
        E parentEntry = subtree.getParentPath().getEntry();
        N parent = getNode(parentEntry);
        if(log.isDebugging()) {
          log.debugFine("parent " + parent);
        }
        double parentDistance2 = distance(parentEntry.getRoutingObjectID(), assignments.getSecondRoutingObject());
        // logger.warning("parent: "+parent.toString()+" split: " +
        // splitNode.toString()+ " dist:"+parentDistance2);
        parent.addDirectoryEntry(createNewDirectoryEntry(newNode, assignments.getSecondRoutingObject(), parentDistance2));

        // adjust the entry representing the (old) node, that has been split
        double parentDistance1 = distance(parentEntry.getRoutingObjectID(), assignments.getFirstRoutingObject());
        // logger.warning("parent: "+parent.toString()+" node: " +
        // node.toString()+ " dist:"+parentDistance1);
        node.adjustEntry(parent.getEntry(nodeIndex), assignments.getFirstRoutingObject(), parentDistance1, this);

        // write changes in parent to file
        writeNode(parent);
        adjustTree(subtree.getParentPath());
      }
    }
    // no overflow, only adjust parameters of the entry representing the node
    else {
      if(!isRoot(node)) {
        E parentEntry = subtree.getParentPath().getEntry();
        N parent = getNode(parentEntry);
        E entry = parent.getEntry(subtree.getIndex());
        boolean changed = node.adjustEntry(entry, entry.getRoutingObjectID(), entry.getParentDistance(), this);
        // write changes in parent to file
        if(changed) {
          writeNode(parent);
          adjustTree(subtree.getParentPath());
        }
      }
      // root level is reached
      else {
        E rootEntry = getRootEntry();
        node.adjustEntry(rootEntry, rootEntry.getRoutingObjectID(), rootEntry.getParentDistance(), this);
      }
    }
  }
145987
def __Build(leaves):
        
        if len(leaves) < 1:
            raise Exception('Leaves must have length')
        if len(leaves) == 1:
            return leaves[0]

        num_parents = int((len(leaves) + 1) / 2)
        parents = [MerkleTreeNode() for i in range(0, num_parents)]

        for i in range(0, num_parents):
            node = parents[i]
            node.LeftChild = leaves[i * 2]
            leaves[i * 2].Parent = node
            if (i * 2 + 1 == len(leaves)):
                node.RightChild = node.LeftChild
            else:
                node.RightChild = leaves[i * 2 + 1]
                leaves[i * 2 + 1].Parent = node

            hasharray = bytearray(node.LeftChild.Hash.ToArray() + node.RightChild.Hash.ToArray())
            node.Hash = UInt256(data=Crypto.Hash256(hasharray))

        return MerkleTree.__Build(parents)
777484
def subtree_leaf_positions(subtree):
    """"""
    relative_leaf_positions = subtree.treepositions('leaves')
    subtree_root_pos = subtree.treeposition()
    absolute_leaf_positions = []
    for rel_leaf_pos in relative_leaf_positions:
        absolute_leaf_positions.append( subtree_root_pos + rel_leaf_pos)
    return absolute_leaf_positions
728368
def check_width(width, root)
      dummy_node = Struct.new(:line)

      root.children.each do |top_node|
        # once we've found one line with leading space, there's no need to check any more lines
        # `haml` will check indenting_at_start, deeper_indenting, inconsistent_indentation
        break if top_node.children.find do |node|
          line = node.source_code
          leading_space = LEADING_SPACES_REGEX.match(line)

          break unless leading_space && !node.disabled?(self)

          if leading_space[1] != ' ' * width
            record_lint dummy_node.new(node.line), "File does not use #{width}-space indentation"
          end

          break true
        end
      end
    end
520315
def leaf_to_root(self):
        """"""
        node = self
        subp = []
        while node:
            if node.type == TYPE_ALTERNATIVES:
                node.alternatives.append(subp)
                if len(node.alternatives) == len(node.children):
                    #last alternative
                    subp = [tuple(node.alternatives)]
                    node.alternatives = []
                    node = node.parent
                    continue
                else:
                    node = node.parent
                    subp = None
                    break

            if node.type == TYPE_GROUP:
                node.group.append(subp)
                #probably should check the number of leaves
                if len(node.group) == len(node.children):
                    subp = get_characteristic_subpattern(node.group)
                    node.group = []
                    node = node.parent
                    continue
                else:
                    node = node.parent
                    subp = None
                    break

            if node.type == token_labels.NAME and node.name:
                #in case of type=name, use the name instead
                subp.append(node.name)
            else:
                subp.append(node.type)

            node = node.parent
        return subp
706398
private void findHomogeneousLeaves(AreaImpl root)
    {
        if (root.getChildCount() > 1)
            findSuperAreas(root, 1);
        for (int i = 0; i < root.getChildCount(); i++)
            findHomogeneousLeaves((AreaImpl) root.getChildAt(i));
    }
1151256
function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
    // If targetInfo.node exists, we zoom to the node,
    // so estimate whold width and heigth by target node.
    var currNode = (targetInfo || {}).node;
    var defaultSize = [containerWidth, containerHeight];

    if (!currNode || currNode === viewRoot) {
        return defaultSize;
    }

    var parent;
    var viewArea = containerWidth * containerHeight;
    var area = viewArea * seriesModel.option.zoomToNodeRatio;

    while (parent = currNode.parentNode) { // jshint ignore:line
        var sum = 0;
        var siblings = parent.children;

        for (var i = 0, len = siblings.length; i < len; i++) {
            sum += siblings[i].getValue();
        }
        var currNodeValue = currNode.getValue();
        if (currNodeValue === 0) {
            return defaultSize;
        }
        area *= sum / currNodeValue;

        // Considering border, suppose aspect ratio is 1.
        var parentModel = parent.getModel();
        var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
        var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
        area += 4 * borderWidth * borderWidth
            + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);

        area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);

        currNode = parent;
    }

    area < viewArea && (area = viewArea);
    var scale = Math.pow(area / viewArea, 0.5);

    return [containerWidth * scale, containerHeight * scale];
}
703123
def node_width(self):
        
        nodes = self.postorder()
        node_width = {}
        for node in nodes:
            sum_width = 0
            for child in self[node].nodes():
                sum_width += node_width[child]
            node_width[node] = (sum_width or 1)
        return node_width
642264
private void getCollocationsList(Tree t, boolean threadSafe) {
    int leftMostLeaf = Trees.leftEdge(t,qTree);
    if (t.isPreTerminal()) return;
    List<Tree> children = t.getChildrenAsList();
    if (children.isEmpty()) return;
    //TODO: fix determineHead
    // - in phrases like "World Trade Organization 's" the head of the parent NP is "POS".
    // - this is problematic for the collocationFinder which assigns this head
    // as the POS for the collocation "World_Trade_Organization"!
    Label headLabel= hf.determineHead(t).label();
    StringBuffer testString = null;
    Integer leftSistersBuffer=0;//measures the length of sisters in words when reading
    for (int i = 0; i < children.size();i++){
      ArrayList<Integer> childConstituents = new ArrayList<Integer>();
      childConstituents.add(i);
      Tree subtree = children.get(i);
      Integer currWindowLength=0; //measures the length in words of the current collocation.
      getCollocationsList(subtree, threadSafe); //recursive call to get colls in subtrees.
      testString = new StringBuffer(160);
      testString.append(treeAsStemmedCollocation(subtree, threadSafe));
      testString.append("_");
      Integer thisSubtreeLength = subtree.yield().size();
      currWindowLength+=thisSubtreeLength;
      StringBuffer testStringNonStemmed = new StringBuffer(160);
      testStringNonStemmed.append(treeAsNonStemmedCollocation(subtree));
      testStringNonStemmed.append("_");

      //for each subtree i, we iteratively append word yields of succeeding sister
      //subtrees j and check their wordnet entries.  if they exist we write them to
      //the global collocationCollector pair by the indices of the leftmost and
      //rightmost words in the collocation.

      for (int j = i+1; j < children.size(); j++) {
        Tree sisterNode = children.get(j);
        childConstituents.add(j);
        testString.append(treeAsStemmedCollocation(sisterNode, threadSafe));
        testStringNonStemmed.append(treeAsNonStemmedCollocation(sisterNode));
        currWindowLength+=sisterNode.yield().size();
        if (DEBUG) {
       //   err.println("Testing string w/ reported indices:" + testString.toString()
         //             + " (" +(leftMostLeaf+leftSistersBuffer)+","+(leftMostLeaf+leftSistersBuffer+currWindowLength-1)+")");
        }
        //ignore collocations beginning with "the" or "a"
        if (StringUtils.lookingAt(testString.toString(), "(?:[Tt]he|THE|[Aa][Nn]?)[ _]")) {
          if (false) {
            err.println("CollocationFinder: Not collapsing the/a word: " +
                testString);
          }
        } else if (wordNetContains(testString.toString())) {
          Pair <Integer, Integer> c = new Pair<Integer,Integer>(leftMostLeaf+leftSistersBuffer,leftMostLeaf+leftSistersBuffer+currWindowLength-1);

          Collocation col = new Collocation(c,t,(ArrayList<Integer>)childConstituents.clone(),testString.toString(),headLabel);
          collocationCollector.add(col);
          if (DEBUG) {
            err.println("Found collocation in wordnet: "+ testString.toString());
            err.println("  Span of collocation is: " + c +
                "; childConstituents is: " + c);
          }
        }
        testString.append("_");
        if (StringUtils.lookingAt(testStringNonStemmed.toString(), "(?:[Tt]he|THE|[Aa][Nn]?)[ _]")) {
          if (false) {
            err.println("CollocationFinder: Not collapsing the/a word: " +
                testStringNonStemmed);
          }
        } else if (wordNetContains(testStringNonStemmed.toString())) {
          Pair <Integer, Integer> c = new Pair<Integer,Integer>(leftMostLeaf+leftSistersBuffer,leftMostLeaf+leftSistersBuffer+currWindowLength-1);

          Collocation col = new Collocation(c,t,(ArrayList<Integer>)childConstituents.clone(),testStringNonStemmed.toString(),headLabel);
          collocationCollector.add(col);
          if (DEBUG) {
            err.println("Found collocation in wordnet: "+ testStringNonStemmed.toString());
            err.println("  Span of collocation is: " + c +
                "; childConstituents is: " + c);
          }
        }
        testStringNonStemmed.append("_");
      }
      leftSistersBuffer+=thisSubtreeLength;
    }
  }
884824
def _compute_node_values(tree_info):
    
    def walk(tree):
        if 'leaf_value' in tree:
            return tree['leaf_value'], tree.get('leaf_count', 0)
        left_value, left_count = walk(tree['left_child'])
        right_value, right_count = walk(tree['right_child'])
        count = left_count + right_count
        if tree['split_gain'] <= 0:
            assert left_value == right_value
            tree['_node_value'] = left_value
        else:
            tree['_node_value'] = (left_value * left_count +
                                  right_value * right_count) / count
        return tree['_node_value'], count

    for tree in tree_info:
        walk(tree['tree_structure'])
925639
def tchar(tree_style, cur_level, level, item, size):
        
        if (cur_level == level):
            i1 = '1' if level == 0 else 'x'
            i2 = '1' if item  == 0 else 'x'
            i3 = 'x'
            if size == 1:
                i3 = '1'
            elif item == (size - 1):
                i3 = 'l'
            index = '{}{}{}'.format(i1, i2, i3)
        else:
            index = 'non' if item == (size - 1) else 'ver'
        return TREE_STYLES[tree_style][index]