@dimod.decorators.vartype_argument('<STR_LIT>')<EOL>def and_gate(variables, vartype=dimod.BINARY, name='<STR_LIT>'):

variables = tuple(variables)<EOL>if vartype is dimod.BINARY:<EOL><INDENT>configurations = frozenset([(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>)])<EOL>def func(in1, in2, out): return (in1 and in2) == out<EOL><DEDENT>else:<EOL><INDENT>configurations = frozenset([(-<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>)])<EOL>def func(in1, in2, out): return ((in1 > <NUM_LIT:0>) and (in2 > <NUM_LIT:0>)) == (out > <NUM_LIT:0>)<EOL><DEDENT>return Constraint(func, configurations, variables, vartype=vartype, name=name)<EOL>

AND gate.

    Args:
        variables (list): Variable labels for the and gate as `[in1, in2, out]`,
            where `in1, in2` are inputs and `out` the gate's output.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='AND'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of an AND gate.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.gates as gates
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c'], name='AND1'))
        >>> csp.check({'a': 1, 'b': 0, 'c': 0})
        True


@dimod.decorators.vartype_argument('<STR_LIT>')<EOL>def or_gate(variables, vartype=dimod.BINARY, name='<STR_LIT>'):

variables = tuple(variables)<EOL>if vartype is dimod.BINARY:<EOL><INDENT>configs = frozenset([(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>)])<EOL>def func(in1, in2, out): return (in1 or in2) == out<EOL><DEDENT>else:<EOL><INDENT>configs = frozenset([(-<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>)])<EOL>def func(in1, in2, out): return ((in1 > <NUM_LIT:0>) or (in2 > <NUM_LIT:0>)) == (out > <NUM_LIT:0>)<EOL><DEDENT>return Constraint(func, configs, variables, vartype=vartype, name=name)<EOL>

OR gate.

    Args:
        variables (list): Variable labels for the and gate as `[in1, in2, out]`,
            where `in1, in2` are inputs and `out` the gate's output.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='OR'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of an OR gate.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.gates as gates
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)
        >>> csp.add_constraint(gates.or_gate(['x', 'y', 'z'], {-1,1}, name='OR1'))
        >>> csp.check({'x': 1, 'y': -1, 'z': 1})
        True


@dimod.decorators.vartype_argument('<STR_LIT>')<EOL>def xor_gate(variables, vartype=dimod.BINARY, name='<STR_LIT>'):

variables = tuple(variables)<EOL>if vartype is dimod.BINARY:<EOL><INDENT>configs = frozenset([(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>)])<EOL>def func(in1, in2, out): return (in1 != in2) == out<EOL><DEDENT>else:<EOL><INDENT>configs = frozenset([(-<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>)])<EOL>def func(in1, in2, out): return ((in1 > <NUM_LIT:0>) != (in2 > <NUM_LIT:0>)) == (out > <NUM_LIT:0>)<EOL><DEDENT>return Constraint(func, configs, variables, vartype=vartype, name=name)<EOL>

XOR gate.

    Args:
        variables (list): Variable labels for the and gate as `[in1, in2, out]`,
            where `in1, in2` are inputs and `out` the gate's output.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='XOR'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of an XOR gate.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.gates as gates
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(gates.xor_gate(['x', 'y', 'z'], name='XOR1'))
        >>> csp.check({'x': 1, 'y': 1, 'z': 1})
        False


variables = tuple(variables)<EOL>if vartype is dimod.BINARY:<EOL><INDENT>configs = frozenset([(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>)])<EOL><DEDENT>else:<EOL><INDENT>configs = frozenset([(-<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>)])<EOL><DEDENT>def func(augend, addend, sum_, carry):<EOL><INDENT>total = (augend > <NUM_LIT:0>) + (addend > <NUM_LIT:0>)<EOL>if total == <NUM_LIT:0>:<EOL><INDENT>return (sum_ <= <NUM_LIT:0>) and (carry <= <NUM_LIT:0>)<EOL><DEDENT>elif total == <NUM_LIT:1>:<EOL><INDENT>return (sum_ > <NUM_LIT:0>) and (carry <= <NUM_LIT:0>)<EOL><DEDENT>elif total == <NUM_LIT:2>:<EOL><INDENT>return (sum_ <= <NUM_LIT:0>) and (carry > <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return Constraint(func, configs, variables, vartype=vartype, name=name)<EOL>

Half adder.

    Args:
        variables (list): Variable labels for the and gate as `[in1, in2, sum, carry]`,
            where `in1, in2` are inputs to be added and `sum` and 'carry' the resultant
            outputs.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='HALF_ADDER'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of a Boolean half adder.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.gates as gates
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(gates.halfadder_gate(['a', 'b', 'total', 'carry'], name='HA1'))
        >>> csp.check({'a': 1, 'b': 1, 'total': 0, 'carry': 1})
        True


variables = tuple(variables)<EOL>if vartype is dimod.BINARY:<EOL><INDENT>configs = frozenset([(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>),<EOL>(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>)])<EOL><DEDENT>else:<EOL><INDENT>configs = frozenset([(-<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>)])<EOL><DEDENT>def func(in1, in2, in3, sum_, carry):<EOL><INDENT>total = (in1 > <NUM_LIT:0>) + (in2 > <NUM_LIT:0>) + (in3 > <NUM_LIT:0>)<EOL>if total == <NUM_LIT:0>:<EOL><INDENT>return (sum_ <= <NUM_LIT:0>) and (carry <= <NUM_LIT:0>)<EOL><DEDENT>elif total == <NUM_LIT:1>:<EOL><INDENT>return (sum_ > <NUM_LIT:0>) and (carry <= <NUM_LIT:0>)<EOL><DEDENT>elif total == <NUM_LIT:2>:<EOL><INDENT>return (sum_ <= <NUM_LIT:0>) and (carry > <NUM_LIT:0>)<EOL><DEDENT>elif total == <NUM_LIT:3>:<EOL><INDENT>return (sum_ > <NUM_LIT:0>) and (carry > <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return Constraint(func, configs, variables, vartype=vartype, name=name)<EOL>

Full adder.

    Args:
        variables (list): Variable labels for the and gate as `[in1, in2, in3, sum, carry]`,
            where `in1, in2, in3` are inputs to be added and `sum` and 'carry' the resultant
            outputs.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='FULL_ADDER'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of a Boolean full adder.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.gates as gates
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(gates.fulladder_gate(['a', 'b', 'c_in', 'total', 'c_out'], name='FA1'))
        >>> csp.check({'a': 1, 'b': 0, 'c_in': 1, 'total': 0, 'c_out': 1})
        True


@dimod.decorators.vartype_argument('<STR_LIT>')<EOL>def sat2in4(pos, neg=tuple(), vartype=dimod.BINARY, name='<STR_LIT>'):

pos = tuple(pos)<EOL>neg = tuple(neg)<EOL>variables = pos + neg<EOL>if len(variables) != <NUM_LIT:4>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if neg and (len(neg) < <NUM_LIT:4>):<EOL><INDENT>const = sat2in4(pos=variables, vartype=vartype)  <EOL>for v in neg:<EOL><INDENT>const.flip_variable(v)<EOL>const.name = name  <EOL><DEDENT>return const<EOL><DEDENT>if vartype is dimod.BINARY:<EOL><INDENT>configurations = frozenset([(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>)])<EOL><DEDENT>else:<EOL><INDENT>configurations = frozenset([(-<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>)])<EOL><DEDENT>def func(a, b, c, d):<EOL><INDENT>if a == b:<EOL><INDENT>return (b != c) and (c == d)<EOL><DEDENT>elif a == c:<EOL><INDENT>return b == d<EOL><DEDENT>else:<EOL><INDENT>return a == d<EOL><DEDENT><DEDENT>return Constraint(func, configurations, variables, vartype=vartype, name=name)<EOL>

Two-in-four (2-in-4) satisfiability.

    Args:
        pos (iterable):
            Variable labels, as an iterable, for non-negated variables of the constraint.
            Exactly four variables are specified by `pos` and `neg` together.
        neg (tuple):
            Variable labels, as an iterable, for negated variables of the constraint.
            Exactly four variables are specified by `pos` and `neg` together.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='2-in-4'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that satisfy a two-in-four satisfiability problem.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.sat as sat
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(sat.sat2in4(['w', 'x', 'y', 'z'], vartype='BINARY', name='sat1'))
        >>> csp.check({'w': 1, 'x': 1, 'y': 0, 'z': 0})
        True


def random_2in4sat(num_variables, num_clauses, vartype=dimod.BINARY, satisfiable=True):

if num_variables < <NUM_LIT:4>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if num_clauses > <NUM_LIT:16> * _nchoosek(num_variables, <NUM_LIT:4>):  <EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>csp = ConstraintSatisfactionProblem(vartype)<EOL>variables = list(range(num_variables))<EOL>constraints = set()<EOL>if satisfiable:<EOL><INDENT>values = tuple(vartype.value)<EOL>planted_solution = {v: choice(values) for v in variables}<EOL>configurations = [(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>), (<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>), (<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>), (<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>), (<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>)]<EOL>while len(constraints) < num_clauses:<EOL><INDENT>constraint_variables = sorted(sample(variables, <NUM_LIT:4>))<EOL>config = choice(configurations)<EOL>pos = tuple(v for idx, v in enumerate(constraint_variables) if config[idx] == (planted_solution[v] > <NUM_LIT:0>))<EOL>neg = tuple(v for idx, v in enumerate(constraint_variables) if config[idx] != (planted_solution[v] > <NUM_LIT:0>))<EOL>const = sat2in4(pos=pos, neg=neg, vartype=vartype)<EOL>assert const.check(planted_solution)<EOL>constraints.add(const)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>while len(constraints) < num_clauses:<EOL><INDENT>constraint_variables = sorted(sample(variables, <NUM_LIT:4>))<EOL>pos = tuple(v for v in constraint_variables if random() > <NUM_LIT>)<EOL>neg = tuple(v for v in constraint_variables if v not in pos)<EOL>const = sat2in4(pos=pos, neg=neg, vartype=vartype)<EOL>constraints.add(const)<EOL><DEDENT><DEDENT>for const in constraints:<EOL><INDENT>csp.add_constraint(const)<EOL><DEDENT>for v in variables:<EOL><INDENT>csp.add_variable(v)<EOL><DEDENT>return csp<EOL>

Random two-in-four (2-in-4) constraint satisfaction problem.

    Args:
        num_variables (integer): Number of variables (at least four).
        num_clauses (integer): Number of constraints that together constitute the
            constraint satisfaction problem.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        satisfiable (bool, optional, default=True): True if the CSP can be satisfied.

    Returns:
        CSP (:obj:`.ConstraintSatisfactionProblem`): CSP that is satisfied when its variables
        are assigned values that satisfy a two-in-four satisfiability problem.

    Examples:
        This example creates a CSP with 6 variables and two random constraints and checks
        whether a particular assignment of variables satisifies it.

        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories as sat
        >>> csp = sat.random_2in4sat(6, 2)
        >>> csp.constraints    # doctest: +SKIP
        [Constraint.from_configurations(frozenset({(1, 0, 1, 0), (1, 0, 0, 1), (1, 1, 1, 1), (0, 1, 1, 0), (0, 0, 0, 0),
         (0, 1, 0, 1)}), (2, 4, 0, 1), Vartype.BINARY, name='2-in-4'),
         Constraint.from_configurations(frozenset({(1, 0, 1, 1), (1, 1, 0, 1), (1, 1, 1, 0), (0, 0, 0, 1),
         (0, 1, 0, 0), (0, 0, 1, 0)}), (1, 2, 4, 5), Vartype.BINARY, name='2-in-4')]
        >>> csp.check({0: 1, 1: 0, 2: 1, 3: 1, 4: 0, 5: 0})       # doctest: +SKIP
        True


def random_xorsat(num_variables, num_clauses, vartype=dimod.BINARY, satisfiable=True):

if num_variables < <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if num_clauses > <NUM_LIT:8> * _nchoosek(num_variables, <NUM_LIT:3>):  <EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>csp = ConstraintSatisfactionProblem(vartype)<EOL>variables = list(range(num_variables))<EOL>constraints = set()<EOL>if satisfiable:<EOL><INDENT>values = tuple(vartype.value)<EOL>planted_solution = {v: choice(values) for v in variables}<EOL>configurations = [(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>), (<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>), (<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>), (<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>)]<EOL>while len(constraints) < num_clauses:<EOL><INDENT>x, y, z = sample(variables, <NUM_LIT:3>)<EOL>if y > x:<EOL><INDENT>x, y = y, x<EOL><DEDENT>const = xor_gate([x, y, z], vartype=vartype)<EOL>config = choice(configurations)<EOL>for idx, v in enumerate(const.variables):<EOL><INDENT>if config[idx] != (planted_solution[v] > <NUM_LIT:0>):<EOL><INDENT>const.flip_variable(v)<EOL><DEDENT><DEDENT>assert const.check(planted_solution)<EOL>constraints.add(const)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>while len(constraints) < num_clauses:<EOL><INDENT>x, y, z = sample(variables, <NUM_LIT:3>)<EOL>if y > x:<EOL><INDENT>x, y = y, x<EOL><DEDENT>const = xor_gate([x, y, z], vartype=vartype)<EOL>for idx, v in enumerate(const.variables):<EOL><INDENT>if random() > <NUM_LIT>:<EOL><INDENT>const.flip_variable(v)<EOL><DEDENT><DEDENT>assert const.check(planted_solution)<EOL>constraints.add(const)<EOL><DEDENT><DEDENT>for const in constraints:<EOL><INDENT>csp.add_constraint(const)<EOL><DEDENT>for v in variables:<EOL><INDENT>csp.add_variable(v)<EOL><DEDENT>return csp<EOL>

Random XOR constraint satisfaction problem.

    Args:
        num_variables (integer): Number of variables (at least three).
        num_clauses (integer): Number of constraints that together constitute the
            constraint satisfaction problem.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        satisfiable (bool, optional, default=True): True if the CSP can be satisfied.

    Returns:
        CSP (:obj:`.ConstraintSatisfactionProblem`): CSP that is satisfied when its variables
        are assigned values that satisfy a XOR satisfiability problem.

    Examples:
        This example creates a CSP with 5 variables and two random constraints and checks
        whether a particular assignment of variables satisifies it.

        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories as sat
        >>> csp = sat.random_xorsat(5, 2)
        >>> csp.constraints    # doctest: +SKIP
        [Constraint.from_configurations(frozenset({(1, 0, 0), (1, 1, 1), (0, 1, 0), (0, 0, 1)}), (4, 3, 0),
         Vartype.BINARY, name='XOR (0 flipped)'),
         Constraint.from_configurations(frozenset({(1, 1, 0), (0, 1, 1), (0, 0, 0), (1, 0, 1)}), (2, 0, 4),
         Vartype.BINARY, name='XOR (2 flipped) (0 flipped)')]
        >>> csp.check({0: 1, 1: 0, 2: 0, 3: 1, 4: 1})       # doctest: +SKIP
        True


if nbit < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>num_multiplier_bits = num_multiplicand_bits = nbit<EOL>csp = ConstraintSatisfactionProblem(vartype)<EOL>a = {i: '<STR_LIT>' % i for i in range(nbit)}<EOL>b = {j: '<STR_LIT>' % j for j in range(nbit)}<EOL>p = {k: '<STR_LIT>' % k for k in range(nbit + nbit)}<EOL>AND = defaultdict(dict)  <EOL>SUM = defaultdict(dict)  <EOL>CARRY = defaultdict(dict)  <EOL>for i in range(num_multiplier_bits):<EOL><INDENT>for j in range(num_multiplicand_bits):<EOL><INDENT>ai = a[i]<EOL>bj = b[j]<EOL>if i == <NUM_LIT:0> and j == <NUM_LIT:0>:<EOL><INDENT>andij = AND[i][j] = p[<NUM_LIT:0>]<EOL>gate = and_gate([ai, bj, andij], vartype=vartype, name='<STR_LIT>' % (ai, bj, andij))<EOL>csp.add_constraint(gate)<EOL>continue<EOL><DEDENT>andij = AND[i][j] = '<STR_LIT>' % (i, j)<EOL>gate = and_gate([ai, bj, andij], vartype=vartype, name='<STR_LIT>' % (ai, bj, andij))<EOL>csp.add_constraint(gate)<EOL>inputs = [andij]<EOL>if i - <NUM_LIT:1> in CARRY and j in CARRY[i - <NUM_LIT:1>]:<EOL><INDENT>inputs.append(CARRY[i - <NUM_LIT:1>][j])<EOL><DEDENT>if i - <NUM_LIT:1> in SUM and j + <NUM_LIT:1> in SUM[i - <NUM_LIT:1>]:<EOL><INDENT>inputs.append(SUM[i - <NUM_LIT:1>][j + <NUM_LIT:1>])<EOL><DEDENT>if len(inputs) == <NUM_LIT:1>:<EOL><INDENT>SUM[i][j] = andij<EOL><DEDENT>elif len(inputs) == <NUM_LIT:2>:<EOL><INDENT>if j == <NUM_LIT:0>:<EOL><INDENT>sumij = SUM[i][j] = p[i]<EOL><DEDENT>else:<EOL><INDENT>sumij = SUM[i][j] = '<STR_LIT>' % (i, j)<EOL><DEDENT>carryij = CARRY[i][j] = '<STR_LIT>' % (i, j)<EOL>name = '<STR_LIT>' % (inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], sumij, carryij)<EOL>gate = halfadder_gate([inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], sumij, carryij], vartype=vartype, name=name)<EOL>csp.add_constraint(gate)<EOL><DEDENT>else:<EOL><INDENT>assert len(inputs) == <NUM_LIT:3>, '<STR_LIT>'<EOL>if j == <NUM_LIT:0>:<EOL><INDENT>sumij = SUM[i][j] = p[i]<EOL><DEDENT>else:<EOL><INDENT>sumij = SUM[i][j] = '<STR_LIT>' % (i, j)<EOL><DEDENT>carryij = CARRY[i][j] = '<STR_LIT>' % (i, j)<EOL>name = '<STR_LIT>' % (inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], inputs[<NUM_LIT:2>], sumij, carryij)<EOL>gate = fulladder_gate([inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], inputs[<NUM_LIT:2>], sumij, carryij], vartype=vartype, name=name)<EOL>csp.add_constraint(gate)<EOL><DEDENT><DEDENT><DEDENT>for col in range(nbit - <NUM_LIT:1>):<EOL><INDENT>inputs = [CARRY[nbit - <NUM_LIT:1>][col], SUM[nbit - <NUM_LIT:1>][col + <NUM_LIT:1>]]<EOL>if col == <NUM_LIT:0>:<EOL><INDENT>sumout = p[nbit + col]<EOL>carryout = CARRY[nbit][col] = '<STR_LIT>' % (nbit, col)<EOL>name = '<STR_LIT>' % (inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], sumout, carryout)<EOL>gate = halfadder_gate([inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], sumout, carryout], vartype=vartype, name=name)<EOL>csp.add_constraint(gate)<EOL>continue<EOL><DEDENT>inputs.append(CARRY[nbit][col - <NUM_LIT:1>])<EOL>sumout = p[nbit + col]<EOL>if col < nbit - <NUM_LIT:2>:<EOL><INDENT>carryout = CARRY[nbit][col] = '<STR_LIT>' % (nbit, col)<EOL><DEDENT>else:<EOL><INDENT>carryout = p[<NUM_LIT:2> * nbit - <NUM_LIT:1>]<EOL><DEDENT>name = '<STR_LIT>' % (inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], inputs[<NUM_LIT:2>], sumout, carryout)<EOL>gate = fulladder_gate([inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], inputs[<NUM_LIT:2>], sumout, carryout], vartype=vartype, name=name)<EOL>csp.add_constraint(gate)<EOL><DEDENT>return csp<EOL>

Multiplication circuit constraint satisfaction problem.

    A constraint satisfaction problem that represents the binary multiplication :math:`ab=p`,
    where the multiplicands are binary variables of length `nbit`; for example,
    :math:`a_0 + 2a_1 + 4a_2 +... +2^ma_{nbit}`.

    The square below shows a graphic representation of the circuit::

      ________________________________________________________________________________
      |                                         and20         and10         and00    |
      |                                           |             |             |      |
      |                           and21         add11──and11  add01──and01    |      |
      |                             |┌───────────┘|┌───────────┘|             |      |
      |             and22         add12──and12  add02──and02    |             |      |
      |               |┌───────────┘|┌───────────┘|             |             |      |
      |             add13─────────add03           |             |             |      |
      |  ┌───────────┘|             |             |             |             |      |
      | p5            p4            p3            p2            p1            p0     |
      --------------------------------------------------------------------------------

    Args:
        nbit (int): Number of bits in the multiplicands.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}

    Returns:
        CSP (:obj:`.ConstraintSatisfactionProblem`): CSP that is satisfied when variables
        :math:`a,b,p` are assigned values that correctly solve binary multiplication :math:`ab=p`.

    Examples:
        This example creates a multiplication circuit CSP that multiplies two 3-bit numbers,
        which is then formulated as a binary quadratic model (BQM). It fixes the multiplacands
        as :math:`a=5, b=6` (:math:`101` and :math:`110`) and uses a simulated annealing sampler
        to find the product, :math:`p=30` (:math:`111100`).

        >>> import dwavebinarycsp
        >>> from dwavebinarycsp.factories.csp.circuits import multiplication_circuit
        >>> import neal
        >>> csp = multiplication_circuit(3)
        >>> bqm = dwavebinarycsp.stitch(csp)
        >>> bqm.fix_variable('a0', 1); bqm.fix_variable('a1', 0); bqm.fix_variable('a2', 1)
        >>> bqm.fix_variable('b0', 1); bqm.fix_variable('b1', 1); bqm.fix_variable('b2', 0)
        >>> sampler = neal.SimulatedAnnealingSampler()
        >>> response = sampler.sample(bqm)
        >>> p = next(response.samples(n=1, sorted_by='energy'))
        >>> print(p['p0'], p['p1'], p['p2'], p['p3'], p['p4'], p['p5'])    # doctest: +SKIP
        1 1 1 1 0 0


fp = iter(fp)  <EOL>csp = ConstraintSatisfactionProblem(dimod.BINARY)<EOL>num_clauses = num_variables = <NUM_LIT:0><EOL>problem_pattern = re.compile(_PROBLEM_REGEX)<EOL>for line in fp:<EOL><INDENT>matches = problem_pattern.findall(line)<EOL>if matches:<EOL><INDENT>if len(matches) > <NUM_LIT:1>:<EOL><INDENT>raise ValueError<EOL><DEDENT>nv, nc = matches[<NUM_LIT:0>]<EOL>num_variables, num_clauses = int(nv), int(nc)<EOL>break<EOL><DEDENT><DEDENT>clause_pattern = re.compile(_CLAUSE_REGEX)<EOL>for line in fp:<EOL><INDENT>if clause_pattern.match(line) is not None:<EOL><INDENT>clause = [int(v) for v in line.split('<STR_LIT:U+0020>')[:-<NUM_LIT:1>]]  <EOL>variables = [abs(v) for v in clause]<EOL>f = _cnf_or(clause)<EOL>csp.add_constraint(f, variables)<EOL><DEDENT><DEDENT>for v in range(<NUM_LIT:1>, num_variables+<NUM_LIT:1>):<EOL><INDENT>csp.add_variable(v)<EOL><DEDENT>for v in csp.variables:<EOL><INDENT>if v > num_variables:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>").format(num_variables, num_clauses, v)<EOL>raise ValueError(msg)<EOL><DEDENT><DEDENT>if len(csp) != num_clauses:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>").format(num_clauses, len(csp))<EOL>raise ValueError(msg)<EOL><DEDENT>return csp<EOL>

Load a constraint satisfaction problem from a .cnf file.

    Args:
        fp (file, optional):
            `.write()`-supporting `file object`_ DIMACS CNF formatted_ file.

    Returns:
        :obj:`.ConstraintSatisfactionProblem` a binary-valued SAT problem.

    Examples:

        >>> import dwavebinarycsp as dbcsp
        ...
        >>> with open('test.cnf', 'r') as fp: # doctest: +SKIP
        ...     csp = dbcsp.cnf.load_cnf(fp)

    .. _file object: https://docs.python.org/3/glossary.html#term-file-object

    .. _formatted: http://www.satcompetition.org/2009/format-benchmarks2009.html


@classmethod<EOL><INDENT>@dimod.decorators.vartype_argument('<STR_LIT>')<EOL>def from_func(cls, func, variables, vartype, name=None):<DEDENT>

variables = tuple(variables)<EOL>configurations = frozenset(config<EOL>for config in itertools.product(vartype.value, repeat=len(variables))<EOL>if func(*config))<EOL>return cls(func, configurations, variables, vartype, name)<EOL>

Construct a constraint from a validation function.

        Args:
            func (function):
                Function that evaluates True when the variables satisfy the constraint.

            variables (iterable):
                Iterable of variable labels.

            vartype (:class:`~dimod.Vartype`/str/set):
                Variable type for the constraint. Accepted input values:

                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``

            name (string, optional, default='Constraint'):
                Name for the constraint.

        Examples:
            This example creates a constraint that binary variables `a` and `b`
            are not equal.

            >>> import dwavebinarycsp
            >>> import operator
            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne, ['a', 'b'], 'BINARY')
            >>> print(const.name)
            Constraint
            >>> (0, 1) in const.configurations
            True

            This example creates a constraint that :math:`out = NOT(x)`
            for spin variables.

            >>> import dwavebinarycsp
            >>> def not_(y, x):  # y=NOT(x) for spin variables
            ...     return (y == -x)
            ...
            >>> const = dwavebinarycsp.Constraint.from_func(
            ...               not_,
            ...               ['out', 'in'],
            ...               {1, -1},
            ...               name='not_spin')
            >>> print(const.name)
            not_spin
            >>> (1, -1) in const.configurations
            True


@classmethod<EOL><INDENT>def from_configurations(cls, configurations, variables, vartype, name=None):<DEDENT>

def func(*args): return args in configurations<EOL>return cls(func, configurations, variables, vartype, name)<EOL>

Construct a constraint from valid configurations.

        Args:
            configurations (iterable[tuple]):
                Valid configurations of the variables. Each configuration is a tuple of variable
                assignments ordered by :attr:`~Constraint.variables`.

            variables (iterable):
                Iterable of variable labels.

            vartype (:class:`~dimod.Vartype`/str/set):
                Variable type for the constraint. Accepted input values:

                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``

            name (string, optional, default='Constraint'):
                Name for the constraint.

        Examples:

            This example creates a constraint that variables `a` and `b` are not equal.

            >>> import dwavebinarycsp
            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],
            ...                   ['a', 'b'], dwavebinarycsp.BINARY)
            >>> print(const.name)
            Constraint
            >>> (0, 0) in const.configurations   # Order matches variables: a,b
            False

            This example creates a constraint based on specified valid configurations
            that represents an OR gate for spin variables.

            >>> import dwavebinarycsp
            >>> const = dwavebinarycsp.Constraint.from_configurations(
            ...           [(-1, -1, -1), (1, -1, 1), (1, 1, -1), (1, 1, 1)],
            ...           ['y', 'x1', 'x2'],
            ...           dwavebinarycsp.SPIN, name='or_spin')
            >>> print(const.name)
            or_spin
            >>> (1, 1, -1) in const.configurations   # Order matches variables: y,x1,x2
            True


return self.variables.__len__()<EOL>


return self.func(*(solution[v] for v in self.variables))<EOL>

Check that a solution satisfies the constraint.

        Args:
            solution (container):
                An assignment for the variables in the constraint.

        Returns:
            bool: True if the solution satisfies the constraint; otherwise False.

        Examples:
            This example creates a constraint that :math:`a \\ne b` on binary variables
            and tests it for two candidate solutions, with additional unconstrained
            variable c.

            >>> import dwavebinarycsp
            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],
            ...             ['a', 'b'], dwavebinarycsp.BINARY)
            >>> solution = {'a': 1, 'b': 1, 'c': 0}
            >>> const.check(solution)
            False
            >>> solution = {'a': 1, 'b': 0, 'c': 0}
            >>> const.check(solution)
            True


variables = self.variables<EOL>try:<EOL><INDENT>idx = variables.index(v)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>".format(v))<EOL><DEDENT>if value not in self.vartype.value:<EOL><INDENT>raise ValueError("<STR_LIT>".format(self.vartype.value, value))<EOL><DEDENT>configurations = frozenset(config[:idx] + config[idx + <NUM_LIT:1>:]  <EOL>for config in self.configurations<EOL>if config[idx] == value)<EOL>if not configurations:<EOL><INDENT>raise UnsatError("<STR_LIT>".format(v, value))<EOL><DEDENT>variables = variables[:idx] + variables[idx + <NUM_LIT:1>:]<EOL>self.configurations = configurations<EOL>self.variables = variables<EOL>def func(*args): return args in configurations<EOL>self.func = func<EOL>self.name = '<STR_LIT>'.format(self.name, v, value)<EOL>

Fix the value of a variable and remove it from the constraint.

        Args:
            v (variable):
                Variable in the constraint to be set to a constant value.

            val (int):
                Value assigned to the variable. Values must match the :class:`.Vartype` of the
                constraint.

        Examples:
            This example creates a constraint that :math:`a \\ne b` on binary variables,
            fixes variable a to 0, and tests two candidate solutions.

            >>> import dwavebinarycsp
            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne,
            ...             ['a', 'b'], dwavebinarycsp.BINARY)
            >>> const.fix_variable('a', 0)
            >>> const.check({'b': 1})
            True
            >>> const.check({'b': 0})
            False


try:<EOL><INDENT>idx = self.variables.index(v)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>".format(v, self.name))<EOL><DEDENT>if self.vartype is dimod.BINARY:<EOL><INDENT>original_func = self.func<EOL>def func(*args):<EOL><INDENT>new_args = list(args)<EOL>new_args[idx] = <NUM_LIT:1> - new_args[idx]  <EOL>return original_func(*new_args)<EOL><DEDENT>self.func = func<EOL>self.configurations = frozenset(config[:idx] + (<NUM_LIT:1> - config[idx],) + config[idx + <NUM_LIT:1>:]<EOL>for config in self.configurations)<EOL><DEDENT>else:  <EOL><INDENT>original_func = self.func<EOL>def func(*args):<EOL><INDENT>new_args = list(args)<EOL>new_args[idx] = -new_args[idx]  <EOL>return original_func(*new_args)<EOL><DEDENT>self.func = func<EOL>self.configurations = frozenset(config[:idx] + (-config[idx],) + config[idx + <NUM_LIT:1>:]<EOL>for config in self.configurations)<EOL><DEDENT>self.name = '<STR_LIT>'.format(self.name, v)<EOL>

Flip a variable in the constraint.

        Args:
            v (variable):
                Variable in the constraint to take the complementary value of its
                construction value.

        Examples:
            This example creates a constraint that :math:`a = b` on binary variables
            and flips variable a.

            >>> import dwavebinarycsp
            >>> const = dwavebinarycsp.Constraint.from_func(operator.eq,
            ...             ['a', 'b'], dwavebinarycsp.BINARY)
            >>> const.check({'a': 0, 'b': 0})
            True
            >>> const.flip_variable('a')
            >>> const.check({'a': 1, 'b': 0})
            True
            >>> const.check({'a': 0, 'b': 0})
            False


<EOL>return self.__class__(self.func, self.configurations, self.variables, self.vartype, name=self.name)<EOL>

Create a copy.

        Examples:
            This example copies constraint :math:`a \\ne b` and tests a solution
            on the copied constraint.

            >>> import dwavebinarycsp
            >>> import operator
            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne,
            ...             ['a', 'b'], 'BINARY')
            >>> const2 = const.copy()
            >>> const2 is const
            False
            >>> const2.check({'a': 1, 'b': 1})
            False


<EOL>variables = set(variables)<EOL>if not variables.issubset(self.variables):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>idxs = [i for i, v in enumerate(self.variables) if v in variables]<EOL>configurations = frozenset(tuple(config[i] for i in idxs) for config in self.configurations)<EOL>variables = tuple(self.variables[i] for i in idxs)<EOL>return self.from_configurations(configurations, variables, self.vartype)<EOL>

Create a new constraint that is the projection onto a subset of the variables.

        Args:
            variables (iterable):
                Subset of the constraint's variables.

        Returns:
            :obj:`.Constraint`: A new constraint over a subset of the variables.

        Examples:

            >>> import dwavebinarycsp
            ...
            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 0), (0, 1)],
            ...                                                       ['a', 'b'],
            ...                                                       dwavebinarycsp.BINARY)
            >>> proj = const.projection(['a'])
            >>> proj.variables
            ['a']
            >>> proj.configurations
            {(0,)}


def add_constraint(self, constraint, variables=tuple()):

if isinstance(constraint, Constraint):<EOL><INDENT>if variables and (tuple(variables) != constraint.variables):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>elif isinstance(constraint, Callable):<EOL><INDENT>constraint = Constraint.from_func(constraint, variables, self.vartype)<EOL><DEDENT>elif isinstance(constraint, Iterable):<EOL><INDENT>constraint = Constraint.from_configurations(constraint, variables, self.vartype)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.constraints.append(constraint)<EOL>for v in constraint.variables:<EOL><INDENT>self.variables[v].append(constraint)<EOL><DEDENT>

Add a constraint.

        Args:
            constraint (function/iterable/:obj:`.Constraint`):
                Constraint definition in one of the supported formats:

                1. Function, with input arguments matching the order and
                   :attr:`~.ConstraintSatisfactionProblem.vartype` type of the `variables`
                   argument, that evaluates True when the constraint is satisfied.
                2. List explicitly specifying each allowed configuration as a tuple.
                3. :obj:`.Constraint` object built either explicitly or by :mod:`dwavebinarycsp.factories`.

            variables(iterable):
                Variables associated with the constraint. Not required when `constraint` is
                a :obj:`.Constraint` object.

        Examples:
            This example defines a function that evaluates True when the constraint is satisfied.
            The function's input arguments match the order and type of the `variables` argument.

            >>> import dwavebinarycsp
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
            >>> def all_equal(a, b, c):  # works for both dwavebinarycsp.BINARY and dwavebinarycsp.SPIN
            ...     return (a == b) and (b == c)
            >>> csp.add_constraint(all_equal, ['a', 'b', 'c'])
            >>> csp.check({'a': 0, 'b': 0, 'c': 0})
            True
            >>> csp.check({'a': 0, 'b': 0, 'c': 1})
            False

            This example explicitly lists allowed configurations.

            >>> import dwavebinarycsp
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)
            >>> eq_configurations = {(-1, -1), (1, 1)}
            >>> csp.add_constraint(eq_configurations, ['v0', 'v1'])
            >>> csp.check({'v0': -1, 'v1': +1})
            False
            >>> csp.check({'v0': -1, 'v1': -1})
            True

            This example uses a :obj:`.Constraint` object built by :mod:`dwavebinarycsp.factories`.

            >>> import dwavebinarycsp
            >>> import dwavebinarycsp.factories.constraint.gates as gates
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
            >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c']))  # add an AND gate
            >>> csp.add_constraint(gates.xor_gate(['a', 'c', 'd']))  # add an XOR gate
            >>> csp.check({'a': 1, 'b': 0, 'c': 0, 'd': 1})
            True


self.variables[v]<EOL>

Add a variable.

        Args:
            v (variable):
                Variable in the constraint satisfaction problem. May be of any type that
                can be a dict key.

        Examples:
            This example adds two variables, one of which is already used in a constraint
            of the constraint satisfaction problem.

            >>> import dwavebinarycsp
            >>> import operator
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)
            >>> csp.add_constraint(operator.eq, ['a', 'b'])
            >>> csp.add_variable('a')  # does nothing, already added as part of the constraint
            >>> csp.add_variable('c')
            >>> csp.check({'a': -1, 'b': -1, 'c': 1})
            True
            >>> csp.check({'a': -1, 'b': -1, 'c': -1})
            True


return all(constraint.check(solution) for constraint in self.constraints)<EOL>

Check that a solution satisfies all of the constraints.

        Args:
            solution (container):
                An assignment of values for the variables in the constraint satisfaction problem.

        Returns:
            bool: True if the solution satisfies all of the constraints; False otherwise.

        Examples:
            This example creates a binary-valued constraint satisfaction problem, adds
            two logic gates implementing Boolean constraints, :math:`c = a \wedge b`
            and :math:`d = a \oplus c`, and verifies that the combined problem is satisfied
            for a given assignment.

            >>> import dwavebinarycsp
            >>> import dwavebinarycsp.factories.constraint.gates as gates
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
            >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c']))  # add an AND gate
            >>> csp.add_constraint(gates.xor_gate(['a', 'c', 'd']))  # add an XOR gate
            >>> csp.check({'a': 1, 'b': 0, 'c': 0, 'd': 1})
            True


if v not in self.variables:<EOL><INDENT>raise ValueError("<STR_LIT>".format(v))<EOL><DEDENT>for constraint in self.variables[v]:<EOL><INDENT>constraint.fix_variable(v, value)<EOL><DEDENT>del self.variables[v]<EOL>

Fix the value of a variable and remove it from the constraint satisfaction problem.

        Args:
            v (variable):
                Variable to be fixed in the constraint satisfaction problem.

            value (int):
                Value assigned to the variable. Values must match the
                :attr:`~.ConstraintSatisfactionProblem.vartype` of the constraint
                satisfaction problem.

        Examples:
            This example creates a spin-valued constraint satisfaction problem, adds two constraints,
            :math:`a = b` and :math:`b \\ne c`, and fixes variable b to +1.

            >>> import dwavebinarycsp
            >>> import operator
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)
            >>> csp.add_constraint(operator.eq, ['a', 'b'])
            >>> csp.add_constraint(operator.ne, ['b', 'c'])
            >>> csp.check({'a': +1, 'b': +1, 'c': -1})
            True
            >>> csp.check({'a': -1, 'b': -1, 'c': +1})
            True
            >>> csp.fix_variable('b', +1)
            >>> csp.check({'a': +1, 'b': +1, 'c': -1})  # 'b' is ignored
            True
            >>> csp.check({'a': -1, 'b': -1, 'c': +1})
            False
            >>> csp.check({'a': +1, 'c': -1})
            True
            >>> csp.check({'a': -1, 'c': +1})
            False


from pkg_resources import iter_entry_points<EOL>from penaltymodel.core import FACTORY_ENTRYPOINT<EOL>from itertools import chain<EOL>supported = ('<STR_LIT>', '<STR_LIT>')<EOL>factories = chain(*(iter_entry_points(FACTORY_ENTRYPOINT, name) for name in supported))<EOL>try:<EOL><INDENT>next(factories)<EOL><DEDENT>except StopIteration:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>"<STR_LIT>".join("<STR_LIT>".format(name) for name in supported)<EOL>))<EOL><DEDENT>

For `dwavebinarycsp` to be functional, at least one penalty model factory
    has to be installed. See discussion in setup.py for details.


def stitch(csp, min_classical_gap=<NUM_LIT>, max_graph_size=<NUM_LIT:8>):

<EOL>try:<EOL><INDENT>dwavebinarycsp.assert_penaltymodel_factory_available()<EOL><DEDENT>except AssertionError as e:<EOL><INDENT>raise RuntimeError(e)<EOL><DEDENT>def aux_factory():<EOL><INDENT>for i in count():<EOL><INDENT>yield '<STR_LIT>'.format(i)<EOL><DEDENT><DEDENT>aux = aux_factory()<EOL>bqm = dimod.BinaryQuadraticModel.empty(csp.vartype)<EOL>for const in csp.constraints:<EOL><INDENT>configurations = const.configurations<EOL>if len(const.variables) > max_graph_size:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>").format(const=const, num_var=len(const.variables), max_graph_size=max_graph_size)<EOL>raise ImpossibleBQM(msg)<EOL><DEDENT>pmodel = None<EOL>if len(const) == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>if min_classical_gap <= <NUM_LIT>:<EOL><INDENT>if len(const) == <NUM_LIT:1> and max_graph_size >= <NUM_LIT:1>:<EOL><INDENT>bqm.update(_bqm_from_1sat(const))<EOL>continue<EOL><DEDENT>elif len(const) == <NUM_LIT:2> and max_graph_size >= <NUM_LIT:2>:<EOL><INDENT>bqm.update(_bqm_from_2sat(const))<EOL>continue<EOL><DEDENT><DEDENT>for G in iter_complete_graphs(const.variables, max_graph_size + <NUM_LIT:1>, aux):<EOL><INDENT>spec = pm.Specification(<EOL>graph=G,<EOL>decision_variables=const.variables,<EOL>feasible_configurations=configurations,<EOL>min_classical_gap=min_classical_gap,<EOL>vartype=csp.vartype<EOL>)<EOL>try:<EOL><INDENT>pmodel = pm.get_penalty_model(spec)<EOL><DEDENT>except pm.ImpossiblePenaltyModel:<EOL><INDENT>continue<EOL><DEDENT>if pmodel.classical_gap >= min_classical_gap:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>msg = ("<STR_LIT>".format(const))<EOL>raise ImpossibleBQM(msg)<EOL><DEDENT>bqm.update(pmodel.model)<EOL><DEDENT>return bqm<EOL>

Build a binary quadratic model with minimal energy levels at solutions to the specified constraint satisfaction
    problem.

    Args:
        csp (:obj:`.ConstraintSatisfactionProblem`):
            Constraint satisfaction problem.

        min_classical_gap (float, optional, default=2.0):
            Minimum energy gap from ground. Each constraint violated by the solution increases
            the energy level of the binary quadratic model by at least this much relative
            to ground energy.

        max_graph_size (int, optional, default=8):
            Maximum number of variables in the binary quadratic model that can be used to
            represent a single constraint.

    Returns:
        :class:`~dimod.BinaryQuadraticModel`

    Notes:
        For a `min_classical_gap` > 2 or constraints with more than two variables, requires
        access to factories from the penaltymodel_ ecosystem to construct the binary quadratic
        model.

    .. _penaltymodel: https://github.com/dwavesystems/penaltymodel

    Examples:
        This example creates a binary-valued constraint satisfaction problem
        with two constraints, :math:`a = b` and :math:`b \\ne c`, and builds
        a binary quadratic model with a minimum energy level of -2 such that
        each constraint violation by a solution adds the default minimum energy gap.

        >>> import dwavebinarycsp
        >>> import operator
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b
        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c
        >>> bqm = dwavebinarycsp.stitch(csp)
        >>> bqm.energy({'a': 0, 'b': 0, 'c': 1})  # satisfies csp
        -2.0
        >>> bqm.energy({'a': 0, 'b': 0, 'c': 0})  # violates one constraint
        0.0
        >>> bqm.energy({'a': 1, 'b': 0, 'c': 0}) # violates two constraints
        2.0

        This example creates a binary-valued constraint satisfaction problem
        with two constraints, :math:`a = b` and :math:`b \\ne c`, and builds
        a binary quadratic model with a minimum energy gap of 4.
        Note that in this case the conversion to binary quadratic model adds two
        ancillary variables that must be minimized over when solving.

        >>> import dwavebinarycsp
        >>> import operator
        >>> import itertools
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b
        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c
        >>> bqm = dwavebinarycsp.stitch(csp, min_classical_gap=4.0)
        >>> list(bqm)   # # doctest: +SKIP
        ['a', 'aux1', 'aux0', 'b', 'c']
        >>> min([bqm.energy({'a': 0, 'b': 0, 'c': 1, 'aux0': aux0, 'aux1': aux1}) for
        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # satisfies csp
        -6.0
        >>> min([bqm.energy({'a': 0, 'b': 0, 'c': 0, 'aux0': aux0, 'aux1': aux1}) for
        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # violates one constraint
        -2.0
        >>> min([bqm.energy({'a': 1, 'b': 0, 'c': 0, 'aux0': aux0, 'aux1': aux1}) for
        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # violates two constraints
        2.0

        This example finds for the previous example the minimum graph size.

        >>> import dwavebinarycsp
        >>> import operator
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b
        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c
        >>> for n in range(8, 1, -1):
        ...     try:
        ...         bqm = dwavebinarycsp.stitch(csp, min_classical_gap=4.0, max_graph_size=n)
        ...     except dwavebinarycsp.exceptions.ImpossibleBQM:
        ...         print(n+1)
        ...
        3


configurations = constraint.configurations<EOL>num_configurations = len(configurations)<EOL>bqm = dimod.BinaryQuadraticModel.empty(constraint.vartype)<EOL>if num_configurations == <NUM_LIT:1>:<EOL><INDENT>val, = next(iter(configurations))<EOL>v, = constraint.variables<EOL>bqm.add_variable(v, -<NUM_LIT:1> if val > <NUM_LIT:0> else +<NUM_LIT:1>, vartype=dimod.SPIN)<EOL><DEDENT>else:<EOL><INDENT>bqm.add_variables_from((v, <NUM_LIT:0.0>) for v in constraint.variables)<EOL><DEDENT>return bqm<EOL>

create a bqm for a constraint with only one variable

    bqm will have exactly classical gap 2.


configurations = constraint.configurations<EOL>variables = constraint.variables<EOL>vartype = constraint.vartype<EOL>u, v = constraint.variables<EOL>if len(configurations) == <NUM_LIT:4>:<EOL><INDENT>return dimod.BinaryQuadraticModel.empty(constraint.vartype)<EOL><DEDENT>components = irreducible_components(constraint)<EOL>if len(components) > <NUM_LIT:1>:<EOL><INDENT>const0 = Constraint.from_configurations(((config[<NUM_LIT:0>],) for config in configurations),<EOL>(u,), vartype)<EOL>const1 = Constraint.from_configurations(((config[<NUM_LIT:1>],) for config in configurations),<EOL>(v,), vartype)<EOL>bqm = _bqm_from_1sat(const0)<EOL>bqm.update(_bqm_from_1sat(const1))<EOL>return bqm<EOL><DEDENT>assert len(configurations) > <NUM_LIT:1>, "<STR_LIT>"<EOL>bqm = dimod.BinaryQuadraticModel.empty(vartype)<EOL>if all(operator.eq(*config) for config in configurations):<EOL><INDENT>bqm.add_interaction(u, v, -<NUM_LIT:1>, vartype=dimod.SPIN)  <EOL><DEDENT>elif all(operator.ne(*config) for config in configurations):<EOL><INDENT>bqm.add_interaction(u, v, +<NUM_LIT:1>, vartype=dimod.SPIN)  <EOL><DEDENT>elif (<NUM_LIT:1>, <NUM_LIT:1>) not in configurations:<EOL><INDENT>bqm.add_interaction(u, v, <NUM_LIT:2>, vartype=dimod.BINARY)  <EOL><DEDENT>elif (-<NUM_LIT:1>, +<NUM_LIT:1>) not in configurations and (<NUM_LIT:0>, <NUM_LIT:1>) not in configurations:<EOL><INDENT>bqm.add_interaction(u, v, -<NUM_LIT:2>, vartype=dimod.BINARY)<EOL>bqm.add_variable(v, <NUM_LIT:2>, vartype=dimod.BINARY)<EOL><DEDENT>elif (+<NUM_LIT:1>, -<NUM_LIT:1>) not in configurations and (<NUM_LIT:1>, <NUM_LIT:0>) not in configurations:<EOL><INDENT>bqm.add_interaction(u, v, -<NUM_LIT:2>, vartype=dimod.BINARY)<EOL>bqm.add_variable(u, <NUM_LIT:2>, vartype=dimod.BINARY)<EOL><DEDENT>else:<EOL><INDENT>bqm.add_interaction(u, v, <NUM_LIT:2>, vartype=dimod.BINARY)<EOL>bqm.add_variable(u, -<NUM_LIT:2>, vartype=dimod.BINARY)<EOL>bqm.add_variable(v, -<NUM_LIT:2>, vartype=dimod.BINARY)<EOL><DEDENT>return bqm<EOL>

create a bqm for a constraint with two variables.

    bqm will have exactly classical gap 2.


@nx.utils.nodes_or_number(<NUM_LIT:0>)<EOL>def iter_complete_graphs(start, stop, factory=None):

_, nodes = start<EOL>nodes = list(nodes)  <EOL>if factory is None:<EOL><INDENT>factory = count()<EOL><DEDENT>while len(nodes) < stop:<EOL><INDENT>G = nx.complete_graph(nodes)<EOL>yield G<EOL>v = next(factory)<EOL>while v in G:<EOL><INDENT>v = next(factory)<EOL><DEDENT>nodes.append(v)<EOL><DEDENT>

Iterate over complete graphs.

    Args:
        start (int/iterable):
            Define the size of the starting graph.
            If an int, the nodes will be index-labeled, otherwise should be an iterable of node
            labels.

        stop (int):
            Stops yielding graphs when the size equals stop.

        factory (iterator, optional):
            If provided, nodes added will be labeled according to the values returned by factory.
            Otherwise the extra nodes will be index-labeled.

    Yields:
        :class:`nx.Graph`


return list(self._results.keys())<EOL>

Returns a list of strings to represent the options for the poll, in
        the order they were given when the poll was created.


return list(self._results.values())<EOL>

Return a list of integers that correspond to the same indexed option
        which specify the current votes for that option.


return sum(self._results.values())<EOL>

Returns the total number of votes on the poll.


if self.id is None:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>'.format(strawpoll.API._BASE_URL, self.id)<EOL>

Returns the url of the poll. If the poll has not been submitted yet,
        an empty string is returned instead.


return self._results.most_common(limit)<EOL>

Returns a list of tuples each containing a string representing an
        option and an int which specify the current votes for that option,
        ordered by their votes count.

        :param int limit: The maximum number of results to return. If not \
        specified, every results will be returned.


return list(self._results.items())[index]<EOL>

Returns a tuple containing a string representing the option and an
        int which specify the current votes for that option.

        :param int index: The index of the wanted option in the options list.


def get_poll(self, arg, *, request_policy=None):

if isinstance(arg, str):<EOL><INDENT>match = self._url_re.match(arg)<EOL>if match:<EOL><INDENT>arg = match.group('<STR_LIT:id>')<EOL><DEDENT><DEDENT>return self._http_client.get('<STR_LIT>'.format(self._POLLS, arg),<EOL>request_policy=request_policy,<EOL>cls=strawpoll.Poll)<EOL>

Retrieves a poll from strawpoll.

        :param arg: Either the ID of the poll or its strawpoll url.
        :param request_policy: Overrides :attr:`API.requests_policy` for that \
        request.
        :type request_policy: Optional[:class:`RequestsPolicy`]

        :raises HTTPException: Requesting the poll failed.

        :returns: A poll constructed with the requested data.
        :rtype: :class:`Poll`


def submit_poll(self, poll, *, request_policy=None):

if poll.id is not None:<EOL><INDENT>raise ExistingPoll()<EOL><DEDENT>options = poll.options<EOL>data = {<EOL>'<STR_LIT:title>': poll.title,<EOL>'<STR_LIT>': options,<EOL>'<STR_LIT>': poll.multi,<EOL>'<STR_LIT>': poll.dupcheck,<EOL>'<STR_LIT>': poll.captcha<EOL>}<EOL>return self._http_client.post(self._POLLS,<EOL>data=data,<EOL>request_policy=request_policy,<EOL>cls=strawpoll.Poll)<EOL>

Submits a poll on strawpoll.

        :param poll: The poll to submit.
        :type poll: :class:`Poll`
        :param request_policy: Overrides :attr:`API.requests_policy` for that \
        request.
        :type request_policy: Optional[:class:`RequestsPolicy`]

        :raises ExistingPoll: This poll instance has already been submitted.
        :raises HTTPException: The submission failed.

        :returns: The given poll updated with the data sent back from the submission.
        :rtype: :class:`Poll`

        .. note::
            Only polls that have a non empty title and between 2 and 30 options
            can be submitted.


try:<EOL><INDENT>return request.headers[key]<EOL><DEDENT>except KeyError:<EOL><INDENT>abort(<NUM_LIT>, '<STR_LIT>' + key)<EOL><DEDENT>


def decorator(func):<EOL><INDENT>self._hooks[event_type].append(func)<EOL>return func<EOL><DEDENT>return decorator<EOL>

Registers a function as a hook. Multiple hooks can be registered for a given type, but the
order in which they are invoke is unspecified.

:param event_type: The event type this hook will be invoked for.


return hmac.new(<EOL>self._secret, request.data, hashlib.sha1).hexdigest() if self._secret else None<EOL>

Return message digest if a secret key was provided


digest = self._get_digest()<EOL>if digest is not None:<EOL><INDENT>sig_parts = _get_header('<STR_LIT>').split('<STR_LIT:=>', <NUM_LIT:1>)<EOL>if not isinstance(digest, six.text_type):<EOL><INDENT>digest = six.text_type(digest)<EOL><DEDENT>if (len(sig_parts) < <NUM_LIT:2> or sig_parts[<NUM_LIT:0>] != '<STR_LIT>'<EOL>or not hmac.compare_digest(sig_parts[<NUM_LIT:1>], digest)):<EOL><INDENT>abort(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT><DEDENT>event_type = _get_header('<STR_LIT>')<EOL>data = request.get_json()<EOL>if data is None:<EOL><INDENT>abort(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>self._logger.info(<EOL>'<STR_LIT>', _format_event(event_type, data), _get_header('<STR_LIT>'))<EOL>for hook in self._hooks.get(event_type, []):<EOL><INDENT>hook(data)<EOL><DEDENT>return '<STR_LIT>', <NUM_LIT><EOL>


logger.debug("<STR_LIT>", command)<EOL>p = subprocess.Popen(command,<EOL>shell=True,<EOL>stdin=subprocess.PIPE,<EOL>stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE,<EOL>close_fds=MUST_CLOSE_FDS)<EOL>stdoutdata, stderrdata = p.communicate(input=input)<EOL>result = stdoutdata + stderrdata<EOL>if p.returncode:<EOL><INDENT>logger.error("<STR_LIT>",<EOL>command)<EOL>logger.error("<STR_LIT>", p.returncode)<EOL>logger.error("<STR_LIT>")<EOL>logger.error(result)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>logger.info(result)<EOL>

commands.getoutput() replacement that also works on windows.

    Code mostly copied from zc.buildout.


usage = "<STR_LIT>"<EOL>parser = optparse.OptionParser(usage=usage)<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>action="<STR_LIT:store_true>", dest="<STR_LIT>", default=False,<EOL>help="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>action="<STR_LIT:store>", type="<STR_LIT:string>", dest="<STR_LIT>",<EOL>default='<STR_LIT>',<EOL>help="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>action="<STR_LIT:store>", type="<STR_LIT:string>", dest="<STR_LIT>",<EOL>default='<STR_LIT>',<EOL>help=("<STR_LIT>" +<EOL>"<STR_LIT>"))<EOL>(options, args) = parser.parse_args()<EOL>if options.verbose:<EOL><INDENT>log_level = logging.DEBUG<EOL><DEDENT>else:<EOL><INDENT>log_level = logging.INFO<EOL><DEDENT>logging.basicConfig(level=log_level,<EOL>format="<STR_LIT>")<EOL>curdir = os.getcwd()<EOL>testbinary = os.path.join(curdir, '<STR_LIT>', '<STR_LIT:test>')<EOL>if not os.path.exists(testbinary):<EOL><INDENT>raise RuntimeError("<STR_LIT>" % testbinary)<EOL><DEDENT>coveragebinary = os.path.join(curdir, '<STR_LIT>', '<STR_LIT>')<EOL>if not os.path.exists(coveragebinary):<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>coveragebinary = '<STR_LIT>'<EOL><DEDENT>logger.info("<STR_LIT>")<EOL>parts = [coveragebinary, '<STR_LIT>', testbinary]<EOL>if options.test_args:<EOL><INDENT>parts.append(options.test_args)<EOL><DEDENT>system("<STR_LIT:U+0020>".join(parts))<EOL>logger.debug("<STR_LIT>")<EOL>if options.output_dir:<EOL><INDENT>coverage_dir = options.output_dir<EOL>open_in_browser = False<EOL><DEDENT>else:<EOL><INDENT>coverage_dir = '<STR_LIT>'  <EOL>open_in_browser = True<EOL><DEDENT>system("<STR_LIT>" % (coveragebinary, coverage_dir))<EOL>logger.info("<STR_LIT>", coverage_dir)<EOL>if open_in_browser:<EOL><INDENT>index_file = os.path.abspath(<EOL>os.path.join(coverage_dir, '<STR_LIT>'))<EOL>logger.debug("<STR_LIT>", index_file)<EOL>webbrowser.open('<STR_LIT>' + index_file)<EOL>logger.info("<STR_LIT>")<EOL><DEDENT>

Create coverage reports and open them in the browser.


context.log.debug(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% scenario.name)<EOL>context.params = {}<EOL>context.exception = None<EOL>context.result = None<EOL>

Add entry to the debug log befere starting the scenario


context.log.debug(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% scenario.name)<EOL>

Add an entry to the debug log after scenario was finished


context.log = _setup_logging()<EOL>

Executes the code before all the tests are run


<EOL>log = logging.getLogger('<STR_LIT>')<EOL>fh = logging.FileHandler(<EOL>filename='<STR_LIT>'.format(REPORT_DIR), mode='<STR_LIT:w>')<EOL>log.setLevel(logging.DEBUG)<EOL>ch = logging.StreamHandler()<EOL>ch.setLevel(logging.INFO)<EOL>fh.setLevel(logging.DEBUG)<EOL>formatter = logging.Formatter(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>')<EOL>ch.setFormatter(formatter)<EOL>fh.setFormatter(formatter)<EOL>log.addHandler(ch)<EOL>log.addHandler(fh)<EOL>return log<EOL>


if key is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>match = re.match(PATTERN, key)<EOL>if not match:<EOL><INDENT>match = re.match(PATTERN_S0, key)<EOL>if not match:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return dict(map(normalise_part, zip([p for p in PARTS_S0.keys()], match.groups())))<EOL><DEDENT>return dict(zip(PARTS.keys(), match.groups()))<EOL>

Parse a hub key into a dictionary of component parts

    :param key: str, a hub key
    :returns: dict, hub key split into parts
    :raises: ValueError


try:<EOL><INDENT>parse_hub_key(value)<EOL>return True<EOL><DEDENT>except (ValueError, TypeError):<EOL><INDENT>return False<EOL><DEDENT>

Test if a value could be a hub key
    :param value: the value to test if it is a hub key
    :returns: True if it is a hub key


if not string or not re.match('<STR_LIT>' + PARTS[part] + '<STR_LIT>', string):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(part, PARTS[part]))<EOL><DEDENT>

Raise an exception if string doesn't match a part's regex

    :param string: str
    :param part: a key in the PARTS dict
    :raises: ValueError, TypeError


return string.encode('<STR_LIT>').decode('<STR_LIT:ascii>')<EOL>

Encode a string as ASCII using IDNA so that it is a valid part of a URI

    See RFC3490.

    :param string: str
    :returns: ASCII string


return quote(string.encode('<STR_LIT:utf8>'), safe='<STR_LIT>')<EOL>

Percent encode a string as ASCII so that it is a valid part of a URI

    :param string: str
    :returns: ASCII string


def generate_hub_key(resolver_id, hub_id, repository_id, entity_type, entity_id=None):

parsed = urlparse(resolver_id)<EOL>if not parsed.scheme:<EOL><INDENT>parsed = parsed._replace(scheme=PROTOCOL, netloc=idna_encode(parsed.path.lower()), path=u'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>parsed = parsed._replace(netloc=idna_encode(parsed.netloc.lower()))<EOL><DEDENT>resolver_id = urlunparse(parsed)<EOL>hub_id = url_quote(hub_id.lower())<EOL>if not entity_id:<EOL><INDENT>entity_id = str(uuid.uuid4()).replace('<STR_LIT:->', '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>match_part(entity_id, '<STR_LIT>')<EOL><DEDENT>match_part(resolver_id, '<STR_LIT>')<EOL>match_part(hub_id, '<STR_LIT>')<EOL>match_part(repository_id, '<STR_LIT>')<EOL>match_part(entity_type, '<STR_LIT>')<EOL>hub_key = SEPARATOR.join(<EOL>[resolver_id, SCHEMA, hub_id, repository_id, entity_type, entity_id])<EOL>return hub_key<EOL>

Create and return an array of hub keys
    :param resolver_id: the service that can resolve this key
    :param hub_id: the unique id of the hub
    :param repository_id: the type of id that the provider recognises
    :param entity_type: the type of the entity to which the key refers.
    :param entity_id: ID of entity (UUID)
    :returns: a hub key
    :raises:
    :AttributeError: if a parameter has a bad value
    :TypeError: if a parameter has a bad value
    :ValueError: if a parameter has a bad value


def get_channel_image(self, channel, img_size=<NUM_LIT>, skip_cache=False):

from bs4 import BeautifulSoup<EOL>from wikipedia.exceptions import PageError<EOL>import re<EOL>import wikipedia<EOL>wikipedia.set_lang('<STR_LIT>')<EOL>if not channel:<EOL><INDENT>_LOGGER.error('<STR_LIT>')<EOL>return<EOL><DEDENT>if channel in self._cache_channel_img and not skip_cache:<EOL><INDENT>img = self._cache_channel_img[channel]<EOL>_LOGGER.debug('<STR_LIT>', channel, img)<EOL>return img<EOL><DEDENT>channel_info = self.get_channel_info(channel)<EOL>query = channel_info['<STR_LIT>']<EOL>if not query:<EOL><INDENT>_LOGGER.debug('<STR_LIT>', channel)<EOL>return<EOL><DEDENT>_LOGGER.debug('<STR_LIT>', query)<EOL>if '<STR_LIT>' in channel_info:<EOL><INDENT>if img_size > channel_info['<STR_LIT>']:<EOL><INDENT>_LOGGER.info(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', channel_info['<STR_LIT>']<EOL>)<EOL>img_size = channel_info['<STR_LIT>']<EOL><DEDENT><DEDENT>try:<EOL><INDENT>page = wikipedia.page(query)<EOL>_LOGGER.debug('<STR_LIT>', page.title)<EOL>soup = BeautifulSoup(page.html(), '<STR_LIT>')<EOL>images = soup.find_all('<STR_LIT>')<EOL>img_src = None<EOL>for i in images:<EOL><INDENT>if i['<STR_LIT>'].startswith('<STR_LIT>'):<EOL><INDENT>img_src = re.sub(r'<STR_LIT>', '<STR_LIT>'.format(img_size),<EOL>i['<STR_LIT:src>'])<EOL><DEDENT><DEDENT>img = '<STR_LIT>'.format(img_src) if img_src else None<EOL>self._cache_channel_img[channel] = img<EOL>return img<EOL><DEDENT>except PageError:<EOL><INDENT>_LOGGER.error('<STR_LIT>', channel)<EOL><DEDENT>


def press_key(self, key, mode=<NUM_LIT:0>):

if isinstance(key, str):<EOL><INDENT>assert key in KEYS, '<STR_LIT>'.format(key)<EOL>key = KEYS[key]<EOL><DEDENT>_LOGGER.info('<STR_LIT>', self.__get_key_name(key))<EOL>return self.rq('<STR_LIT>', OrderedDict([('<STR_LIT:key>', key), ('<STR_LIT>', mode)]))<EOL>

modes:
    0 -> simple press
    1 -> long press
    2 -> release after long press


objtype = type(obj)<EOL>typename = str(objtype.__module__) + "<STR_LIT:.>" + objtype.__name__<EOL>prettytype = typename.replace("<STR_LIT>", "<STR_LIT>")<EOL>name = getattr(obj, "<STR_LIT>", "<STR_LIT>")<EOL>if name:<EOL><INDENT>prettytype = "<STR_LIT>" % (prettytype, name)<EOL><DEDENT>key = "<STR_LIT>"<EOL>if referent:<EOL><INDENT>key = self.get_refkey(obj, referent)<EOL><DEDENT>url = reverse('<STR_LIT>', args=(<EOL>typename,<EOL>id(obj)<EOL>))<EOL>return ('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>% (url, id(obj), prettytype, key, get_repr(obj, <NUM_LIT:100>))<EOL>)<EOL>

Return an HTML tree block describing the given object.


if isinstance(obj, dict):<EOL><INDENT>for k, v in obj.items():<EOL><INDENT>if v is referent:<EOL><INDENT>return "<STR_LIT>" % k<EOL><DEDENT><DEDENT><DEDENT>for k in dir(obj) + ['<STR_LIT>']:<EOL><INDENT>if getattr(obj, k, None) is referent:<EOL><INDENT>return "<STR_LIT>" % k<EOL><DEDENT><DEDENT>return "<STR_LIT>"<EOL>

Return the dict key or attribute name of obj which refers to
        referent.


def walk(self, maxresults=<NUM_LIT:100>, maxdepth=None):

log.debug("<STR_LIT>")<EOL>self.seen = {}<EOL>self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore)<EOL>self.ignore_caller()<EOL>self.maxdepth = maxdepth<EOL>count = <NUM_LIT:0><EOL>log.debug("<STR_LIT>")<EOL>for result in self._gen(self.obj):<EOL><INDENT>log.debug("<STR_LIT>")<EOL>yield result<EOL>count += <NUM_LIT:1><EOL>if maxresults and count >= maxresults:<EOL><INDENT>yield <NUM_LIT:0>, <NUM_LIT:0>, "<STR_LIT>"<EOL>return<EOL><DEDENT><DEDENT>

Walk the object tree, ignoring duplicates and circular refs.


def print_tree(self, maxresults=<NUM_LIT:100>, maxdepth=None):

self.ignore_caller()<EOL>for depth, refid, rep in self.walk(maxresults, maxdepth):<EOL><INDENT>print(("<STR_LIT>" % refid), ("<STR_LIT:U+0020>" * depth * <NUM_LIT:2>), rep)<EOL><DEDENT>

Walk the object tree, pretty-printing each branch.


self.stops = <NUM_LIT:0><EOL>self.seen = {}<EOL>self.ignore(self, self.__dict__, self.seen, self._ignore)<EOL>self.ignore_caller()<EOL>self.maxdepth = maxdepth<EOL>count = <NUM_LIT:0><EOL>for result in self._gen(self.obj):<EOL><INDENT>yield result<EOL>count += <NUM_LIT:1><EOL>if maxresults and count >= maxresults:<EOL><INDENT>yield <NUM_LIT:0>, <NUM_LIT:0>, "<STR_LIT>"<EOL>return<EOL><DEDENT><DEDENT>

Walk the object tree, showing circular referents.


self.ignore_caller()<EOL>for trail in self.walk(maxresults, maxdepth):<EOL><INDENT>print(trail)<EOL><DEDENT>if self.stops:<EOL><INDENT>print("<STR_LIT>" % self.stops)<EOL><DEDENT>


def has_address(start: int, data_length: int) -> bool:

return bool(<NUM_LIT> & start) or (start == <NUM_LIT> and data_length == <NUM_LIT:16>)<EOL>

Determine whether the packet has an "address" encoded into it.
There exists an undocumented bug/edge case in the spec - some packets
with 0x82 as _start_, still encode the address into the packet, and thus
throws off decoding. This edge case is handled explicitly.


def decode_timestamp(data: str) -> datetime.datetime:

year = <NUM_LIT> + int(data[<NUM_LIT:0>:<NUM_LIT:2>])<EOL>month = int(data[<NUM_LIT:2>:<NUM_LIT:4>])<EOL>day = int(data[<NUM_LIT:4>:<NUM_LIT:6>])<EOL>hour = int(data[<NUM_LIT:6>:<NUM_LIT:8>])<EOL>minute = int(data[<NUM_LIT:8>:<NUM_LIT:10>])<EOL>second = int(data[<NUM_LIT:10>:<NUM_LIT:12>])<EOL>if minute == <NUM_LIT>:<EOL><INDENT>minute = <NUM_LIT:0><EOL>hour += <NUM_LIT:1><EOL><DEDENT>return datetime.datetime(year=year, month=month, day=day, hour=hour,<EOL>minute=minute, second=second)<EOL>

Decode timestamp using bespoke decoder.
Cannot use simple strptime since the ness panel contains a bug
that P199E zone and state updates emitted on the hour cause a minute
value of `60` to be sent, causing strptime to fail. This decoder handles
this edge case.


@classmethod<EOL><INDENT>def decode(cls, _data: str) -> '<STR_LIT>':<DEDENT>

<EOL>data = DataIterator(_data)<EOL>_LOGGER.debug("<STR_LIT>", _data)<EOL>start = data.take_hex()<EOL>address = None<EOL>if has_address(start, len(_data)):<EOL><INDENT>address = data.take_hex(half=is_user_interface_req(start))<EOL><DEDENT>length = data.take_hex()<EOL>data_length = length & <NUM_LIT><EOL>seq = length >> <NUM_LIT:7><EOL>command = CommandType(data.take_hex())<EOL>msg_data = data.take_bytes(data_length,<EOL>half=is_user_interface_req(start))<EOL>timestamp = None<EOL>if has_timestamp(start):<EOL><INDENT>timestamp = decode_timestamp(data.take_bytes(<NUM_LIT:6>))<EOL><DEDENT>checksum = data.take_hex()  <EOL>if not data.is_consumed():<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return Packet(<EOL>is_user_interface_resp=(is_user_interface_resp(start) and<EOL>command == CommandType.USER_INTERFACE),<EOL>address=address,<EOL>seq=seq,<EOL>command=command,<EOL>data=msg_data,<EOL>timestamp=timestamp,<EOL>)<EOL>

Packets are ASCII encoded data. Packet layout is as follows:

+---------------------------------------------------------------------------+
| start | address | length | command | data | timestamp | checksum | finish |
| hex   | hex     | hex    | hex     | str  | dec       | hex      | crlf   |
| 1     | 1       | 1      | 1       | n    | 6         | 1        |        |
+---------------------------------------------------------------------------+

Timestamp:
    Timestamps are formatted in the following format, where each field is
    decimal encoded:

    YY MM DD HH MM SS

Checksum:
    Calculated by...?

Since data is ASCII encoded, each byte uses 2 ASCII character to be
represented. However, we cannot simply do a hex decode on the entire
message, since the timestamp and data fields are represented using a
non-hex representation and therefore must be manually decoded.


_LOGGER.debug("<STR_LIT>")<EOL>await asyncio.gather(<EOL>self.send_command('<STR_LIT>'),<EOL>self.send_command('<STR_LIT>'),<EOL>)<EOL>


await asyncio.sleep(self._update_interval)<EOL>while not self._closed:<EOL><INDENT>await self.update()<EOL>await asyncio.sleep(self._update_interval)<EOL><DEDENT>

Schedule a state update to keep the connection alive


def _handle_system_status_event(self, event: SystemStatusEvent) -> None:

if event.type == SystemStatusEvent.EventType.UNSEALED:<EOL><INDENT>return self._update_zone(event.zone, True)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.SEALED:<EOL><INDENT>return self._update_zone(event.zone, False)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.ALARM:<EOL><INDENT>return self._update_arming_state(ArmingState.TRIGGERED)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.ALARM_RESTORE:<EOL><INDENT>if self.arming_state != ArmingState.DISARMED:<EOL><INDENT>return self._update_arming_state(ArmingState.ARMED)<EOL><DEDENT><DEDENT>elif event.type == SystemStatusEvent.EventType.ENTRY_DELAY_START:<EOL><INDENT>return self._update_arming_state(ArmingState.ENTRY_DELAY)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.ENTRY_DELAY_END:<EOL><INDENT>pass<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.EXIT_DELAY_START:<EOL><INDENT>return self._update_arming_state(ArmingState.EXIT_DELAY)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.EXIT_DELAY_END:<EOL><INDENT>if self.arming_state == ArmingState.EXIT_DELAY:<EOL><INDENT>return self._update_arming_state(ArmingState.ARMED)<EOL><DEDENT><DEDENT>elif event.type in Alarm.ARM_EVENTS:<EOL><INDENT>return self._update_arming_state(ArmingState.ARMING)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.DISARMED:<EOL><INDENT>return self._update_arming_state(ArmingState.DISARMED)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.ARMING_DELAYED:<EOL><INDENT>pass<EOL><DEDENT>

DISARMED -> ARMED_AWAY -> EXIT_DELAY_START -> EXIT_DELAY_END
 (trip): -> ALARM -> OUTPUT_ON -> ALARM_RESTORE
    (disarm): -> DISARMED -> OUTPUT_OFF
 (disarm): -> DISARMED
 (disarm before EXIT_DELAY_END): -> DISARMED -> EXIT_DELAY_END

TODO(NW): Check ALARM_RESTORE state transition to move back into ARMED_AWAY state


ports = []<EOL>if not os.path.exists(PROC_TCP):<EOL><INDENT>return ports<EOL><DEDENT>with open(PROC_TCP) as fh:<EOL><INDENT>for line in fh:<EOL><INDENT>if '<STR_LIT>' not in line:<EOL><INDENT>continue<EOL><DEDENT>parts = line.lstrip('<STR_LIT:U+0020>').split('<STR_LIT:U+0020>')<EOL>if parts[<NUM_LIT:2>] != '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>local_port = parts[<NUM_LIT:1>].split('<STR_LIT::>')[<NUM_LIT:1>]<EOL>local_port = int('<STR_LIT>' + local_port, base=<NUM_LIT:16>)<EOL>ports.append(local_port)<EOL><DEDENT><DEDENT>return ports<EOL>

Reads listening ports from /proc/net/tcp


idx = self._padding<EOL>while idx < len(self._data):<EOL><INDENT>tobject, hole = self._read_next(idx, len(self._data))<EOL>if tobject is None:<EOL><INDENT>return<EOL><DEDENT>if hole:<EOL><INDENT>idx += hole[<NUM_LIT:1>]  <EOL><DEDENT>idx += tobject.bytes_length + self._padding<EOL>yield tobject, hole<EOL><DEDENT>

An iterator that yields a tuple of (thrift object, hole), where
hole is a tuple of (start, skipped) bytes.


def get_ip_packet(data, client_port, server_port, is_loopback=False):

header = _loopback if is_loopback else _ethernet<EOL>try:<EOL><INDENT>header.unpack(data)<EOL><DEDENT>except Exception as ex:<EOL><INDENT>raise ValueError('<STR_LIT>' % ex)<EOL><DEDENT>tcp_p = getattr(header.data, '<STR_LIT:data>', None)<EOL>if type(tcp_p) != dpkt.tcp.TCP:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if tcp_p.dport == server_port:<EOL><INDENT>if client_port != <NUM_LIT:0> and tcp_p.sport != client_port:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>elif tcp_p.sport == server_port:<EOL><INDENT>if client_port != <NUM_LIT:0> and tcp_p.dport != client_port:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return header.data<EOL>

if client_port is 0 any client_port is good


return self._length<EOL>


return len(self)<EOL>

for ThriftStruct, __len__ means something different so lets
        add this other property to unify the way to refer to bytes


<EOL>if len(data) < cls.MIN_MESSAGE_SIZE:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if protocol is None:<EOL><INDENT>protocol = cls.detect_protocol(data, fallback_protocol)<EOL><DEDENT>trans = TTransport.TMemoryBuffer(data)<EOL>proto = protocol(trans)<EOL>header = None<EOL>if finagle_thrift:<EOL><INDENT>try:<EOL><INDENT>header = ThriftStruct.read(<EOL>proto,<EOL>max_fields,<EOL>max_list_size,<EOL>max_map_size,<EOL>max_set_size,<EOL>read_values)<EOL><DEDENT>except:<EOL><INDENT>trans = TTransport.TMemoryBuffer(data)<EOL>proto = protocol(trans)<EOL><DEDENT><DEDENT>method, mtype, seqid = proto.readMessageBegin()<EOL>mtype = cls.message_type_to_str(mtype)<EOL>if len(method) == <NUM_LIT:0> or method.isspace() or method.startswith('<STR_LIT:U+0020>'):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if len(method) > cls.MAX_METHOD_LENGTH:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>valid = range(<NUM_LIT>, <NUM_LIT>)<EOL>if any(ord(char) not in valid for char in method):<EOL><INDENT>raise ValueError('<STR_LIT>' % method)<EOL><DEDENT>args = ThriftStruct.read(<EOL>proto,<EOL>max_fields,<EOL>max_list_size,<EOL>max_map_size,<EOL>max_set_size,<EOL>read_values)<EOL>proto.readMessageEnd()<EOL>msglen = trans._buffer.tell()<EOL>return cls(method, mtype, seqid, args, header, msglen), msglen<EOL>

tries to deserialize a message, might fail if data is missing


@classmethod<EOL><INDENT>def detect_protocol(cls, data, default=None):<DEDENT>

if cls.is_compact_protocol(data):<EOL><INDENT>return TCompactProtocol<EOL><DEDENT>elif cls.is_binary_protocol(data):<EOL><INDENT>return TBinaryProtocol<EOL><DEDENT>elif cls.is_json_protocol(data):<EOL><INDENT>return TJSONProtocol<EOL><DEDENT>if default is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return default<EOL>

TODO: support fbthrift, finagle-thrift, finagle-mux, CORBA


return self._length<EOL>

how many bytes have been through the stream


size = <NUM_LIT:0><EOL>popped = []<EOL>with self._lock_packets:<EOL><INDENT>while size < nbytes:<EOL><INDENT>try:<EOL><INDENT>packet = self._packets.pop(<NUM_LIT:0>)<EOL>size += len(packet.data.data)<EOL>self._remaining -= len(packet.data.data)<EOL>popped.append(packet)<EOL><DEDENT>except IndexError:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return popped<EOL>

pops packets with _at least_ nbytes of payload


last_timestamp = <NUM_LIT:0><EOL>data = []<EOL>for packet in self.pop(nbytes):<EOL><INDENT>last_timestamp = packet.timestamp<EOL>data.append(packet.data.data)<EOL><DEDENT>return '<STR_LIT>'.join(data), last_timestamp<EOL>

similar to pop, but returns payload + last timestamp


data_len = len(ip_packet.data.data)<EOL>seq_id = ip_packet.data.seq<EOL>if data_len == <NUM_LIT:0>:<EOL><INDENT>self._next_seq_id = seq_id<EOL>return False<EOL><DEDENT>if self._next_seq_id != -<NUM_LIT:1> and seq_id != self._next_seq_id:<EOL><INDENT>return False<EOL><DEDENT>self._next_seq_id = seq_id + data_len<EOL>with self._lock_packets:<EOL><INDENT>self._length += len(ip_packet.data.data)<EOL>self._remaining += len(ip_packet.data.data)<EOL>self._packets.append(ip_packet)<EOL><DEDENT>return True<EOL>


while True:<EOL><INDENT>try:<EOL><INDENT>timestamp, ip_p = self._queue.popleft()<EOL>src_ip = get_ip(ip_p, ip_p.src)<EOL>dst_ip = get_ip(ip_p, ip_p.dst)<EOL>src = intern('<STR_LIT>' % (src_ip, ip_p.data.sport))<EOL>dst = intern('<STR_LIT>' % (dst_ip, ip_p.data.dport))<EOL>key = intern('<STR_LIT>' % (src, dst))<EOL>stream = self._streams.get(key)<EOL>if stream is None:<EOL><INDENT>stream = Stream(src, dst)<EOL>self._streams[key] = stream<EOL><DEDENT>setattr(ip_p, '<STR_LIT>', timestamp)<EOL>pushed = stream.push(ip_p)<EOL>if not pushed:<EOL><INDENT>continue<EOL><DEDENT>for handler in self._handlers:<EOL><INDENT>try:<EOL><INDENT>handler(stream)<EOL><DEDENT>except Exception as ex:<EOL><INDENT>print('<STR_LIT>' % ex)<EOL><DEDENT><DEDENT><DEDENT>except Exception:<EOL><INDENT>time.sleep(<NUM_LIT>)<EOL><DEDENT><DEDENT>


def __init__(self, iface, port, stream_handler=None, offline=None, ip=None):

super(Sniffer, self).__init__()<EOL>self.setDaemon(True)<EOL>self._iface = iface<EOL>self._port = port<EOL>self._offline = offline<EOL>self._ip = ip if ip else []<EOL>self._queue = deque()  <EOL>self._dispatcher = Dispatcher(self._queue)<EOL>self._dispatcher.add_handler(stream_handler)<EOL>self._wants_stop = False<EOL>self.start()<EOL>

A Sniffer that merges packets into a stream

        Params:
            ``iface``           The interface in which to listen
            ``port``            The TCP port that we care about
            ``stream_handler``  The callback for each stream
            ``offline``         Path to a pcap file
            ``ip``              A list of IPs that we care about


def __call__(self, timestamp, src, dst, msg):

if msg.type == '<STR_LIT>':<EOL><INDENT>replies = self._replies[dst][src][msg.method]<EOL>if len(replies) > <NUM_LIT:0>:<EOL><INDENT>reply_timestamp, reply = replies.popleft()<EOL>self._print_pair(<EOL>timestamp, msg, reply_timestamp, reply, src, dst)<EOL><DEDENT>else:<EOL><INDENT>self._requests[src][dst][msg.method].append(<EOL>(timestamp, msg))<EOL><DEDENT><DEDENT>elif msg.type == '<STR_LIT>':<EOL><INDENT>requests = self._requests[dst][src][msg.method]<EOL>if len(requests) > <NUM_LIT:0>:<EOL><INDENT>request_timestamp, request = requests.popleft()<EOL>self._print_pair(<EOL>request_timestamp, request, timestamp, msg,<EOL>dst, src)<EOL><DEDENT>else:<EOL><INDENT>self._replies[src][dst][msg.method].append(<EOL>(timestamp, msg))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print_msg(timestamp, src, dst, msg, self._format_opts,<EOL>output=self._output)<EOL><DEDENT>return True<EOL>

We need to match up each (request, reply) pair. Presumably,
pcap _shouldn't_ deliver packets out of order, but
things could get mixed up somewhere withing the
TCP stream being reassembled and the StreamHandler
thread. So, we don't assume that a 'reply' implies
the corresponding 'call' has been seen.

It could also be that we started sniffing after
the 'call' message... but there's no easy way to tell
(given we don't keep the startup time around...)


if msg.type == '<STR_LIT>':<EOL><INDENT>self._requests[src][dst][msg.method][msg.seqid] = (timestamp, msg)<EOL><DEDENT>elif msg.type == '<STR_LIT>':<EOL><INDENT>calls = self._requests[dst][src][msg.method]<EOL>if msg.seqid in calls:<EOL><INDENT>request_timestamp, request = calls.pop(msg.seqid)<EOL>latency = timestamp - request_timestamp<EOL>self._latencies_by_method[msg.method].append(latency)<EOL>self._seen += <NUM_LIT:1><EOL>self._output.write('<STR_LIT>' % (<EOL>self._seen, self._expected))<EOL>self._output.flush()<EOL><DEDENT><DEDENT>if self._seen < self._expected:<EOL><INDENT>return True  <EOL><DEDENT>self.report()<EOL>unmatched = <NUM_LIT:0><EOL>for src, dst in self._requests.items():<EOL><INDENT>for method, calls in dst.items():<EOL><INDENT>unmatched += len(calls)<EOL><DEDENT><DEDENT>if unmatched > <NUM_LIT:0>:<EOL><INDENT>self._output.write('<STR_LIT>' % unmatched)<EOL><DEDENT>return False<EOL>

Slightly simplified logic wrt what PairedPrinter has:
we assume 'call' messages will be seen before their
corresponding 'reply'.


self._output.write('<STR_LIT:\r>')<EOL>sort_by = '<STR_LIT>'<EOL>results = {}<EOL>for key, latencies in self._latencies_by_method.items():<EOL><INDENT>result = {}<EOL>result['<STR_LIT:count>'] = len(latencies)<EOL>result['<STR_LIT>'] = sum(latencies) / len(latencies)<EOL>result['<STR_LIT>'] = min(latencies)<EOL>result['<STR_LIT>'] = max(latencies)<EOL>latencies = sorted(latencies)<EOL>result['<STR_LIT>'] = percentile(latencies, <NUM_LIT>)<EOL>result['<STR_LIT>'] = percentile(latencies, <NUM_LIT>)<EOL>result['<STR_LIT>'] = percentile(latencies, <NUM_LIT>)<EOL>result['<STR_LIT>'] = percentile(latencies, <NUM_LIT>)<EOL>results[key] = result<EOL><DEDENT>headers = ['<STR_LIT>', '<STR_LIT:count>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>data = []<EOL>results = sorted(results.items(), key=lambda it: it[<NUM_LIT:1>][sort_by], reverse=True)<EOL>def row(key, res):<EOL><INDENT>data = [key] + [res[header] for header in headers[<NUM_LIT:1>:]]<EOL>return tuple(data)<EOL><DEDENT>data = [row(key, result) for key, result in results]<EOL>self._output.write('<STR_LIT>' % tabulate(data, headers=headers))<EOL>self._output.flush()<EOL>


return (isinstance(other, self.__class__)<EOL>and<EOL>len(self.fields) == len(other.fields)<EOL>and<EOL>all(a.is_isomorphic_to(b) for a, b in zip(self.fields,<EOL>other.fields)))<EOL>

Returns true if all fields of other struct are isomorphic to this
struct's fields


return isinstance(other, self.__class__) and self.fields == other.fields<EOL>

we ignore the length, it might not be set


return len(self._fields)<EOL>


return (isinstance(other, self.__class__)<EOL>and self.field_type == other.field_type<EOL>and self.field_id == other.field_id)<EOL>

Returns true if other field's meta data (everything except value)
is same as this one


@classmethod<EOL><INDENT>def of_structs(cls, a, b):<DEDENT>

t_diff = ThriftDiff(a, b)<EOL>t_diff._do_diff()<EOL>return t_diff<EOL>

Diff two thrift structs and return the result as a ThriftDiff instance


@classmethod<EOL><INDENT>def of_messages(cls, msg_a, msg_b):<DEDENT>

ok_to_diff, reason = cls.can_diff(msg_a, msg_b)<EOL>if not ok_to_diff:<EOL><INDENT>raise ValueError(reason)<EOL><DEDENT>return [cls.of_structs(x.value, y.value)<EOL>for x, y in zip(msg_a.args, msg_b.args)<EOL>if x.field_type == '<STR_LIT>']<EOL>

Diff two thrift messages by comparing their args, raises exceptions if
for some reason the messages can't be diffed. Only args of type 'struct'
are compared.

Returns a list of ThriftDiff results - one for each struct arg


if msg_a.method != msg_b.method:<EOL><INDENT>return False, '<STR_LIT>'<EOL><DEDENT>if len(msg_a.args) != len(msg_b.args)or not msg_a.args.is_isomorphic_to(msg_b.args):<EOL><INDENT>return False, '<STR_LIT>'<EOL><DEDENT>return True, None<EOL>

Check if two thrift messages are diff ready.

Returns a tuple of (boolean, reason_string), i.e. (False, reason_string)
if the messages can not be diffed along with the reason and
(True, None) for the opposite case


return self._common_fields<EOL>

List of isomorphically equivalent field pairs which may or may not have
same value


return self._fields_only_in_a<EOL>

List of fields exclusive to first struct


return self._fields_only_in_b<EOL>

List of fields exclusive to second struct


return self._fields_with_same_value<EOL>

List of isomorphically equivalent fields for which value is also equal
Note: this doesn't return a list of 'pairs'


return self._fields_with_different_value<EOL>

List of isomorphically equivalent field pairs for which value is NOT
equal


<EOL>domain = "<STR_LIT>"<EOL>save_url = urljoin(domain, "<STR_LIT>")<EOL>headers = {<EOL>'<STR_LIT>': user_agent,<EOL>"<STR_LIT:host>": "<STR_LIT>",<EOL>}<EOL>logger.debug("<STR_LIT>".format(domain + "<STR_LIT:/>"))<EOL>get_kwargs = dict(<EOL>timeout=<NUM_LIT>,<EOL>allow_redirects=True,<EOL>headers=headers,<EOL>)<EOL>if proxies:<EOL><INDENT>get_kwargs['<STR_LIT>'] = proxies<EOL><DEDENT>response = requests.get(domain + "<STR_LIT:/>", **get_kwargs)<EOL>response.raise_for_status()<EOL>html = str(response.content)<EOL>try:<EOL><INDENT>unique_id = html.split('<STR_LIT>', <NUM_LIT:1>)[<NUM_LIT:1>].split('<STR_LIT>', <NUM_LIT:1>)[<NUM_LIT:1>].split('<STR_LIT:">', <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>logger.debug("<STR_LIT>".format(unique_id))<EOL><DEDENT>except IndexError:<EOL><INDENT>logger.warn("<STR_LIT>")<EOL>unique_id = None<EOL><DEDENT>data = {<EOL>"<STR_LIT:url>": target_url,<EOL>"<STR_LIT>": <NUM_LIT:1>,<EOL>}<EOL>if unique_id:<EOL><INDENT>data.update({"<STR_LIT>": unique_id})<EOL><DEDENT>post_kwargs = dict(<EOL>timeout=<NUM_LIT>,<EOL>allow_redirects=True,<EOL>headers=headers,<EOL>data=data<EOL>)<EOL>if proxies:<EOL><INDENT>post_kwargs['<STR_LIT>'] = proxies<EOL><DEDENT>logger.debug("<STR_LIT>".format(save_url))<EOL>response = requests.post(save_url, **post_kwargs)<EOL>response.raise_for_status()<EOL>if '<STR_LIT>' in response.headers:<EOL><INDENT>memento = str(response.headers['<STR_LIT>']).split('<STR_LIT>')[<NUM_LIT:1>]<EOL>logger.debug("<STR_LIT>".format(memento))<EOL>return memento<EOL><DEDENT>if '<STR_LIT>' in response.headers:<EOL><INDENT>memento = response.headers['<STR_LIT>']<EOL>logger.debug("<STR_LIT>".format(memento))<EOL>return memento<EOL><DEDENT>logger.debug("<STR_LIT>")<EOL>for i, r in enumerate(response.history):<EOL><INDENT>logger.debug("<STR_LIT>".format(i))<EOL>logger.debug(r.headers)<EOL>if '<STR_LIT>' in r.headers:<EOL><INDENT>memento = r.headers['<STR_LIT>']<EOL>logger.debug("<STR_LIT>".format(i+<NUM_LIT:1>, memento))<EOL>return memento<EOL><DEDENT><DEDENT>logger.error("<STR_LIT>")<EOL>logger.error("<STR_LIT>".format(response.status_code))<EOL>logger.error(response.headers)<EOL>logger.error(response.text)<EOL>raise Exception("<STR_LIT>")<EOL>

Archives the provided URL using archive.is

Returns the URL where the capture is stored.


@click.command()<EOL>@click.argument("<STR_LIT:url>")<EOL>@click.option("<STR_LIT>", "<STR_LIT>", help="<STR_LIT>")<EOL>def cli(url, user_agent):

kwargs = {}<EOL>if user_agent:<EOL><INDENT>kwargs['<STR_LIT>'] = user_agent<EOL><DEDENT>archive_url = capture(url, **kwargs)<EOL>click.echo(archive_url)<EOL>

Archives the provided URL using archive.is.


client_id = os.environ.get('<STR_LIT>')<EOL>client_secret = os.environ.get('<STR_LIT>')<EOL>if client_id is None or client_secret is None:<EOL><INDENT>click.echo('<STR_LIT>')<EOL>return<EOL><DEDENT>client = ImgurClient(client_id, client_secret)<EOL>click.echo('<STR_LIT>'.format(click.format_filename(gif)))<EOL>response = client.upload_from_path(gif)<EOL>click.echo('<STR_LIT>'.format(response['<STR_LIT>']))<EOL>


with open(os.path.join(*paths), '<STR_LIT:r>') as f:<EOL><INDENT>return f.read()<EOL><DEDENT>

Build a file path from *paths* and return the contents.


def _unwrap_stream(uri, timeout, scanner, requests_session):

original_uri = uri<EOL>seen_uris = set()<EOL>deadline = time.time() + timeout<EOL>while time.time() < deadline:<EOL><INDENT>if uri in seen_uris:<EOL><INDENT>logger.info(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', uri)<EOL>return None<EOL><DEDENT>else:<EOL><INDENT>seen_uris.add(uri)<EOL><DEDENT>logger.debug('<STR_LIT>', uri)<EOL>try:<EOL><INDENT>scan_timeout = deadline - time.time()<EOL>if scan_timeout < <NUM_LIT:0>:<EOL><INDENT>logger.info(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', uri, timeout)<EOL>return None<EOL><DEDENT>scan_result = scanner.scan(uri, timeout=scan_timeout)<EOL><DEDENT>except exceptions.ScannerError as exc:<EOL><INDENT>logger.debug('<STR_LIT>', uri, exc)<EOL>scan_result = None<EOL><DEDENT>if scan_result is not None and not (<EOL>scan_result.mime.startswith('<STR_LIT>') or<EOL>scan_result.mime.startswith('<STR_LIT>')):<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>', scan_result.mime, uri)<EOL>return uri<EOL><DEDENT>download_timeout = deadline - time.time()<EOL>if download_timeout < <NUM_LIT:0>:<EOL><INDENT>logger.info(<EOL>'<STR_LIT>',<EOL>uri, timeout)<EOL>return None<EOL><DEDENT>content = http.download(<EOL>requests_session, uri, timeout=download_timeout)<EOL>if content is None:<EOL><INDENT>logger.info(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', original_uri, uri)<EOL>return None<EOL><DEDENT>uris = playlists.parse(content)<EOL>if not uris:<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>',<EOL>uri)<EOL>return uri<EOL><DEDENT>logger.debug(<EOL>'<STR_LIT>', uri, uris[<NUM_LIT:0>])<EOL>uri = uris[<NUM_LIT:0>]<EOL><DEDENT>

Get a stream URI from a playlist URI, ``uri``.
Unwraps nested playlists until something that's not a playlist is found or
the ``timeout`` is reached.


def mylogger(name=None, filename=None, indent_offset=<NUM_LIT:7>, level=_logging.DEBUG, stream_level=_logging.WARN, file_level=_logging.INFO):

if name is not None:<EOL><INDENT>logger = _logging.getLogger(name)<EOL><DEDENT>else:<EOL><INDENT>logger = _logging.getLogger()<EOL><DEDENT>logger.setLevel(level)<EOL>fmtr         = IndentFormatter(indent_offset=indent_offset)<EOL>fmtr_msgonly = IndentFormatter('<STR_LIT>')<EOL>ch = _logging.StreamHandler()<EOL>ch.setLevel(stream_level)<EOL>ch.setFormatter(fmtr_msgonly)<EOL>logger.addHandler(ch)<EOL>if filename is not None:<EOL><INDENT>debugh = _logging.FileHandler(filename='<STR_LIT>'.format(filename), mode='<STR_LIT:w>')<EOL>debugh.setLevel(_logging.DEBUG)<EOL>debugh.setFormatter(fmtr_msgonly)<EOL>logger.addHandler(debugh)<EOL>fh = _logging.FileHandler(filename='<STR_LIT>'.format(filename), mode='<STR_LIT:w>')<EOL>fh.setLevel(file_level)<EOL>fh.setFormatter(fmtr)<EOL>logger.addHandler(fh)<EOL><DEDENT>return logger<EOL>

Sets up logging to *filename*.debug.log, *filename*.log, and the terminal. *indent_offset* attempts to line up the lowest indent level to 0. Custom levels:

* *level*: Parent logging level.
* *stream_level*: Logging level for console stream.
* *file_level*: Logging level for general file log.


expon = _np.int(_np.floor(_np.log10(_np.abs(x))))<EOL>mant = x/_np.power(<NUM_LIT:10>, expon)<EOL>return (mant, expon)<EOL>

Finds the mantissa and exponent of a number :math:`x` such that :math:`x = m 10^e`.

Parameters
----------

x : float
    Number :math:`x` such that :math:`x = m 10^e`.

Returns
-------

mantissa : float
    Number :math:`m` such that :math:`x = m 10^e`.
exponent : float
    Number :math:`e` such that :math:`x = m 10^e`.


def linspacestep(start, stop, step=<NUM_LIT:1>):

<EOL>numsteps = _np.int((stop-start)/step)<EOL>return _np.linspace(start, start+step*numsteps, numsteps+<NUM_LIT:1>)<EOL>

Create a vector of values over an interval with a specified step size.

Parameters
----------

start : float
    The beginning of the interval.
stop : float
    The end of the interval.
step : float
    The step size.

Returns
-------
vector : :class:`numpy.ndarray`
    The vector of values.


return _np.exp(-(x-mu)**<NUM_LIT:2>/(<NUM_LIT:2>*sigma**<NUM_LIT:2>)) / (_np.sqrt(<NUM_LIT:2>*_np.pi) * sigma)<EOL>

Gaussian function of the form :math:`\\frac{1}{\\sqrt{2 \\pi}\\sigma} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}`.

.. versionadded:: 1.5

Parameters
----------
x : float
    Function variable :math:`x`.
mu : float
    Mean of the Gaussian function.
sigma : float
    Standard deviation of the Gaussian function.


<EOL>dela = array[<NUM_LIT:1>] - array[<NUM_LIT:0>]<EOL>new_arr = _np.array([array[<NUM_LIT:0>] - dela / <NUM_LIT:2>])<EOL>delb = array[-<NUM_LIT:1>] - array[-<NUM_LIT:2>]<EOL>array = _np.append(array, array[-<NUM_LIT:1>] + delb)<EOL>for i, val in enumerate(array):<EOL><INDENT>try:<EOL><INDENT>avg = (array[i] + array[i + <NUM_LIT:1>]) / <NUM_LIT:2><EOL>new_arr = _np.append(new_arr, avg)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return new_arr<EOL>

Generate a new array with numbers interpolated between the numbers of the input array. Extrapolates elements to the left and right sides to get the exterior border as well.

Parameters
----------

array : :class:`numpy.ndarray`
    The original array.

Returns
-------

array : :class:`numpy.ndarray`
    The interpolated/extrapolated array.


return [key for key in obj.keys()]<EOL>

Returns an array of strings of the keys like Python 2 used to do.

.. versionadded:: 1.4

Parameters
----------

obj : object
    Object to get keys from.

Returns
-------

keys : list
    List of keys.


if key in f.keys():<EOL><INDENT>val = f[key].value<EOL>if default is None:<EOL><INDENT>return val<EOL><DEDENT>else:<EOL><INDENT>if _np.shape(val) == _np.shape(default):<EOL><INDENT>return val<EOL><DEDENT><DEDENT><DEDENT>return default<EOL>

Gets an array from datasets.

.. versionadded:: 1.4


<EOL>verbose = kwargs.pop('<STR_LIT>', False)<EOL>popt, pcov = _spopt.curve_fit(*args, **kwargs)<EOL>func = args[<NUM_LIT:0>]<EOL>x    = args[<NUM_LIT:1>]<EOL>y    = args[<NUM_LIT:2>]<EOL>ddof = len(popt)<EOL>try:<EOL><INDENT>sigma = kwargs['<STR_LIT>']<EOL>if sigma is None:<EOL><INDENT>sigma = _np.ones(len(y))<EOL><DEDENT>y_expect = func(x, *popt)<EOL>chisq_red = _chisquare(y, y_expect, sigma, ddof, verbose=verbose)<EOL>pcov = pcov / chisq_red<EOL>return popt, pcov, chisq_red<EOL><DEDENT>except ValueError:<EOL><INDENT>print('<STR_LIT:hello>')<EOL><DEDENT>

Use the reduced chi square to unscale :mod:`scipy`'s scaled :func:`scipy.optimize.curve_fit`. *\*args* and *\*\*kwargs* are passed through to :func:`scipy.optimize.curve_fit`. The tuple *popt, pcov, chisq_red* is returned, where *popt* is the optimal values for the parameters, *pcov* is the estimated covariance of *popt*, and *chisq_red* is the reduced chi square. See http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.curve_fit.html.