INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Check to see if there exists a rational number r = p/q
in reduced form for which the difference between element/np.pi
and r is small and q <= 8.
:param element: float
:return element: pretty print string if true, else standard representation. | def _check_for_pi(element):
"""
Check to see if there exists a rational number r = p/q
in reduced form for which the difference between element/np.pi
and r is small and q <= 8.
:param element: float
:return element: pretty print string if true, else standard representation.
"""
frac = F... |
Add generic damping and dephasing noise to a program.
.. warning::
This function is deprecated. Please use :py:func:`add_decoherence_noise` instead.
:param prog: A pyquil program consisting of I, RZ, CZ, and RX(+-pi/2) instructions
:param Union[Dict[int,float],float] T1: The T1 amplitude damping ... | def add_noise_to_program(prog, T1=30e-6, T2=30e-6, gate_time_1q=50e-9, gate_time_2q=150e-09,
ro_fidelity=0.95):
"""
Add generic damping and dephasing noise to a program.
.. warning::
This function is deprecated. Please use :py:func:`add_decoherence_noise` instead.
:pa... |
All bitstrings in lexicographical order as a 2d np.ndarray.
This should be the same as ``np.array(list(itertools.product([0,1], repeat=n_bits)))``
but faster. | def all_bitstrings(n_bits):
"""All bitstrings in lexicographical order as a 2d np.ndarray.
This should be the same as ``np.array(list(itertools.product([0,1], repeat=n_bits)))``
but faster.
"""
n_bitstrings = 2 ** n_bits
out = np.zeros(shape=(n_bitstrings, n_bits), dtype=np.int8)
tf = np.a... |
Lifts input k-qubit gate on adjacent qubits starting from qubit i
to complete Hilbert space of dimension 2 ** num_qubits.
Ex: 1-qubit gate, lifts from qubit i
Ex: 2-qubit gate, lifts from qubits (i+1, i)
Ex: 3-qubit gate, lifts from qubits (i+2, i+1, i), operating in that order
In general, this ta... | def qubit_adjacent_lifted_gate(i, matrix, n_qubits):
"""
Lifts input k-qubit gate on adjacent qubits starting from qubit i
to complete Hilbert space of dimension 2 ** num_qubits.
Ex: 1-qubit gate, lifts from qubit i
Ex: 2-qubit gate, lifts from qubits (i+1, i)
Ex: 3-qubit gate, lifts from qubit... |
Generate the permutation matrix that permutes two single-particle Hilbert
spaces into adjacent positions.
ALWAYS swaps j TO k. Recall that Hilbert spaces are ordered in decreasing
qubit index order. Hence, j > k implies that j is to the left of k.
End results:
j == k: nothing happens
j... | def two_swap_helper(j, k, num_qubits, qubit_map):
"""
Generate the permutation matrix that permutes two single-particle Hilbert
spaces into adjacent positions.
ALWAYS swaps j TO k. Recall that Hilbert spaces are ordered in decreasing
qubit index order. Hence, j > k implies that j is to the left of ... |
Lift a unitary matrix to act on the specified qubits in a full ``n_qubits``-qubit
Hilbert space.
For 1-qubit gates, this is easy and can be achieved with appropriate kronning of identity
matrices. For 2-qubit gates acting on adjacent qubit indices, it is also easy. However,
for a multiqubit gate acting... | def lifted_gate_matrix(matrix: np.ndarray, qubit_inds: List[int], n_qubits: int):
"""
Lift a unitary matrix to act on the specified qubits in a full ``n_qubits``-qubit
Hilbert space.
For 1-qubit gates, this is easy and can be achieved with appropriate kronning of identity
matrices. For 2-qubit gate... |
Lift a pyquil :py:class:`Gate` in a full ``n_qubits``-qubit Hilbert space.
This function looks up the matrix form of the gate and then dispatches to
:py:func:`lifted_gate_matrix` with the target qubits.
:param gate: A gate
:param n_qubits: The total number of qubits.
:return: A 2^n by 2^n lifted v... | def lifted_gate(gate: Gate, n_qubits: int):
"""
Lift a pyquil :py:class:`Gate` in a full ``n_qubits``-qubit Hilbert space.
This function looks up the matrix form of the gate and then dispatches to
:py:func:`lifted_gate_matrix` with the target qubits.
:param gate: A gate
:param n_qubits: The to... |
Return the unitary of a pyQuil program.
:param program: A program consisting only of :py:class:`Gate`.:
:return: a unitary corresponding to the composition of the program's gates. | def program_unitary(program, n_qubits):
"""
Return the unitary of a pyQuil program.
:param program: A program consisting only of :py:class:`Gate`.:
:return: a unitary corresponding to the composition of the program's gates.
"""
umat = np.eye(2 ** n_qubits)
for instruction in program:
... |
Takes a PauliSum object along with a list of
qubits and returns a matrix corresponding the tensor representation of the
object.
Useful for generating the full Hamiltonian after a particular fermion to
pauli transformation. For example:
Converting a PauliSum X0Y1 + Y1X0 into the matrix
.. code... | def lifted_pauli(pauli_sum: Union[PauliSum, PauliTerm], qubits: List[int]):
"""
Takes a PauliSum object along with a list of
qubits and returns a matrix corresponding the tensor representation of the
object.
Useful for generating the full Hamiltonian after a particular fermion to
pauli transfor... |
Takes a PauliSum object along with a list of
qubits and returns a matrix corresponding the tensor representation of the
object.
This is the same as :py:func:`lifted_pauli`. Nick R originally wrote this functionality
and really likes the name ``tensor_up``. Who can blame him?
:param pauli_sum: Paul... | def tensor_up(pauli_sum: Union[PauliSum, PauliTerm], qubits: List[int]):
"""
Takes a PauliSum object along with a list of
qubits and returns a matrix corresponding the tensor representation of the
object.
This is the same as :py:func:`lifted_pauli`. Nick R originally wrote this functionality
an... |
Take a TensorProductState along with a list of qubits and return a matrix
corresponding to the tensored-up representation of the states' density operator form.
Developer note: Quil and the QVM like qubits to be ordered such that qubit 0 is on the right.
Therefore, in ``qubit_adjacent_lifted_gate``, ``lifte... | def lifted_state_operator(state: TensorProductState, qubits: List[int]):
"""Take a TensorProductState along with a list of qubits and return a matrix
corresponding to the tensored-up representation of the states' density operator form.
Developer note: Quil and the QVM like qubits to be ordered such that qu... |
Create an abbreviated string representation of a Program.
This will join all instructions onto a single line joined by '; '. If the number of
instructions exceeds ``max_len``, some will be excluded from the string representation. | def _abbrev_program(program: Program, max_len=10):
"""Create an abbreviated string representation of a Program.
This will join all instructions onto a single line joined by '; '. If the number of
instructions exceeds ``max_len``, some will be excluded from the string representation.
"""
program_lin... |
Convenience method to save pyquil.operator_estimation objects as a JSON file.
See :py:func:`read_json`. | def to_json(fn, obj):
"""Convenience method to save pyquil.operator_estimation objects as a JSON file.
See :py:func:`read_json`.
"""
with open(fn, 'w') as f:
json.dump(obj, f, cls=OperatorEncoder, indent=2, ensure_ascii=False)
return fn |
Convenience method to read pyquil.operator_estimation objects from a JSON file.
See :py:func:`to_json`. | def read_json(fn):
"""Convenience method to read pyquil.operator_estimation objects from a JSON file.
See :py:func:`to_json`.
"""
with open(fn) as f:
return json.load(f, object_hook=_operator_object_hook) |
Prepare the index-th SIC basis state. | def _one_q_sic_prep(index, qubit):
"""Prepare the index-th SIC basis state."""
if index == 0:
return Program()
theta = 2 * np.arccos(1 / np.sqrt(3))
zx_plane_rotation = Program([
RX(-pi / 2, qubit),
RZ(theta - pi, qubit),
RX(-pi / 2, qubit),
])
if index == 1:
... |
Prepare the index-th eigenstate of the pauli operator given by label. | def _one_q_pauli_prep(label, index, qubit):
"""Prepare the index-th eigenstate of the pauli operator given by label."""
if index not in [0, 1]:
raise ValueError(f'Bad Pauli index: {index}')
if label == 'X':
if index == 0:
return Program(RY(pi / 2, qubit))
else:
... |
Prepare a one qubit state.
Either SIC[0-3], X[0-1], Y[0-1], or Z[0-1]. | def _one_q_state_prep(oneq_state: _OneQState):
"""Prepare a one qubit state.
Either SIC[0-3], X[0-1], Y[0-1], or Z[0-1].
"""
label = oneq_state.label
if label == 'SIC':
return _one_q_sic_prep(oneq_state.index, oneq_state.qubit)
elif label in ['X', 'Y', 'Z']:
return _one_q_pauli_... |
Generate gate sequence to measure in the eigenbasis of a Pauli operator, assuming
we are only able to measure in the Z eigenbasis. (Note: The unitary operations of this
Program are essentially the Hermitian conjugates of those in :py:func:`_one_q_pauli_prep`) | def _local_pauli_eig_meas(op, idx):
"""
Generate gate sequence to measure in the eigenbasis of a Pauli operator, assuming
we are only able to measure in the Z eigenbasis. (Note: The unitary operations of this
Program are essentially the Hermitian conjugates of those in :py:func:`_one_q_pauli_prep`)
... |
Construct a graph where an edge signifies two experiments are diagonal in a TPB. | def construct_tpb_graph(experiments: TomographyExperiment):
"""
Construct a graph where an edge signifies two experiments are diagonal in a TPB.
"""
g = nx.Graph()
for expt in experiments:
assert len(expt) == 1, 'already grouped?'
expt = expt[0]
if expt not in g:
... |
Group experiments that are diagonal in a shared tensor product basis (TPB) to minimize number
of QPU runs, using a graph clique removal algorithm.
:param experiments: a tomography experiment
:return: a tomography experiment with all the same settings, just grouped according to shared
TPBs. | def group_experiments_clique_removal(experiments: TomographyExperiment) -> TomographyExperiment:
"""
Group experiments that are diagonal in a shared tensor product basis (TPB) to minimize number
of QPU runs, using a graph clique removal algorithm.
:param experiments: a tomography experiment
:return... |
Construct a PauliTerm operator by taking the non-identity single-qubit operator at each
qubit position.
This function will return ``None`` if the input operators do not share a natural tensor
product basis.
For example, the max_weight_operator of ["XI", "IZ"] is "XZ". Asking for the max weight
ope... | def _max_weight_operator(ops: Iterable[PauliTerm]) -> Union[None, PauliTerm]:
"""Construct a PauliTerm operator by taking the non-identity single-qubit operator at each
qubit position.
This function will return ``None`` if the input operators do not share a natural tensor
product basis.
For exampl... |
Construct a TensorProductState by taking the single-qubit state at each
qubit position.
This function will return ``None`` if the input states are not compatible
For example, the max_weight_state of ["(+X, q0)", "(-Z, q1)"] is "(+X, q0; -Z q1)". Asking for
the max weight state of something like ["(+X,... | def _max_weight_state(states: Iterable[TensorProductState]) -> Union[None, TensorProductState]:
"""Construct a TensorProductState by taking the single-qubit state at each
qubit position.
This function will return ``None`` if the input states are not compatible
For example, the max_weight_state of ["(+... |
Given an input TomographyExperiment, provide a dictionary indicating which ExperimentSettings
share a tensor product basis
:param tomo_expt: TomographyExperiment, from which to group ExperimentSettings that share a tpb
and can be run together
:return: dictionary keyed with ExperimentSetting (specif... | def _max_tpb_overlap(tomo_expt: TomographyExperiment):
"""
Given an input TomographyExperiment, provide a dictionary indicating which ExperimentSettings
share a tensor product basis
:param tomo_expt: TomographyExperiment, from which to group ExperimentSettings that share a tpb
and can be run to... |
Greedy method to group ExperimentSettings in a given TomographyExperiment
:param tomo_expt: TomographyExperiment to group ExperimentSettings within
:return: TomographyExperiment, with grouped ExperimentSettings according to whether
it consists of PauliTerms diagonal in the same tensor product basis | def group_experiments_greedy(tomo_expt: TomographyExperiment):
"""
Greedy method to group ExperimentSettings in a given TomographyExperiment
:param tomo_expt: TomographyExperiment to group ExperimentSettings within
:return: TomographyExperiment, with grouped ExperimentSettings according to whether
... |
Group experiments that are diagonal in a shared tensor product basis (TPB) to minimize number
of QPU runs.
Background
----------
Given some PauliTerm operator, the 'natural' tensor product basis to
diagonalize this term is the one which diagonalizes each Pauli operator in the
product term-by-t... | def group_experiments(experiments: TomographyExperiment,
method: str = 'greedy') -> TomographyExperiment:
"""
Group experiments that are diagonal in a shared tensor product basis (TPB) to minimize number
of QPU runs.
Background
----------
Given some PauliTerm operator, th... |
Measure all the observables in a TomographyExperiment.
:param qc: A QuantumComputer which can run quantum programs
:param tomo_experiment: A suite of tomographic observables to measure
:param n_shots: The number of shots to take per ExperimentSetting
:param progress_callback: If not None, this function... | def measure_observables(qc: QuantumComputer, tomo_experiment: TomographyExperiment,
n_shots: int = 10000, progress_callback=None, active_reset=False,
symmetrize_readout: str = 'exhaustive',
calibrate_readout: str = 'plus-eig'):
"""
Measure ... |
:param ops_bool: tuple of booleans specifying the operation to be carried out on `qubits`
:param qubits: list specifying the qubits to be carried operations on
:return: Program with the operations specified in `ops_bool` on the qubits specified in
`qubits` | def _ops_bool_to_prog(ops_bool: Tuple[bool], qubits: List[int]) -> Program:
"""
:param ops_bool: tuple of booleans specifying the operation to be carried out on `qubits`
:param qubits: list specifying the qubits to be carried operations on
:return: Program with the operations specified in `ops_bool` on ... |
:param bs_results: results from running `qc.run`
:param qubit_index_map: dict mapping qubit to classical register index
:param setting: ExperimentSetting
:param n_shots: number of shots in the measurement process
:param coeff: coefficient of the operator being estimated
:return: tuple specifying (me... | def _stats_from_measurements(bs_results: np.ndarray, qubit_index_map: Dict,
setting: ExperimentSetting, n_shots: int,
coeff: float = 1.0) -> Tuple[float]:
"""
:param bs_results: results from running `qc.run`
:param qubit_index_map: dict mapping qubit... |
r"""
Given random variables 'A' and 'B', compute the variance on the ratio Y = A/B. Denote the
mean of the random variables as a = E[A] and b = E[B] while the variances are var_a = Var[A]
and var_b = Var[B] and the covariance as Cov[A,B]. The following expression approximates the
variance of Y
Var[... | def ratio_variance(a: Union[float, np.ndarray],
var_a: Union[float, np.ndarray],
b: Union[float, np.ndarray],
var_b: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
r"""
Given random variables 'A' and 'B', compute the variance on the ratio Y = A/B.... |
Perform exhaustive symmetrization
:param qc: A QuantumComputer which can run quantum programs
:param qubits: qubits on which the symmetrization program runs
:param shots: number of shots in the symmetrized program
:prog: program to symmetrize
:return: - the equivalent of a `run` output, but with ex... | def _exhaustive_symmetrization(qc: QuantumComputer, qubits: List[int],
shots: int, prog: Program) -> (np.ndarray, Dict):
"""
Perform exhaustive symmetrization
:param qc: A QuantumComputer which can run quantum programs
:param qubits: qubits on which the symmetrization pro... |
Program required for calibration in a tomography-like experiment.
:param tomo_experiment: A suite of tomographic observables
:param ExperimentSetting: The particular tomographic observable to measure
:param symmetrize_readout: Method used to symmetrize the readout errors (see docstring for
`measure... | def _calibration_program(qc: QuantumComputer, tomo_experiment: TomographyExperiment,
setting: ExperimentSetting) -> Program:
"""
Program required for calibration in a tomography-like experiment.
:param tomo_experiment: A suite of tomographic observables
:param ExperimentSetting... |
Get the value of the environment variable or config file value.
The environment variable takes precedence.
:param env: The environment variable name.
:param name: The config file key.
:return: The value or None if not found | def _env_or_config_or_default(self, env=None, file=None, section=None, name=None, default=None):
"""
Get the value of the environment variable or config file value.
The environment variable takes precedence.
:param env: The environment variable name.
:param name: The config file... |
Cache threadpool since context is
recreated for each request | def instance(cls, size):
"""
Cache threadpool since context is
recreated for each request
"""
if not getattr(cls, "_instance", None):
cls._instance = {}
if size not in cls._instance:
cls._instance[size] = ThreadPool(size)
return cls._instan... |
Runs thumbor server with the specified arguments. | def main(arguments=None):
'''Runs thumbor server with the specified arguments.'''
if arguments is None:
arguments = sys.argv[1:]
server_parameters = get_server_parameters(arguments)
config = get_config(server_parameters.config_path, server_parameters.use_environment)
configure_log(config, s... |
Retrieves mime metadata if available
:return: | def mime(self):
'''
Retrieves mime metadata if available
:return:
'''
return self.metadata['ContentType'] if 'ContentType' in self.metadata else BaseEngine.get_mimetype(self.buffer) |
Cache statsd client so it doesn't do a DNS lookup
over and over | def client(cls, config):
"""
Cache statsd client so it doesn't do a DNS lookup
over and over
"""
if not hasattr(cls, "_client"):
cls._client = statsd.StatsClient(config.STATSD_HOST, config.STATSD_PORT, config.STATSD_PREFIX)
return cls._client |
Pads the image with transparent pixels if necessary. | def handle_padding(self, padding):
'''Pads the image with transparent pixels if necessary.'''
left = padding[0]
top = padding[1]
right = padding[2]
bottom = padding[3]
offset_x = 0
offset_y = 0
new_width = self.engine.size[0]
new_height = self.eng... |
Returns the target dimensions and calculates them if necessary.
The target dimensions are display independent.
:return: Target dimensions as a tuple (width, height)
:rtype: (int, int) | def get_target_dimensions(self):
"""
Returns the target dimensions and calculates them if necessary.
The target dimensions are display independent.
:return: Target dimensions as a tuple (width, height)
:rtype: (int, int)
"""
if self.target_height is None:
... |
If ENGINE_THREADPOOL_SIZE > 0, this will schedule the image operations
into a threadpool. If not, it just executes them synchronously, and
calls self.done_callback when it's finished.
The actual work happens in self.img_operation_worker | def do_image_operations(self):
"""
If ENGINE_THREADPOOL_SIZE > 0, this will schedule the image operations
into a threadpool. If not, it just executes them synchronously, and
calls self.done_callback when it's finished.
The actual work happens in self.img_operation_worker
... |
Returns the image orientation of the buffer image or None
if it is undefined. Gets the original value from the Exif tag.
If the buffer has been rotated, then the value is adjusted to 1.
:return: Orientation value (1 - 8)
:rtype: int or None | def get_orientation(self):
"""
Returns the image orientation of the buffer image or None
if it is undefined. Gets the original value from the Exif tag.
If the buffer has been rotated, then the value is adjusted to 1.
:return: Orientation value (1 - 8)
:rtype: int or None
... |
Rotates the image in the buffer so that it is oriented correctly.
If override_exif is True (default) then the metadata
orientation is adjusted as well.
:param override_exif: If the metadata should be adjusted as well.
:type override_exif: Boolean | def reorientate(self, override_exif=True):
"""
Rotates the image in the buffer so that it is oriented correctly.
If override_exif is True (default) then the metadata
orientation is adjusted as well.
:param override_exif: If the metadata should be adjusted as well.
:type o... |
This function is called after the PRE_LOAD filters have been applied.
It applies the AFTER_LOAD filters on the result, then crops the image. | def get_image(self):
"""
This function is called after the PRE_LOAD filters have been applied.
It applies the AFTER_LOAD filters on the result, then crops the image.
"""
try:
result = yield self._fetch(
self.context.request.image_url
)
... |
Converts a given url with the specified arguments. | def main(arguments=None):
'''Converts a given url with the specified arguments.'''
parsed_options, arguments = get_options(arguments)
image_url = arguments[0]
image_url = quote(image_url)
try:
config = Config.load(None)
except Exception:
config = None
if not parsed_option... |
checkImages(images)
Check numpy images and correct intensity range etc.
The same for all movie formats. | def checkImages(images):
""" checkImages(images)
Check numpy images and correct intensity range etc.
The same for all movie formats.
"""
# Init results
images2 = []
for im in images:
if PIL and isinstance(im, PIL.Image.Image):
# We assume PIL images are allright
... |
Integer to two bytes | def intToBin(i):
""" Integer to two bytes """
# devide in two parts (bytes)
i1 = i % 256
i2 = int(i / 256)
# make string (little endian)
return chr(i1) + chr(i2) |
writeGif(filename, images, duration=0.1, repeat=True, dither=False,
nq=0, subRectangles=True, dispose=None)
Write an animated gif from the specified images.
Parameters
----------
filename : string
The name of the file to write the image to.
images : list
Should ... | def writeGif(
filename, images, duration=0.1, repeat=True, dither=False,
nq=0, subRectangles=True, dispose=None):
""" writeGif(filename, images, duration=0.1, repeat=True, dither=False,
nq=0, subRectangles=True, dispose=None)
Write an animated gif from the specified images.
... |
readGif(filename, asNumpy=True)
Read images from an animated GIF file. Returns a list of numpy
arrays, or, if asNumpy is false, a list if PIL images. | def readGif(filename, asNumpy=True):
""" readGif(filename, asNumpy=True)
Read images from an animated GIF file. Returns a list of numpy
arrays, or, if asNumpy is false, a list if PIL images.
"""
# Check PIL
if PIL is None:
raise RuntimeError("Need PIL to read animated gif files.")
... |
getheaderAnim(im)
Get animation header. To replace PILs getheader()[0] | def getheaderAnim(self, im):
""" getheaderAnim(im)
Get animation header. To replace PILs getheader()[0]
"""
bb = "GIF89a"
bb += intToBin(im.size[0])
bb += intToBin(im.size[1])
bb += "\x87\x00\x00"
return bb |
getImageDescriptor(im, xy=None)
Used for the local color table properties per image.
Otherwise global color table applies to all frames irrespective of
whether additional colors comes in play that require a redefined
palette. Still a maximum of 256 color per frame, obviously.
W... | def getImageDescriptor(self, im, xy=None):
""" getImageDescriptor(im, xy=None)
Used for the local color table properties per image.
Otherwise global color table applies to all frames irrespective of
whether additional colors comes in play that require a redefined
palette. Still ... |
getAppExt(loops=float('inf'))
Application extention. This part specifies the amount of loops.
If loops is 0 or inf, it goes on infinitely. | def getAppExt(self, loops=float('inf')):
""" getAppExt(loops=float('inf'))
Application extention. This part specifies the amount of loops.
If loops is 0 or inf, it goes on infinitely.
"""
if loops == 0 or loops == float('inf'):
loops = 2 ** 16 - 1
# bb ... |
getGraphicsControlExt(duration=0.1, dispose=2)
Graphics Control Extension. A sort of header at the start of
each image. Specifies duration and transparancy.
Dispose
-------
* 0 - No disposal specified.
* 1 - Do not dispose. The graphic is to be left in place.
... | def getGraphicsControlExt(self, duration=0.1, dispose=2):
""" getGraphicsControlExt(duration=0.1, dispose=2)
Graphics Control Extension. A sort of header at the start of
each image. Specifies duration and transparancy.
Dispose
-------
* 0 - No disposal specified.
... |
handleSubRectangles(images)
Handle the sub-rectangle stuff. If the rectangles are given by the
user, the values are checked. Otherwise the subrectangles are
calculated automatically. | def handleSubRectangles(self, images, subRectangles):
""" handleSubRectangles(images)
Handle the sub-rectangle stuff. If the rectangles are given by the
user, the values are checked. Otherwise the subrectangles are
calculated automatically.
"""
if isinstance(subRectang... |
getSubRectangles(ims)
Calculate the minimal rectangles that need updating each frame.
Returns a two-element tuple containing the cropped images and a
list of x-y positions.
Calculating the subrectangles takes extra time, obviously. However,
if the image sizes were reduced, the ... | def getSubRectangles(self, ims):
""" getSubRectangles(ims)
Calculate the minimal rectangles that need updating each frame.
Returns a two-element tuple containing the cropped images and a
list of x-y positions.
Calculating the subrectangles takes extra time, obviously. However,
... |
convertImagesToPIL(images, nq=0)
Convert images to Paletted PIL images, which can then be
written to a single animaged GIF. | def convertImagesToPIL(self, images, dither, nq=0):
""" convertImagesToPIL(images, nq=0)
Convert images to Paletted PIL images, which can then be
written to a single animaged GIF.
"""
# Convert to PIL images
images2 = []
for im in images:
if isinsta... |
Generate an application string based on some of the given information
that can be pulled from the test object: app_env, start_time. | def generate_application_string(cls, test):
""" Generate an application string based on some of the given information
that can be pulled from the test object: app_env, start_time. """
app_env = 'test'
if hasattr(test, 'env'):
app_env = test.env
elif hasattr(test,... |
This method removes the outer parentheses for xpath grouping.
The xpath converter will break otherwise.
Example:
"(//button[@type='submit'])[1]" becomes "//button[@type='submit'][1]" | def _filter_xpath_grouping(xpath):
"""
This method removes the outer parentheses for xpath grouping.
The xpath converter will break otherwise.
Example:
"(//button[@type='submit'])[1]" becomes "//button[@type='submit'][1]"
"""
# First remove the first open parentheses
xpath = xpath[1:]
... |
Implementation of https://stackoverflow.com/a/35293284 for
https://stackoverflow.com/questions/12848327/
(Run Selenium on a proxy server that requires authentication.)
Solution involves creating & adding a Chrome extension on the fly.
* CHROME-ONLY for now! * | def create_proxy_zip(proxy_string, proxy_user, proxy_pass):
""" Implementation of https://stackoverflow.com/a/35293284 for
https://stackoverflow.com/questions/12848327/
(Run Selenium on a proxy server that requires authentication.)
Solution involves creating & adding a Chrome extension on th... |
Remove Chrome extension zip file used for proxy server authentication.
Used in the implementation of https://stackoverflow.com/a/35293284
for https://stackoverflow.com/questions/12848327/ | def remove_proxy_zip_if_present():
""" Remove Chrome extension zip file used for proxy server authentication.
Used in the implementation of https://stackoverflow.com/a/35293284
for https://stackoverflow.com/questions/12848327/
"""
try:
if os.path.exists(PROXY_ZIP_PATH):
o... |
This method clicks on a list of elements in succession.
'spacing' is the amount of time to wait between clicks. (sec) | def click_chain(self, selectors_list, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT, spacing=0):
""" This method clicks on a list of elements in succession.
'spacing' is the amount of time to wait between clicks. (sec) """
if self.timeout_multiplier and timeout == se... |
Returns True if the link text appears in the HTML of the page.
The element doesn't need to be visible,
such as elements hidden inside a dropdown selection. | def is_link_text_present(self, link_text):
""" Returns True if the link text appears in the HTML of the page.
The element doesn't need to be visible,
such as elements hidden inside a dropdown selection. """
soup = self.get_beautiful_soup()
html_links = soup.find_all('a')
... |
Finds a link by link text and then returns the attribute's value.
If the link text or attribute cannot be found, an exception will
get raised if hard_fail is True (otherwise None is returned). | def get_link_attribute(self, link_text, attribute, hard_fail=True):
""" Finds a link by link text and then returns the attribute's value.
If the link text or attribute cannot be found, an exception will
get raised if hard_fail is True (otherwise None is returned). """
soup = self... |
This method clicks link text on a page | def click_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT):
""" This method clicks link text on a page """
# If using phantomjs, might need to extract and open the link directly
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeo... |
Same as self.click_link_text() | def click_link(self, link_text, timeout=settings.SMALL_TIMEOUT):
""" Same as self.click_link_text() """
self.click_link_text(link_text, timeout=timeout) |
This method clicks the partial link text on a page. | def click_partial_link_text(self, partial_link_text,
timeout=settings.SMALL_TIMEOUT):
""" This method clicks the partial link text on a page. """
# If using phantomjs, might need to extract and open the link directly
if self.timeout_multiplier and timeout == setti... |
This method uses JavaScript to get the value of an attribute. | def get_attribute(self, selector, attribute, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" This method uses JavaScript to get the value of an attribute. """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(tim... |
This method uses JavaScript to set/update an attribute. | def set_attribute(self, selector, attribute, value, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" This method uses JavaScript to set/update an attribute. """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(ti... |
Returns the property value of a page element's computed style.
Example:
opacity = self.get_property_value("html body a", "opacity")
self.assertTrue(float(opacity) > 0, "Element not visible!") | def get_property_value(self, selector, property, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Returns the property value of a page element's computed style.
Example:
opacity = self.get_property_value("html body a", "opacity")
sel... |
Extracts the URL from an image element on the page. | def get_image_url(self, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Extracts the URL from an image element on the page. """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return ... |
The more-reliable version of driver.send_keys()
Similar to update_text(), but won't clear the text field first. | def add_text(self, selector, new_value, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" The more-reliable version of driver.send_keys()
Similar to update_text(), but won't clear the text field first. """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEO... |
Same as add_text() -> more reliable, but less name confusion. | def send_keys(self, selector, new_value, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" Same as add_text() -> more reliable, but less name confusion. """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
... |
The shorter version of update_text_value(), which
clears existing text and adds new text into the text field.
We want to keep the old version for backward compatibility. | def update_text(self, selector, new_value, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT, retry=False):
""" The shorter version of update_text_value(), which
clears existing text and adds new text into the text field.
We want to keep the old version for backward ... |
Returns a list of matching WebElements.
If "limit" is set and > 0, will only return that many elements. | def find_elements(self, selector, by=By.CSS_SELECTOR, limit=0):
""" Returns a list of matching WebElements.
If "limit" is set and > 0, will only return that many elements. """
self.wait_for_ready_state_complete()
if page_utils.is_xpath_selector(selector):
by = By.XPATH
... |
Returns a list of matching WebElements that are visible.
If "limit" is set and > 0, will only return that many elements. | def find_visible_elements(self, selector, by=By.CSS_SELECTOR, limit=0):
""" Returns a list of matching WebElements that are visible.
If "limit" is set and > 0, will only return that many elements. """
self.wait_for_ready_state_complete()
if page_utils.is_xpath_selector(selector):
... |
Finds all matching page elements and clicks visible ones in order.
If a click reloads or opens a new page, the clicking will stop.
Works best for actions such as clicking all checkboxes on a page.
Example: self.click_visible_elements('input[type="checkbox"]')
If "limit" ... | def click_visible_elements(self, selector, by=By.CSS_SELECTOR, limit=0):
""" Finds all matching page elements and clicks visible ones in order.
If a click reloads or opens a new page, the clicking will stop.
Works best for actions such as clicking all checkboxes on a page.
Ex... |
Returns True if the selector's element is located in an iframe.
Otherwise returns False. | def is_element_in_an_iframe(self, selector, by=By.CSS_SELECTOR):
""" Returns True if the selector's element is located in an iframe.
Otherwise returns False. """
selector, by = self.__recalculate_selector(selector, by)
if self.is_element_present(selector, by=by):
return F... |
Creates a tour for a website. By default, the Shepherd JavaScript
Library is used with the Shepherd "Light" / "Arrows" theme.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
theme - Sets ... | def create_tour(self, name=None, theme=None):
""" Creates a tour for a website. By default, the Shepherd JavaScript
Library is used with the Shepherd "Light" / "Arrows" theme.
@Params
name - If creating multiple tours at the same time,
use this to select th... |
Creates a Shepherd JS website tour.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
theme - Sets the default theme for the tour.
Choose from "light"/"arrows", "dark", "default", "... | def create_shepherd_tour(self, name=None, theme=None):
""" Creates a Shepherd JS website tour.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
theme - Sets the default theme for the tour.
... |
Creates a Bootstrap tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to. | def create_bootstrap_tour(self, name=None):
""" Creates a Bootstrap tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
"""
if not name:
name = "default"
... |
Creates an Hopscotch tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to. | def create_hopscotch_tour(self, name=None):
""" Creates an Hopscotch tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
"""
if not name:
name = "default"
... |
Creates an IntroJS tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to. | def create_introjs_tour(self, name=None):
""" Creates an IntroJS tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
"""
if not name:
name = "default"
... |
Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.... | def add_tour_step(self, message, selector=None, name=None,
title=None, theme=None, alignment=None, duration=None):
""" Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element t... |
Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.... | def __add_shepherd_tour_step(self, message, selector=None, name=None,
title=None, theme=None, alignment=None):
""" Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the El... |
Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.... | def __add_bootstrap_tour_step(self, message, selector=None, name=None,
title=None, alignment=None, duration=None):
""" Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of t... |
Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.... | def __add_hopscotch_tour_step(self, message, selector=None, name=None,
title=None, alignment=None):
""" Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to a... |
Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.... | def __add_introjs_tour_step(self, message, selector=None, name=None,
title=None, alignment=None):
""" Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attac... |
Plays a tour on the current website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
interval - The delay time between autoplaying tour steps.
If set to 0 (default), the tour i... | def play_tour(self, name=None, interval=0):
""" Plays a tour on the current website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
interval - The delay time between autoplaying tour steps.
... |
Exports a tour as a JS file.
You can call self.export_tour() anywhere where you would
normally use self.play_tour() to play a tour.
It will include necessary resources as well, such as jQuery.
You'll be able to copy the tour directly into the Console of
any we... | def export_tour(self, name=None, filename="my_tour.js", url=None):
""" Exports a tour as a JS file.
You can call self.export_tour() anywhere where you would
normally use self.play_tour() to play a tour.
It will include necessary resources as well, such as jQuery.
... |
Sets a theme for posting messages.
Themes: ["flat", "future", "block", "air", "ice"]
Locations: ["top_left", "top_center", "top_right",
"bottom_left", "bottom_center", "bottom_right"]
max_messages is the limit of concurrent messages to display. | def set_messenger_theme(self, theme="default", location="default",
max_messages="default"):
""" Sets a theme for posting messages.
Themes: ["flat", "future", "block", "air", "ice"]
Locations: ["top_left", "top_center", "top_right",
"bot... |
Post a message on the screen with Messenger.
Arguments:
message: The message to display.
duration: The time until the message vanishes. (Default: 2.55s)
pause: If True, the program waits until the message completes.
style: "info", "success", or... | def post_message(self, message, duration=None, pause=True, style="info"):
""" Post a message on the screen with Messenger.
Arguments:
message: The message to display.
duration: The time until the message vanishes. (Default: 2.55s)
pause: If True, the p... |
Updates the Z-index of a page element to bring it into view.
Useful when getting a WebDriverException, such as the one below:
{ Element is not clickable at point (#, #).
Other element would receive the click: ... } | def bring_to_front(self, selector, by=By.CSS_SELECTOR):
""" Updates the Z-index of a page element to bring it into view.
Useful when getting a WebDriverException, such as the one below:
{ Element is not clickable at point (#, #).
Other element would receive the clic... |
This method uses fancy JavaScript to highlight an element.
Used during demo_mode.
@Params
selector - the selector of the element to find
by - the type of selector to search by (Default: CSS)
loops - # of times to repeat the highlight animation
... | def highlight(self, selector, by=By.CSS_SELECTOR,
loops=settings.HIGHLIGHTS, scroll=True):
""" This method uses fancy JavaScript to highlight an element.
Used during demo_mode.
@Params
selector - the selector of the element to find
by - the type ... |
Fast scroll to destination | def scroll_to(self, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
''' Fast scroll to destination '''
if self.demo_mode:
self.slow_scroll_to(selector, by=by, timeout=timeout)
return
if self.timeout_multiplier and timeout == settings.SMALL... |
Slow motion scroll to destination | def slow_scroll_to(self, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
''' Slow motion scroll to destination '''
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
element = self.wait_for... |
Clicks an element using pure JS. Does not use jQuery. | def js_click(self, selector, by=By.CSS_SELECTOR):
""" Clicks an element using pure JS. Does not use jQuery. """
selector, by = self.__recalculate_selector(selector, by)
if by == By.LINK_TEXT:
message = (
"Pure JavaScript doesn't support clicking by Link Text. "
... |
Clicks an element using jQuery. Different from using pure JS. | def jquery_click(self, selector, by=By.CSS_SELECTOR):
""" Clicks an element using jQuery. Different from using pure JS. """
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_element_present(
selector, by=by, timeout=settings.SMALL_TIMEOUT)
if self.is_elem... |
Alternative to self.driver.find_element_by_*(SELECTOR).submit() | def submit(self, selector, by=By.CSS_SELECTOR):
""" Alternative to self.driver.find_element_by_*(SELECTOR).submit() """
if page_utils.is_xpath_selector(selector):
by = By.XPATH
element = self.wait_for_element_visible(
selector, by=by, timeout=settings.SMALL_TIMEOUT)
... |
Hide the first element on the page that matches the selector. | def hide_element(self, selector, by=By.CSS_SELECTOR):
""" Hide the first element on the page that matches the selector. """
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_onl... |
Hide all elements on the page that match the selector. | def hide_elements(self, selector, by=By.CSS_SELECTOR):
""" Hide all elements on the page that match the selector. """
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
hide_script = """jQuery('%s').hide()""" % selector
... |
Show the first element on the page that matches the selector. | def show_element(self, selector, by=By.CSS_SELECTOR):
""" Show the first element on the page that matches the selector. """
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_onl... |
Show all elements on the page that match the selector. | def show_elements(self, selector, by=By.CSS_SELECTOR):
""" Show all elements on the page that match the selector. """
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
show_script = """jQuery('%s').show(0)""" % selector
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.