_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q268500 | QasmLexer.input | test | def input(self, data):
"""Set the input text data."""
| python | {
"resource": ""
} |
q268501 | QasmLexer.pop | test | def pop(self):
"""Pop a PLY lexer off the stack."""
self.lexer = self.stack.pop()
| python | {
"resource": ""
} |
q268502 | QasmLexer.push | test | def push(self, filename):
"""Push a PLY lexer on the stack to parse filename."""
self.lexer.qasm_file = self.filename
| python | {
"resource": ""
} |
q268503 | ConsolidateBlocks.run | test | def run(self, dag):
"""iterate over each block and replace it with an equivalent Unitary
on the same wires.
"""
new_dag = DAGCircuit()
for qreg in dag.qregs.values():
new_dag.add_qreg(qreg)
for creg in dag.cregs.values():
new_dag.add_creg(creg)
# compute ordered indices for the global circuit wires
global_index_map = {}
for wire in dag.wires:
if not isinstance(wire[0], QuantumRegister):
continue
global_qregs = list(dag.qregs.values())
global_index_map[wire] = global_qregs.index(wire[0]) + wire[1]
blocks = self.property_set['block_list']
nodes_seen = set()
for node in dag.topological_op_nodes():
# skip already-visited nodes or input/output nodes
if node in nodes_seen or node.type == 'in' or node.type == 'out':
continue
# check if the node belongs to the next block
if blocks and node in blocks[0]:
block = blocks[0]
# find the qubits involved in this block
block_qargs = set()
for nd in block:
block_qargs |= set(nd.qargs)
# convert block to a sub-circuit, then simulate unitary and add
block_width = len(block_qargs)
q = QuantumRegister(block_width)
subcirc = QuantumCircuit(q)
block_index_map = self._block_qargs_to_indices(block_qargs,
global_index_map)
for nd in block: | python | {
"resource": ""
} |
q268504 | ConversionMethodBinder.get_bound_method | test | def get_bound_method(self, instruction):
"""Get conversion method for instruction."""
try:
return self._bound_instructions[type(instruction)]
except KeyError:
| python | {
"resource": ""
} |
q268505 | PulseQobjConverter.convert_acquire | test | def convert_acquire(self, shift, instruction):
"""Return converted `AcquireInstruction`.
Args:
shift(int): Offset time.
instruction (AcquireInstruction): acquire instruction.
Returns:
dict: Dictionary of required parameters.
"""
meas_level = self._run_config.get('meas_level', 2)
command_dict = {
'name': 'acquire',
't0': shift+instruction.start_time,
'duration': instruction.duration,
'qubits': [q.index for q in instruction.acquires],
'memory_slot': [m.index for m in instruction.mem_slots]
}
if meas_level == 2:
# setup discriminators
if instruction.command.discriminator:
command_dict.update({
'discriminators': [
QobjMeasurementOption(
name=instruction.command.discriminator.name,
| python | {
"resource": ""
} |
q268506 | PulseQobjConverter.convert_frame_change | test | def convert_frame_change(self, shift, instruction):
"""Return converted `FrameChangeInstruction`.
Args:
shift(int): Offset time.
instruction (FrameChangeInstruction): frame change instruction.
Returns:
dict: Dictionary of required parameters.
"""
command_dict = {
'name': 'fc',
't0': | python | {
"resource": ""
} |
q268507 | PulseQobjConverter.convert_persistent_value | test | def convert_persistent_value(self, shift, instruction):
"""Return converted `PersistentValueInstruction`.
Args:
shift(int): Offset time.
instruction (PersistentValueInstruction): persistent value instruction.
Returns:
dict: Dictionary of required parameters.
"""
command_dict = {
'name': 'pv',
| python | {
"resource": ""
} |
q268508 | PulseQobjConverter.convert_drive | test | def convert_drive(self, shift, instruction):
"""Return converted `PulseInstruction`.
Args:
shift(int): Offset time.
instruction (PulseInstruction): drive instruction.
Returns:
dict: Dictionary of required parameters.
"""
| python | {
"resource": ""
} |
q268509 | PulseQobjConverter.convert_snapshot | test | def convert_snapshot(self, shift, instruction):
"""Return converted `Snapshot`.
Args:
shift(int): Offset time.
instruction (Snapshot): snapshot instruction.
Returns:
| python | {
"resource": ""
} |
q268510 | _update_annotations | test | def _update_annotations(discretized_pulse: Callable) -> Callable:
"""Update annotations of discretized continuous pulse function with duration.
Args:
discretized_pulse: Discretized decorated continuous pulse.
"""
undecorated_annotations = list(discretized_pulse.__annotations__.items())
| python | {
"resource": ""
} |
q268511 | sampler | test | def sampler(sample_function: Callable) -> Callable:
"""Sampler decorator base method.
Samplers are used for converting an continuous function to a discretized pulse.
They operate on a function with the signature:
`def f(times: np.ndarray, *args, **kwargs) -> np.ndarray`
Where `times` is a numpy array of floats with length n_times and the output array
is a complex numpy array with length n_times. The output of the decorator is an
instance of `FunctionalPulse` with signature:
`def g(duration: int, *args, **kwargs) -> SamplePulse`
Note if your continuous pulse function outputs a `complex` scalar rather than a
`np.ndarray`, you should first vectorize it before applying a sampler.
This class implements the sampler boilerplate for the sampler.
Args:
sample_function: A sampler function to be decorated.
"""
def generate_sampler(continuous_pulse: Callable) -> Callable:
"""Return a decorated sampler function."""
@functools.wraps(continuous_pulse)
def call_sampler(duration: int, *args, **kwargs) -> commands.SamplePulse:
"""Replace the call to the continuous function with a call to the sampler applied
to the anlytic pulse function."""
sampled_pulse = sample_function(continuous_pulse, duration, *args, **kwargs)
return np.asarray(sampled_pulse, dtype=np.complex_)
| python | {
"resource": ""
} |
q268512 | filter_backends | test | def filter_backends(backends, filters=None, **kwargs):
"""Return the backends matching the specified filtering.
Filter the `backends` list by their `configuration` or `status`
attributes, or from a boolean callable. The criteria for filtering can
be specified via `**kwargs` or as a callable via `filters`, and the
backends must fulfill all specified conditions.
Args:
backends (list[BaseBackend]): list of backends.
filters (callable): filtering conditions as a callable.
**kwargs (dict): dict of criteria.
Returns:
list[BaseBackend]: a list of backend instances matching the
conditions.
"""
def _match_all(obj, criteria):
"""Return True if all items in criteria matches items in obj."""
return all(getattr(obj, key_, None) == value_ for
key_, value_ in criteria.items())
# Inspect the backends to decide which filters belong to
# backend.configuration and which ones to backend.status, as it does
# not involve querying the API.
configuration_filters = {}
status_filters = {}
for key, value in kwargs.items():
if all(key in backend.configuration() for backend in backends):
configuration_filters[key] = value
| python | {
"resource": ""
} |
q268513 | resolve_backend_name | test | def resolve_backend_name(name, backends, deprecated, aliased):
"""Resolve backend name from a deprecated name or an alias.
A group will be resolved in order of member priorities, depending on
availability.
Args:
name (str): name of backend to resolve
backends (list[BaseBackend]): list of available backends.
deprecated (dict[str: str]): dict of deprecated names.
aliased (dict[str: list[str]]): dict of aliased names.
Returns:
str: resolved name (name of an available backend)
Raises:
LookupError: if name cannot be resolved through regular available
names, nor deprecated, nor alias names.
"""
available = [backend.name() | python | {
"resource": ""
} |
q268514 | dag_to_circuit | test | def dag_to_circuit(dag):
"""Build a ``QuantumCircuit`` object from a ``DAGCircuit``.
Args:
dag (DAGCircuit): the input dag.
Return:
QuantumCircuit: the circuit representing the input dag.
"""
qregs = collections.OrderedDict()
for qreg in dag.qregs.values():
qreg_tmp = QuantumRegister(qreg.size, name=qreg.name)
qregs[qreg.name] = qreg_tmp
cregs = collections.OrderedDict()
for creg in dag.cregs.values():
creg_tmp = ClassicalRegister(creg.size, name=creg.name)
cregs[creg.name] = creg_tmp
name = dag.name or None
circuit = QuantumCircuit(*qregs.values(), *cregs.values(), name=name)
for node in dag.topological_op_nodes():
qubits = []
for qubit in node.qargs:
| python | {
"resource": ""
} |
q268515 | make_dict_observable | test | def make_dict_observable(matrix_observable):
"""Convert an observable in matrix form to dictionary form.
Takes in a diagonal observable as a matrix and converts it to a dictionary
form. Can also handle a list sorted of the diagonal elements.
Args:
matrix_observable (list): The observable to be converted to dictionary
form. Can be a matrix or just an ordered list of observed values
Returns:
| python | {
"resource": ""
} |
q268516 | QasmParser.update_symtab | test | def update_symtab(self, obj):
"""Update a node in the symbol table.
Everything in the symtab must be a node with these attributes:
name - the string name of the object
type - the string type of the object
line - the source line where the type was first found
file - the source file where the type was first found
"""
if obj.name in self.current_symtab:
prev = self.current_symtab[obj.name]
raise QasmError("Duplicate declaration for", obj.type + " '"
| python | {
"resource": ""
} |
q268517 | QasmParser.verify_declared_bit | test | def verify_declared_bit(self, obj):
"""Verify a qubit id against the gate prototype."""
# We are verifying gate args against the formal parameters of a
# gate prototype.
if obj.name not in self.current_symtab:
raise QasmError("Cannot find symbol '" + obj.name
+ "' in argument list for gate, line",
str(obj.line), 'file', obj.file)
| python | {
"resource": ""
} |
q268518 | QasmParser.verify_exp_list | test | def verify_exp_list(self, obj):
"""Verify each expression in a list."""
# A tad harder. This is a list of expressions each of which could be
# the head of a tree. We need to recursively walk each of these and
# ensure that any Id elements resolve to the current stack.
#
# I believe we only have to look at the current symtab.
if obj.children is not None:
for children in obj.children:
| python | {
"resource": ""
} |
q268519 | QasmParser.verify_as_gate | test | def verify_as_gate(self, obj, bitlist, arglist=None):
"""Verify a user defined gate call."""
if obj.name not in self.global_symtab:
raise QasmError("Cannot find gate definition for '" + obj.name
+ "', line", str(obj.line), 'file', obj.file)
g_sym = self.global_symtab[obj.name]
if not (g_sym.type == 'gate' or g_sym.type == 'opaque'):
raise QasmError("'" + obj.name + "' is used as a gate "
+ "or opaque call but the symbol is neither;"
+ " it is a '" + g_sym.type + "' line",
str(obj.line), 'file', obj.file)
if g_sym.n_bits() != bitlist.size():
raise QasmError("Gate or opaque call to '" + obj.name
+ "' uses", str(bitlist.size()),
"qubits but is declared for",
str(g_sym.n_bits()), "qubits", "line",
str(obj.line), | python | {
"resource": ""
} |
q268520 | QasmParser.verify_reg | test | def verify_reg(self, obj, object_type):
"""Verify a register."""
# How to verify:
# types must match
# indexes must be checked
if obj.name not in self.global_symtab:
raise QasmError('Cannot find definition for', object_type, "'"
+ obj.name + "'", 'at line', str(obj.line),
'file', obj.file)
g_sym = self.global_symtab[obj.name]
if g_sym.type != object_type:
raise QasmError("Type for '" + g_sym.name + "' should be '"
+ object_type + "' but was found to be '"
+ g_sym.type + "'", "line", str(obj.line),
"file", obj.file)
if obj.type == 'indexed_id':
| python | {
"resource": ""
} |
q268521 | QasmParser.verify_reg_list | test | def verify_reg_list(self, obj, object_type):
"""Verify a list of registers."""
# We expect the object to be a bitlist or an idlist, we don't | python | {
"resource": ""
} |
q268522 | QasmParser.find_column | test | def find_column(self, input_, token):
"""Compute the column.
Input is the input text string.
token is a token instance.
"""
if token is None:
return 0
| python | {
"resource": ""
} |
q268523 | QasmParser.parse_debug | test | def parse_debug(self, val):
"""Set the parse_deb field."""
if val is True:
self.parse_deb = True
elif val is False:
self.parse_deb = False
else:
| python | {
"resource": ""
} |
q268524 | QasmParser.parse | test | def parse(self, data):
"""Parse some data."""
self.parser.parse(data, lexer=self.lexer, debug=self.parse_deb)
if self.qasm is None:
| python | {
"resource": ""
} |
q268525 | QasmParser.run | test | def run(self, data):
"""Parser runner.
To use this module stand-alone.
"""
ast | python | {
"resource": ""
} |
q268526 | Qasm.parse | test | def parse(self):
"""Parse the data."""
if self._filename:
with open(self._filename) as ifile:
| python | {
"resource": ""
} |
q268527 | crz | test | def crz(self, theta, ctl, tgt):
"""Apply crz from ctl to tgt with angle theta."""
| python | {
"resource": ""
} |
q268528 | basis_state | test | def basis_state(str_state, num):
"""
Return a basis state ndarray.
Args:
str_state (string): a string representing the state.
num (int): the number of qubits
Returns:
ndarray: state(2**num) a quantum state with basis basis state.
Raises:
QiskitError: if the dimensions is wrong
"""
| python | {
"resource": ""
} |
q268529 | projector | test | def projector(state, flatten=False):
"""
maps a pure state to a state matrix
Args:
state (ndarray): the number of qubits
flatten (bool): determine if state matrix of column work
Returns:
ndarray: state_mat(2**num, 2**num) if flatten is false
ndarray: state_mat(4**num) if flatten is true stacked | python | {
"resource": ""
} |
q268530 | purity | test | def purity(state):
"""Calculate the purity of a quantum state.
Args:
state (ndarray): a quantum state
Returns:
float: purity.
| python | {
"resource": ""
} |
q268531 | CommutationAnalysis.run | test | def run(self, dag):
"""
Run the pass on the DAG, and write the discovered commutation relations
into the property_set.
"""
# Initiate the commutation set
self.property_set['commutation_set'] = defaultdict(list)
# Build a dictionary to keep track of the gates on each qubit
for wire in dag.wires:
wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1]))
self.property_set['commutation_set'][wire_name] = []
# Add edges to the dictionary for each qubit
for node in dag.topological_op_nodes():
for (_, _, edge_data) in dag.edges(node):
| python | {
"resource": ""
} |
q268532 | backend_widget | test | def backend_widget(backend):
"""Creates a backend widget.
"""
config = backend.configuration().to_dict()
props = backend.properties().to_dict()
name = widgets.HTML(value="<h4>{name}</h4>".format(name=backend.name()),
layout=widgets.Layout())
n_qubits = config['n_qubits']
qubit_count = widgets.HTML(value="<h5><b>{qubits}</b></h5>".format(qubits=n_qubits),
layout=widgets.Layout(justify_content='center'))
cmap = widgets.Output(layout=widgets.Layout(min_width='250px', max_width='250px',
max_height='250px',
min_height='250px',
justify_content='center',
align_items='center',
margin='0px 0px 0px 0px'))
with cmap:
_cmap_fig = plot_gate_map(backend,
plot_directed=False,
label_qubits=False)
if _cmap_fig is not None:
display(_cmap_fig)
# Prevents plot from showing up twice.
plt.close(_cmap_fig)
pending = generate_jobs_pending_widget()
is_oper = widgets.HTML(value="<h5></h5>",
| python | {
"resource": ""
} |
q268533 | update_backend_info | test | def update_backend_info(self, interval=60):
"""Updates the monitor info
Called from another thread.
"""
my_thread = threading.currentThread()
current_interval = 0
started = False
all_dead = False
stati = [None]*len(self._backends)
while getattr(my_thread, "do_run", True) and not all_dead:
if current_interval == interval or started is False:
for ind, back in enumerate(self._backends):
_value = self.children[ind].children[2].value
_head = _value.split('<b>')[0]
try:
_status = back.status()
stati[ind] = _status
except Exception: # pylint: disable=W0703
self.children[ind].children[2].value = _value.replace(
_head, "<h5 style='color:#ff5c49'>")
self.children[ind]._is_alive = False
else:
self.children[ind]._is_alive = True
self.children[ind].children[2].value = _value.replace(
_head, "<h5>")
idx = list(range(len(self._backends)))
pending = [s.pending_jobs for s in stati]
_, least_idx = zip(*sorted(zip(pending, idx)))
# Make sure least pending is operational
for ind in least_idx:
if stati[ind].operational:
least_pending_idx = ind
break
for var in idx:
if var == least_pending_idx:
self.children[var].children[4].value = "<h5 style='color:#34bc6e'>True</h5>"
else:
| python | {
"resource": ""
} |
q268534 | generate_jobs_pending_widget | test | def generate_jobs_pending_widget():
"""Generates a jobs_pending progress bar widget.
"""
pbar = widgets.IntProgress(
value=0,
min=0,
max=50,
description='',
orientation='horizontal', layout=widgets.Layout(max_width='180px'))
pbar.style.bar_color = '#71cddd'
pbar_current = widgets.Label(
value=str(pbar.value), layout=widgets.Layout(min_width='auto'))
pbar_max = widgets.Label(
value=str(pbar.max), layout=widgets.Layout(min_width='auto'))
def _on_max_change(change):
pbar_max.value = str(change['new'])
def _on_val_change(change): | python | {
"resource": ""
} |
q268535 | CXCancellation.run | test | def run(self, dag):
"""
Run one pass of cx cancellation on the circuit
Args:
dag (DAGCircuit): the directed acyclic graph to run on.
Returns:
DAGCircuit: Transformed DAG.
"""
cx_runs = dag.collect_runs(["cx"])
for cx_run in cx_runs:
# Partition the cx_run into chunks with equal gate arguments
partition = []
chunk = []
for i in range(len(cx_run) - 1):
chunk.append(cx_run[i])
qargs0 = cx_run[i].qargs
qargs1 = cx_run[i + 1].qargs
if qargs0 != qargs1:
partition.append(chunk)
chunk = []
chunk.append(cx_run[-1])
| python | {
"resource": ""
} |
q268536 | BaseProvider.get_backend | test | def get_backend(self, name=None, **kwargs):
"""Return a single backend matching the specified filtering.
Args:
name (str): name of the backend.
**kwargs (dict): dict used for filtering.
Returns:
BaseBackend: a backend matching the filtering.
Raises:
QiskitBackendNotFoundError: if no backend could be found or
more than one backend matches.
"""
backends = self.backends(name, **kwargs)
| python | {
"resource": ""
} |
q268537 | Choi._bipartite_shape | test | def _bipartite_shape(self):
"""Return the shape for bipartite matrix"""
return | python | {
"resource": ""
} |
q268538 | _get_register_specs | test | def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
| python | {
"resource": ""
} |
q268539 | _truncate_float | test | def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
| python | {
"resource": ""
} |
q268540 | QCircuitImage.latex | test | def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
| python | {
"resource": ""
} |
q268541 | QCircuitImage._get_image_depth | test | def _get_image_depth(self):
"""Get depth information for the circuit.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
"""
max_column_widths = []
for layer in self.ops:
# store the max width for the layer
current_max = 0
for op in layer:
# update current op width
arg_str_len = 0
# the wide gates
for arg in op.op.params:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, str(arg))
arg_str_len += len(arg_str)
# the width of the column is the max of all the gates in the column
current_max = max(arg_str_len, current_max)
max_column_widths.append(current_max)
# wires in the beginning and end
| python | {
"resource": ""
} |
q268542 | QCircuitImage._get_beamer_page | test | def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5 | python | {
"resource": ""
} |
q268543 | _load_schema | test | def _load_schema(file_path, name=None):
"""Loads the QObj schema for use in future validations.
Caches schema in _SCHEMAS module attribute.
Args:
file_path(str): Path to schema.
name(str): Given name for schema. Defaults to file_path filename
| python | {
"resource": ""
} |
q268544 | _get_validator | test | def _get_validator(name, schema=None, check_schema=True,
validator_class=None, **validator_kwargs):
"""Generate validator for JSON schema.
Args:
name (str): Name for validator. Will be validator key in
`_VALIDATORS` dict.
schema (dict): JSON schema `dict`. If not provided searches for schema
in `_SCHEMAS`.
check_schema (bool): Verify schema is valid.
validator_class (jsonschema.IValidator): jsonschema IValidator instance.
Default behavior is to determine this from the schema `$schema`
field.
**validator_kwargs (dict): Additional keyword arguments for validator.
Return:
jsonschema.IValidator: Validator for JSON schema.
Raises:
SchemaValidationError: Raised if validation fails.
"""
if schema is None:
try:
schema = _SCHEMAS[name]
except KeyError:
raise SchemaValidationError("Valid schema name or schema must "
| python | {
"resource": ""
} |
q268545 | _load_schemas_and_validators | test | def _load_schemas_and_validators():
"""Load all default schemas into `_SCHEMAS`."""
schema_base_path = os.path.join(os.path.dirname(__file__), '../..')
for name, path in | python | {
"resource": ""
} |
q268546 | validate_json_against_schema | test | def validate_json_against_schema(json_dict, schema,
err_msg=None):
"""Validates JSON dict against a schema.
Args:
json_dict (dict): JSON to be validated.
schema (dict or str): JSON schema dictionary or the name of one of the
standards schemas in Qiskit to validate against it. The list of
standard schemas is: ``backend_configuration``,
``backend_properties``, ``backend_status``,
``default_pulse_configuration``, ``job_status``, ``qobj``,
``result``.
err_msg (str): Optional error message.
Raises:
SchemaValidationError: Raised if validation fails.
"""
try:
if isinstance(schema, str):
schema_name = schema
schema = _SCHEMAS[schema_name]
validator = _get_validator(schema_name)
validator.validate(json_dict)
else:
| python | {
"resource": ""
} |
q268547 | _format_causes | test | def _format_causes(err, level=0):
"""Return a cascading explanation of the validation error.
Returns a cascading explanation of the validation error in the form of::
<validator> failed @ <subfield_path> because of:
<validator> failed @ <subfield_path> because of:
...
<validator> failed @ <subfield_path> because of:
...
...
For example::
'oneOf' failed @ '<root>' because of:
'required' failed @ '<root>.config' because of:
'meas_level' is a required property
Meaning the validator 'oneOf' failed while validating the whole object
because of the validator 'required' failing while validating the property
'config' because its 'meas_level' field is missing.
The cascade repeats the format "<validator> failed @ <path> because of"
until there are no deeper causes. In this case, the string representation
of the error is shown.
Args:
err (jsonschema.ValidationError): the instance to explain.
level (int): starting level of indentation for the cascade of
explanations.
Return:
str: a formatted string with the explanation of the error.
"""
lines = []
def _print(string, offset=0):
lines.append(_pad(string, offset=offset))
def _pad(string, offset=0):
| python | {
"resource": ""
} |
q268548 | majority | test | def majority(p, a, b, c):
"""Majority gate."""
p.cx(c, b)
| python | {
"resource": ""
} |
q268549 | unmajority | test | def unmajority(p, a, b, c):
"""Unmajority | python | {
"resource": ""
} |
q268550 | _generate_latex_source | test | def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True, justify=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
str: Latex string appropriate for writing to file.
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
| python | {
"resource": ""
} |
q268551 | _matplotlib_circuit_drawer | test | def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
matplotlib.figure: | python | {
"resource": ""
} |
q268552 | random_unitary | test | def random_unitary(dim, seed=None):
"""
Return a random dim x dim unitary Operator from the Haar measure.
Args:
dim (int): the dim of the state space.
seed (int): Optional. To set a random seed.
Returns:
Operator: (dim, dim) unitary operator.
Raises:
QiskitError: if dim is not a positive power of 2.
"""
if dim == 0 or not math.log2(dim).is_integer():
raise QiskitError("Desired unitary dimension not a positive power of 2.")
matrix = np.zeros([dim, dim], dtype=complex)
for j in range(dim):
if j == 0:
a = random_state(dim, seed)
else:
| python | {
"resource": ""
} |
q268553 | random_density_matrix | test | def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None):
"""
Generate a random density matrix rho.
Args:
length (int): the length of the density matrix.
rank (int or None): the rank of the density matrix. The default
value is full-rank.
method (string): the method to use.
'Hilbert-Schmidt': sample rho from the Hilbert-Schmidt metric.
'Bures': sample rho from the Bures metric.
seed (int): Optional. To set a random seed.
Returns:
ndarray: rho (length, length) a density matrix.
Raises:
| python | {
"resource": ""
} |
q268554 | __ginibre_matrix | test | def __ginibre_matrix(nrow, ncol=None, seed=None):
"""
Return a normally distributed complex random matrix.
Args:
nrow (int): number of rows in output matrix.
ncol (int): number of columns in output matrix.
seed (int): Optional. To set a random seed.
Returns:
ndarray: A complex rectangular matrix where each real and imaginary
| python | {
"resource": ""
} |
q268555 | __random_density_hs | test | def __random_density_hs(N, rank=None, seed=None):
"""
Generate a random density matrix from the Hilbert-Schmidt metric.
Args:
N (int): the length of the density matrix.
rank (int or None): the rank of the density matrix. The default
value is full-rank.
seed (int): | python | {
"resource": ""
} |
q268556 | __random_density_bures | test | def __random_density_bures(N, rank=None, seed=None):
"""
Generate a random density matrix from the Bures metric.
Args:
N (int): the length of the density matrix.
rank (int or None): the rank of the density matrix. The default
value is full-rank.
seed (int): Optional. To set a random | python | {
"resource": ""
} |
q268557 | GateBody.calls | test | def calls(self):
"""Return a list of custom gate names in this gate body."""
lst = []
for children in self.children:
| python | {
"resource": ""
} |
q268558 | SuperOp.power | test | def power(self, n):
"""Return the compose of a QuantumChannel with itself n times.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
SuperOp: the n-times composition channel as a SuperOp object.
Raises:
QiskitError: if the input and output dimensions of the
QuantumChannel are not equal, or the power is not an integer.
"""
if not isinstance(n, (int, np.integer)):
raise QiskitError("Can only power with integer powers.")
if self._input_dim != self._output_dim:
| python | {
"resource": ""
} |
q268559 | SuperOp._compose_subsystem | test | def _compose_subsystem(self, other, qargs, front=False):
"""Return the composition channel."""
# Compute tensor contraction indices from qargs
input_dims = list(self.input_dims())
output_dims = list(self.output_dims())
if front:
num_indices = len(self.input_dims())
shift = 2 * len(self.output_dims())
right_mul = True
for pos, qubit in enumerate(qargs):
input_dims[qubit] = other._input_dims[pos]
else:
num_indices = len(self.output_dims())
shift = 0
right_mul = False | python | {
"resource": ""
} |
q268560 | SuperOp._instruction_to_superop | test | def _instruction_to_superop(cls, instruction):
"""Convert a QuantumCircuit or Instruction to a SuperOp."""
# Convert circuit to an instruction
if isinstance(instruction, QuantumCircuit):
| python | {
"resource": ""
} |
q268561 | BarrierBeforeFinalMeasurements.run | test | def run(self, dag):
"""Return a circuit with a barrier before last measurements."""
# Collect DAG nodes which are followed only by barriers or other measures.
final_op_types = ['measure', 'barrier']
final_ops = []
for candidate_node in dag.named_nodes(*final_op_types):
is_final_op = True
for _, child_successors in dag.bfs_successors(candidate_node):
if any(suc.type == 'op' and suc.name not in final_op_types
for suc in child_successors):
is_final_op = False
break
if is_final_op:
final_ops.append(candidate_node)
if not final_ops:
return dag
# Create a layer with the barrier and add registers from the original dag.
barrier_layer = DAGCircuit()
for qreg in dag.qregs.values():
barrier_layer.add_qreg(qreg)
for creg in dag.cregs.values():
barrier_layer.add_creg(creg)
final_qubits = set(final_op.qargs[0] for final_op in final_ops)
barrier_layer.apply_operation_back(
Barrier(len(final_qubits)), list(final_qubits), [])
# Preserve order of final ops collected earlier from the original DAG.
ordered_final_nodes = [node for node in dag.topological_op_nodes()
| python | {
"resource": ""
} |
q268562 | circuits_to_qobj | test | def circuits_to_qobj(circuits, qobj_header=None,
qobj_id=None, backend_name=None,
config=None, shots=None, max_credits=None,
basis_gates=None,
coupling_map=None, seed=None, memory=None):
"""Convert a list of circuits into a qobj.
Args:
circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile
qobj_header (QobjHeader): header to pass to the results
qobj_id (int): TODO: delete after qiskit-terra 0.8
backend_name (str): TODO: delete after qiskit-terra 0.8
config (dict): TODO: delete after qiskit-terra 0.8
shots (int): TODO: delete after qiskit-terra 0.8
max_credits (int): TODO: delete after qiskit-terra 0.8
basis_gates (str): TODO: delete after qiskit-terra 0.8
coupling_map (list): TODO: delete after qiskit-terra 0.8
seed (int): TODO: delete after qiskit-terra 0.8
memory (bool): TODO: delete after qiskit-terra 0.8
Returns:
Qobj: the Qobj to be run on the backends
"""
warnings.warn('circuits_to_qobj is deprecated and will be removed in Qiskit Terra 0.9. '
'Use qiskit.compiler.assemble() to serialize circuits into a qobj.',
DeprecationWarning)
qobj_header | python | {
"resource": ""
} |
q268563 | Unroll3qOrMore.run | test | def run(self, dag):
"""Expand 3+ qubit gates using their decomposition rules.
Args:
dag(DAGCircuit): input dag
Returns:
DAGCircuit: output dag with maximum node degrees of 2
Raises:
QiskitError: if a 3q+ gate is not decomposable
"""
for node in dag.threeQ_or_more_gates():
# TODO: allow choosing other possible decompositions
rule = node.op.definition
if not rule:
raise QiskitError("Cannot unroll all 3q or more gates. "
"No rule to expand instruction %s." %
node.op.name)
# hacky way to build a dag on the same register as the rule is defined
| python | {
"resource": ""
} |
q268564 | Decompose.run | test | def run(self, dag):
"""Expand a given gate into its decomposition.
Args:
dag(DAGCircuit): input dag
Returns:
DAGCircuit: output dag where gate was expanded.
"""
# Walk through the DAG and expand each non-basis node
for node in dag.op_nodes(self.gate):
# opaque or built-in gates are not decomposable
if not node.op.definition:
continue
# TODO: allow choosing among multiple decomposition rules
rule = node.op.definition
# hacky way to build a dag on the | python | {
"resource": ""
} |
q268565 | UnitaryGate._define | test | def _define(self):
"""Calculate a subcircuit that implements this unitary."""
if self.num_qubits == 1:
q = QuantumRegister(1, "q")
angles = euler_angles_1q(self.to_matrix())
| python | {
"resource": ""
} |
q268566 | Nested.check_type | test | def check_type(self, value, attr, data):
"""Validate if the value is of the type of the schema's model.
Assumes the nested schema is a ``BaseSchema``.
"""
if self.many and not is_collection(value):
raise self._not_expected_type(
value, Iterable, fields=[self], field_names=attr, data=data)
_check_type = super().check_type
errors = []
values = value if self.many else [value]
for idx, v in enumerate(values):
try:
| python | {
"resource": ""
} |
q268567 | List.check_type | test | def check_type(self, value, attr, data):
"""Validate if it's a list of valid item-field values.
Check if each element in the list can be validated by the item-field
passed during construction.
"""
| python | {
"resource": ""
} |
q268568 | BaseOperator._atol | test | def _atol(self, atol):
"""Set the absolute tolerence parameter for float comparisons."""
# NOTE: that this overrides the class value so applies to all
# instances of the class.
max_tol = self.__class__.MAX_TOL
if atol < 0:
raise | python | {
"resource": ""
} |
q268569 | BaseOperator._rtol | test | def _rtol(self, rtol):
"""Set the relative tolerence parameter for float comparisons."""
# NOTE: that this overrides the class value so applies to all
# instances of the class.
max_tol = self.__class__.MAX_TOL
if rtol < 0:
raise | python | {
"resource": ""
} |
q268570 | BaseOperator._reshape | test | def _reshape(self, input_dims=None, output_dims=None):
"""Reshape input and output dimensions of operator.
Arg:
input_dims (tuple): new subsystem input dimensions.
output_dims (tuple): new subsystem output dimensions.
Returns:
Operator: returns self with reshaped input and output dimensions.
Raises:
QiskitError: if combined size of all subsystem input dimension or
| python | {
"resource": ""
} |
q268571 | BaseOperator.input_dims | test | def input_dims(self, qargs=None):
"""Return tuple of input dimension for specified subsystems."""
if qargs is None:
| python | {
"resource": ""
} |
q268572 | BaseOperator.output_dims | test | def output_dims(self, qargs=None):
"""Return tuple of output dimension for specified subsystems."""
if qargs is None:
| python | {
"resource": ""
} |
q268573 | BaseOperator.copy | test | def copy(self):
"""Make a copy of current operator."""
# pylint: disable=no-value-for-parameter
# The constructor of subclasses from raw data should be | python | {
"resource": ""
} |
q268574 | BaseOperator.power | test | def power(self, n):
"""Return the compose of a operator with itself n times.
Args:
n (int): the number of times to compose with self (n>0).
Returns:
BaseOperator: the n-times composed operator.
Raises:
QiskitError: if the input and output dimensions of the operator
are not equal, or the power is not a positive integer.
"""
# NOTE: if a subclass can have negative or non-integer powers
# this method should be overriden in that class.
if not isinstance(n, (int, np.integer)) or n < 1:
| python | {
"resource": ""
} |
q268575 | BaseOperator._automatic_dims | test | def _automatic_dims(cls, dims, size):
"""Check if input dimension corresponds to qubit subsystems."""
if dims is None:
dims = size
elif np.product(dims) != size:
raise QiskitError("dimensions do not match size.")
if isinstance(dims, (int, np.integer)):
| python | {
"resource": ""
} |
q268576 | BaseOperator._einsum_matmul | test | def _einsum_matmul(cls, tensor, mat, indices, shift=0, right_mul=False):
"""Perform a contraction using Numpy.einsum
Args:
tensor (np.array): a vector or matrix reshaped to a rank-N tensor.
mat (np.array): a matrix reshaped to a rank-2M tensor.
indices (list): tensor indices to contract with mat.
shift (int): shift for indicies of tensor to contract [Default: 0].
right_mul (bool): if True right multiply tensor by mat
(else left multiply) [Default: False].
Returns:
Numpy.ndarray: the matrix multiplied rank-N tensor.
Raises:
QiskitError: if mat is not an even rank tensor.
"""
rank = tensor.ndim
rank_mat = mat.ndim
if rank_mat % 2 != 0:
raise QiskitError(
"Contracted matrix must have an even number of indices.")
# Get einsum indices for tensor
| python | {
"resource": ""
} |
q268577 | BasePolyField._deserialize | test | def _deserialize(self, value, attr, data):
"""Override ``_deserialize`` for customizing the exception raised."""
try:
return super()._deserialize(value, attr, data)
except ValidationError as ex:
| python | {
"resource": ""
} |
q268578 | BasePolyField._serialize | test | def _serialize(self, value, key, obj):
"""Override ``_serialize`` for customizing the exception raised."""
try:
return super()._serialize(value, key, obj)
except TypeError as ex:
| python | {
"resource": ""
} |
q268579 | ByType.check_type | test | def check_type(self, value, attr, data):
"""Check if at least one of the possible choices validates the value.
Possible choices are assumed to be ``ModelTypeValidator`` fields.
"""
for field in self.choices:
if isinstance(field, ModelTypeValidator):
try:
return field.check_type(value, attr, data)
except ValidationError: | python | {
"resource": ""
} |
q268580 | state_fidelity | test | def state_fidelity(state1, state2):
"""Return the state fidelity between two quantum states.
Either input may be a state vector, or a density matrix. The state
fidelity (F) for two density matrices is defined as::
F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2
For a pure state and mixed state the fidelity is given by::
F(|psi1>, rho2) = <psi1|rho2|psi1>
For two pure states the fidelity is given by::
F(|psi1>, |psi2>) = |<psi1|psi2>|^2
Args:
state1 (array_like): a quantum state vector or density matrix.
state2 (array_like): a quantum state vector or density matrix.
Returns:
array_like: The state fidelity F(state1, state2).
"""
# convert input to numpy arrays
s1 = np.array(state1)
s2 = np.array(state2)
| python | {
"resource": ""
} |
q268581 | _funm_svd | test | def _funm_svd(a, func):
"""Apply real scalar function to singular values of a matrix.
Args:
a (array_like): (N, N) Matrix at which to evaluate the function.
func (callable): Callable object | python | {
"resource": ""
} |
q268582 | Snapshot.inverse | test | def inverse(self):
"""Special case. Return self."""
return Snapshot(self.num_qubits, self.num_clbits, | python | {
"resource": ""
} |
q268583 | Snapshot.label | test | def label(self, name):
"""Set snapshot label to name
Args:
name (str or None): label to assign unitary
Raises:
TypeError: name is not string or None.
"""
| python | {
"resource": ""
} |
q268584 | QuantumChannel.is_unitary | test | def is_unitary(self, atol=None, rtol=None):
"""Return True if QuantumChannel is a unitary channel."""
try:
op = self.to_operator()
| python | {
"resource": ""
} |
q268585 | QuantumChannel.to_operator | test | def to_operator(self):
"""Try to convert channel to a unitary representation Operator."""
mat | python | {
"resource": ""
} |
q268586 | QuantumChannel.to_instruction | test | def to_instruction(self):
"""Convert to a Kraus or UnitaryGate circuit instruction.
If the channel is unitary it will be added as a unitary gate,
otherwise it will be added as a kraus simulator instruction.
Returns:
Instruction: A kraus instruction for the channel.
Raises:
QiskitError: if input data is not an N-qubit CPTP quantum channel.
"""
from qiskit.circuit.instruction import Instruction
# Check if input is an N-qubit CPTP channel.
n_qubits = int(np.log2(self._input_dim))
if self._input_dim != self._output_dim or 2**n_qubits != self._input_dim:
raise QiskitError(
'Cannot convert QuantumChannel to Instruction: channel is not an N-qubit channel.'
)
if not self.is_cptp():
raise QiskitError(
'Cannot convert QuantumChannel to Instruction: channel is not CPTP.'
)
# Next we convert to the Kraus representation. Since channel is CPTP we know
| python | {
"resource": ""
} |
q268587 | QuantumChannel._init_transformer | test | def _init_transformer(cls, data):
"""Convert input into a QuantumChannel subclass object or Operator object"""
# This handles common conversion for all QuantumChannel subclasses.
# If the input is already a QuantumChannel subclass it will return
# the original object
if isinstance(data, QuantumChannel):
return data
if hasattr(data, 'to_quantumchannel'):
# If the data object is not a QuantumChannel it will give
# preference to a 'to_quantumchannel' attribute that allows
| python | {
"resource": ""
} |
q268588 | sort_enum_for_model | test | def sort_enum_for_model(cls, name=None, symbol_name=_symbol_name):
"""Create Graphene Enum for sorting a SQLAlchemy class query
Parameters
- cls : Sqlalchemy model class
Model used to create the sort enumerator
- name : str, optional, default None
Name to use for the enumerator. If not provided it will be set to `cls.__name__ + 'SortEnum'`
- symbol_name : function, optional, default `_symbol_name`
Function which takes the column name and a boolean indicating if the sort direction | python | {
"resource": ""
} |
q268589 | patch_strptime | test | def patch_strptime():
"""Monkey patching _strptime to avoid problems related with non-english
locale changes on the system.
For example, if system's locale is set to fr_FR. Parser won't recognize
any date since all languages are translated to english dates.
"""
_strptime = imp.load_module(
'strptime_patched', *imp.find_module('_strptime')
)
_calendar = imp.load_module(
'calendar_patched', *imp.find_module('_strptime')
)
_strptime._getlang = lambda: ('en_US', 'UTF-8')
_strptime.calendar = _calendar
_strptime.calendar.day_abbr = [
'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'
]
_strptime.calendar.day_name = [
'monday', 'tuesday', 'wednesday', 'thursday',
| python | {
"resource": ""
} |
q268590 | LocaleDataLoader.get_locale_map | test | def get_locale_map(self, languages=None, locales=None, region=None,
use_given_order=False, allow_conflicting_locales=False):
"""
Get an ordered mapping with locale codes as keys
and corresponding locale instances as values.
:param languages:
A list of language codes, e.g. ['en', 'es', 'zh-Hant'].
If locales are not given, languages and region are
used to construct locales to load.
:type languages: list
:param locales:
A list of codes of locales which are to be loaded,
e.g. ['fr-PF', 'qu-EC', 'af-NA']
:type locales: list
:param region:
A region code, e.g. 'IN', '001', 'NE'.
If locales are not given, languages and region are
used to construct locales to load.
:type region: str|unicode
:param use_given_order:
If True, the returned mapping is ordered in the order locales are given.
:type allow_redetect_language: bool
| python | {
"resource": ""
} |
q268591 | LocaleDataLoader.get_locales | test | def get_locales(self, languages=None, locales=None, region=None,
use_given_order=False, allow_conflicting_locales=False):
"""
Yield locale instances.
:param languages:
A list of language codes, e.g. ['en', 'es', 'zh-Hant'].
If locales are not given, languages and region are
used to construct locales to load.
:type languages: list
:param locales:
A list of codes of locales which are to be loaded,
e.g. ['fr-PF', 'qu-EC', 'af-NA']
:type locales: list
| python | {
"resource": ""
} |
q268592 | Dictionary.are_tokens_valid | test | def are_tokens_valid(self, tokens):
"""
Check if tokens are valid tokens for the locale.
:param tokens:
a list of string or unicode tokens.
:type tokens: list
:return: True if tokens are valid, False otherwise.
"""
match_relative_regex = self._get_match_relative_regex_cache()
for token in tokens:
| python | {
"resource": ""
} |
q268593 | Dictionary.split | test | def split(self, string, keep_formatting=False):
"""
Split the date string using translations in locale info.
:param string:
Date string to be splitted.
:type string:
str|unicode
:param keep_formatting:
If True, retain formatting of the date string.
:type keep_formatting: bool
:return: A list of string tokens formed after splitting the date string.
"""
if not string:
return string
split_relative_regex = self._get_split_relative_regex_cache()
match_relative_regex = self._get_match_relative_regex_cache()
| python | {
"resource": ""
} |
q268594 | parse | test | def parse(date_string, date_formats=None, languages=None, locales=None, region=None, settings=None):
"""Parse date and time from given date string.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:param date_formats:
A list of format strings using directives as given
`here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_.
The parser applies formats one by one, taking into account the detected languages/locales.
:type date_formats: list
:param languages:
A list of language codes, e.g. ['en', 'es', 'zh-Hant'].
If locales are not given, languages and region are used to construct locales for translation.
| python | {
"resource": ""
} |
q268595 | FreshnessDateDataParser._parse_time | test | def _parse_time(self, date_string, settings):
"""Attemps to parse time part of date strings like '1 day ago, 2 PM' """
date_string = PATTERN.sub('', date_string)
date_string = re.sub(r'\b(?:ago|in)\b', '', | python | {
"resource": ""
} |
q268596 | Locale.is_applicable | test | def is_applicable(self, date_string, strip_timezone=False, settings=None):
"""
Check if the locale is applicable to translate date string.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:param strip_timezone:
If True, timezone is stripped from date string.
:type strip_timezone: bool
:return: boolean value representing if the locale is applicable for the date string or not.
"""
if strip_timezone:
date_string, _ = pop_tz_offset_from_string(date_string, as_offset=False)
date_string = self._translate_numerals(date_string) | python | {
"resource": ""
} |
q268597 | Locale.translate | test | def translate(self, date_string, keep_formatting=False, settings=None):
"""
Translate the date string to its English equivalent.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:param keep_formatting:
If True, retain formatting of the date string after translation.
:type keep_formatting: bool
:return: translated date string.
"""
date_string = self._translate_numerals(date_string)
if settings.NORMALIZE:
date_string = normalize_unicode(date_string)
date_string = self._simplify(date_string, settings=settings)
dictionary = self._get_dictionary(settings)
date_string_tokens = dictionary.split(date_string, keep_formatting)
relative_translations = self._get_relative_translations(settings=settings)
for i, word in enumerate(date_string_tokens):
| python | {
"resource": ""
} |
q268598 | parse_with_formats | test | def parse_with_formats(date_string, date_formats, settings):
""" Parse with formats and return a dictionary with 'period' and 'obj_date'.
:returns: :class:`datetime.datetime`, dict or None
"""
period = 'day'
for date_format in date_formats:
try:
date_obj = datetime.strptime(date_string, date_format)
except ValueError:
continue
else:
# If format does not include the day, use last day of the month
# instead of first, because the first is usually out of range.
if '%d' not in date_format:
period = 'month'
| python | {
"resource": ""
} |
q268599 | ComponentFactory.get_ammo_generator | test | def get_ammo_generator(self):
"""
return ammo generator
"""
af_readers = {
'phantom': missile.AmmoFileReader,
'slowlog': missile.SlowLogReader,
'line': missile.LineReader,
'uri': missile.UriReader,
'uripost': missile.UriPostReader,
'access': missile.AccessLogReader,
'caseline': missile.CaseLineReader,
}
if self.uris and self.ammo_file:
raise StepperConfigurationError(
'Both uris and ammo file specified. You must specify only one of them'
)
elif self.uris:
ammo_gen = missile.UriStyleGenerator(
self.uris, self.headers, http_ver=self.http_ver)
elif self.ammo_file:
if self.ammo_type in af_readers:
if self.ammo_type == 'phantom':
opener = resource.get_opener(self.ammo_file)
with opener(self.use_cache) as ammo:
try:
if not ammo.next()[0].isdigit():
self.ammo_type = 'uri'
self.log.info(
"Setting ammo_type 'uri' because ammo is not started with digit and you did not specify ammo format"
)
else:
self.log.info(
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.