Instruction:
Can you generate a brief explanation for the following Python 3 code
def _insert_operations(self,
                           operations: Sequence[ops.Operation],
                           insertion_indices: Sequence[int]) -> None:
        """Inserts operations at the specified moments. Appends new moments if
        necessary.

        Args:
            operations: The operations to insert.
            insertion_indices: Where to insert them, i.e. operations[i] is
                inserted into moments[insertion_indices[i].

        Raises:
            ValueError: operations and insert_indices have different lengths.

        NB: It's on the caller to ensure that the operations won't conflict
        with operations already in the moment or even each other.
        """
        if len(operations) != len(insertion_indices):
            raise ValueError('operations and insertion_indices must have the'
                             'same length.')
        self._moments += [
            ops.Moment() for _ in range(1 + max(insertion_indices) - len(self))
        ]
        moment_to_ops = defaultdict(list
                                    )  # type: Dict[int, List[ops.Operation]]
        for op_index, moment_index in enumerate(insertion_indices):
            moment_to_ops[moment_index].append(operations[op_index])
        for moment_index, new_ops in moment_to_ops.items():
            self._moments[moment_index] = ops.Moment(
                self._moments[moment_index].operations + tuple(new_ops))

Response: Inserts operations at the specified moments. Appends new moments if necessary.


Instruction:
Explain what the following Python 3 code does
def insert_at_frontier(self,
                           operations: ops.OP_TREE,
                           start: int,
                           frontier: Dict[ops.Qid, int] = None
                           ) -> Dict[ops.Qid, int]:
        """Inserts operations inline at frontier.

        Args:
            operations: the operations to insert
            start: the moment at which to start inserting the operations
            frontier: frontier[q] is the earliest moment in which an operation
                acting on qubit q can be placed.
        """
        if frontier is None:
            frontier = defaultdict(lambda: 0)
        operations = tuple(ops.flatten_op_tree(operations))
        if not operations:
            return frontier
        qubits = set(q for op in operations for q in op.qubits)
        if any(frontier[q] > start for q in qubits):
            raise ValueError('The frontier for qubits on which the operations'
                             'to insert act cannot be after start.')

        next_moments = self.next_moments_operating_on(qubits, start)

        insertion_indices, _ = self._pick_inserted_ops_moment_indices(
            operations, start, frontier)

        self._push_frontier(frontier, next_moments)

        self._insert_operations(operations, insertion_indices)

        return frontier

Response: Inserts operations inline at frontier.


Instruction:
Create a Python 3 function for
removing several operations from a circuit.

Response:
def batch_remove(self,
                     removals: Iterable[Tuple[int, ops.Operation]]) -> None:
        """Removes several operations from a circuit.

        Args:
            removals: A sequence of (moment_index, operation) tuples indicating
                operations to delete from the moments that are present. All
                listed operations must actually be present or the edit will
                fail (without making any changes to the circuit).

        ValueError:
            One of the operations to delete wasn't present to start with.

        IndexError:
            Deleted from a moment that doesn't exist.
        """
        copy = self.copy()
        for i, op in removals:
            if op not in copy._moments[i].operations:
                raise ValueError(
                    "Can't remove {} @ {} because it doesn't exist.".format(
                        op, i))
            copy._moments[i] = ops.Moment(
                old_op
                for old_op in copy._moments[i].operations
                if op != old_op)
        self._device.validate_circuit(copy)
        self._moments = copy._moments


Instruction:
Implement a Python 3 function for
inserting operations into empty spaces in existing moments.

Response:
def batch_insert_into(self,
                          insert_intos: Iterable[Tuple[int, ops.Operation]]
                          ) -> None:
        """Inserts operations into empty spaces in existing moments.

        If any of the insertions fails (due to colliding with an existing
        operation), this method fails without making any changes to the circuit.

        Args:
            insert_intos: A sequence of (moment_index, new_operation)
                pairs indicating a moment to add a new operation into.

        ValueError:
            One of the insertions collided with an existing operation.

        IndexError:
            Inserted into a moment index that doesn't exist.
        """
        copy = self.copy()
        for i, op in insert_intos:
            copy._moments[i] = copy._moments[i].with_operation(op)
        self._device.validate_circuit(copy)
        self._moments = copy._moments


Instruction:
How would you code a function in Python 3 to
apply a batched insert operation to the circuit.

Response:
def batch_insert(self,
                     insertions: Iterable[Tuple[int, ops.OP_TREE]]) -> None:
        """Applies a batched insert operation to the circuit.

        Transparently handles the fact that earlier insertions may shift
        the index that later insertions should occur at. For example, if you
        insert an operation at index 2 and at index 4, but the insert at index 2
        causes a new moment to be created, then the insert at "4" will actually
        occur at index 5 to account for the shift from the new moment.

        All insertions are done with the strategy 'EARLIEST'.

        When multiple inserts occur at the same index, the gates from the later
        inserts end up before the gates from the earlier inserts (exactly as if
        you'd called list.insert several times with the same index: the later
        inserts shift the earliest inserts forward).

        Args:
            insertions: A sequence of (insert_index, operations) pairs
                indicating operations to add into the circuit at specific
                places.
        """
        # Work on a copy in case validation fails halfway through.
        copy = self.copy()
        shift = 0
        # Note: python `sorted` is guaranteed to be stable. This matters.
        insertions = sorted(insertions, key=lambda e: e[0])
        groups = _group_until_different(insertions,
                                        key=lambda e: e[0],
                                        value=lambda e: e[1])
        for i, group in groups:
            insert_index = i + shift
            next_index = copy.insert(insert_index,
                                     reversed(group),
                                     InsertStrategy.EARLIEST)
            if next_index > insert_index:
                shift += next_index - insert_index
        self._moments = copy._moments


Instruction:
Can you generate the documentation for the following Python 3 function
def append(
            self,
            moment_or_operation_tree: Union[ops.Moment, ops.OP_TREE],
            strategy: InsertStrategy = InsertStrategy.EARLIEST):
        """Appends operations onto the end of the circuit.

        Moments within the operation tree are appended intact.

        Args:
            moment_or_operation_tree: The moment or operation tree to append.
            strategy: How to pick/create the moment to put operations into.
        """
        self.insert(len(self._moments), moment_or_operation_tree, strategy)

Response: Appends operations onto the end of the circuit.


Instruction:
Can you create a Python 3 function that
clears operations that are touching given qubits at given moments.

Response:
def clear_operations_touching(self,
                                  qubits: Iterable[ops.Qid],
                                  moment_indices: Iterable[int]):
        """Clears operations that are touching given qubits at given moments.

        Args:
            qubits: The qubits to check for operations on.
            moment_indices: The indices of moments to check for operations
                within.
        """
        qubits = frozenset(qubits)
        for k in moment_indices:
            if 0 <= k < len(self._moments):
                self._moments[k] = self._moments[k].without_operations_touching(
                    qubits)


Instruction:
Can you write a function in Python 3 where it
returns the set of all qubits acted upon by Operations in this circuit.

Response:
def all_qubits(self) -> FrozenSet[ops.Qid]:
        """Returns the qubits acted upon by Operations in this circuit."""
        return frozenset(q for m in self._moments for q in m.qubits)


Instruction:
Can you write a function in Python 3 where it
iterates over the operations applied by this circuit.

Response:
def all_operations(self) -> Iterator[ops.Operation]:
        """Iterates over the operations applied by this circuit.

        Operations from earlier moments will be iterated over first. Operations
        within a moment are iterated in the order they were given to the
        moment's constructor.
        """
        return (op for moment in self for op in moment.operations)


Instruction:
Write a Python 3 function for
converting the circuit into a unitary matrix if possible.

Response:
def _unitary_(self) -> Union[np.ndarray, NotImplementedType]:
        """Converts the circuit into a unitary matrix, if possible.

        If the circuit contains any non-terminal measurements, the conversion
        into a unitary matrix fails (i.e. returns NotImplemented). Terminal
        measurements are ignored when computing the unitary matrix. The unitary
        matrix is the product of the unitary matrix of all operations in the
        circuit (after expanding them to apply to the whole system).
        """
        if not self._has_unitary_():
            return NotImplemented
        return self.to_unitary_matrix(ignore_terminal_measurements=True)


Instruction:
Write a Python 3 script to
convert the given state to a unitary matrix.

Response:
def to_unitary_matrix(
            self,
            qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
            qubits_that_should_be_present: Iterable[ops.Qid] = (),
            ignore_terminal_measurements: bool = True,
            dtype: Type[np.number] = np.complex128) -> np.ndarray:
        """Converts the circuit into a unitary matrix, if possible.

        Args:
            qubit_order: Determines how qubits are ordered when passing matrices
                into np.kron.
            qubits_that_should_be_present: Qubits that may or may not appear
                in operations within the circuit, but that should be included
                regardless when generating the matrix.
            ignore_terminal_measurements: When set, measurements at the end of
                the circuit are ignored instead of causing the method to
                fail.
            dtype: The numpy dtype for the returned unitary. Defaults to
                np.complex128. Specifying np.complex64 will run faster at the
                cost of precision. `dtype` must be a complex np.dtype, unless
                all operations in the circuit have unitary matrices with
                exclusively real coefficients (e.g. an H + TOFFOLI circuit).

        Returns:
            A (possibly gigantic) 2d numpy array corresponding to a matrix
            equivalent to the circuit's effect on a quantum state.

        Raises:
            ValueError: The circuit contains measurement gates that are not
                ignored.
            TypeError: The circuit contains gates that don't have a known
                unitary matrix, e.g. gates parameterized by a Symbol.
        """

        if not ignore_terminal_measurements and any(
                protocols.is_measurement(op)
                for op in self.all_operations()):
            raise ValueError('Circuit contains a measurement.')

        if not self.are_all_measurements_terminal():
            raise ValueError('Circuit contains a non-terminal measurement.')

        qs = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
            self.all_qubits().union(qubits_that_should_be_present))
        n = len(qs)

        state = np.eye(1 << n, dtype=np.complex128)
        state.shape = (2,) * (2 * n)

        result = _apply_unitary_circuit(self, state, qs, dtype)
        return result.reshape((1 << n, 1 << n))


Instruction:
Can you create a Python 3 function that
returns a TextDiagramDrawer instance with the circuit drawn into it.

Response:
def to_text_diagram_drawer(
            self,
            *,
            use_unicode_characters: bool = True,
            qubit_namer: Optional[Callable[[ops.Qid], str]] = None,
            transpose: bool = False,
            precision: Optional[int] = 3,
            qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
            get_circuit_diagram_info:
                Optional[Callable[[ops.Operation,
                                   protocols.CircuitDiagramInfoArgs],
                                  protocols.CircuitDiagramInfo]]=None
    ) -> TextDiagramDrawer:
        """Returns a TextDiagramDrawer with the circuit drawn into it.

        Args:
            use_unicode_characters: Determines if unicode characters are
                allowed (as opposed to ascii-only diagrams).
            qubit_namer: Names qubits in diagram. Defaults to str.
            transpose: Arranges qubit wires vertically instead of horizontally.
            precision: Number of digits to use when representing numbers.
            qubit_order: Determines how qubits are ordered in the diagram.
            get_circuit_diagram_info: Gets circuit diagram info. Defaults to
                protocol with fallback.

        Returns:
            The TextDiagramDrawer instance.
        """
        qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
            self.all_qubits())
        qubit_map = {qubits[i]: i for i in range(len(qubits))}

        if qubit_namer is None:
            qubit_namer = lambda q: str(q) + ('' if transpose else ': ')
        diagram = TextDiagramDrawer()
        for q, i in qubit_map.items():
            diagram.write(0, i, qubit_namer(q))

        moment_groups = []  # type: List[Tuple[int, int]]
        for moment in self._moments:
            _draw_moment_in_diagram(moment,
                                    use_unicode_characters,
                                    qubit_map,
                                    diagram,
                                    precision,
                                    moment_groups,
                                    get_circuit_diagram_info)

        w = diagram.width()
        for i in qubit_map.values():
            diagram.horizontal_line(i, 0, w)

        if moment_groups:
            _draw_moment_groups_in_diagram(moment_groups,
                                           use_unicode_characters,
                                           diagram)

        if transpose:
            diagram = diagram.transpose()

        return diagram


Instruction:
Write a Python 3 function that can
return a QASM object equivalent to the circuit.

Response:
def _to_qasm_output(
            self,
            header: Optional[str] = None,
            precision: int = 10,
            qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
    ) -> QasmOutput:
        """Returns a QASM object equivalent to the circuit.

        Args:
            header: A multi-line string that is placed in a comment at the top
                of the QASM. Defaults to a cirq version specifier.
            precision: Number of digits to use when representing numbers.
            qubit_order: Determines how qubits are ordered in the QASM
                register.
        """
        if header is None:
            header = 'Generated from Cirq v{}'.format(
                cirq._version.__version__)
        qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
            self.all_qubits())
        return QasmOutput(operations=self.all_operations(),
                          qubits=qubits,
                          header=header,
                          precision=precision,
                          version='2.0')


Instruction:
Can you implement a function in Python 3 that
returns the QASM equivalent to the circuit.

Response:
def to_qasm(self,
                header: Optional[str] = None,
                precision: int = 10,
                qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
                ) -> str:
        """Returns QASM equivalent to the circuit.

        Args:
            header: A multi-line string that is placed in a comment at the top
                of the QASM. Defaults to a cirq version specifier.
            precision: Number of digits to use when representing numbers.
            qubit_order: Determines how qubits are ordered in the QASM
                register.
        """
        return str(self._to_qasm_output(header, precision, qubit_order))


Instruction:
Write a Python 3 function for
saving a QASM file equivalent to the circuit.

Response:
def save_qasm(self,
                  file_path: Union[str, bytes, int],
                  header: Optional[str] = None,
                  precision: int = 10,
                  qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
                  ) -> None:
        """Save a QASM file equivalent to the circuit.

        Args:
            file_path: The location of the file where the qasm will be written.
            header: A multi-line string that is placed in a comment at the top
                of the QASM. Defaults to a cirq version specifier.
            precision: Number of digits to use when representing numbers.
            qubit_order: Determines how qubits are ordered in the QASM
                register.
        """
        self._to_qasm_output(header, precision, qubit_order).save(file_path)


Instruction:
Can you tell what is the following Python 3 function doing
def qasm(val: Any,
         *,
         args: Optional[QasmArgs] = None,
         qubits: Optional[Iterable['cirq.Qid']] = None,
         default: TDefault = RaiseTypeErrorIfNotProvided
         ) -> Union[str, TDefault]:
    """Returns QASM code for the given value, if possible.

    Different values require different sets of arguments. The general rule of
    thumb is that circuits don't need any, operations need a `QasmArgs`, and
    gates need both a `QasmArgs` and `qubits`.

    Args:
        val: The value to turn into QASM code.
        args: A `QasmArgs` object to pass into the value's `_qasm_` method.
            This is for needed for objects that only have a local idea of what's
            going on, e.g. a `cirq.Operation` in a bigger `cirq.Circuit`
            involving qubits that the operation wouldn't otherwise know about.
        qubits: A list of qubits that the value is being applied to. This is
            needed for `cirq.Gate` values, which otherwise wouldn't know what
            qubits to talk about.
        default: A default result to use if the value doesn't have a
            `_qasm_` method or that method returns `NotImplemented` or
            `None`. If not specified, undecomposable values cause a `TypeError`.

    Returns:
        The result of `val._qasm_(...)`, if `val` has a `_qasm_`
        method and it didn't return `NotImplemented` or `None`. Otherwise
        `default` is returned, if it was specified. Otherwise an error is
        raised.

    TypeError:
        `val` didn't have a `_qasm_` method (or that method returned
        `NotImplemented` or `None`) and `default` wasn't set.
    """
    method = getattr(val, '_qasm_', None)
    result = NotImplemented
    if method is not None:
        kwargs = {}  # type: Dict[str, Any]
        if args is not None:
            kwargs['args'] = args
        if qubits is not None:
            kwargs['qubits'] = tuple(qubits)
        result = method(**kwargs)
    if result is not None and result is not NotImplemented:
        return result

    if default is not RaiseTypeErrorIfNotProvided:
        return default
    if method is None:
        raise TypeError("object of type '{}' "
                        "has no _qasm_ method.".format(type(val)))
    raise TypeError("object of type '{}' does have a _qasm_ method, "
                    "but it returned NotImplemented or None.".format(type(val)))

Response: Returns the QASM code for the given value.


Instruction:
Make a summary of the following Python 3 code
def format_field(self, value: Any, spec: str) -> str:
        from cirq import ops  # HACK: avoids cyclic dependency.
        if isinstance(value, (float, int)):
            if isinstance(value, float):
                value = round(value, self.precision)
            if spec == 'half_turns':
                value = 'pi*{}'.format(value) if value != 0 else '0'
                spec = ''
        elif isinstance(value, ops.Qid):
            value = self.qubit_id_map[value]
        elif isinstance(value, str) and spec == 'meas':
            value = self.meas_key_id_map[value]
            spec = ''
        return super().format_field(value, spec)

Response: Method of string. Formatter that specifies the output of format_field.


Instruction:
Can you write a function in Python 3 where it
generates the oracle of the given input_qubits and outputs the result.

Response:
def make_oracle(input_qubits,
                output_qubit,
                secret_factor_bits,
                secret_bias_bit):
    """Gates implementing the function f(a) = a·factors + bias (mod 2)."""

    if secret_bias_bit:
        yield cirq.X(output_qubit)

    for qubit, bit in zip(input_qubits, secret_factor_bits):
        if bit:
            yield cirq.CNOT(qubit, output_qubit)


Instruction:
Can you generate the documentation for the following Python 3 function
def make_bernstein_vazirani_circuit(input_qubits, output_qubit, oracle):

    c = cirq.Circuit()

    # Initialize qubits.
    c.append([
        cirq.X(output_qubit),
        cirq.H(output_qubit),
        cirq.H.on_each(*input_qubits),
    ])

    # Query oracle.
    c.append(oracle)

    # Measure in X basis.
    c.append([
        cirq.H.on_each(*input_qubits),
        cirq.measure(*input_qubits, key='result')
    ])

    return c

Response: Creates a Bernstein Vazirani circuit.


Instruction:
How would you code a function in Python 3 to
return the big - endian integers specified by groups of bits.

Response:
def _tuple_of_big_endian_int(bit_groups: Tuple[np.ndarray, ...]
                             ) -> Tuple[int, ...]:
    """Returns the big-endian integers specified by groups of bits.

    Args:
        bit_groups: Groups of descending bits, each specifying a big endian
            integer with the 1s bit at the end.

    Returns:
        A tuple containing the integer for each group.
    """
    return tuple(_big_endian_int(bits) for bits in bit_groups)


Instruction:
Make a summary of the following Python 3 code
def _big_endian_int(bits: np.ndarray) -> int:
    result = 0
    for e in bits:
        result <<= 1
        if e:
            result |= 1
    return result

Response: Returns the big - endian integer specified by the given bits.


Instruction:
Here you have a function in Python 3, explain what it does
def make_oracle(q0, q1, secret_function):

    # coverage: ignore
    if secret_function[0]:
        yield [CNOT(q0, q1), X(q1)]

    if secret_function[1]:
        yield CNOT(q0, q1)

Response: Yields the oracle of the secret function f.


Instruction:
Given the following Python 3 function, write the documentation
def chip_as_adjacency_list(device: 'cirq.google.XmonDevice',
                           ) -> Dict[GridQubit, List[GridQubit]]:
    """Gives adjacency list representation of a chip.

    The adjacency list is constructed in order of above, left_of, below and
    right_of consecutively.

    Args:
        device: Chip to be converted.

    Returns:
        Map from nodes to list of qubits which represent all the neighbours of
        given qubit.
    """
    c_set = set(device.qubits)
    c_adj = {} # type: Dict[GridQubit, List[GridQubit]]
    for n in device.qubits:
        c_adj[n] = []
        for m in [above(n), left_of(n), below(n), right_of(n)]:
            if m in c_set:
                c_adj[n].append(m)
    return c_adj

Response: Converts a chip into an adjacency list representation of a chip.


Instruction:
Here you have a function in Python 3, explain what it does
def hhl_circuit(A, C, t, register_size, *input_prep_gates):

    ancilla = cirq.GridQubit(0, 0)
    # to store eigenvalues of the matrix
    register = [cirq.GridQubit(i+1, 0) for i in range(register_size)]
    # to store input and output vectors
    memory = cirq.GridQubit(register_size+1, 0)

    c = cirq.Circuit()
    hs = HamiltonianSimulation(A, t)
    pe = PhaseEstimation(register_size+1, hs)
    c.append([gate(memory) for gate in input_prep_gates])
    c.append([
        pe(*(register + [memory])),
        EigenRotation(register_size+1, C, t)(*(register+[ancilla])),
        pe(*(register + [memory]))**-1,
        cirq.measure(ancilla)
    ])

    # Pauli observable display
    c.append([
        cirq.pauli_string_expectation(
            cirq.PauliString({ancilla: cirq.Z}),
            key='a'
        ),
        cirq.pauli_string_expectation(
            cirq.PauliString({memory: cirq.X}),
            key='x'
        ),
        cirq.pauli_string_expectation(
            cirq.PauliString({memory: cirq.Y}),
            key='y'
        ),
        cirq.pauli_string_expectation(
            cirq.PauliString({memory: cirq.Z}),
            key='z'
        ),
    ])

    return c

Response: Constructs the HHL circuit.


Instruction:
Given the following Python 3 function, write the documentation
def main():

    # Eigendecomposition:
    #   (4.537, [-0.971555, -0.0578339+0.229643j])
    #   (0.349, [-0.236813, 0.237270-0.942137j])
    # |b> = (0.64510-0.47848j, 0.35490-0.47848j)
    # |x> = (-0.0662724-0.214548j, 0.784392-0.578192j)
    A = np.array([[4.30213466-6.01593490e-08j,
                   0.23531802+9.34386156e-01j],
                  [0.23531882-9.34388383e-01j,
                   0.58386534+6.01593489e-08j]])
    t = 0.358166*math.pi
    register_size = 4
    input_prep_gates = [cirq.Rx(1.276359), cirq.Rz(1.276359)]
    expected = (0.144130, 0.413217, -0.899154)

    # Set C to be the smallest eigenvalue that can be represented by the
    # circuit.
    C = 2*math.pi / (2**register_size * t)

    # Simulate circuit
    print("Expected observable outputs:")
    print("X =", expected[0])
    print("Y =", expected[1])
    print("Z =", expected[2])
    print("Actual: ")
    simulate(hhl_circuit(A, C, t, register_size, *input_prep_gates))

Response:
Simulates HHL with matrix input and outputs Pauli observables of the
    resulting qubit state x.


Instruction:
Write a Python 3 script for
running the sweeps for the given set of time - related objects.

Response:
def _run(
        self,
        circuit: circuits.Circuit,
        param_resolver: study.ParamResolver,
        repetitions: int,
    ) -> Dict[str, List[np.ndarray]]:
        """See definition in `cirq.SimulatesSamples`."""

        circuit = protocols.resolve_parameters(circuit, param_resolver)
        _verify_xmon_circuit(circuit)

        # Delegate to appropriate method based on contents.
        if circuit.are_all_measurements_terminal():
            return self._run_sweep_sample(circuit, repetitions)
        else:
            return self._run_sweep_repeat(circuit, repetitions)


Instruction:
Make a summary of the following Python 3 code
def _base_iterator(
        self,
        circuit: circuits.Circuit,
        qubit_order: ops.QubitOrderOrList,
        initial_state: Union[int, np.ndarray],
        perform_measurements: bool=True,
    ) -> Iterator['XmonStepResult']:
        """See definition in `cirq.SimulatesIntermediateState`.

        If the initial state is an int, the state is set to the computational
        basis state corresponding to this state. Otherwise  if the initial
        state is a np.ndarray it is the full initial state. In this case it
        must be the correct size, be normalized (an L2 norm of 1), and
        be safely castable to an appropriate dtype for the simulator.
        """
        qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
            circuit.all_qubits())
        qubit_map = {q: i for i, q in enumerate(reversed(qubits))}
        if isinstance(initial_state, np.ndarray):
            initial_state = initial_state.astype(dtype=np.complex64,
                                                 casting='safe')

        with xmon_stepper.Stepper(
            num_qubits=len(qubits),
            num_prefix_qubits=self.options.num_prefix_qubits,
            initial_state=initial_state,
            min_qubits_before_shard=self.options.min_qubits_before_shard,
            use_processes=self.options.use_processes
        ) as stepper:
            if len(circuit) == 0:
                yield XmonStepResult(stepper, qubit_map, {})
            for moment in circuit:
                measurements = collections.defaultdict(
                    list)  # type: Dict[str, List[bool]]
                phase_map = {}  # type: Dict[Tuple[int, ...], float]
                for op in moment.operations:
                    gate = cast(ops.GateOperation, op).gate
                    if isinstance(gate, ops.ZPowGate):
                        index = qubit_map[op.qubits[0]]
                        phase_map[(index,)] = cast(float, gate.exponent)
                    elif isinstance(gate, ops.CZPowGate):
                        index0 = qubit_map[op.qubits[0]]
                        index1 = qubit_map[op.qubits[1]]
                        phase_map[(index0, index1)] = cast(float,
                                                           gate.exponent)
                    elif isinstance(gate, ops.XPowGate):
                        index = qubit_map[op.qubits[0]]
                        stepper.simulate_w(
                            index=index,
                            half_turns=gate.exponent,
                            axis_half_turns=0)
                    elif isinstance(gate, ops.YPowGate):
                        index = qubit_map[op.qubits[0]]
                        stepper.simulate_w(
                            index=index,
                            half_turns=gate.exponent,
                            axis_half_turns=0.5)
                    elif isinstance(gate, ops.PhasedXPowGate):
                        index = qubit_map[op.qubits[0]]
                        stepper.simulate_w(
                            index=index,
                            half_turns=gate.exponent,
                            axis_half_turns=gate.phase_exponent)
                    elif isinstance(gate, ops.MeasurementGate):
                        if perform_measurements:
                            invert_mask = (
                                gate.invert_mask or len(op.qubits) * (False,))
                            for qubit, invert in zip(op.qubits, invert_mask):
                                index = qubit_map[qubit]
                                result = stepper.simulate_measurement(index)
                                if invert:
                                    result = not result
                                key = protocols.measurement_key(gate)
                                measurements[key].append(result)
                    else:
                        # coverage: ignore
                        raise TypeError('{!r} is not supported by the '
                                        'xmon simulator.'.format(gate))
                stepper.simulate_phases(phase_map)
                yield XmonStepResult(stepper, qubit_map, measurements)

Response: A base iterator for the internal state of the system.


Instruction:
Can you write a function in Python 3 where it
updates the state of the simulator to the given state.

Response:
def set_state_vector(self, state: Union[int, np.ndarray]):
        """Updates the state of the simulator to the given new state.

        Args:
            state: If this is an int, then this is the state to reset
            the stepper to, expressed as an integer of the computational basis.
            Integer to bitwise indices is little endian. Otherwise if this is
            a np.ndarray this must be the correct size and have dtype of
            np.complex64.

        Raises:
            ValueError if the state is incorrectly sized or not of the correct
            dtype.
        """
        self._stepper.reset_state(state)


Instruction:
Write a Python 3 script for
sampling from the wave function at this point in the computation.

Response:
def sample(self, qubits: List[ops.Qid], repetitions: int=1):
        """Samples from the wave function at this point in the computation.

        Note that this does not collapse the wave function.

        Returns:
            Measurement results with True corresponding to the `|1>` state.
            The outer list is for repetitions, and the inner corresponds to
            measurements ordered by the supplied qubits.
        """
        return self._stepper.sample_measurements(
            indices=[self.qubit_map[q] for q in qubits],
            repetitions=repetitions)


Instruction:
Write a Python 3 function for
adding possibly stateful noise to a series of moments.

Response:
def noisy_moments(self, moments: 'Iterable[cirq.Moment]',
                      system_qubits: Sequence['cirq.Qid']
                     ) -> Sequence['cirq.OP_TREE']:
        """Adds possibly stateful noise to a series of moments.

        Args:
            moments: The moments to add noise to.
            system_qubits: A list of all qubits in the system.

        Returns:
            A sequence of OP_TREEs, with the k'th tree corresponding to the
            noisy operations for the k'th moment.
        """
        if not hasattr(self.noisy_moment, '_not_overridden'):
            result = []
            for moment in moments:
                result.append(self.noisy_moment(moment, system_qubits))
            return result

        if not hasattr(self.noisy_operation, '_not_overridden'):
            result = []
            for moment in moments:
                result.append([self.noisy_operation(op) for op in moment])
            return result

        assert False, 'Should be unreachable.'


Instruction:
Can you implement a function in Python 3 that
adds noise to the operations from a moment.

Response:
def noisy_moment(self, moment: 'cirq.Moment',
                     system_qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
        """Adds noise to the operations from a moment.

        Args:
            moment: The moment to add noise to.
            system_qubits: A list of all qubits in the system.

        Returns:
            An OP_TREE corresponding to the noisy operations for the moment.
        """
        if not hasattr(self.noisy_moments, '_not_overridden'):
            return self.noisy_moments([moment], system_qubits)

        if not hasattr(self.noisy_operation, '_not_overridden'):
            return [self.noisy_operation(op) for op in moment]

        assert False, 'Should be unreachable.'


Instruction:
Write a Python 3 function that can
add noise to an individual operation.

Response:
def noisy_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE':
        """Adds noise to an individual operation.

        Args:
            operation: The operation to make noisy.

        Returns:
            An OP_TREE corresponding to the noisy operations implementing the
            noisy version of the given operation.
        """
        if not hasattr(self.noisy_moments, '_not_overridden'):
            return self.noisy_moments([ops.Moment([operation])],
                                      operation.qubits)

        if not hasattr(self.noisy_moment, '_not_overridden'):
            return self.noisy_moment(ops.Moment([operation]), operation.qubits)

        assert False, 'Should be unreachable.'


Instruction:
Write a Python 3 function that can
return the measurement key for the given value.

Response:
def measurement_key(
        val: Any,
        default: Any = RaiseTypeErrorIfNotProvided):
    """Get the measurement key for the given value.

    Args:
        val: The value which has the measurement key..
        default: Determines the fallback behavior when `val` doesn't have
            a measurement key. If `default` is not set, a TypeError is raised.
            If default is set to a value, that value is returned if the value
            does not have `_measurement_key_`.

    Returns:
        If `val` has a `_measurement_key_` method and its result is not
        `NotImplemented`, that result is returned. Otherwise, if a default
        value was specified, the default value is returned.

    Raises:
        TypeError: `val` doesn't have a _measurement_key_ method (or that method
            returned NotImplemented) and also no default value was specified.
    """
    getter = getattr(val, '_measurement_key_', None)
    result = NotImplemented if getter is None else getter()
    if result is not NotImplemented:
        return result

    if default is not RaiseTypeErrorIfNotProvided:
        return default

    if getter is None:
        raise TypeError(
                "object of type '{}' has no _measurement_key_ method."
                    .format(type(val)))

    raise TypeError("object of type '{}' does have a _measurement_key_ method, "
                    "but it returned NotImplemented.".format(type(val)))


Instruction:
Implement a Python 3 function for
generating a Google Random Circuits v2 for the given set of qubits.

Response:
def generate_supremacy_circuit_google_v2(qubits: Iterable[devices.GridQubit],
                                         cz_depth: int,
                                         seed: int) -> circuits.Circuit:
    """
    Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2.
    See also https://arxiv.org/abs/1807.10749

    Args:
        qubits: qubit grid in which to generate the circuit.
        cz_depth: number of layers with CZ gates.
        seed: seed for the random instance.

    Returns:
        A circuit corresponding to instance
        inst_{n_rows}x{n_cols}_{cz_depth+1}_{seed}

    The mapping of qubits is cirq.GridQubit(j,k) -> q[j*n_cols+k]
    (as in the QASM mapping)
    """

    non_diagonal_gates = [ops.pauli_gates.X**(1/2), ops.pauli_gates.Y**(1/2)]
    rand_gen = random.Random(seed).random

    circuit = circuits.Circuit()

    # Add an initial moment of Hadamards
    circuit.append(ops.common_gates.H(qubit) for qubit in qubits)

    layer_index = 0
    if cz_depth:
        layer_index = _add_cz_layer(layer_index, circuit)
        # In the first moment, add T gates when possible
        for qubit in qubits:
            if not circuit.operation_at(qubit, 1):
                circuit.append(ops.common_gates.T(qubit),
                               strategy=InsertStrategy.EARLIEST)

    for moment_index in range(2, cz_depth+1):
        layer_index = _add_cz_layer(layer_index, circuit)
        # Add single qubit gates in the same moment
        for qubit in qubits:
            if not circuit.operation_at(qubit, moment_index):
                last_op = circuit.operation_at(qubit, moment_index-1)
                if last_op:
                    gate = cast(ops.GateOperation, last_op).gate
                    # Add a random non diagonal gate after a CZ
                    if gate == ops.CZ:
                        circuit.append(_choice(rand_gen,
                                               non_diagonal_gates).on(qubit),
                                       strategy=InsertStrategy.EARLIEST)
                    # Add a T gate after a non diagonal gate
                    elif not gate == ops.T:
                        circuit.append(ops.common_gates.T(qubit),
                                       strategy=InsertStrategy.EARLIEST)

    # Add a final moment of Hadamards
    circuit.append([ops.common_gates.H(qubit) for qubit in qubits],
                   strategy=InsertStrategy.NEW_THEN_INLINE)

    return circuit


Instruction:
Can you implement a function in Python 3 that
generates a 2D supremacy circuit for a random instance of the class.

Response:
def generate_supremacy_circuit_google_v2_grid(n_rows: int, n_cols: int,
                                              cz_depth: int, seed: int
                                              ) -> circuits.Circuit:
    """
    Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2.
    See also https://arxiv.org/abs/1807.10749

    Args:
        n_rows: number of rows of a 2D lattice.
        n_cols: number of columns.
        cz_depth: number of layers with CZ gates.
        seed: seed for the random instance.

    Returns:
        A circuit corresponding to instance
        inst_{n_rows}x{n_cols}_{cz_depth+1}_{seed}

    The mapping of qubits is cirq.GridQubit(j,k) -> q[j*n_cols+k]
    (as in the QASM mapping)
    """
    qubits = [devices.GridQubit(i, j) for i in range(n_rows)
              for j in range(n_cols)]
    return generate_supremacy_circuit_google_v2(qubits, cz_depth, seed)


Instruction:
Can you generate the documentation for the following Python 3 function
def generate_supremacy_circuit_google_v2_bristlecone(n_rows: int,
                                                     cz_depth: int, seed: int
                                                     ) -> circuits.Circuit:
    """
    Generates Google Random Circuits v2 in Bristlecone.
    See also https://arxiv.org/abs/1807.10749

    Args:
        n_rows: number of rows in a Bristlecone lattice.
          Note that we do not include single qubit corners.
        cz_depth: number of layers with CZ gates.
        seed: seed for the random instance.

    Returns:
        A circuit with given size and seed.
    """
    def get_qubits(n_rows):
        def count_neighbors(qubits, qubit):
            """Counts the qubits that the given qubit can interact with."""
            possibles = [
                devices.GridQubit(qubit.row + 1, qubit.col),
                devices.GridQubit(qubit.row - 1, qubit.col),
                devices.GridQubit(qubit.row, qubit.col + 1),
                devices.GridQubit(qubit.row, qubit.col - 1),
                ]
            return len(list(e for e in possibles if e in qubits))

        assert 1 <= n_rows <= 11
        max_row = n_rows - 1
        dev = google.Bristlecone
        # we need a consistent order of qubits
        qubits = list(dev.qubits)
        qubits.sort()
        qubits = [q for q in qubits
                      if  q.row <= max_row and  q.row + q.col < n_rows + 6
                      and q.row - q.col < n_rows - 5]
        qubits = [q for q in qubits if count_neighbors(qubits, q) > 1]
        return qubits

    qubits = get_qubits(n_rows)
    return generate_supremacy_circuit_google_v2(qubits, cz_depth, seed)

Response: Generates a supremacy circuit for a given number of rows in a Bristlecone lattice.


Instruction:
Given the following Python 3 function, write the documentation
def _choice(rand_gen: Callable[[], float], sequence: Sequence[T]) -> T:
    return sequence[int(rand_gen() * len(sequence))]

Response: Choose a random element from a non - empty sequence.


Instruction:
How would you implement a function in Python 3 that
creates a CZ layer for the given set of qubits.

Response:
def _make_cz_layer(qubits: Iterable[devices.GridQubit], layer_index: int
                   ) -> Iterable[ops.Operation]:
    """
    Each layer index corresponds to a shift/transpose of this CZ pattern:

        ●───●   ●   ●   ●───●   ●   ● . . .

        ●   ●   ●───●   ●   ●   ●───● . . .

        ●───●   ●   ●   ●───●   ●   ● . . .

        ●   ●   ●───●   ●   ●   ●───● . . .

        ●───●   ●   ●   ●───●   ●   ● . . .

        ●   ●   ●───●   ●   ●   ●───● . . .
        .   .   .   .   .   .   .   . .
        .   .   .   .   .   .   .   .   .
        .   .   .   .   .   .   .   .     .

    Labelled edges, showing the exact index-to-CZs mapping (mod 8):

         ●─0─●─2─●─4─●─6─●─0─. . .
        3│  7│  3│  7│  3│
         ●─4─●─6─●─0─●─2─●─4─. . .
        1│  5│  1│  5│  1│
         ●─0─●─2─●─4─●─6─●─0─. . .
        7│  3│  7│  3│  7│
         ●─4─●─6─●─0─●─2─●─4─. . .
        5│  1│  5│  1│  5│
         ●─0─●─2─●─4─●─6─●─0─. . .
        3│  7│  3│  7│  3│
         .   .   .   .   .   .
         .   .   .   .   .     .
         .   .   .   .   .       .

    Note that, for small devices, some layers will be empty because the layer
    only contains edges not present on the device.
    """

    # map to an internal layer index to match the cycle order of public circuits
    layer_index_map = [0, 3, 2, 1, 4, 7, 6, 5]
    internal_layer_index = layer_index_map[layer_index % 8]

    dir_row = internal_layer_index % 2
    dir_col = 1 - dir_row
    shift = (internal_layer_index >> 1) % 4

    for q in qubits:
        q2 = devices.GridQubit(q.row + dir_row, q.col + dir_col)
        if q2 not in qubits:
            continue  # This edge isn't on the device.
        if (q.row * (2 - dir_row) + q.col * (2 - dir_col)) % 4 != shift:
            continue  # No CZ along this edge for this layer.

        yield ops.common_gates.CZ(q, q2)


Instruction:
How would you code a function in Python 3 to
determine the effect of an operation on the given qubits and returns a matrix equivalent to the effect of the operation on the given qubits.

Response:
def _op_to_matrix(self,
                      op: Optional[ops.Operation],
                      qubits: Tuple[ops.Qid, ...]
                      ) -> Optional[np.ndarray]:
        """Determines the effect of an operation on the given qubits.

        If the operation is a 1-qubit operation on one of the given qubits,
        or a 2-qubit operation on both of the given qubits, and also the
        operation has a known matrix, then a matrix is returned. Otherwise None
        is returned.

        Args:
            op: The operation to understand.
            qubits: The qubits we care about. Order determines matrix tensor
                order.

        Returns:
            None, or else a matrix equivalent to the effect of the operation.
        """
        q1, q2 = qubits

        matrix = protocols.unitary(op, None)
        if matrix is None:
            return None

        assert op is not None
        if op.qubits == qubits:
            return matrix
        if op.qubits == (q2, q1):
            return MergeInteractions._flip_kron_order(matrix)
        if op.qubits == (q1,):
            return np.kron(matrix, np.eye(2))
        if op.qubits == (q2,):
            return np.kron(np.eye(2), matrix)

        return None


Instruction:
Can you implement a function in Python 3 that
scans the two qubit operations into a matrix.

Response:
def _scan_two_qubit_ops_into_matrix(
            self,
            circuit: circuits.Circuit,
            index: Optional[int],
            qubits: Tuple[ops.Qid, ...]
    ) -> Tuple[List[ops.Operation], List[int], np.ndarray]:
        """Accumulates operations affecting the given pair of qubits.

        The scan terminates when it hits the end of the circuit, finds an
        operation without a known matrix, or finds an operation that interacts
        the given qubits with other qubits.

        Args:
            circuit: The circuit to scan for operations.
            index: The index to start scanning forward from.
            qubits: The pair of qubits we care about.

        Returns:
            A tuple containing:
                0. The operations.
                1. The moment indices those operations were on.
                2. A matrix equivalent to the effect of the scanned operations.
        """

        product = np.eye(4, dtype=np.complex128)
        all_operations = []
        touched_indices = []

        while index is not None:
            operations = list({circuit.operation_at(q, index) for q in qubits})
            op_data = [
                self._op_to_matrix(op, qubits)
                for op in operations
                if op is not None
            ]

            # Stop at any non-constant or non-local interaction.
            if any(e is None for e in op_data):
                break
            present_ops = [op for op in operations if op]
            present_op_data = cast(List[np.ndarray], op_data)

            for op_mat in present_op_data:
                product = np.dot(op_mat, product)
            all_operations.extend(present_ops)

            touched_indices.append(index)
            index = circuit.next_moment_operating_on(qubits, index + 1)

        return all_operations, touched_indices, product


Instruction:
Explain what the following Python 3 code does
def _flip_kron_order(mat4x4: np.ndarray) -> np.ndarray:
        result = np.array([[0] * 4] * 4, dtype=np.complex128)
        order = [0, 2, 1, 3]
        for i in range(4):
            for j in range(4):
                result[order[i], order[j]] = mat4x4[i, j]
        return result

Response: Given mat4x4 returns M = sum of krons of a_i and b_i.


Instruction:
How would you explain what the following Python 3 function does
def control(controllee: Union['cirq.Gate', op_tree.OP_TREE],
            control_qubits: Sequence['cirq.Qid'] = None,
            default: Any = RaiseTypeErrorIfNotProvided) -> Any:
    """Returns a Controlled version of the given value, if defined.

    Controllees define how to be controlled by defining a method
    controlled_by(self, control_qubits). Note that the method may return
    NotImplemented to indicate a particular controlling can't be done.

    Args:
        controllee: The gate, operation or iterable of operations to control.
        control_qubits: A list of Qids that would control this controllee.
        default: Determines the fallback behavior when `controllee` doesn't
            have a controlling defined. If `default` is not set and the
            fallback occurs, a TypeError is raised instead.

    Returns:
        If `controllee` has a controlled_by method that returns something
        besides NotImplemented, that result is returned. For an OP_TREE,
        transformation is applied at the leaf. Otherwise, if a default value
        was specified, the default value is returned.

    Raises:
        TypeError: `controllee` doesn't have a controlled_by method (or that
            method returned NotImplemented) and no `default` was specified.
    """
    if control_qubits is None:
        control_qubits = []
    controller = getattr(controllee, 'controlled_by', None)
    result = NotImplemented if controller is None else controller(
                                                           *control_qubits)
    if result is not NotImplemented:
        return result

    if isinstance(controllee, collections.Iterable):
        return op_tree.transform_op_tree(
            controllee,
            op_transformation=lambda op: control(op, control_qubits))

    if default is not RaiseTypeErrorIfNotProvided:
        return default

    if controller is None:
        raise TypeError("object of type '{}' has no controlled_by "
                        "method.".format(type(controllee)))
    raise TypeError("object of type '{}' does have a controlled_by method, "
                    "but it returned NotImplemented.".format(type(controllee)))

Response: Returns a new version of the given value if the given controlling is defined.


Instruction:
Write a Python 3 script for
returning the inverse of the given value if defined.

Response:
def inverse(val: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Any:
    """Returns the inverse `val**-1` of the given value, if defined.

    An object can define an inverse by defining a __pow__(self, exponent) method
    that returns something besides NotImplemented when given the exponent -1.
    The inverse of iterables is by default defined to be the iterable's items,
    each inverted, in reverse order.

    Args:
        val: The value (or iterable of invertible values) to invert.
        default: Determines the fallback behavior when `val` doesn't have
            an inverse defined. If `default` is not set, a TypeError is raised.
            If `default` is set to a value, that value is returned.

    Returns:
        If `val` has a __pow__ method that returns something besides
        NotImplemented when given an exponent of -1, that result is returned.
        Otherwise, if `val` is iterable, the result is a tuple with the same
        items as `val` but in reverse order and with each item inverted.
        Otherwise, if a `default` argument was specified, it is returned.

    Raises:
        TypeError: `val` doesn't have a __pow__ method, or that method returned
            NotImplemented when given -1. Furthermore `val` isn't an
            iterable containing invertible items. Also, no `default` argument
            was specified.
    """
    from cirq import ops  # HACK: avoid circular import

    # Check if object defines an inverse via __pow__.
    raiser = getattr(val, '__pow__', None)
    result = NotImplemented if raiser is None else raiser(-1)
    if result is not NotImplemented:
        return result

    # Maybe it's an iterable of invertible items?
    # Note: we avoid str because 'a'[0] == 'a', which creates an infinite loop.
    if (isinstance(val, collections.Iterable) and
            not isinstance(val, (str, ops.Operation))):
        unique_indicator = []  # type: List[Any]
        results = tuple(inverse(e, unique_indicator) for e in val)
        if all(e is not unique_indicator for e in results):
            return results[::-1]

    # Can't invert.
    if default is not RaiseTypeErrorIfNotProvided:
        return default
    raise TypeError(
        "object of type '{}' isn't invertible. "
        "It has no __pow__ method (or the method returned NotImplemented) "
        "and it isn't an iterable of invertible objects.".format(type(val)))


Instruction:
Implement a Python 3 function for
decomposing a two - qubit operation into MS - single - qubit rotation gates.

Response:
def two_qubit_matrix_to_ion_operations(q0: ops.Qid,
                                       q1: ops.Qid,
                                       mat: np.ndarray,
                                       atol: float = 1e-8
                                       ) -> List[ops.Operation]:
    """Decomposes a two-qubit operation into MS/single-qubit rotation gates.

    Args:
        q0: The first qubit being operated on.
        q1: The other qubit being operated on.
        mat: Defines the operation to apply to the pair of qubits.
        tolerance: A limit on the amount of error introduced by the
            construction.

    Returns:
        A list of operations implementing the matrix.
    """
    kak = linalg.kak_decomposition(mat, atol=atol)
    operations = _kak_decomposition_to_operations(q0,
        q1, kak, atol)
    return _cleanup_operations(operations)


Instruction:
Implement a Python 3 function for
yielding an XX interaction framed by the given operation.

Response:
def _parity_interaction(q0: ops.Qid,
                        q1: ops.Qid,
                        rads: float,
                        atol: float,
                        gate: Optional[ops.Gate] = None):
    """Yields an XX interaction framed by the given operation."""

    if abs(rads) < atol:
        return

    if gate is not None:
        g = cast(ops.Gate, gate)
        yield g.on(q0), g.on(q1)

    yield MS(-1 * rads).on(q0, q1)

    if gate is not None:
        g = protocols.inverse(gate)
        yield g.on(q0), g.on(q1)


Instruction:
Can you generate the documentation for the following Python 3 function
def _non_local_part(q0: ops.Qid,
                    q1: ops.Qid,
                    interaction_coefficients: Tuple[float, float, float],
                    atol: float = 1e-8):
    """Yields non-local operation of KAK decomposition."""

    x, y, z = interaction_coefficients

    return [
        _parity_interaction(q0, q1, x, atol),
        _parity_interaction(q0, q1, y, atol, ops.Z ** -0.5),
        _parity_interaction(q0, q1, z, atol, ops.Y ** 0.5)]

Response: Yields non - local part of KAK decomposition.


Instruction:
Write a Python 3 script for
attempting to resolve a Symbol or name or float to its assigned value.

Response:
def value_of(
            self,
            value: Union[sympy.Basic, float, str]
    ) -> Union[sympy.Basic, float]:
        """Attempt to resolve a Symbol or name or float to its assigned value.

        If unable to resolve a sympy.Symbol, returns it unchanged.
        If unable to resolve a name, returns a sympy.Symbol with that name.

        Args:
            value: The sympy.Symbol or name or float to try to resolve into just
                a float.

        Returns:
            The value of the parameter as resolved by this resolver.
        """
        if isinstance(value, str):
            return self.param_dict.get(value, sympy.Symbol(value))
        if isinstance(value, sympy.Basic):
            if sys.version_info.major < 3:
                # coverage: ignore
                # HACK: workaround https://github.com/sympy/sympy/issues/16087
                d = {k.encode(): v for k, v in self.param_dict.items()}
                v = value.subs(d)
            else:
                v = value.subs(self.param_dict)
            return v if v.free_symbols else float(v)
        return value


Instruction:
Given the following Python 3 function, write the documentation
def value_equality(cls: type = None,
                   *,
                   unhashable: bool = False,
                   distinct_child_types: bool = False,
                   manual_cls: bool = False,
                   approximate: bool = False
                  ) -> Union[Callable[[type], type], type]:
    """Implements __eq__/__ne__/__hash__ via a _value_equality_values_ method.

    _value_equality_values_ is a method that the decorated class must implement.

    _value_equality_approximate_values_ is a method that the decorated class
    might implement if special support for approximate equality is required.
    This is only used when approximate argument is set. When approximate
    argument is set and _value_equality_approximate_values_ is not defined,
    _value_equality_values_ values are used for approximate equality.
    For example, this can be used to compare periodic values like angles: the
    angle value can be wrapped with `PeriodicValue`. When returned as part of
    approximate values a special normalization will be done automatically to
    guarantee correctness.

    Note that the type of the decorated value is included as part of the value
    equality values. This is so that completely separate classes with identical
    equality values (e.g. a Point2D and a Vector2D) don't compare as equal.
    Further note that this means that child types of the decorated type will be
    considered equal to each other, though this behavior can be changed via
    the 'distinct_child_types` argument. The type logic is implemented behind
    the scenes by a `_value_equality_values_cls_` method added to the class.

    Args:
        cls: The type to decorate. Automatically passed in by python when using
            the @cirq.value_equality decorator notation on a class.
        unhashable: When set, the __hash__ method will be set to None instead of
            to a hash of the equality class and equality values. Useful for
            mutable types such as dictionaries.
        distinct_child_types: When set, classes that inherit from the decorated
            class will not be considered equal to it. Also, different child
            classes will not be considered equal to each other. Useful for when
            the decorated class is an abstract class or trait that is helping to
            define equality for many conceptually distinct concrete classes.
        manual_cls: When set, the method '_value_equality_values_cls_' must be
            implemented. This allows a new class to compare as equal to another
            existing class that is also using value equality, by having the new
            class return the existing class' type.
            Incompatible with `distinct_child_types`.
        approximate: When set, the decorated class will be enhanced with
            `_approx_eq_` implementation and thus start to support the
            `SupportsApproximateEquality` protocol.
    """

    # If keyword arguments were specified, python invokes the decorator method
    # without a `cls` argument, then passes `cls` into the result.
    if cls is None:
        return lambda deferred_cls: value_equality(deferred_cls,
                                                   unhashable=unhashable,
                                                   manual_cls=manual_cls,
                                                   distinct_child_types=
                                                   distinct_child_types,
                                                   approximate=approximate)

    if distinct_child_types and manual_cls:
        raise ValueError("'distinct_child_types' is "
                         "incompatible with 'manual_cls")

    values_getter = getattr(cls, '_value_equality_values_', None)
    if values_getter is None:
        raise TypeError('The @cirq.value_equality decorator requires a '
                        '_value_equality_values_ method to be defined.')

    if distinct_child_types:
        setattr(cls, '_value_equality_values_cls_', lambda self: type(self))
    elif manual_cls:
        cls_getter = getattr(cls, '_value_equality_values_cls_', None)
        if cls_getter is None:
            raise TypeError('The @cirq.value_equality decorator requires a '
                            '_value_equality_values_cls_ method to be defined '
                            'when "manual_cls" is set.')
    else:
        setattr(cls, '_value_equality_values_cls_', lambda self: cls)
    setattr(cls, '__hash__', None if unhashable else _value_equality_hash)
    setattr(cls, '__eq__', _value_equality_eq)
    setattr(cls, '__ne__', _value_equality_ne)

    if approximate:
        if not hasattr(cls, '_value_equality_approximate_values_'):
            setattr(cls, '_value_equality_approximate_values_', values_getter)
        setattr(cls, '_approx_eq_', _value_equality_approx_eq)

    return cls

Response: Returns a function that can be used to compare two value types of a given class.


Instruction:
Implement a Python 3 function for
returning a set of interesting lines from a GNU unified diff format.

Response:
def diff_to_new_interesting_lines(unified_diff_lines: List[str]
                                  ) -> Dict[int, str]:
    """
    Extracts a set of 'interesting' lines out of a GNU unified diff format.

    Format:
      gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html

      @@ from-line-numbers to-line-numbers @@
        line-from-either-file
        ...
      @@ start,count start,count @@
        line-from-either-file
        ...
      @@ single start,count @@
        line-from-either-file
        ...
    Examples:
      Deleted line (5 is the deleted LOC, 7 is the guessed would-have-been loc
      in the updated file given other changes pushing the line around):
        @@ 5 7,0 @@
         - content-of-line

      Added line:
        @@ 5,0 7 @@
         + content-of-line

      Modified chunk:
        @@ 10,15 11,5 @@
         - removed-line
         + added-line
         ...

    Args:
        unified_diff_lines: Lines of output from git diff.
    Returns:
        A dictionary of "touched lines", with key equal to the line number and
        value equal to the reason the line was touched. Includes added lines
        and lines near changes (including removals).
    """
    interesting_lines = dict()
    for diff_line in unified_diff_lines:
        # Parse the 'new file' range parts of the unified diff.
        if not diff_line.startswith('@@ '):
            continue
        change = diff_line[3:diff_line.index(' @@', 3)]
        new = change.split(' ')[1]
        start = int(new.split(',')[0])
        count = 1 if ',' not in new else int(new.split(',')[1])

        # The lines before and after a deletion should still be covered.
        if count == 0:
            for i in range(start, start + 2):
                interesting_lines[i] = 'is near a removal'
        else:
            for i in range(start, start + count):
                interesting_lines[i] = 'is new or changed'
    return interesting_lines


Instruction:
How would you code a function in Python 3 to
return a list of tuples of indices content and reason - for - including of those uncovered lines in the given file.

Response:
def get_incremental_uncovered_lines(abs_path: str,
                                    base_commit: str,
                                    actual_commit: Optional[str]
                                    ) -> List[Tuple[int, str, str]]:
    """
    Uses git diff and the annotation files created by
    `pytest --cov-report annotate` to find touched but uncovered lines in the
    given file.

    Args:
        abs_path: The path of a file to look for uncovered lines in.
        base_commit: Old state to diff against.
        actual_commit: Current state. Use None to use local uncommitted files.

    Returns:
        A list of the indices, content, and reason-for-including of
        'interesting' uncovered lines. An interesting uncovered line is one
        involved with the diff.
    """
    # Deleted files don't have any lines that need to be covered.
    if not os.path.isfile(abs_path):
        return []

    unified_diff_lines_str = shell_tools.output_of(
        'git',
        'diff',
        '--unified=0',
        base_commit,
        actual_commit,
        '--',
        abs_path)
    unified_diff_lines = [e
                          for e in unified_diff_lines_str.split('\n')
                          if e.strip()]

    touched_lines = diff_to_new_interesting_lines(unified_diff_lines)

    with open(abs_path, 'r') as actual_file:
        ignored_lines = determine_ignored_lines(actual_file.read())

    cover_path = abs_path + ',cover'
    has_cover_file = os.path.isfile(cover_path)
    content_file = cover_path if has_cover_file else abs_path
    with open(content_file, 'r') as annotated_coverage_file:
        return [(i, fix_line_from_coverage_file(line), touched_lines[i])
                for i, line in enumerate(annotated_coverage_file, start=1)
                if i in touched_lines and i not in ignored_lines
                if line_counts_as_uncovered(line, has_cover_file)]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def line_content_counts_as_uncovered_manual(content: str) -> bool:
    # Omit empty lines.
    if not content:
        return False

    # Omit declarations.
    for keyword in ['def', 'class']:
        if content.startswith(keyword) and content.endswith(':'):
            return False

    # TODO: multiline comments, multiline strings, etc, etc.
    return True

Response: Returns True if the line content counts as uncovered in the coverage report.


Instruction:
Write a Python 3 script for
returning True if the line counts as uncovered.

Response:
def line_counts_as_uncovered(line: str,
                             is_from_cover_annotation_file: bool) -> bool:
    """
    Args:
        line: The line of code (including coverage annotation).
        is_from_cover_annotation_file: Whether this line has been annotated.
    Returns:
        Does the line count as uncovered?
    """

    # Ignore this line?
    if is_from_cover_annotation_file:
        # Already covered, or the tool deemed it not relevant for coverage.
        if not line.startswith('! '):
            return False

        content = line[2:]
    else:
        content = line

    # Ignore surrounding whitespace.
    content = content.strip()

    # Ignore end-of-line comments.
    # TODO: avoid # in strings, etc.
    if '#' in content:
        content = content[:content.index('#')].strip()

    # Ignored line pattern?
    if any(re.search(pat, content) for pat in IGNORED_LINE_PATTERNS):
        return False

    return (is_from_cover_annotation_file or
            line_content_counts_as_uncovered_manual(content))


Instruction:
Explain what the following Python 3 code does
def is_applicable_python_file(rel_path: str) -> bool:
    return (rel_path.endswith('.py') and
            not any(re.search(pat, rel_path) for pat in IGNORED_FILE_PATTERNS))

Response: Determines if a file should be included in incremental coverage analysis.


Instruction:
Create a Python 3 function to
calculate the approximate common period of the given list of periods.

Response:
def _approximate_common_period(periods: List[float],
                               approx_denom: int = 60,
                               reject_atol: float = 1e-8) -> Optional[float]:
    """Finds a value that is nearly an integer multiple of multiple periods.

    The returned value should be the smallest non-negative number with this
    property. If `approx_denom` is too small the computation can fail to satisfy
    the `reject_atol` criteria and return `None`. This is actually desirable
    behavior, since otherwise the code would e.g. return a nonsense value when
    asked to compute the common period of `np.e` and `np.pi`.

    Args:
        periods: The result must be an approximate integer multiple of each of
            these.
        approx_denom: Determines how the floating point values are rounded into
            rational values (so that integer methods such as lcm can be used).
            Each floating point value f_k will be rounded to a rational number
            of the form n_k / approx_denom. If you want to recognize rational
            periods of the form i/d then d should divide `approx_denom`.
        reject_atol: If the computed approximate common period is at least this
            far from an integer multiple of any of the given periods, then it
            is discarded and `None` is returned instead.

    Returns:
        The approximate common period, or else `None` if the given
        `approx_denom` wasn't sufficient to approximate the common period to
        within the given `reject_atol`.
    """
    if not periods:
        return None
    if any(e == 0 for e in periods):
        return None
    if len(periods) == 1:
        return abs(periods[0])
    approx_rational_periods = [
        fractions.Fraction(int(np.round(abs(p) * approx_denom)), approx_denom)
        for p in periods
    ]
    common = float(_common_rational_period(approx_rational_periods))

    for p in periods:
        if p != 0 and abs(p * np.round(common / p) - common) > reject_atol:
            return None

    return common


Instruction:
How would you implement a function in Python 3 that
finds the least common integer multiple of some fractions. rational_periods

Response:
def _common_rational_period(rational_periods: List[fractions.Fraction]
                            ) -> fractions.Fraction:
    """Finds the least common integer multiple of some fractions.

    The solution is the smallest positive integer c such that there
    exists integers n_k satisfying p_k * n_k = c for all k.
    """
    assert rational_periods, "no well-defined solution for an empty list"
    common_denom = _lcm(p.denominator for p in rational_periods)
    int_periods = [p.numerator * common_denom // p.denominator
                   for p in rational_periods]
    int_common_period = _lcm(int_periods)
    return fractions.Fraction(int_common_period, common_denom)


Instruction:
Explain what the following Python 3 code does
def fit(self, X):
        X = column_or_1d(X, warn=True)
        _check_numpy_unicode_bug(X)
        self.classes_ = np.unique(X)
        return self

Response: Fit label encoder to a set of target values.


Instruction:
Write a Python 3 script for
fitting label encoder and return encoded labels.

Response:
def fit_transform(self, X, y=None, **fit_params):
        """Fit label encoder and return encoded labels

        Parameters
        ----------
        y : array-like of shape [n_samples]
            Target values.

        Returns
        -------
        y : array-like of shape [n_samples]
        """
        y = column_or_1d(X, warn=True)
        _check_numpy_unicode_bug(X)
        self.classes_, X = np.unique(X, return_inverse=True)
        return X


Instruction:
Create a Python 3 function to
transform labels to normalized encoding.

Response:
def transform(self, y):
        """Transform labels to normalized encoding.

        Parameters
        ----------
        y : array-like of shape [n_samples]
            Target values.

        Returns
        -------
        y : array-like of shape [n_samples]
        """
        check_is_fitted(self, 'classes_')
        y = column_or_1d(y, warn=True)

        classes = np.unique(y)
        _check_numpy_unicode_bug(classes)
        if len(np.intersect1d(classes, self.classes_)) < len(classes):
            diff = np.setdiff1d(classes, self.classes_)
            raise ValueError("y contains new labels: %s" % str(diff))
        return np.searchsorted(self.classes_, y)


Instruction:
Implement a function in Python 3 to
transform labels back to original encoding.

Response:
def inverse_transform(self, y):
        """Transform labels back to original encoding.

        Parameters
        ----------
        y : numpy array of shape [n_samples]
            Target values.

        Returns
        -------
        y : numpy array of shape [n_samples]
        """
        check_is_fitted(self, 'classes_')

        diff = np.setdiff1d(y, np.arange(len(self.classes_)))
        if diff:
            raise ValueError("y contains new labels: %s" % str(diff))
        y = np.asarray(y)
        return self.classes_[y]


Instruction:
Write a Python 3 function that can
transform features per specified math function.

Response:
def transform(self, y):
        """
        Transform features per specified math function.
        :param y:
        :return:
        """
        if self.transform_type == 'log':
            return np.log(y)
        elif self.transform_type == 'exp':
            return np.exp(y)
        elif self.transform_type == 'sqrt':
            return np.sqrt(y)
        elif self.transform_type == 'sin':
            return np.sin(y)
        elif self.transform_type == 'cos':
            return np.cos(y)
        elif self.transform_type == 'tan':
            return np.tan(y)
        elif self.transform_type == 'abs':
             return np.abs(y)


Instruction:
Here you have a function in Python 3, explain what it does
def fit(self, X, y=None, **fit_params):
        if self.transform_type not in self.valid_transforms:
                warnings.warn("Invalid transform type.", stacklevel=2)
        return self

Response: Fit a binary math operator on the data.


Instruction:
Can you create a Python 3 function that
transforms features per specified math function.

Response:
def transform(self, y):
        """
        Transform features per specified math function.
        :param y:
        :return:
        """
        if isinstance(y, pd.DataFrame):
            x = y.ix[:,0]
            y = y.ix[:,1]
        else:
            x = y[:,0]
            y = y[:,1]
        if self.transform_type == 'add':
            return pd.DataFrame(np.add(x, y))
        elif self.transform_type == 'sub':
            return pd.DataFrame(np.subtract(x, y))
        elif self.transform_type == 'mul':
            return pd.DataFrame(np.multiply(x, y))
        elif self.transform_type == 'div':
            return pd.DataFrame(np.divide(x, y))
        elif self.transform_type == 'rem':
            return pd.DataFrame(np.remainder(x, y))
        elif self.transform_type == 'pow':
            return pd.DataFrame(x**y)


Instruction:
How would you explain what the following Python 3 function does
def serialize_tree(tree, feature_names, outfile):

        tree_ = tree.tree_
        feature_name = [feature_names[i] if i != _tree.TREE_UNDEFINED else 'n/a' for i in tree_.feature]

        def traverse(node, depth, outfile):
            if tree_.feature[node] != _tree.TREE_UNDEFINED:
                name = feature_name[node]
                threshold = tree_.threshold[node]

                # Define internal node for serialization
                internal_node = {
                    'type': 'internal',
                    'split': {
                        'type': 'continuous',
                        'featureIndex': feature_names.index(name),
                        'threshold': threshold
                    }
                }

                # Serialize the internal Node
                json.dump(internal_node, outfile)
                outfile.write('\n')

                # Traverse Left
                traverse(tree_.children_left[node], depth + 1, outfile)

                # Traverse Rigiht
                traverse(tree_.children_right[node], depth + 1, outfile)
            else:
                leaf_node = {
                    'type': 'leaf',
                    'values': tree_.value[node].tolist()[0]
                }

                # Serialize the leaf node
                json.dump(leaf_node, outfile)
                outfile.write('\n')

        traverse(0, 1, outfile)

Response: Serialize the tree to a file.


Instruction:
Can you implement a function in Python 3 that
serializes the decision tree to a bundle.

Response:
def serialize_to_bundle(self, transformer, path, model_name, serialize_node=True):
        """
        :type transformer: sklearn.tree.tree.BaseDecisionTree
        :type path: str
        :type model_name: str
        :type serialize_node: bool
        :param transformer:
        :param path:
        :param model_name:
        :return:
        """

        # Define attributes
        attributes = list()
        attributes.append(('num_features', transformer.n_features_))
        if isinstance(transformer, DecisionTreeClassifier):
            attributes.append(('num_classes', int(transformer.n_classes_)))

        inputs = []
        outputs = []
        if serialize_node:
            # define node inputs and outputs
            inputs = [{
                      "name": transformer.input_features,
                      "port": "features"
                    }]

            outputs = [{
                      "name": transformer.prediction_column,
                      "port": "prediction"
                    }]

        self.serialize(transformer, path, model_name, attributes, inputs, outputs, node=serialize_node)

        # Serialize tree.json
        tree_path = "{}/{}.node/tree.json".format(path, model_name)
        if not serialize_node:
            tree_path = "{}/{}/tree.json".format(path, model_name)
        with open(tree_path, 'w') as outfile:
            self.serialize_tree(transformer, transformer.feature_names, outfile)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sent2vec(self, words, transformer):
        sent_vec = np.zeros(transformer.vector_size)
        numw = 0
        for w in words:
            try:
                sent_vec = np.add(sent_vec, transformer.wv[w])
                numw += 1
            except:
                continue
        return sent_vec / np.sqrt(sent_vec.dot(sent_vec))

Response:
Used with sqrt kernel
        Used with sqrt kernel


Instruction:
How would you explain what the following Python 3 function does
def serialize_to_bundle(self, transformer, path, model):

        # Define Node Inputs and Outputs
        inputs = [{
                  "name": transformer.input_features,
                  "port": "features"
                }]

        outputs = list()
        outputs.append({
                  "name": transformer.prediction_column,
                  "port": "prediction"
                })

        outputs.append({
              "name": "raw_prediction",
              "port": "raw_prediction"
             })

        outputs.append({
              "name": "probability",
              "port": "probability"
            })

        # compile tuples of model attributes to serialize
        tree_weights = Vector([1.0 for x in range(0, len(transformer.estimators_))])
        attributes = list()
        attributes.append(('num_features', transformer.n_features_))
        attributes.append(('tree_weights', tree_weights))
        attributes.append(('trees', ["tree{}".format(x) for x in range(0, len(transformer.estimators_))]))
        if isinstance(transformer, RandomForestClassifier):
            attributes.append(('num_classes', transformer.n_classes_)) # TODO: get number of classes from the transformer

        self.serialize(transformer, path, model, attributes, inputs, outputs)

        rf_path = "{}/{}.node".format(path, model)

        estimators = transformer.estimators_

        i = 0
        for estimator in estimators:
            estimator.mlinit(input_features = transformer.input_features, prediction_column = transformer.prediction_column, feature_names=transformer.feature_names)
            model_name = "tree{}".format(i)
            estimator.serialize_to_bundle(rf_path, model_name, serialize_node=False)

            i += 1

Response: This method serializes the model to a sklearn bundle.


Instruction:
Given the following Python 3 function, write the documentation
def get_mleap_model(self, transformer, attributes_to_serialize=None):
        js = {
            'op': transformer.op
        }

        # If the transformer doesn't have any attributes, return just the op name
        if attributes_to_serialize is None:
            return js

        attributes = {}

        for name, value in attributes_to_serialize:
            if isinstance(value, float):
                attributes[name] = {
                    "double": value
                }

            elif isinstance(value, bool) and value in [True, False]:
                attributes[name] = {
                    "boolean": value
                }

            elif isinstance(value, int):
                attributes[name] = {
                    "long": value
                }
            elif isinstance(value, Vector):
                attributes[name] = {
                    "type": "list",
                    "double": value.values
                }
            elif isinstance(value, list) and (isinstance(value[0], np.float64) or isinstance(value[0], np.float32) or isinstance(value[0], float)):
                base = type(value[0])
                attributes[name] = {
                    _type_map[base]: value,
                    "shape": {
                        "dimensions": [{
                            "size": len(value),
                            "name": ""
                        }]
                    },
                    "type": "tensor"
                }
            elif isinstance(value, list) and isinstance(value[0], str):
                attributes[name] = {
                      "type": "list",
                      "string": value
                }

            elif isinstance(value, np.ndarray):
                attributes[name] = {
                    "double":  list(value.flatten()),
                    "shape": {
                        "dimensions": [{
                            "size": list(value.shape),
                            "name": ""
                        }]
                    },
                    "type": "tensor"
                }

            elif isinstance(value, str):
                attributes[name] = {
                    'string': value
                }

            elif isinstance(value, dict):
                shapes = list()
                for shape in value['data_shape']:
                    if shape['shape'] == 'scalar':
                        shapes.append(({"base": "scalar",
                                        "isNullable": False}))
                    elif shape['shape'] == 'tensor':
                        shapes.append(({"base": "tensor",
                                        "isNullable": False,
                                        "tensorShape": {
                                            "dimensions": [{
                                                "size": shape['tensor_shape']['dimensions'][0]['size'],
                                                "name": ""
                                                }]
                                            }
                                        }
                                       ))
                attributes[name] = {
                    'type': 'list',
                    'data_shape': shapes
                }

        js['attributes'] = attributes

        return js

Response: Generates the model. json given a list of attributes which are a tuple comprised of name value.


Instruction:
Explain what the following Python 3 code does
def wait_until(what, times=-1):
    while times:
        logger.info('Waiting times left %d', times)
        try:
            if what() is True:
                return True
        except:
            logger.exception('Wait failed')
        else:
            logger.warning('Trial[%d] failed', times)
        times -= 1
        time.sleep(1)

    return False

Response: Wait until what returns True.


Instruction:
Can you tell what is the following Python 3 function doing
def _init_devices(self):
        if not settings.PDU_CONTROLLER_TYPE:
            if settings.AUTO_DUT:
                return

            for device in settings.GOLDEN_DEVICES:
                port, _ = device
                try:
                    with OpenThreadController(port) as otc:
                        logger.info('Resetting %s', port)
                        otc.reset()
                except:
                    logger.exception('Failed to reset device %s', port)
                    self.history.mark_bad_golden_device(device)

            return

        tries = 3
        pdu_factory = PduControllerFactory()

        while True:
            try:
                pdu = pdu_factory.create_pdu_controller(settings.PDU_CONTROLLER_TYPE)
                pdu.open(**settings.PDU_CONTROLLER_OPEN_PARAMS)
            except EOFError:
                logger.warning('Failed to connect to telnet')
                tries = tries - 1
                if tries:
                    time.sleep(10)
                    continue
                else:
                    logger.error('Fatal error: cannot connect to apc')
                    raise
            else:
                pdu.reboot(**settings.PDU_CONTROLLER_REBOOT_PARAMS)
                pdu.close()
                break

        time.sleep(len(settings.GOLDEN_DEVICES))

Response: Initialize all usb devices.


Instruction:
Write a Python 3 function that can
restart the harness backend service.

Response:
def _init_harness(self):
        """Restart harness backend service.

        Please start the harness controller before running the cases, otherwise, nothing happens
        """
        self._hc = HarnessController(self.result_dir)
        self._hc.stop()
        time.sleep(1)
        self._hc.start()
        time.sleep(2)

        harness_config = ConfigParser.ConfigParser()
        harness_config.read('%s\\Config\\Configuration.ini' % settings.HARNESS_HOME)
        if harness_config.has_option('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate') and \
                harness_config.getboolean('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate'):
            logger.error('BrowserAutoNavigate in Configuration.ini should be False')
            raise FailError('BrowserAutoNavigate in Configuration.ini should be False')
        if settings.MIXED_DEVICE_TYPE:
            if harness_config.has_option('THREAD_HARNESS_CONFIG', 'EnableDeviceSelection') and \
                    not harness_config.getboolean('THREAD_HARNESS_CONFIG', 'EnableDeviceSelection'):
                logger.error('EnableDeviceSelection in Configuration.ini should be True')
                raise FailError('EnableDeviceSelection in Configuration.ini should be True')


Instruction:
Can you generate the documentation for the following Python 3 function
def _init_dut(self):
        if self.auto_dut:
            self.dut = None
            return

        dut_port = settings.DUT_DEVICE[0]
        dut = OpenThreadController(dut_port)
        self.dut = dut

Response:
Initialize the DUT.

        DUT will be restarted. and openthread will started.


Instruction:
Implement a Python 3 function for
setting up the Harness instance.

Response:
def setUp(self):
        """Prepare to run test case.

        Start harness service, init golden devices, reset DUT and open browser.
        """
        if self.__class__ is HarnessCase:
            return

        logger.info('Setting up')
        # clear files
        logger.info('Deleting all .pdf')
        os.system('del /q "%HOMEDRIVE%%HOMEPATH%\\Downloads\\NewPdf_*.pdf"')
        logger.info('Deleting all .xlsx')
        os.system('del /q "%HOMEDRIVE%%HOMEPATH%\\Downloads\\ExcelReport*.xlsx"')
        logger.info('Deleting all .pcapng')
        os.system('del /q "%s\\Captures\\*.pcapng"' % settings.HARNESS_HOME)

        # using temp files to fix excel downloading fail
        logger.info('Empty files in temps')
        os.system('del /q "%s\\Thread_Harness\\temp\\*.*"' % settings.HARNESS_HOME)

        # create directory
        os.system('mkdir %s' % self.result_dir)
        self._init_harness()
        self._init_devices()
        self._init_dut()
        self._init_rf_shield()


Instruction:
How would you explain what the following Python 3 function does
def tearDown(self):
        if self.__class__ is HarnessCase:
            return

        logger.info('Tearing down')
        self._destroy_harness()
        self._destroy_browser()
        self._destroy_dut()
        self._destroy_rf_shield()

Response: Clean up after each case.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _setup_page(self):
        if not self.started:
            self.started = time.time()

        if time.time() - self.started > 5*len(settings.GOLDEN_DEVICES):
            self._browser.refresh()
            return

        # Detect Sniffer
        try:
            dialog = self._browser.find_element_by_id('capture-Setup-modal')
        except:
            logger.exception('Failed to get dialog.')
        else:
            if dialog and dialog.get_attribute('aria-hidden') == 'false':
                times = 100
                while times:
                    status = dialog.find_element_by_class_name('status-notify').text
                    if 'Searching' in status:
                        logger.info('Still detecting..')
                    elif 'Not' in status:
                        logger.warning('Sniffer device not verified!')
                        button = dialog.find_element_by_id('snifferAutoDetectBtn')
                        button.click()
                    elif 'Verified' in status:
                        logger.info('Verified!')
                        button = dialog.find_element_by_id('saveCaptureSettings')
                        button.click()
                        break
                    else:
                        logger.warning('Unexpected sniffer verification status')

                    times = times - 1
                    time.sleep(1)

                if not times:
                    raise Exception('Unable to detect sniffer device')

        time.sleep(1)

        try:
            skip_button = self._browser.find_element_by_id('SkipPrepareDevice')
            if skip_button.is_enabled():
                skip_button.click()
                time.sleep(1)
        except:
            logger.info('Still detecting sniffers')

        try:
            next_button = self._browser.find_element_by_id('nextButton')
        except:
            logger.exception('Failed to finish setup')
            return

        if not next_button.is_enabled():
            logger.info('Harness is still not ready')
            return

        # General Setup
        try:
            if self.child_timeout or self.sed_polling_interval:
                logger.info('finding general Setup button')
                button = self._browser.find_element_by_id('general-Setup')
                button.click()
                time.sleep(2)

                dialog = self._browser.find_element_by_id('general-Setup-modal')
                if dialog.get_attribute('aria-hidden') != 'false':
                    raise Exception('Missing General Setup dialog')

                field = dialog.find_element_by_id('inp_general_child_update_wait_time')
                field.clear()
                if self.child_timeout:
                    field.send_keys(str(self.child_timeout))

                field = dialog.find_element_by_id('inp_general_sed_polling_rate')
                field.clear()
                if self.sed_polling_interval:
                    field.send_keys(str(self.sed_polling_interval))

                button = dialog.find_element_by_id('saveGeneralSettings')
                button.click()
                time.sleep(1)

        except:
            logger.info('general setup exception')
            logger.exception('Failed to do general setup')
            return

        # Finish this page
        next_button.click()
        time.sleep(1)

Response: Do sniffer settings and general setup


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _select_case(self, role, case):
        # select the case
        elem = Select(self._browser.find_element_by_id('select-dut'))
        elem.select_by_value(str(role))
        time.sleep(1)

        checkbox = None
        wait_until(lambda: self._browser.find_elements_by_css_selector('.tree-node .tree-title') and True)
        elems = self._browser.find_elements_by_css_selector('.tree-node .tree-title')
        finder = re.compile(r'.*\b' + case + r'\b')
        finder_dotted = re.compile(r'.*\b' + case.replace(' ', r'\.') + r'\b')
        for elem in elems:
            action_chains = ActionChains(self._browser)
            action_chains.move_to_element(elem)
            action_chains.perform()
            logger.debug(elem.text)
            if finder.match(elem.text) or finder_dotted.match(elem.text):
                parent = elem.find_element_by_xpath('..')
                checkbox = parent.find_element_by_class_name('tree-checkbox')
                break

        if not checkbox:
            time.sleep(5)
            raise Exception('Failed to find the case')

        self._browser.execute_script("$('.overview').css('left', '0')")
        checkbox.click()
        time.sleep(1)

        elem = self._browser.find_element_by_id('runTest')
        elem.click()
        if not wait_until(lambda: self._browser.find_element_by_id('stopTest') and True, 10):
            raise Exception('Failed to start test case')

Response: Select the test case.


Instruction:
Write a Python 3 function that can
collect test result. Generate PDF, excel and pcap file

Response:
def _collect_result(self):
        """Collect test result.

        Generate PDF, excel and pcap file
        """
        # generate pdf
        self._browser.find_element_by_class_name('save-pdf').click()
        time.sleep(1)
        try:
            dialog = self._browser.find_element_by_id('Testinfo')
        except:
            logger.exception('Failed to get test info dialog.')
        else:
            if dialog.get_attribute('aria-hidden') != 'false':
                raise Exception('Test information dialog not ready')

            version = self.auto_dut and settings.DUT_VERSION or self.dut.version
            dialog.find_element_by_id('inp_dut_manufacturer').send_keys(settings.DUT_MANUFACTURER)
            dialog.find_element_by_id('inp_dut_firmware_version').send_keys(version)
            dialog.find_element_by_id('inp_tester_name').send_keys(settings.TESTER_NAME)
            dialog.find_element_by_id('inp_remarks').send_keys(settings.TESTER_REMARKS)
            dialog.find_element_by_id('generatePdf').click()

        time.sleep(1)
        main_window = self._browser.current_window_handle

        # generate excel
        self._browser.find_element_by_class_name('save-excel').click()
        time.sleep(1)
        for window_handle in self._browser.window_handles:
            if window_handle != main_window:
                self._browser.switch_to.window(window_handle)
                self._browser.close()
        self._browser.switch_to.window(main_window)

        # save pcap
        self._browser.find_element_by_class_name('save-wireshark').click()
        time.sleep(1)
        for window_handle in self._browser.window_handles:
            if window_handle != main_window:
                self._browser.switch_to.window(window_handle)
                self._browser.close()
        self._browser.switch_to.window(main_window)

        os.system('copy "%%HOMEPATH%%\\Downloads\\NewPdf_*.pdf" %s\\'
                  % self.result_dir)
        os.system('copy "%%HOMEPATH%%\\Downloads\\ExcelReport_*.xlsx" %s\\'
                  % self.result_dir)
        os.system('copy "%s\\Captures\\*.pcapng" %s\\'
                  % (settings.HARNESS_HOME, self.result_dir))
        os.system('copy "%s\\Thread_Harness\\temp\\*.*" "%s"'
                  % (settings.HARNESS_HOME, self.result_dir))