Sort given rules using toposort with dependency parameter.
    :param rules:
    :type rules:
    :return:
    :rtype:
196166
def toposort_rules(rules):
    
    graph = {}
    class_dict = {}
    for rule in rules:
        if rule.__class__ in class_dict:
            raise ValueError("Duplicate class rules are not allowed: %s" % rule.__class__)
        class_dict[rule.__class__] = rule
    for rule in rules:
        if not is_iterable(rule.dependency) and rule.dependency:
            rule_dependencies = [rule.dependency]
        else:
            rule_dependencies = rule.dependency
        dependencies = set()
        if rule_dependencies:
            for dependency in rule_dependencies:
                if inspect.isclass(dependency):
                    dependency = class_dict.get(dependency)
                if dependency:
                    dependencies.add(dependency)
        graph[rule] = dependencies
    return toposort(graph)
1050908
protected function mapRules($rules) : Collection
	{
		return Collection::make($rules)
			->only($this->allowed)
			->flatMap(function ($item, $key) {
				if ($key == 'required') {
					$rule[] = $item ? 'required' : '';
				} else {
					$rule[] = $key . ':' . $item;
				}
				return $rule;
			});
	}
770950
def _drop_remaining_rules(self, *rules):
        
        if rules:
            for rule in rules:
                try:
                    self._remaining_rules.remove(rule)
                except ValueError:
                    pass
        else:
            self._remaining_rules = []
1012954
function(rules) {
      var normalizedRules = {};
      _.each(rules, function(rule) {
        _.each(rule.apiGroups, function(apiGroup) {
          if (!normalizedRules[apiGroup]) {
            normalizedRules[apiGroup] = {};
          }
          _.each(rule.resources, function(resource) {
            normalizedRules[apiGroup][resource] = rule.verbs;
          });
        });
      });
      return normalizedRules;
    }
994109
def from_raw(self, rule_ids, outputs, raw_rules):
        
        self._rule_pool = [([], [])] + raw_rules
        self._rule_list = []
        for i, idx in enumerate(rule_ids):
            rule = Rule([Clause(f, c) for f, c in zip(*self._rule_pool[idx])], outputs[i])
            self._rule_list.append(rule)
            # self._rule_list.append(rule_str2rule(_rule_name, outputs[i]))
        self._rule_ids = rule_ids
        self._rule_outputs = outputs
178715
def unit_rules_restore(root):
    # type: (Nonterminal) -> Nonterminal
    
    items = Traversing.post_order(root)
    items = filter(lambda x: isinstance(x, ReducedUnitRule), items)
    for rule in items:
        parent_nonterm = rule.from_symbols[0]  # type: Nonterminal
        # restore chain of unit rules
        for r in rule.by_rules:
            created_rule = r()  # type: Rule
            parent_nonterm._set_to_rule(created_rule)
            created_rule._from_symbols.append(parent_nonterm)
            created_nonterm = r.toSymbol()  # type: Nonterminal
            created_rule._to_symbols.append(created_nonterm)
            created_nonterm._set_from_rule(created_rule)
            parent_nonterm = created_nonterm
        # restore last rule
        last_rule = rule.end_rule()  # type: Rule
        last_rule._from_symbols.append(parent_nonterm)
        parent_nonterm._set_to_rule(last_rule)
        for ch in rule.to_symbols:  # type: Nonterminal
            ch._set_from_rule(last_rule)
            last_rule._to_symbols.append(ch)
    return root
371348
def sort_top_targets(self, top, orders):
        '''
        
        '''
        sorted_top = collections.defaultdict(OrderedDict)
        # pylint: disable=cell-var-from-loop
        for saltenv, targets in six.iteritems(top):
            sorted_targets = sorted(targets,
                    key=lambda target: orders[saltenv][target])
            for target in sorted_targets:
                sorted_top[saltenv][target] = targets[target]
        # pylint: enable=cell-var-from-loop
        return sorted_top
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)
711131
def create_mv_rule(tensorprod_rule, dim):
    """"""
    def mv_rule(order, sparse=False, part=None):
        """
        Multidimensional integration rule.

        Args:
            order (int, numpy.ndarray) : order of integration rule. If numpy.ndarray,
                order along each axis.
            sparse (bool) : use Smolyak sparse grid.

        Returns:
            (numpy.ndarray, numpy.ndarray) abscissas and weights.
        """
        if sparse:
            order = numpy.ones(dim, dtype=int)*order
            tensorprod_rule_ = lambda order, part=part:\
                tensorprod_rule(order, part=part)
            return chaospy.quad.sparse_grid(tensorprod_rule_, order)

        return tensorprod_rule(order, part=part)

    return mv_rule
124031
def load_rules(self):
        
        self.col_maps = []
        #print("reading mapping table")
        with open(self.col_file, 'r') as f:
            for line in f:
                rule = MapColumn(line)
                #rule = line
                self.col_maps.append(rule)
1039314
def get_rule_table(rules):
    
    table = formatting.Table(['Id', 'KeyName'], "Rules")
    for rule in rules:
        table.add_row([rule['id'], rule['keyName']])
    return table
990020
def addRule( self, rule ):
        
        self._rules[rule.term()] = rule
        self.updateRules()
845678
def load_rules(self):
        
        self.maps = []
        with open(self.map_file, 'r') as f:
            for line in f:
                if line.strip(' ')[0:1] != '#':
                    rule = MapRule(line)
                    #print('rule = ', rule)
                    self.maps.append(rule)
1128001
def from_dict(cls, rules_dict: dict, default_rule=None, raise_error=False):
        """"""

        # Parse the rules stored in the dictionary
        rules = {k: _parser.parse_rule(v, raise_error)
                 for k, v in rules_dict.items()}

        return cls(rules, default_rule)
160722
def match(self, rule):
        
        if len(self.filters) == 0:
            return True

        for filter in self.filters:
            if filter.match(rule):
                return True
        return False
1032936
def filter(self, scored_list):
        '''
        

        '''
        top_n_key = -1 * self.top_n
        top_n_list = sorted(scored_list, key=lambda x: x[1])[top_n_key:]
        result_list = sorted(top_n_list, key=lambda x: x[0])
        return result_list
911517
def _orderedCleanDict(attrsObj):
    
    def _filt(k, v):
        if attr.has(v):
            return not not any(attr.astuple(v))
        return not not v

    return attr.asdict(attrsObj,
        dict_factory=OrderedDict,
        recurse=False,
        filter=_filt)