_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q268100 | bdist_wheel.add_requirements | test | def add_requirements(self, metadata_path):
"""Add additional requirements from setup.cfg to file metadata_path"""
additional = list(self.setupcfg_requirements())
if not additional: return
pkg_info = read_pkg_info(metadata_path)
if 'Provides-Extra' in pkg_info or 'Requires-Dist' i... | python | {
"resource": ""
} |
q268101 | bdist_wheel.egg2dist | test | def egg2dist(self, egginfo_path, distinfo_path):
"""Convert an .egg-info directory into a .dist-info directory"""
def adios(p):
"""Appropriately delete directory, file or link."""
if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
shutil.rmtree(p... | python | {
"resource": ""
} |
q268102 | MessageFactory.text | test | def text(text: str, speak: str = None, input_hint: Union[InputHints, str] = InputHints.accepting_input) -> Activity:
"""
Returns a simple text message.
:Example:
message = MessageFactory.text('Greetings from example message')
await context.send_activity(message)
:param ... | python | {
"resource": ""
} |
q268103 | MessageFactory.suggested_actions | test | def suggested_actions(actions: List[CardAction], text: str = None, speak: str = None,
input_hint: Union[InputHints, str] = InputHints.accepting_input) -> Activity:
"""
Returns a message that includes a set of suggested actions and optional text.
:Example:
messa... | python | {
"resource": ""
} |
q268104 | MessageFactory.attachment | test | def attachment(attachment: Attachment, text: str = None, speak: str = None,
input_hint: Union[InputHints, str] = None):
"""
Returns a single message activity containing an attachment.
:Example:
message = MessageFactory.attachment(CardFactory.hero_card(HeroCard(title='... | python | {
"resource": ""
} |
q268105 | MessageFactory.list | test | def list(attachments: List[Attachment], text: str = None, speak: str = None,
input_hint: Union[InputHints, str] = None) -> Activity:
"""
Returns a message that will display a set of attachments in list form.
:Example:
message = MessageFactory.list([CardFactory.hero_card(Her... | python | {
"resource": ""
} |
q268106 | MessageFactory.content_url | test | def content_url(url: str, content_type: str, name: str = None, text: str = None, speak: str = None,
input_hint: Union[InputHints, str] = None):
"""
Returns a message that will display a single image or video to a user.
:Example:
message = MessageFactory.content_url('... | python | {
"resource": ""
} |
q268107 | ActivityUtil.create_trace | test | def create_trace(
turn_activity: Activity,
name: str,
value: object = None,
value_type: str = None,
label: str = None,
) -> Activity:
"""Creates a trace activity based on this activity.
:param turn_activity:
:type turn_activity: Activity
:para... | python | {
"resource": ""
} |
q268108 | Dialog.telemetry_client | test | def telemetry_client(self, value: BotTelemetryClient) -> None:
"""
Sets the telemetry client for logging events.
"""
if value is None:
self._telemetry_client = NullTelemetryClient()
else:
self._telemetry_client = value | python | {
"resource": ""
} |
q268109 | CosmosDbStorage.read | test | async def read(self, keys: List[str]) -> dict:
"""Read storeitems from storage.
:param keys:
:return dict:
"""
try:
# check if the database and container exists and if not create
if not self.__container_exists:
self.__create_db_and_contain... | python | {
"resource": ""
} |
q268110 | CosmosDbStorage.write | test | async def write(self, changes: Dict[str, StoreItem]):
"""Save storeitems to storage.
:param changes:
:return:
"""
try:
# check if the database and container exists and if not create
if not self.__container_exists:
self.__create_db_and_cont... | python | {
"resource": ""
} |
q268111 | CosmosDbStorage.delete | test | async def delete(self, keys: List[str]):
"""Remove storeitems from storage.
:param keys:
:return:
"""
try:
# check if the database and container exists and if not create
if not self.__container_exists:
self.__create_db_and_container()
... | python | {
"resource": ""
} |
q268112 | CosmosDbStorage.__create_si | test | def __create_si(self, result) -> StoreItem:
"""Create a StoreItem from a result out of CosmosDB.
:param result:
:return StoreItem:
"""
# get the document item from the result and turn into a dict
doc = result.get('document')
# readd the e_tag from Cosmos
... | python | {
"resource": ""
} |
q268113 | CosmosDbStorage.__create_dict | test | def __create_dict(self, si: StoreItem) -> Dict:
"""Return the dict of a StoreItem.
This eliminates non_magic attributes and the e_tag.
:param si:
:return dict:
"""
# read the content
non_magic_attr = ([attr for attr in dir(si)
if not at... | python | {
"resource": ""
} |
q268114 | CosmosDbStorage.__sanitize_key | test | def __sanitize_key(self, key) -> str:
"""Return the sanitized key.
Replace characters that are not allowed in keys in Cosmos.
:param key:
:return str:
"""
# forbidden characters
bad_chars = ['\\', '?', '/', '#', '\t', '\n', '\r']
# replace those with wit... | python | {
"resource": ""
} |
q268115 | CosmosDbStorage.__create_db_and_container | test | def __create_db_and_container(self):
"""Call the get or create methods."""
db_id = self.config.database
container_name = self.config.container
self.db = self.__get_or_create_database(self.client, db_id)
self.container = self.__get_or_create_container(
self.client, con... | python | {
"resource": ""
} |
q268116 | CosmosDbStorage.__get_or_create_database | test | def __get_or_create_database(self, doc_client, id) -> str:
"""Return the database link.
Check if the database exists or create the db.
:param doc_client:
:param id:
:return str:
"""
# query CosmosDB for a database with that name/id
dbs = list(doc_client.... | python | {
"resource": ""
} |
q268117 | CosmosDbStorage.__get_or_create_container | test | def __get_or_create_container(self, doc_client, container) -> str:
"""Return the container link.
Check if the container exists or create the container.
:param doc_client:
:param container:
:return str:
"""
# query CosmosDB for a container in the database with th... | python | {
"resource": ""
} |
q268118 | QnAMaker.fill_qna_event | test | def fill_qna_event(
self,
query_results: [QueryResult],
turn_context: TurnContext,
telemetry_properties: Dict[str,str] = None,
telemetry_metrics: Dict[str,float] = None
) -> EventData:
"""
Fills the event properties and metrics for the QnaMessage event for tel... | python | {
"resource": ""
} |
q268119 | TurnContext.get_conversation_reference | test | def get_conversation_reference(activity: Activity) -> ConversationReference:
"""
Returns the conversation reference for an activity. This can be saved as a plain old JSON
object and then later used to message the user proactively.
Usage Example:
reference = TurnContext.get_conve... | python | {
"resource": ""
} |
q268120 | WaterfallDialog.get_step_name | test | def get_step_name(self, index: int) -> str:
"""
Give the waterfall step a unique name
"""
step_name = self._steps[index].__qualname__
if not step_name or ">" in step_name :
step_name = f"Step{index + 1}of{len(self._steps)}"
return step_name | python | {
"resource": ""
} |
q268121 | Channel.supports_suggested_actions | test | def supports_suggested_actions(channel_id: str, button_cnt: int = 100) -> bool:
"""Determine if a number of Suggested Actions are supported by a Channel.
Args:
channel_id (str): The Channel to check the if Suggested Actions are supported in.
button_cnt (int, optional): Defaults ... | python | {
"resource": ""
} |
q268122 | Channel.supports_card_actions | test | def supports_card_actions(channel_id: str, button_cnt: int = 100) -> bool:
"""Determine if a number of Card Actions are supported by a Channel.
Args:
channel_id (str): The Channel to check if the Card Actions are supported in.
button_cnt (int, optional): Defaults to 100. The num... | python | {
"resource": ""
} |
q268123 | Channel.get_channel_id | test | def get_channel_id(turn_context: TurnContext) -> str:
"""Get the Channel Id from the current Activity on the Turn Context.
Args:
turn_context (TurnContext): The Turn Context to retrieve the Activity's Channel Id from.
Returns:
str: The Channel Id from the Turn Context's... | python | {
"resource": ""
} |
q268124 | EmulatorValidation.is_token_from_emulator | test | def is_token_from_emulator(auth_header: str) -> bool:
""" Determines if a given Auth header is from the Bot Framework Emulator
:param auth_header: Bearer Token, in the 'Bearer [Long String]' Format.
:type auth_header: str
:return: True, if the token was issued by the Emulator. Otherwis... | python | {
"resource": ""
} |
q268125 | CardFactory.hero_card | test | def hero_card(card: HeroCard) -> Attachment:
"""
Returns an attachment for a hero card. Will raise a TypeError if 'card' argument is not a HeroCard.
Hero cards tend to have one dominant full width image and the cards text & buttons can
usually be found below the image.
:return:
... | python | {
"resource": ""
} |
q268126 | Instruction.params | test | def params(self):
"""return instruction params"""
# if params already defined don't attempt to get them from definition
if self._definition and not self._params:
self._params = []
for sub_instr, _, _ in self._definition:
self._params.extend(sub_instr.param... | python | {
"resource": ""
} |
q268127 | Instruction.mirror | test | def mirror(self):
"""For a composite instruction, reverse the order of sub-gates.
This is done by recursively mirroring all sub-instructions.
It does not invert any gate.
Returns:
Instruction: a fresh gate with sub-gates reversed
"""
if not self._definition:... | python | {
"resource": ""
} |
q268128 | Instruction.inverse | test | def inverse(self):
"""Invert this instruction.
If the instruction is composite (i.e. has a definition),
then its definition will be recursively inverted.
Special instructions inheriting from Instruction can
implement their own inverse (e.g. T and Tdg, Barrier, etc.)
Re... | python | {
"resource": ""
} |
q268129 | Instruction.c_if | test | def c_if(self, classical, val):
"""Add classical control on register classical and value val."""
if not isinstance(classical, ClassicalRegister):
raise QiskitError("c_if must be used with a classical register")
if val < 0:
raise QiskitError("control value should be non-ne... | python | {
"resource": ""
} |
q268130 | Instruction.copy | test | def copy(self, name=None):
"""
shallow copy of the instruction.
Args:
name (str): name to be given to the copied circuit,
if None then the name stays the same
Returns:
Instruction: a shallow copy of the current instruction, with the name
upda... | python | {
"resource": ""
} |
q268131 | Instruction._qasmif | test | def _qasmif(self, string):
"""Print an if statement if needed."""
if self.control is None:
return string
return "if(%s==%d) " % (self.control[0].name, self.control[1]) + string | python | {
"resource": ""
} |
q268132 | Instruction.qasm | test | def qasm(self):
"""Return a default OpenQASM string for the instruction.
Derived instructions may override this to print in a
different format (e.g. measure q[0] -> c[0];).
"""
name_param = self.name
if self.params:
name_param = "%s(%s)" % (name_param, ",".jo... | python | {
"resource": ""
} |
q268133 | PassManager.run | test | def run(self, circuit):
"""Run all the passes on a QuantumCircuit
Args:
circuit (QuantumCircuit): circuit to transform via all the registered passes
Returns:
QuantumCircuit: Transformed circuit.
"""
name = circuit.name
dag = circuit_to_dag(circui... | python | {
"resource": ""
} |
q268134 | PassManager._do_pass | test | def _do_pass(self, pass_, dag, options):
"""Do a pass and its "requires".
Args:
pass_ (BasePass): Pass to do.
dag (DAGCircuit): The dag on which the pass is ran.
options (dict): PassManager options.
Returns:
DAGCircuit: The transformed dag in case... | python | {
"resource": ""
} |
q268135 | PassManager.passes | test | def passes(self):
"""
Returns a list structure of the appended passes and its options.
Returns (list): The appended passes.
"""
ret = []
for pass_ in self.working_list:
ret.append(pass_.dump_passes())
return ret | python | {
"resource": ""
} |
q268136 | FlowController.dump_passes | test | def dump_passes(self):
"""
Fetches the passes added to this flow controller.
Returns (dict): {'options': self.options, 'passes': [passes], 'type': type(self)}
"""
ret = {'options': self.options, 'passes': [], 'type': type(self)}
for pass_ in self._passes:
if ... | python | {
"resource": ""
} |
q268137 | FlowController.controller_factory | test | def controller_factory(cls, passes, options, **partial_controller):
"""
Constructs a flow controller based on the partially evaluated controller arguments.
Args:
passes (list[BasePass]): passes to add to the flow controller.
options (dict): PassManager options.
... | python | {
"resource": ""
} |
q268138 | u_base | test | def u_base(self, theta, phi, lam, q):
"""Apply U to q."""
return self.append(UBase(theta, phi, lam), [q], []) | python | {
"resource": ""
} |
q268139 | single_gate_params | test | def single_gate_params(gate, params=None):
"""Apply a single qubit gate to the qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
tuple: a tuple of U gate parameters (theta, phi, lam)
Raises:
QiskitError: if th... | python | {
"resource": ""
} |
q268140 | single_gate_matrix | test | def single_gate_matrix(gate, params=None):
"""Get the matrix for a single qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
array: A numpy array representing the matrix
"""
# Converting sym to floats improves the... | python | {
"resource": ""
} |
q268141 | einsum_matmul_index | test | def einsum_matmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix-matrix multiplication.
The returned indices are to perform a matrix multiplication A.B where
the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and
M <= N, and identity matrices a... | python | {
"resource": ""
} |
q268142 | einsum_vecmul_index | test | def einsum_vecmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix-vector multiplication.
The returned indices are to perform a matrix multiplication A.v where
the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and
M <= N, and identity matrices a... | python | {
"resource": ""
} |
q268143 | _einsum_matmul_index_helper | test | def _einsum_matmul_index_helper(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix multiplication.
The returned indices are to perform a matrix multiplication A.v where
the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and
M <= N, and identity matrices ... | python | {
"resource": ""
} |
q268144 | circuit_to_dag | test | def circuit_to_dag(circuit):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register ... | python | {
"resource": ""
} |
q268145 | exp_fit_fun | test | def exp_fit_fun(x, a, tau, c):
"""Function used to fit the exponential decay."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) + c | python | {
"resource": ""
} |
q268146 | osc_fit_fun | test | def osc_fit_fun(x, a, tau, f, phi, c):
"""Function used to fit the decay cosine."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) * np.cos(2 * np.pi * f * x + phi) + c | python | {
"resource": ""
} |
q268147 | plot_coherence | test | def plot_coherence(xdata, ydata, std_error, fit, fit_function, xunit, exp_str,
qubit_label):
"""Plot coherence data.
Args:
xdata
ydata
std_error
fit
fit_function
xunit
exp_str
qubit_label
Raises:
ImportError: If matp... | python | {
"resource": ""
} |
q268148 | shape_rb_data | test | def shape_rb_data(raw_rb):
"""Take the raw rb data and convert it into averages and std dev
Args:
raw_rb (numpy.array): m x n x l list where m is the number of seeds, n
is the number of Clifford sequences and l is the number of qubits
Return:
numpy_array: 2 x n x l list where i... | python | {
"resource": ""
} |
q268149 | plot_rb_data | test | def plot_rb_data(xdata, ydatas, yavg, yerr, fit, survival_prob, ax=None,
show_plt=True):
"""Plot randomized benchmarking data.
Args:
xdata (list): list of subsequence lengths
ydatas (list): list of lists of survival probabilities for each
sequence
yavg (list... | python | {
"resource": ""
} |
q268150 | _split_runs_on_parameters | test | def _split_runs_on_parameters(runs):
"""Finds runs containing parameterized gates and splits them into sequential
runs excluding the parameterized gates.
"""
def _is_dagnode_parameterized(node):
return any(isinstance(param, Parameter) for param in node.op.params)
out = []
for run in ru... | python | {
"resource": ""
} |
q268151 | Optimize1qGates.compose_u3 | test | def compose_u3(theta1, phi1, lambda1, theta2, phi2, lambda2):
"""Return a triple theta, phi, lambda for the product.
u3(theta, phi, lambda)
= u3(theta1, phi1, lambda1).u3(theta2, phi2, lambda2)
= Rz(phi1).Ry(theta1).Rz(lambda1+phi2).Ry(theta2).Rz(lambda2)
= Rz(phi1).Rz(... | python | {
"resource": ""
} |
q268152 | Optimize1qGates.yzy_to_zyz | test | def yzy_to_zyz(xi, theta1, theta2, eps=1e-9): # pylint: disable=invalid-name
"""Express a Y.Z.Y single qubit gate as a Z.Y.Z gate.
Solve the equation
.. math::
Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda)
for theta, phi, and lambda.
Return a solution ... | python | {
"resource": ""
} |
q268153 | _validate_input_state | test | def _validate_input_state(quantum_state):
"""Validates the input to state visualization functions.
Args:
quantum_state (ndarray): Input state / density matrix.
Returns:
rho: A 2d numpy array for the density matrix.
Raises:
VisualizationError: Invalid input.
"""
rho = np.... | python | {
"resource": ""
} |
q268154 | _trim | test | def _trim(image):
"""Trim a PIL image and remove white space."""
background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))
diff = PIL.ImageChops.difference(image, background)
diff = PIL.ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
image = image.cr... | python | {
"resource": ""
} |
q268155 | _get_gate_span | test | def _get_gate_span(qregs, instruction):
"""Get the list of qubits drawing this gate would cover"""
min_index = len(qregs)
max_index = 0
for qreg in instruction.qargs:
index = qregs.index(qreg)
if index < min_index:
min_index = index
if index > max_index:
... | python | {
"resource": ""
} |
q268156 | circuit_to_instruction | test | def circuit_to_instruction(circuit):
"""Build an ``Instruction`` object from a ``QuantumCircuit``.
The instruction is anonymous (not tied to a named quantum register),
and so can be inserted into another circuit. The instruction will
have the same string name as the circuit.
Args:
circuit ... | python | {
"resource": ""
} |
q268157 | DenseLayout.run | test | def run(self, dag):
"""
Pick a convenient layout depending on the best matching
qubit connectivity, and set the property `layout`.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than self.coupling_map
"""
... | python | {
"resource": ""
} |
q268158 | DenseLayout._best_subset | test | def _best_subset(self, n_qubits):
"""Computes the qubit mapping with the best connectivity.
Args:
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best connectivity mapping.
"""
if n_qubits == 1:
... | python | {
"resource": ""
} |
q268159 | barrier | test | def barrier(self, *qargs):
"""Apply barrier to circuit.
If qargs is None, applies to all the qbits.
Args is a list of QuantumRegister or single qubits.
For QuantumRegister, applies barrier to all the qubits in that register."""
qubits = []
qargs = _convert_to_bits(qargs, [qbit for qreg in self.... | python | {
"resource": ""
} |
q268160 | average_data | test | def average_data(counts, observable):
"""Compute the mean value of an diagonal observable.
Takes in a diagonal observable in dictionary, list or matrix format and then
calculates the sum_i value(i) P(i) where value(i) is the value of the
observable for state i.
Args:
counts (dict): a dict ... | python | {
"resource": ""
} |
q268161 | AstInterpreter._process_bit_id | test | def _process_bit_id(self, node):
"""Process an Id or IndexedId node as a bit or register type.
Return a list of tuples (Register,index).
"""
# pylint: disable=inconsistent-return-statements
reg = None
if node.name in self.dag.qregs:
reg = self.dag.qregs[node.... | python | {
"resource": ""
} |
q268162 | AstInterpreter._process_custom_unitary | test | def _process_custom_unitary(self, node):
"""Process a custom unitary node."""
name = node.name
if node.arguments is not None:
args = self._process_node(node.arguments)
else:
args = []
bits = [self._process_bit_id(node_element)
for node_elem... | python | {
"resource": ""
} |
q268163 | AstInterpreter._process_gate | test | def _process_gate(self, node, opaque=False):
"""Process a gate node.
If opaque is True, process the node as an opaque gate node.
"""
self.gates[node.name] = {}
de_gate = self.gates[node.name]
de_gate["print"] = True # default
de_gate["opaque"] = opaque
d... | python | {
"resource": ""
} |
q268164 | AstInterpreter._process_cnot | test | def _process_cnot(self, node):
"""Process a CNOT gate node."""
id0 = self._process_bit_id(node.children[0])
id1 = self._process_bit_id(node.children[1])
if not(len(id0) == len(id1) or len(id0) == 1 or len(id1) == 1):
raise QiskitError("internal error: qreg size mismatch",
... | python | {
"resource": ""
} |
q268165 | AstInterpreter._process_measure | test | def _process_measure(self, node):
"""Process a measurement node."""
id0 = self._process_bit_id(node.children[0])
id1 = self._process_bit_id(node.children[1])
if len(id0) != len(id1):
raise QiskitError("internal error: reg size mismatch",
"line=%s... | python | {
"resource": ""
} |
q268166 | AstInterpreter._process_if | test | def _process_if(self, node):
"""Process an if node."""
creg_name = node.children[0].name
creg = self.dag.cregs[creg_name]
cval = node.children[1].value
self.condition = (creg, cval)
self._process_node(node.children[2])
self.condition = None | python | {
"resource": ""
} |
q268167 | AstInterpreter._create_dag_op | test | def _create_dag_op(self, name, params, qargs):
"""
Create a DAG node out of a parsed AST op node.
Args:
name (str): operation name to apply to the dag.
params (list): op parameters
qargs (list(QuantumRegister, int)): qubits to attach to
Raises:
... | python | {
"resource": ""
} |
q268168 | Schedule.ch_duration | test | def ch_duration(self, *channels: List[Channel]) -> int:
"""Return duration of supplied channels.
Args:
*channels: Supplied channels
"""
return self.timeslots.ch_duration(*channels) | python | {
"resource": ""
} |
q268169 | Schedule.ch_start_time | test | def ch_start_time(self, *channels: List[Channel]) -> int:
"""Return minimum start time for supplied channels.
Args:
*channels: Supplied channels
"""
return self.timeslots.ch_start_time(*channels) | python | {
"resource": ""
} |
q268170 | Schedule.ch_stop_time | test | def ch_stop_time(self, *channels: List[Channel]) -> int:
"""Return maximum start time for supplied channels.
Args:
*channels: Supplied channels
"""
return self.timeslots.ch_stop_time(*channels) | python | {
"resource": ""
} |
q268171 | Schedule._instructions | test | def _instructions(self, time: int = 0) -> Iterable[Tuple[int, 'Instruction']]:
"""Iterable for flattening Schedule tree.
Args:
time: Shifted time due to parent
Yields:
Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
at and... | python | {
"resource": ""
} |
q268172 | ModelTypeValidator.check_type | test | def check_type(self, value, attr, data):
"""Validates a value against the correct type of the field.
It calls ``_expected_types`` to get a list of valid types.
Subclasses can do one of the following:
1. They can override the ``valid_types`` property with a tuple with
t... | python | {
"resource": ""
} |
q268173 | BaseSchema.dump_additional_data | test | def dump_additional_data(self, valid_data, many, original_data):
"""Include unknown fields after dumping.
Unknown fields are added with no processing at all.
Args:
valid_data (dict or list): data collected and returned by ``dump()``.
many (bool): if True, data and origi... | python | {
"resource": ""
} |
q268174 | BaseSchema.load_additional_data | test | def load_additional_data(self, valid_data, many, original_data):
"""Include unknown fields after load.
Unknown fields are added with no processing at all.
Args:
valid_data (dict or list): validated data returned by ``load()``.
many (bool): if True, data and original_dat... | python | {
"resource": ""
} |
q268175 | _SchemaBinder._create_validation_schema | test | def _create_validation_schema(schema_cls):
"""Create a patched Schema for validating models.
Model validation is not part of Marshmallow. Schemas have a ``validate``
method but this delegates execution on ``load`` and discards the result.
Similarly, ``load`` will call ``_deserialize`` o... | python | {
"resource": ""
} |
q268176 | _SchemaBinder._validate | test | def _validate(instance):
"""Validate the internal representation of the instance."""
try:
_ = instance.schema.validate(instance.to_dict())
except ValidationError as ex:
raise ModelValidationError(
ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwarg... | python | {
"resource": ""
} |
q268177 | _SchemaBinder._validate_after_init | test | def _validate_after_init(init_method):
"""Add validation after instantiation."""
@wraps(init_method)
def _decorated(self, **kwargs):
try:
_ = self.shallow_schema.validate(kwargs)
except ValidationError as ex:
raise ModelValidationError(
... | python | {
"resource": ""
} |
q268178 | BaseModel.to_dict | test | def to_dict(self):
"""Serialize the model into a Python dict of simple types.
Note that this method requires that the model is bound with
``@bind_schema``.
"""
try:
data, _ = self.schema.dump(self)
except ValidationError as ex:
raise ModelValidati... | python | {
"resource": ""
} |
q268179 | BaseModel.from_dict | test | def from_dict(cls, dict_):
"""Deserialize a dict of simple types into an instance of this class.
Note that this method requires that the model is bound with
``@bind_schema``.
"""
try:
data, _ = cls.schema.load(dict_)
except ValidationError as ex:
... | python | {
"resource": ""
} |
q268180 | qft | test | def qft(circ, q, n):
"""n-qubit QFT on q in circ."""
for j in range(n):
for k in range(j):
circ.cu1(math.pi / float(2**(j - k)), q[j], q[k])
circ.h(q[j]) | python | {
"resource": ""
} |
q268181 | __partial_trace_vec | test | def __partial_trace_vec(vec, trace_systems, dimensions, reverse=True):
"""
Partial trace over subsystems of multi-partite vector.
Args:
vec (vector_like): complex vector N
trace_systems (list(int)): a list of subsystems (starting from 0) to
trace over.
... | python | {
"resource": ""
} |
q268182 | vectorize | test | def vectorize(density_matrix, method='col'):
"""Flatten an operator to a vector in a specified basis.
Args:
density_matrix (ndarray): a density matrix.
method (str): the method of vectorization. Allowed values are
- 'col' (default) flattens to column-major vector.
- 'row... | python | {
"resource": ""
} |
q268183 | devectorize | test | def devectorize(vectorized_mat, method='col'):
"""Devectorize a vectorized square matrix.
Args:
vectorized_mat (ndarray): a vectorized density matrix.
method (str): the method of devectorization. Allowed values are
- 'col' (default): flattens to column-major vector.
- 'r... | python | {
"resource": ""
} |
q268184 | choi_to_rauli | test | def choi_to_rauli(choi, order=1):
"""
Convert a Choi-matrix to a Pauli-basis superoperator.
Note that this function assumes that the Choi-matrix
is defined in the standard column-stacking convention
and is normalized to have trace 1. For a channel E this
is defined as: choi = (I \\otimes E)(bel... | python | {
"resource": ""
} |
q268185 | chop | test | def chop(array, epsilon=1e-10):
"""
Truncate small values of a complex array.
Args:
array (array_like): array to truncte small values.
epsilon (float): threshold.
Returns:
np.array: A new operator with small values set to zero.
"""
ret = np.array(array)
if np.isrea... | python | {
"resource": ""
} |
q268186 | outer | test | def outer(vector1, vector2=None):
"""
Construct the outer product of two vectors.
The second vector argument is optional, if absent the projector
of the first vector will be returned.
Args:
vector1 (ndarray): the first vector.
vector2 (ndarray): the (optional) second vector.
R... | python | {
"resource": ""
} |
q268187 | concurrence | test | def concurrence(state):
"""Calculate the concurrence.
Args:
state (np.array): a quantum state (1x4 array) or a density matrix (4x4
array)
Returns:
float: concurrence.
Raises:
Exception: if attempted on more than two qubits.
"""
rho = np.array(st... | python | {
"resource": ""
} |
q268188 | shannon_entropy | test | def shannon_entropy(pvec, base=2):
"""
Compute the Shannon entropy of a probability vector.
The shannon entropy of a probability vector pv is defined as
$H(pv) = - \\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$.
Args:
pvec (array_like): a probability vector.
base (int): the bas... | python | {
"resource": ""
} |
q268189 | entropy | test | def entropy(state):
"""
Compute the von-Neumann entropy of a quantum state.
Args:
state (array_like): a density matrix or state vector.
Returns:
float: The von-Neumann entropy S(rho).
"""
rho = np.array(state)
if rho.ndim == 1:
return 0
evals = np.maximum(np.li... | python | {
"resource": ""
} |
q268190 | mutual_information | test | def mutual_information(state, d0, d1=None):
"""
Compute the mutual information of a bipartite state.
Args:
state (array_like): a bipartite state-vector or density-matrix.
d0 (int): dimension of the first subsystem.
d1 (int or None): dimension of the second subsystem.
Returns:
... | python | {
"resource": ""
} |
q268191 | entanglement_of_formation | test | def entanglement_of_formation(state, d0, d1=None):
"""
Compute the entanglement of formation of quantum state.
The input quantum state must be either a bipartite state vector, or a
2-qubit density matrix.
Args:
state (array_like): (N) array_like or (4,4) array_like, a
bipartite... | python | {
"resource": ""
} |
q268192 | __eof_qubit | test | def __eof_qubit(rho):
"""
Compute the Entanglement of Formation of a 2-qubit density matrix.
Args:
rho ((array_like): (4,4) array_like, input density matrix.
Returns:
float: The entanglement of formation.
"""
c = concurrence(rho)
c = 0.5 + 0.5 * np.sqrt(1 - c * c)
retur... | python | {
"resource": ""
} |
q268193 | flatten | test | def flatten(schedule: ScheduleComponent, name: str = None) -> Schedule:
"""Create a flattened schedule.
Args:
schedule: Schedules to flatten
name: Name of the new schedule. Defaults to first element of `schedules`
"""
if name is None:
name = schedule.name
return Schedule(*s... | python | {
"resource": ""
} |
q268194 | shift | test | def shift(schedule: ScheduleComponent, time: int, name: str = None) -> Schedule:
"""Return schedule shifted by `time`.
Args:
schedule: The schedule to shift
time: The time to shift by
name: Name of shifted schedule. Defaults to name of `schedule`
"""
if name is None:
nam... | python | {
"resource": ""
} |
q268195 | insert | test | def insert(parent: ScheduleComponent, time: int, child: ScheduleComponent,
name: str = None) -> Schedule:
"""Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`.
Args:
parent: Schedule to be inserted into
time: Time to be inserted defined with r... | python | {
"resource": ""
} |
q268196 | append | test | def append(parent: ScheduleComponent, child: ScheduleComponent,
name: str = None) -> Schedule:
r"""Return a new schedule with by appending `child` to `parent` at
the last time of the `parent` schedule's channels
over the intersection of the parent and child schedule's channels.
$t =... | python | {
"resource": ""
} |
q268197 | u3 | test | def u3(self, theta, phi, lam, q):
"""Apply u3 to q."""
return self.append(U3Gate(theta, phi, lam), [q], []) | python | {
"resource": ""
} |
q268198 | BaseBackend.status | test | def status(self):
"""Return backend status.
Returns:
BackendStatus: the status of the backend.
"""
return BackendStatus(backend_name=self.name(),
backend_version=__version__,
operational=True,
... | python | {
"resource": ""
} |
q268199 | BaseProgressBar.start | test | def start(self, iterations):
"""Start the progress bar.
Parameters:
iterations (int): Number of iterations.
"""
self.touched = True
self.iter = int(iterations)
self.t_start = time.time() | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.