Given a set of already adapted rules, build the alpha part of
        the RETE network starting at `root_node`.
503777
def build_alpha_part(ruleset, root_node):
        
        # Adds a dummy rule with InitialFact as LHS for always generate
        # the alpha part matching InitialFact(). This is needed for the
        # CE using InitialFact
        ruleset = ruleset.copy()
        ruleset.add(Rule(InitialFact()))

        # Generate a dictionary with rules and the set of facts of the
        # rule.
        rule_facts = {rule: extract_facts(rule) for rule in ruleset}

        # For each fact build a list of checker function capable of
        # check for each part in the fact.
        fact_checks = {fact: set(generate_checks(fact))
                       for fact in chain.from_iterable(rule_facts.values())}

        # Make a ranking of the most used checks
        check_rank = Counter(chain.from_iterable(fact_checks.values()))

        def weighted_check_sort(check):
            """Sort check by its type and number of times seen."""
            if isinstance(check, TypeCheck):
                return (float('inf'), hash(check))
            elif isinstance(check, FactCapture):
                return (float('-inf'), hash(check))
            elif isinstance(check, FeatureCheck):
                return (check_rank[check], hash(check))
            else:
                raise TypeError("Unknown check type.")  # pragma: no cover

        def weighted_rule_sort(rule):
            """Sort rules by the average weight of its checks."""
            total = 0
            for fact in rule_facts[rule]:
                for check in fact_checks[fact]:
                    total += check_rank[check]
            return total / len(rule_facts[rule])

        sorted_rules = sorted(ruleset, key=weighted_rule_sort, reverse=True)

        fact_terminal_nodes = dict()
        # For rule in rank order and for each rule fact also in rank
        # order, build the alpha brank looking for an existing node
        # first.
        for rule in sorted_rules:
            for fact in rule_facts[rule]:
                current_node = root_node
                fact_sorted_checks = sorted(
                    fact_checks[fact],
                    key=weighted_check_sort,
                    reverse=True)

                for check in fact_sorted_checks:
                    # Look for a child node with the given check in the
                    # current parent node.
                    for child in current_node.children:
                        if child.node.matcher is check:
                            current_node = child.node
                            break
                    else:
                        # Create a new node and append as child
                        new_node = FeatureTesterNode(check)
                        current_node.add_child(new_node, new_node.activate)
                        current_node = new_node

                fact_terminal_nodes[fact] = current_node

        # Return this dictionary containing the last alpha node for each
        # fact.
        return fact_terminal_nodes
738997
def build_rule(expression)
      rule = build_root_recurrence_rule(expression)
      rule = build_year_rules(rule, expression)
      rule = build_weekday_rule(rule, expression)
      rule = build_day_rules(rule, expression)
      rule = build_time_rules(rule, expression)
      rule = rule.until(expression.until) unless expression.until.blank?

      rule
    end
1299434
def make_neurites(rdw):
    ''''''
    post_action = _NEURITE_ACTION[rdw.fmt]
    trunks = rdw.neurite_root_section_ids()
    if not trunks:
        return [], []

    # One pass over sections to build nodes
    nodes = tuple(Section(section_id=i,
                          points=rdw.data_block[sec.ids],
                          section_type=_TREE_TYPES[sec.ntype])
                  for i, sec in enumerate(rdw.sections))

    # One pass over nodes to connect children to parents
    for i, node in enumerate(nodes):
        parent_id = rdw.sections[i].pid
        parent_type = nodes[parent_id].type
        # only connect neurites
        if parent_id != ROOT_ID and parent_type != NeuriteType.soma:
            nodes[parent_id].add_child(node)

    neurites = tuple(Neurite(nodes[i]) for i in trunks)

    if post_action is not None:
        for n in neurites:
            post_action(n.root_node)

    return neurites, nodes
900145
function alterneigh(rad, i, b, g, r) {

    var j;
    var k;
    var lo;
    var hi;
    var a;
    var m;
    var p;

    lo = i - rad;
    if (lo < -1) lo = -1;

    hi = i + rad;
    if (hi > netsize) hi = netsize;

    j = i + 1;
    k = i - 1;
    m = 1;

    while ((j < hi) || (k > lo)) {
      a = radpower[m++];

      if (j < hi) {
        p = network[j++];

        try {
          p[0] -= (a * (p[0] - b)) / alpharadbias;
          p[1] -= (a * (p[1] - g)) / alpharadbias;
          p[2] -= (a * (p[2] - r)) / alpharadbias;
        } catch (e) { } // prevents 1.3 miscompilation
      }

      if (k > lo) {
        p = network[k--];

        try {
          p[0] -= (a * (p[0] - b)) / alpharadbias;
          p[1] -= (a * (p[1] - g)) / alpharadbias;
          p[2] -= (a * (p[2] - r)) / alpharadbias;
        } catch (e) { }
      }
    }
  }
1130075
public void initialize(RuleRegressionNode oldLearningNode) {
		if(oldLearningNode.perceptron!=null)
		{
			this.perceptron=new Perceptron(oldLearningNode.perceptron);
			this.perceptron.resetError();
			this.perceptron.setLearningRatio(oldLearningNode.learningRatio);
		}

		if(oldLearningNode.targetMean!=null)
		{
			this.targetMean= new TargetMean(oldLearningNode.targetMean);
			this.targetMean.resetError();
		}
		//reset statistics
		this.nodeStatistics.setValue(0, 0);
		this.nodeStatistics.setValue(1, 0);
		this.nodeStatistics.setValue(2, 0);
	}
657802
def flatten_rules(root)
      root.children.each do |child|
        case child
        when Tree::RuleNode
          flatten_rule(child)
        when Tree::DirectiveNode
          flatten_rules(child)
        end
      end
    end
130131
def build_tree(X, y, criterion, max_depth, current_depth=1):
    

    # check for max_depth accomplished
    if max_depth >= 0 and current_depth >= max_depth:
        return Leaf(y)

    # check for 0 gain
    gain, question = find_best_question(X, y, criterion)
    if gain == 0:
        return Leaf(y)

    # split
    true_X, false_X, true_y, false_y = split(X, y, question)

    # Build the `true` branch of the tree recursively
    true_branch = build_tree(
        true_X, true_y,
        criterion,
        max_depth,
        current_depth=current_depth+1
    )
    
    # Build the `false` branch of the tree recursively
    false_branch = build_tree(
        false_X, false_y,
        criterion,
        max_depth,
        current_depth=current_depth+1
    )

    # returning the root of the tree/subtree
    return Node(
        question=question,
        true_branch=true_branch,
        false_branch=false_branch
    )
303544
def _build_ex_tree(self):
        """"""
        # Load exception data into tree structure
        sep = self._exh_obj.callables_separator
        data = self._exh_obj.exceptions_db
        if not data:
            raise RuntimeError("Exceptions database is empty")
        # Add root node to exceptions, needed when tracing done
        # through test runner which is excluded from callable path
        for item in data:
            item["name"] = "root{sep}{name}".format(sep=sep, name=item["name"])
        self._tobj = ptrie.Trie(sep)
        try:
            self._tobj.add_nodes(data)
        except ValueError as eobj:
            if str(eobj).startswith("Illegal node name"):
                raise RuntimeError("Exceptions do not have a common callable")
            raise
        # Find closest root node to first multi-leaf branching or first
        # callable with exceptions and make that the root node
        node = self._tobj.root_name
        while (len(self._tobj.get_children(node)) == 1) and (
            not self._tobj.get_data(node)
        ):
            node = self._tobj.get_children(node)[0]
        if not self._tobj.is_root(node):  # pragma: no branch
            self._tobj.make_root(node)
            nsep = self._tobj.node_separator
            prefix = nsep.join(node.split(self._tobj.node_separator)[:-1])
            self._tobj.delete_prefix(prefix)
        self._print_ex_tree()
361194
def loop_node_skeleton(self, test, node):
        """"""
        body_connect_stmts = self.stmt_star_handler(
            node.body,
            prev_node_to_avoid=self.nodes[-1]
        )

        test.connect(body_connect_stmts.first_statement)
        test.connect_predecessors(body_connect_stmts.last_statements)

        # last_nodes is used for making connections to the next node in the parent node
        # this is handled in stmt_star_handler
        last_nodes = list()
        last_nodes.extend(body_connect_stmts.break_statements)

        if node.orelse:
            orelse_connect_stmts = self.stmt_star_handler(
                node.orelse,
                prev_node_to_avoid=self.nodes[-1]
            )

            test.connect(orelse_connect_stmts.first_statement)
            last_nodes.extend(orelse_connect_stmts.last_statements)
        else:
            last_nodes.append(test)  # if there is no orelse, test needs an edge to the next_node

        return ControlFlowNode(test, last_nodes, list())
76323
def build(self):
        
        self.children = BasicFactory.build(self.root, self)
        collated = BasicFactory.collate(self.children)
        self.children = collated[0]
        self.attributes = collated[2]
        self.imports = collated[1]
        self.elements = collated[3]
        self.types = collated[4]
        self.groups = collated[5]
        self.agrps = collated[6]
887720
def build_module(name, doc=None):
    """"""
    node = nodes.Module(name, doc, pure_python=False)
    node.package = False
    node.parent = None
    return node
1179752
def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize, position0, momentum0):
        
        if depth == 0:

            position_bar, momentum_bar, candidate_set_size, accept_set_bool =\
                self._initalize_tree(position, momentum, slice_var, direction * stepsize)

            alpha = min(1, self._acceptance_prob(position, position_bar, momentum, momentum_bar))

            return (position_bar, momentum_bar, position_bar, momentum_bar, position_bar,
                    candidate_set_size, accept_set_bool, alpha, 1)

        else:
            (position_backward, momentum_backward, position_forward, momentum_forward, position_bar,
             candidate_set_size, accept_set_bool, alpha, n_alpha) =\
                self._build_tree(position, momentum, slice_var,
                                 direction, depth - 1, stepsize, position0, momentum0)

            if accept_set_bool == 1:
                if direction == -1:
                    # Build tree in backward direction
                    (position_backward, momentum_backward, _, _, position_bar2, candidate_set_size2, accept_set_bool2,
                     alpha2, n_alpha2) = self._build_tree(position_backward, momentum_backward, slice_var, direction,
                                                          depth - 1, stepsize, position0, momentum0)
                else:
                    # Build tree in forward direction
                    (_, _, position_forward, momentum_forward, position_bar2, candidate_set_size2, accept_set_bool2,
                     alpha2, n_alpha2) = self._build_tree(position_forward, momentum_forward, slice_var, direction,
                                                          depth - 1, stepsize, position0, momentum0)

                if np.random.rand() < candidate_set_size2 / (candidate_set_size2 + candidate_set_size):
                    position_bar = position_bar2

                alpha += alpha2
                n_alpha += n_alpha2
                accept_set_bool, candidate_set_size =\
                    self._update_acceptance_criteria(position_forward, position_backward, momentum_forward,
                                                     momentum_backward, accept_set_bool2, candidate_set_size,
                                                     candidate_set_size2)

            return (position_backward, momentum_backward, position_forward, momentum_forward, position_bar,
                    candidate_set_size, accept_set_bool, alpha, n_alpha)
697274
def flatten_rule(rule)
      while rule.children.size == 1 && rule.children.first.is_a?(Tree::RuleNode)
        child = rule.children.first

        if first_simple_sel(child).is_a?(Sass::Selector::Parent)
          rule.parsed_rules = child.parsed_rules.resolve_parent_refs(rule.parsed_rules)
        else
          rule.parsed_rules = make_seq(*(first_seq(rule).members + first_seq(child).members))
        end

        rule.children = child.children
      end

      flatten_rules(rule)
    end
684696
def _build_rules(specs):
    
    for spec in specs:
        if "context" in spec:
            yield Context(spec["context"], list(_build_rules(spec.get("routes", []))))
        else:
            rulespec = spec.copy()
            match = rulespec.pop("match")
            name = rulespec.pop("name")
            yield Rule(match, endpoint=name, **rulespec)
986760
def make_limit_node(root, limit):
    

    # Build the base limit node
    limit_node = etree.SubElement(root, 'limit',
                                  {'class': limit._limit_full_name})

    # Walk through all the recognized attributes
    for attr in sorted(limit.attrs):
        desc = limit.attrs[attr]
        attr_type = desc.get('type', str)
        value = getattr(limit, attr)

        # Determine the default value, if we have one...
        if 'default' in desc:
            default = (desc['default']() if callable(desc['default']) else
                       desc['default'])

            # Skip attributes that have their default settings
            if value == default:
                continue

        # Set up the attr node
        attr_node = etree.SubElement(limit_node, 'attr', name=attr)

        # Treat lists and dicts specially
        if attr_type == list:
            for val in value:
                val_node = etree.SubElement(attr_node, 'value')
                val_node.text = str(val)
        elif attr_type == dict:
            for key, val in sorted(value.items(), key=lambda x: x[0]):
                val_node = etree.SubElement(attr_node, 'value', key=key)
                val_node.text = str(val)
        else:
            attr_node.text = str(value)
451134
void  build() {
           // If there were no rules, just return.  This situation can easily arise
           //   for the reverse rules.
           if (fRB.fTreeRoots[fRootIx]==null) {
               return;
           }

           //
           // Walk through the tree, replacing any references to $variables with a copy of the
           //   parse tree for the substition expression.
           //
           fRB.fTreeRoots[fRootIx] = fRB.fTreeRoots[fRootIx].flattenVariables();
           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("ftree")>=0) {
               System.out.println("Parse tree after flattening variable references.");
               fRB.fTreeRoots[fRootIx].printTree(true);
           }

           //
           // If the rules contained any references to {bof}
           //   add a {bof} <cat> <former root of tree> to the
           //   tree.  Means that all matches must start out with the
           //   {bof} fake character.
           //
           if (fRB.fSetBuilder.sawBOF()) {
               RBBINode bofTop    = new RBBINode(RBBINode.opCat);
               RBBINode bofLeaf   = new RBBINode(RBBINode.leafChar);
               bofTop.fLeftChild  = bofLeaf;
               bofTop.fRightChild = fRB.fTreeRoots[fRootIx];
               bofLeaf.fParent    = bofTop;
               bofLeaf.fVal       = 2;      // Reserved value for {bof}.
               fRB.fTreeRoots[fRootIx] = bofTop;
           }

           //
           // Add a unique right-end marker to the expression.
           //   Appears as a cat-node, left child being the original tree,
           //   right child being the end marker.
           //
           RBBINode cn = new RBBINode(RBBINode.opCat);
           cn.fLeftChild = fRB.fTreeRoots[fRootIx];
           fRB.fTreeRoots[fRootIx].fParent = cn;
           cn.fRightChild = new RBBINode(RBBINode.endMark);
           cn.fRightChild.fParent = cn;
           fRB.fTreeRoots[fRootIx] = cn;

           //
           //  Replace all references to UnicodeSets with the tree for the equivalent
           //      expression.
           //
           fRB.fTreeRoots[fRootIx].flattenSets();
           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("stree")>=0) {
               System.out.println("Parse tree after flattening Unicode Set references.");
               fRB.fTreeRoots[fRootIx].printTree(true);
           }


           //
           // calculate the functions nullable, firstpos, lastpos and followpos on
           // nodes in the parse tree.
           //    See the alogrithm description in Aho.
           //    Understanding how this works by looking at the code alone will be
           //       nearly impossible.
           //
           calcNullable(fRB.fTreeRoots[fRootIx]);
           calcFirstPos(fRB.fTreeRoots[fRootIx]);
           calcLastPos(fRB.fTreeRoots[fRootIx]);
           calcFollowPos(fRB.fTreeRoots[fRootIx]);
           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("pos")>=0) {
               System.out.print("\n");
               printPosSets(fRB.fTreeRoots[fRootIx]);
           }

           //
           //  For "chained" rules, modify the followPos sets
           //
           if (fRB.fChainRules) {
               calcChainedFollowPos(fRB.fTreeRoots[fRootIx]);
           }

           //
           //  BOF (start of input) test fixup.
           //
           if (fRB.fSetBuilder.sawBOF()) {
               bofFixup();
           }

           //
           // Build the DFA state transition tables.
           //
           buildStateTable();
           flagAcceptingStates();
           flagLookAheadStates();
           flagTaggedStates();

           //
           // Update the global table of rule status {tag} values
           // The rule builder has a global vector of status values that are common
           //    for all tables.  Merge the ones from this table into the global set.
           //
           mergeRuleStatusVals();

           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("states")>=0) {printStates();}
       }
267622
def expand_rule(self, rule):
        ""
        init_ptrs = set()
        def _expand_rule(rule):
            assert not rule.is_term, rule

            for r in self.rules_by_origin[rule]:
                init_ptr = RulePtr(r, 0)
                init_ptrs.add(init_ptr)

                if r.expansion: # if not empty rule
                    new_r = init_ptr.next
                    if not new_r.is_term:
                        yield new_r

        for _ in bfs([rule], _expand_rule):
            pass

        return fzset(init_ptrs)