generator to extract operators and operands in pairs
188653
def _operatorOperands(tokenlist):
        ""
        it = iter(tokenlist)
        while 1:
            try:
                yield (it.next(), it.next())
            except StopIteration:
                break
175338
function getOperands(node, parentOp) {
  // We can only recurse on operations of type op.
  // If the node is not an operator node or of the right operation type,
  // we can't break up or flatten this tree any further, so we return just
  // the current node, and recurse on it to flatten its ops.
  if (!Node.Type.isOperator(node)) {
    return [flattenOperands(node)];
  }
  switch (node.op) {
  // division is part of flattening multiplication
  case '*':
  case '/':
    if (parentOp !== '*') {
      return [flattenOperands(node)];
    }
    break;
  case '+':
  case '-':
    if (parentOp !== '+') {
      return [flattenOperands(node)];
    }
    break;
  default:
    return [flattenOperands(node)];
  }
  if (Node.PolynomialTerm.isPolynomialTerm(node, true)) {
    node.args.forEach((arg, i) => {
      node.args[i] = flattenOperands(node.args[i]);
    });
    return [node];
  }

  // If we're flattening over *, check for a polynomial term (ie a
  // coefficient multiplied by a symbol such as 2x^2 or 3y)
  // This is true if there's an implicit multiplication and the right operand
  // is a symbol or a symbol to an exponent.
  else if (parentOp === '*' && isPolynomialTermMultiplication(node)) {
    return maybeFlattenPolynomialTerm(node);
  }
  else if (parentOp === '*' && node.op === '/') {
    return flattenDivision(node);
  }
  else if (node.op === '-') {
    // this operation will become addition e.g. 2 - 3 -> 2 + -(-3)
    const secondOperand = node.args[1];
    const negativeSecondOperand = Negative.negate(secondOperand, true);
    const operands = [
      getOperands(node.args[0], parentOp),
      getOperands(negativeSecondOperand, parentOp)
    ];
    return [].concat.apply([], operands);
  }
  else {
    const operands = [];
    node.args.forEach((child) => {
      // This will make an array of arrays
      operands.push(getOperands(child, parentOp));
    });
    return [].concat.apply([], operands);
  }
}
645029
def parse_operand(string, location, tokens):
    
    mod = " ".join(tokens.get("modifier", ""))

    if "immediate" in tokens:
        imm = parse_immediate("".join(tokens["immediate"]))
        size = modifier_size.get(mod, None)

        oprnd = X86ImmediateOperand(imm, size)

    if "register" in tokens:
        name = tokens["register"]
        size = arch_info.registers_size[tokens["register"]]

        oprnd = X86RegisterOperand(name, size)

    if "memory" in tokens:
        seg_reg = tokens.get("segment", None)
        base_reg = tokens.get("base", None)
        index_reg = tokens.get("index", None)
        scale_imm = int(tokens.get("scale", "0x1"), 16)
        displ_imm = int("".join(tokens.get("displacement", "0x0")), 16)

        oprnd = X86MemoryOperand(seg_reg, base_reg, index_reg, scale_imm, displ_imm)

    oprnd.modifier = mod

    if not oprnd.size and oprnd.modifier:
        oprnd.size = modifier_size[oprnd.modifier]

    return oprnd
565088
def match_indices(match):
    """"""
    a, b, size = match
    for i in range(size):
        yield a + i, b + i
788966
def _generate_net(cls, flatterm: FlatTerm, final_label: T) -> _State[T]:
        """"""
        # Capture the last sequence wildcard for every level of operation nesting on a stack
        # Used to add backtracking edges in case the "match" fails later
        last_wildcards = [None]
        # Generate a fail state for every level of nesting to backtrack to a sequence wildcard in a parent Expression
        # in case no match can be found
        fail_states = [None]
        operand_counts = [0]
        root = state = _State()
        states = {root.id: root}

        for term in flatterm:
            if operand_counts[-1] >= 0:
                operand_counts[-1] += 1

            # For wildcards, generate a chain of #min_count Wildcard edges
            # If the wildcard is unbounded (fixed_size = False),
            # add a wildcard self loop at the end
            if isinstance(term, Wildcard):
                # Generate a chain of #min_count Wildcard edges
                for _ in range(term.min_count):
                    state = cls._create_child_state(state, Wildcard)
                    states[state.id] = state
                # If it is a sequence wildcard, add a self loop
                if not term.fixed_size:
                    state[Wildcard] = state
                    last_wildcards[-1] = state
                    operand_counts[-1] = -1
            else:
                state = cls._create_child_state(state, term)
                states[state.id] = state
                if is_operation(term):
                    fail_state = None
                    if last_wildcards[-1] or fail_states[-1]:
                        last_fail_state = (
                            fail_states[-1]
                            if not isinstance(fail_states[-1], list) else fail_states[-1][operand_counts[-1]]
                        )
                        if term.arity.fixed_size:
                            fail_state = _State()
                            states[fail_state.id] = fail_state
                            new_fail_states = [fail_state]
                            for _ in range(term.arity.min_count):
                                new_fail_state = _State()
                                states[new_fail_state.id] = new_fail_state
                                fail_state[Wildcard] = new_fail_state
                                fail_state = new_fail_state
                                new_fail_states.append(new_fail_state)
                            fail_state[OPERATION_END] = last_wildcards[-1] or last_fail_state
                            fail_state = new_fail_states
                        else:
                            fail_state = _State()
                            states[fail_state.id] = fail_state
                            fail_state[OPERATION_END] = last_wildcards[-1] or last_fail_state
                            fail_state[Wildcard] = fail_state
                    fail_states.append(fail_state)
                    last_wildcards.append(None)
                    operand_counts.append(0)
                elif term == OPERATION_END:
                    fail_states.pop()
                    last_wildcards.pop()
                    operand_counts.pop()

            if last_wildcards[-1] != state:
                if last_wildcards[-1]:
                    state[EPSILON] = last_wildcards[-1]
                elif fail_states[-1]:
                    last_fail_state = (
                        fail_states[-1]
                        if not isinstance(fail_states[-1], list) else fail_states[-1][operand_counts[-1]]
                    )
                    state[EPSILON] = last_fail_state

        state.payload = [final_label]

        return cls._convert_nfa_to_dfa(root, states)
316726
function parse_operator_type(op, def) {
	op = ''+op;
	if(op.indexOf(':') === -1) {
		return def || 'boolean';
	}
	return op.split(':')[1];
}
896134
def ast2expr(ast):
    """"""
    if ast[0] == 'const':
        return _CONSTS[ast[1]]
    elif ast[0] == 'var':
        return exprvar(ast[1], ast[2])
    else:
        xs = [ast2expr(x) for x in ast[1:]]
        return ASTOPS[ast[0]](*xs, simplify=False)
600320
def _preprocess_input(self):
    """"""
    # Compute the sets of MTF dimensions used in operations/tensors.

    # a {string: frozenset(string)}, mapping operation name to MTF dimension
    # names.
    self._operation_name_to_mtf_dimension_set = {}
    # a {string: frozenset(string)}, mapping tensor name to MTF dimension names.
    self._tensor_name_to_mtf_dimension_set = {}

    for operation_name in self._graph.get_all_operation_names():
      self._operation_name_to_mtf_dimension_set[operation_name] = frozenset(
          set(self._graph.get_operation_mtf_dimension_names(
              operation_name)).intersection(
                  self._layout_validator.splittable_mtf_dimension_names))
    for tensor_name in self._graph.get_all_tensor_names():
      self._tensor_name_to_mtf_dimension_set[tensor_name] = frozenset(
          set(self._graph.get_tensor_mtf_dimension_names(tensor_name))
          .intersection(self._layout_validator.splittable_mtf_dimension_names))

    self._operation_mtf_dimension_sets = set(
        self._operation_name_to_mtf_dimension_set.values())
    self._mtf_dimension_sets = self._operation_mtf_dimension_sets | set(
        self._tensor_name_to_mtf_dimension_set.values())

    # Compute possible assignments for each set of MTF dimensions.
    self._assignments = {}  # indexed by MTF dimension set
    for mtf_dimension_set in self._mtf_dimension_sets:
      self._assignments[mtf_dimension_set] = _generate_assignments(
          mtf_dimension_set, self._layout_validator.mesh_dimension_name_to_size)
342796
def to_gremlin(self):
        """"""
        self.validate()

        immediate_operator_format = u'({left} {operator} {right})'
        dotted_operator_format = u'{left}.{operator}({right})'
        intersects_operator_format = u'(!{left}.{operator}({right}).empty)'

        translation_table = {
            u'=': (u'==', immediate_operator_format),
            u'!=': (u'!=', immediate_operator_format),
            u'>=': (u'>=', immediate_operator_format),
            u'<=': (u'<=', immediate_operator_format),
            u'>': (u'>', immediate_operator_format),
            u'<': (u'<', immediate_operator_format),
            u'+': (u'+', immediate_operator_format),
            u'||': (u'||', immediate_operator_format),
            u'&&': (u'&&', immediate_operator_format),
            u'contains': (u'contains', dotted_operator_format),
            u'intersects': (u'intersect', intersects_operator_format),
            u'has_substring': (u'contains', dotted_operator_format),
        }

        gremlin_operator, format_spec = translation_table.get(self.operator, (None, None))
        if not gremlin_operator:
            raise AssertionError(u'Unrecognized operator used: '
                                 u'{} {}'.format(self.operator, self))

        return format_spec.format(operator=gremlin_operator,
                                  left=self.left.to_gremlin(),
                                  right=self.right.to_gremlin())
648310
def normalized_operator(self):
        """"""
        if self._operator.lower() == "lt" or self._operator == "<":
            return u"LT"
        elif self._operator.lower() == "gt" or self._operator == ">":
            return u"GT"
        elif self._operator.lower() == "lte" or self._operator == "<=":
            return u"LTE"
        elif self._operator.lower() == "gte" or self._operator == ">=":
            return u"GTE"
441032
def mul(self, *args, **kwargs):
        
        return self._apply(operator.mul, *args, **kwargs)
498228
def expr_to_str(n, l=None):
    
    op = n[0]
    if op.startswith('_') and op.endswith('_'):
        op = op.strip('_')
        if op == 'var':
            return n[1]
        elif op == 'literal':
            if isinstance(n[1], basestring):
                return "'%s'" % n[1]
            return str(n[1])
        elif op == 'cast':
            return "(%s)::%s" % (expr_to_str(n[1]), n[2])
    elif op in '+-*/':
        return "(%s) %s (%s)" % (expr_to_str(n[1]), op, expr_to_str(n[2]))
    elif op == "extract":
        return "extract( %s from %s )" % (n[1], expr_to_str(n[2]))
    else:
        arg = ','.join(map(expr_to_str, n[1:]))
        return "%s(%s)" % (op, arg)
640369
def casting_operators(
            self,
            name=None,
            function=None,
            return_type=None,
            arg_types=None,
            header_dir=None,
            header_file=None,
            recursive=None,
            allow_empty=None):
        """"""
        return (
            self._find_multiple(
                self._impl_matchers[scopedef_t.casting_operator],
                name=name,
                function=function,
                decl_type=self._impl_decl_types[
                    scopedef_t.casting_operator],
                return_type=return_type,
                arg_types=arg_types,
                header_dir=header_dir,
                header_file=header_file,
                recursive=recursive,
                allow_empty=allow_empty)
        )
612921
def simplify(self):
        """"""
        def mul(op1, op2):
            if op1 == "I":
                return 1.0, op2
            if op2 == "I":
                return 1.0, op1
            if op1 == op2:
                return 1.0, "I"
            if op1 == "X":
                return (-1j, "Z") if op2 == "Y" else (1j, "Y")
            if op1 == "Y":
                return (-1j, "X") if op2 == "Z" else (1j, "Z")
            if op1 == "Z":
                return (-1j, "Y") if op2 == "X" else (1j, "X")

        before = defaultdict(list)
        for op in self.ops:
            if op.op == "I":
                continue
            before[op.n].append(op.op)
        new_coeff = self.coeff
        new_ops = []
        for n in sorted(before.keys()):
            ops = before[n]
            assert ops
            k = 1.0
            op = ops[0]
            for _op in ops[1:]:
                _k, op = mul(op, _op)
                k *= _k
            new_coeff *= k
            if new_coeff.imag == 0:
                # cast to float
                new_coeff = new_coeff.real
            if op != "I":
                new_ops.append(pauli_from_char(op, n))
        return Term(tuple(new_ops), new_coeff)
621792
def of_operator(context, x, y):
    
    return x.eval(context), y.eval(context)
327865
def define(cls, expr):
        

        try:
            lang = cls.lang
            items = items_(expr)
            for item in items:
                op, term = item
                full_op = operators.get(op)
                if full_op:
                    class_ = lang.ops[full_op.id]
                    clauses = {k: jx_expression(v) for k, v in expr.items() if k != op}
                    break
            else:
                if not items:
                    return NULL
                raise Log.error("{{operator|quote}} is not a known operator", operator=expr)

            if term == None:
                return class_([], **clauses)
            elif is_list(term):
                terms = [jx_expression(t) for t in term]
                return class_(terms, **clauses)
            elif is_data(term):
                items = items_(term)
                if class_.has_simple_form:
                    if len(items) == 1:
                        k, v = items[0]
                        return class_([Variable(k), Literal(v)], **clauses)
                    else:
                        return class_({k:  Literal(v) for k, v in items}, **clauses)
                else:
                    return class_(_jx_expression(term, lang), **clauses)
            else:
                if op in ["literal", "date", "offset"]:
                    return class_(term, **clauses)
                else:
                    return class_(_jx_expression(term, lang), **clauses)
        except Exception as e:
            Log.error("programmer error expr = {{value|quote}}", value=expr, cause=e)
770017
def _extract(expr, pat, flags=0, group=0):
    

    return _string_op(expr, Extract, _pat=pat, _flags=flags, _group=group)