repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
rigetti/quantumflow
quantumflow/measures.py
mutual_info
def mutual_info(rho: Density, qubits0: Qubits, qubits1: Qubits = None, base: float = None) -> float: """Compute the bipartite von-Neumann mutual information of a mixed quantum state. Args: rho: A density matrix of the complete system qubits...
python
def mutual_info(rho: Density, qubits0: Qubits, qubits1: Qubits = None, base: float = None) -> float: """Compute the bipartite von-Neumann mutual information of a mixed quantum state. Args: rho: A density matrix of the complete system qubits...
[ "def", "mutual_info", "(", "rho", ":", "Density", ",", "qubits0", ":", "Qubits", ",", "qubits1", ":", "Qubits", "=", "None", ",", "base", ":", "float", "=", "None", ")", "->", "float", ":", "if", "qubits1", "is", "None", ":", "qubits1", "=", "tuple",...
Compute the bipartite von-Neumann mutual information of a mixed quantum state. Args: rho: A density matrix of the complete system qubits0: Qubits of system 0 qubits1: Qubits of system 1. If none, taken to be all remaining qubits base: Optional logarithm base. Default is bas...
[ "Compute", "the", "bipartite", "von", "-", "Neumann", "mutual", "information", "of", "a", "mixed", "quantum", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L152-L178
train
rigetti/quantumflow
quantumflow/measures.py
gate_angle
def gate_angle(gate0: Gate, gate1: Gate) -> bk.BKTensor: """The Fubini-Study angle between gates""" return fubini_study_angle(gate0.vec, gate1.vec)
python
def gate_angle(gate0: Gate, gate1: Gate) -> bk.BKTensor: """The Fubini-Study angle between gates""" return fubini_study_angle(gate0.vec, gate1.vec)
[ "def", "gate_angle", "(", "gate0", ":", "Gate", ",", "gate1", ":", "Gate", ")", "->", "bk", ".", "BKTensor", ":", "return", "fubini_study_angle", "(", "gate0", ".", "vec", ",", "gate1", ".", "vec", ")" ]
The Fubini-Study angle between gates
[ "The", "Fubini", "-", "Study", "angle", "between", "gates" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L183-L185
train
rigetti/quantumflow
quantumflow/measures.py
channel_angle
def channel_angle(chan0: Channel, chan1: Channel) -> bk.BKTensor: """The Fubini-Study angle between channels""" return fubini_study_angle(chan0.vec, chan1.vec)
python
def channel_angle(chan0: Channel, chan1: Channel) -> bk.BKTensor: """The Fubini-Study angle between channels""" return fubini_study_angle(chan0.vec, chan1.vec)
[ "def", "channel_angle", "(", "chan0", ":", "Channel", ",", "chan1", ":", "Channel", ")", "->", "bk", ".", "BKTensor", ":", "return", "fubini_study_angle", "(", "chan0", ".", "vec", ",", "chan1", ".", "vec", ")" ]
The Fubini-Study angle between channels
[ "The", "Fubini", "-", "Study", "angle", "between", "channels" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L199-L201
train
rigetti/quantumflow
quantumflow/qubits.py
inner_product
def inner_product(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor: """ Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match. """ if vec0.rank != vec1.rank or vec0.qubit_nb != vec1.qubit_nb: raise ValueError('Incompatibly vectors. Qubits and rank must ma...
python
def inner_product(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor: """ Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match. """ if vec0.rank != vec1.rank or vec0.qubit_nb != vec1.qubit_nb: raise ValueError('Incompatibly vectors. Qubits and rank must ma...
[ "def", "inner_product", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ")", "->", "bk", ".", "BKTensor", ":", "if", "vec0", ".", "rank", "!=", "vec1", ".", "rank", "or", "vec0", ".", "qubit_nb", "!=", "vec1", ".", "qubit_nb", ":", ...
Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match.
[ "Hilbert", "-", "Schmidt", "inner", "product", "between", "qubit", "vectors" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L233-L242
train
rigetti/quantumflow
quantumflow/qubits.py
outer_product
def outer_product(vec0: QubitVector, vec1: QubitVector) -> QubitVector: """Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint. """ R = vec0.rank R1 = vec1.rank N0 = vec0.qubit_nb N1 = vec1.qubit_nb if R != R1: raise ValueError('Incompatibly...
python
def outer_product(vec0: QubitVector, vec1: QubitVector) -> QubitVector: """Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint. """ R = vec0.rank R1 = vec1.rank N0 = vec0.qubit_nb N1 = vec1.qubit_nb if R != R1: raise ValueError('Incompatibly...
[ "def", "outer_product", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ")", "->", "QubitVector", ":", "R", "=", "vec0", ".", "rank", "R1", "=", "vec1", ".", "rank", "N0", "=", "vec0", ".", "qubit_nb", "N1", "=", "vec1", ".", "qubit...
Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint.
[ "Direct", "product", "of", "qubit", "vectors" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L248-L277
train
rigetti/quantumflow
quantumflow/qubits.py
vectors_close
def vectors_close(vec0: QubitVector, vec1: QubitVector, tolerance: float = TOLERANCE) -> bool: """Return True if vectors in close in the projective Hilbert space. Similarity is measured with the Fubini–Study metric. """ if vec0.rank != vec1.rank: return False if vec0.qubi...
python
def vectors_close(vec0: QubitVector, vec1: QubitVector, tolerance: float = TOLERANCE) -> bool: """Return True if vectors in close in the projective Hilbert space. Similarity is measured with the Fubini–Study metric. """ if vec0.rank != vec1.rank: return False if vec0.qubi...
[ "def", "vectors_close", "(", "vec0", ":", "QubitVector", ",", "vec1", ":", "QubitVector", ",", "tolerance", ":", "float", "=", "TOLERANCE", ")", "->", "bool", ":", "if", "vec0", ".", "rank", "!=", "vec1", ".", "rank", ":", "return", "False", "if", "vec...
Return True if vectors in close in the projective Hilbert space. Similarity is measured with the Fubini–Study metric.
[ "Return", "True", "if", "vectors", "in", "close", "in", "the", "projective", "Hilbert", "space", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L310-L325
train
rigetti/quantumflow
quantumflow/qubits.py
QubitVector.flatten
def flatten(self) -> bk.BKTensor: """Return tensor with with qubit indices flattened""" N = self.qubit_nb R = self.rank return bk.reshape(self.tensor, [2**N]*R)
python
def flatten(self) -> bk.BKTensor: """Return tensor with with qubit indices flattened""" N = self.qubit_nb R = self.rank return bk.reshape(self.tensor, [2**N]*R)
[ "def", "flatten", "(", "self", ")", "->", "bk", ".", "BKTensor", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "self", ".", "rank", "return", "bk", ".", "reshape", "(", "self", ".", "tensor", ",", "[", "2", "**", "N", "]", "*", "R", ")" ]
Return tensor with with qubit indices flattened
[ "Return", "tensor", "with", "with", "qubit", "indices", "flattened" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L131-L135
train
rigetti/quantumflow
quantumflow/qubits.py
QubitVector.relabel
def relabel(self, qubits: Qubits) -> 'QubitVector': """Return a copy of this vector with new qubits""" qubits = tuple(qubits) assert len(qubits) == self.qubit_nb vec = copy(self) vec.qubits = qubits return vec
python
def relabel(self, qubits: Qubits) -> 'QubitVector': """Return a copy of this vector with new qubits""" qubits = tuple(qubits) assert len(qubits) == self.qubit_nb vec = copy(self) vec.qubits = qubits return vec
[ "def", "relabel", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'QubitVector'", ":", "qubits", "=", "tuple", "(", "qubits", ")", "assert", "len", "(", "qubits", ")", "==", "self", ".", "qubit_nb", "vec", "=", "copy", "(", "self", ")", "vec",...
Return a copy of this vector with new qubits
[ "Return", "a", "copy", "of", "this", "vector", "with", "new", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L137-L143
train
rigetti/quantumflow
quantumflow/qubits.py
QubitVector.H
def H(self) -> 'QubitVector': """Return the conjugate transpose of this tensor.""" N = self.qubit_nb R = self.rank # (super) operator transpose tensor = self.tensor tensor = bk.reshape(tensor, [2**(N*R//2)] * 2) tensor = bk.transpose(tensor) tensor = bk.r...
python
def H(self) -> 'QubitVector': """Return the conjugate transpose of this tensor.""" N = self.qubit_nb R = self.rank # (super) operator transpose tensor = self.tensor tensor = bk.reshape(tensor, [2**(N*R//2)] * 2) tensor = bk.transpose(tensor) tensor = bk.r...
[ "def", "H", "(", "self", ")", "->", "'QubitVector'", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "self", ".", "rank", "tensor", "=", "self", ".", "tensor", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "(", "N", ...
Return the conjugate transpose of this tensor.
[ "Return", "the", "conjugate", "transpose", "of", "this", "tensor", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L165-L178
train
rigetti/quantumflow
quantumflow/qubits.py
QubitVector.norm
def norm(self) -> bk.BKTensor: """Return the norm of this vector""" return bk.absolute(bk.inner(self.tensor, self.tensor))
python
def norm(self) -> bk.BKTensor: """Return the norm of this vector""" return bk.absolute(bk.inner(self.tensor, self.tensor))
[ "def", "norm", "(", "self", ")", "->", "bk", ".", "BKTensor", ":", "return", "bk", ".", "absolute", "(", "bk", ".", "inner", "(", "self", ".", "tensor", ",", "self", ".", "tensor", ")", ")" ]
Return the norm of this vector
[ "Return", "the", "norm", "of", "this", "vector" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L180-L182
train
rigetti/quantumflow
quantumflow/qubits.py
QubitVector.partial_trace
def partial_trace(self, qubits: Qubits) -> 'QubitVector': """ Return the partial trace over some subset of qubits""" N = self.qubit_nb R = self.rank if R == 1: raise ValueError('Cannot take trace of vector') new_qubits: List[Qubit] = list(self.qubits) ...
python
def partial_trace(self, qubits: Qubits) -> 'QubitVector': """ Return the partial trace over some subset of qubits""" N = self.qubit_nb R = self.rank if R == 1: raise ValueError('Cannot take trace of vector') new_qubits: List[Qubit] = list(self.qubits) ...
[ "def", "partial_trace", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'QubitVector'", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "self", ".", "rank", "if", "R", "==", "1", ":", "raise", "ValueError", "(", "'Cannot take trace of vector'", ...
Return the partial trace over some subset of qubits
[ "Return", "the", "partial", "trace", "over", "some", "subset", "of", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L201-L227
train
rigetti/quantumflow
examples/tensorflow2_fit_gate.py
fit_zyz
def fit_zyz(target_gate): """ Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ steps = 1000 dev = '/gpu:0' if bk.DEVICE == 'gpu' else '/cpu:0' with tf.device(dev): t = tf.Variable(tf.r...
python
def fit_zyz(target_gate): """ Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ steps = 1000 dev = '/gpu:0' if bk.DEVICE == 'gpu' else '/cpu:0' with tf.device(dev): t = tf.Variable(tf.r...
[ "def", "fit_zyz", "(", "target_gate", ")", ":", "steps", "=", "1000", "dev", "=", "'/gpu:0'", "if", "bk", ".", "DEVICE", "==", "'gpu'", "else", "'/cpu:0'", "with", "tf", ".", "device", "(", "dev", ")", ":", "t", "=", "tf", ".", "Variable", "(", "tf...
Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate.
[ "Tensorflow", "2", ".", "0", "example", ".", "Given", "an", "arbitrary", "one", "-", "qubit", "gate", "use", "gradient", "descent", "to", "find", "corresponding", "parameters", "of", "a", "universal", "ZYZ", "gate", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/tensorflow2_fit_gate.py#L21-L53
train
rigetti/quantumflow
quantumflow/programs.py
Program.run
def run(self, ket: State = None) -> State: """Compiles and runs a program. The optional program argument supplies the initial state and memory. Else qubits and classical bits start from zero states. """ if ket is None: qubits = self.qubits ket = zero_state...
python
def run(self, ket: State = None) -> State: """Compiles and runs a program. The optional program argument supplies the initial state and memory. Else qubits and classical bits start from zero states. """ if ket is None: qubits = self.qubits ket = zero_state...
[ "def", "run", "(", "self", ",", "ket", ":", "State", "=", "None", ")", "->", "State", ":", "if", "ket", "is", "None", ":", "qubits", "=", "self", ".", "qubits", "ket", "=", "zero_state", "(", "qubits", ")", "ket", "=", "self", ".", "_initilize", ...
Compiles and runs a program. The optional program argument supplies the initial state and memory. Else qubits and classical bits start from zero states.
[ "Compiles", "and", "runs", "a", "program", ".", "The", "optional", "program", "argument", "supplies", "the", "initial", "state", "and", "memory", ".", "Else", "qubits", "and", "classical", "bits", "start", "from", "zero", "states", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/programs.py#L152-L170
train
rigetti/quantumflow
quantumflow/ops.py
Gate.relabel
def relabel(self, qubits: Qubits) -> 'Gate': """Return a copy of this Gate with new qubits""" gate = copy(self) gate.vec = gate.vec.relabel(qubits) return gate
python
def relabel(self, qubits: Qubits) -> 'Gate': """Return a copy of this Gate with new qubits""" gate = copy(self) gate.vec = gate.vec.relabel(qubits) return gate
[ "def", "relabel", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'Gate'", ":", "gate", "=", "copy", "(", "self", ")", "gate", ".", "vec", "=", "gate", ".", "vec", ".", "relabel", "(", "qubits", ")", "return", "gate" ]
Return a copy of this Gate with new qubits
[ "Return", "a", "copy", "of", "this", "Gate", "with", "new", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L142-L146
train
rigetti/quantumflow
quantumflow/ops.py
Gate.run
def run(self, ket: State) -> State: """Apply the action of this gate upon a state""" qubits = self.qubits indices = [ket.qubits.index(q) for q in qubits] tensor = bk.tensormul(self.tensor, ket.tensor, indices) return State(tensor, ket.qubits, ket.memory)
python
def run(self, ket: State) -> State: """Apply the action of this gate upon a state""" qubits = self.qubits indices = [ket.qubits.index(q) for q in qubits] tensor = bk.tensormul(self.tensor, ket.tensor, indices) return State(tensor, ket.qubits, ket.memory)
[ "def", "run", "(", "self", ",", "ket", ":", "State", ")", "->", "State", ":", "qubits", "=", "self", ".", "qubits", "indices", "=", "[", "ket", ".", "qubits", ".", "index", "(", "q", ")", "for", "q", "in", "qubits", "]", "tensor", "=", "bk", "....
Apply the action of this gate upon a state
[ "Apply", "the", "action", "of", "this", "gate", "upon", "a", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L161-L166
train
rigetti/quantumflow
quantumflow/ops.py
Gate.evolve
def evolve(self, rho: Density) -> Density: """Apply the action of this gate upon a density""" # TODO: implement without explicit channel creation? chan = self.aschannel() return chan.evolve(rho)
python
def evolve(self, rho: Density) -> Density: """Apply the action of this gate upon a density""" # TODO: implement without explicit channel creation? chan = self.aschannel() return chan.evolve(rho)
[ "def", "evolve", "(", "self", ",", "rho", ":", "Density", ")", "->", "Density", ":", "chan", "=", "self", ".", "aschannel", "(", ")", "return", "chan", ".", "evolve", "(", "rho", ")" ]
Apply the action of this gate upon a density
[ "Apply", "the", "action", "of", "this", "gate", "upon", "a", "density" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L168-L172
train
rigetti/quantumflow
quantumflow/ops.py
Gate.aschannel
def aschannel(self) -> 'Channel': """Converts a Gate into a Channel""" N = self.qubit_nb R = 4 tensor = bk.outer(self.tensor, self.H.tensor) tensor = bk.reshape(tensor, [2**N]*R) tensor = bk.transpose(tensor, [0, 3, 1, 2]) return Channel(tensor, self.qubits)
python
def aschannel(self) -> 'Channel': """Converts a Gate into a Channel""" N = self.qubit_nb R = 4 tensor = bk.outer(self.tensor, self.H.tensor) tensor = bk.reshape(tensor, [2**N]*R) tensor = bk.transpose(tensor, [0, 3, 1, 2]) return Channel(tensor, self.qubits)
[ "def", "aschannel", "(", "self", ")", "->", "'Channel'", ":", "N", "=", "self", ".", "qubit_nb", "R", "=", "4", "tensor", "=", "bk", ".", "outer", "(", "self", ".", "tensor", ",", "self", ".", "H", ".", "tensor", ")", "tensor", "=", "bk", ".", ...
Converts a Gate into a Channel
[ "Converts", "a", "Gate", "into", "a", "Channel" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L243-L252
train
rigetti/quantumflow
quantumflow/ops.py
Gate.su
def su(self) -> 'Gate': """Convert gate tensor to the special unitary group.""" rank = 2**self.qubit_nb U = asarray(self.asoperator()) U /= np.linalg.det(U) ** (1/rank) return Gate(tensor=U, qubits=self.qubits)
python
def su(self) -> 'Gate': """Convert gate tensor to the special unitary group.""" rank = 2**self.qubit_nb U = asarray(self.asoperator()) U /= np.linalg.det(U) ** (1/rank) return Gate(tensor=U, qubits=self.qubits)
[ "def", "su", "(", "self", ")", "->", "'Gate'", ":", "rank", "=", "2", "**", "self", ".", "qubit_nb", "U", "=", "asarray", "(", "self", ".", "asoperator", "(", ")", ")", "U", "/=", "np", ".", "linalg", ".", "det", "(", "U", ")", "**", "(", "1"...
Convert gate tensor to the special unitary group.
[ "Convert", "gate", "tensor", "to", "the", "special", "unitary", "group", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L254-L259
train
rigetti/quantumflow
quantumflow/ops.py
Channel.relabel
def relabel(self, qubits: Qubits) -> 'Channel': """Return a copy of this channel with new qubits""" chan = copy(self) chan.vec = chan.vec.relabel(qubits) return chan
python
def relabel(self, qubits: Qubits) -> 'Channel': """Return a copy of this channel with new qubits""" chan = copy(self) chan.vec = chan.vec.relabel(qubits) return chan
[ "def", "relabel", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'Channel'", ":", "chan", "=", "copy", "(", "self", ")", "chan", ".", "vec", "=", "chan", ".", "vec", ".", "relabel", "(", "qubits", ")", "return", "chan" ]
Return a copy of this channel with new qubits
[ "Return", "a", "copy", "of", "this", "channel", "with", "new", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L298-L302
train
rigetti/quantumflow
quantumflow/ops.py
Channel.permute
def permute(self, qubits: Qubits) -> 'Channel': """Return a copy of this channel with qubits in new order""" vec = self.vec.permute(qubits) return Channel(vec.tensor, qubits=vec.qubits)
python
def permute(self, qubits: Qubits) -> 'Channel': """Return a copy of this channel with qubits in new order""" vec = self.vec.permute(qubits) return Channel(vec.tensor, qubits=vec.qubits)
[ "def", "permute", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'Channel'", ":", "vec", "=", "self", ".", "vec", ".", "permute", "(", "qubits", ")", "return", "Channel", "(", "vec", ".", "tensor", ",", "qubits", "=", "vec", ".", "qubits", ...
Return a copy of this channel with qubits in new order
[ "Return", "a", "copy", "of", "this", "channel", "with", "qubits", "in", "new", "order" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L304-L307
train
rigetti/quantumflow
quantumflow/ops.py
Channel.sharp
def sharp(self) -> 'Channel': r"""Return the 'sharp' transpose of the superoperator. The transpose :math:`S^\#` switches the two covariant (bra) indices of the superoperator. (Which in our representation are the 2nd and 3rd super-indices) If :math:`S^\#` is Hermitian, then :mat...
python
def sharp(self) -> 'Channel': r"""Return the 'sharp' transpose of the superoperator. The transpose :math:`S^\#` switches the two covariant (bra) indices of the superoperator. (Which in our representation are the 2nd and 3rd super-indices) If :math:`S^\#` is Hermitian, then :mat...
[ "def", "sharp", "(", "self", ")", "->", "'Channel'", ":", "r", "N", "=", "self", ".", "qubit_nb", "tensor", "=", "self", ".", "tensor", "tensor", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "N", "]", "*", "4", ")", "tensor", ...
r"""Return the 'sharp' transpose of the superoperator. The transpose :math:`S^\#` switches the two covariant (bra) indices of the superoperator. (Which in our representation are the 2nd and 3rd super-indices) If :math:`S^\#` is Hermitian, then :math:`S` is a Hermitian-map (i.e....
[ "r", "Return", "the", "sharp", "transpose", "of", "the", "superoperator", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L315-L335
train
rigetti/quantumflow
quantumflow/ops.py
Channel.choi
def choi(self) -> bk.BKTensor: """Return the Choi matrix representation of this super operator""" # Put superop axes in [ok, ib, ob, ik] and reshape to matrix N = self.qubit_nb return bk.reshape(self.sharp.tensor, [2**(N*2)] * 2)
python
def choi(self) -> bk.BKTensor: """Return the Choi matrix representation of this super operator""" # Put superop axes in [ok, ib, ob, ik] and reshape to matrix N = self.qubit_nb return bk.reshape(self.sharp.tensor, [2**(N*2)] * 2)
[ "def", "choi", "(", "self", ")", "->", "bk", ".", "BKTensor", ":", "N", "=", "self", ".", "qubit_nb", "return", "bk", ".", "reshape", "(", "self", ".", "sharp", ".", "tensor", ",", "[", "2", "**", "(", "N", "*", "2", ")", "]", "*", "2", ")" ]
Return the Choi matrix representation of this super operator
[ "Return", "the", "Choi", "matrix", "representation", "of", "this", "super", "operator" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L337-L342
train
rigetti/quantumflow
quantumflow/ops.py
Channel.evolve
def evolve(self, rho: Density) -> Density: """Apply the action of this channel upon a density""" N = rho.qubit_nb qubits = rho.qubits indices = list([qubits.index(q) for q in self.qubits]) + \ list([qubits.index(q) + N for q in self.qubits]) tensor = bk.tensormul(se...
python
def evolve(self, rho: Density) -> Density: """Apply the action of this channel upon a density""" N = rho.qubit_nb qubits = rho.qubits indices = list([qubits.index(q) for q in self.qubits]) + \ list([qubits.index(q) + N for q in self.qubits]) tensor = bk.tensormul(se...
[ "def", "evolve", "(", "self", ",", "rho", ":", "Density", ")", "->", "Density", ":", "N", "=", "rho", ".", "qubit_nb", "qubits", "=", "rho", ".", "qubits", "indices", "=", "list", "(", "[", "qubits", ".", "index", "(", "q", ")", "for", "q", "in",...
Apply the action of this channel upon a density
[ "Apply", "the", "action", "of", "this", "channel", "upon", "a", "density" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L354-L363
train
rigetti/quantumflow
quantumflow/backend/eagerbk.py
fcast
def fcast(value: float) -> TensorLike: """Cast to float tensor""" newvalue = tf.cast(value, FTYPE) if DEVICE == 'gpu': newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover return newvalue
python
def fcast(value: float) -> TensorLike: """Cast to float tensor""" newvalue = tf.cast(value, FTYPE) if DEVICE == 'gpu': newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover return newvalue
[ "def", "fcast", "(", "value", ":", "float", ")", "->", "TensorLike", ":", "newvalue", "=", "tf", ".", "cast", "(", "value", ",", "FTYPE", ")", "if", "DEVICE", "==", "'gpu'", ":", "newvalue", "=", "newvalue", ".", "gpu", "(", ")", "return", "newvalue"...
Cast to float tensor
[ "Cast", "to", "float", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/eagerbk.py#L52-L57
train
rigetti/quantumflow
quantumflow/backend/eagerbk.py
astensor
def astensor(array: TensorLike) -> BKTensor: """Convert to product tensor""" tensor = tf.convert_to_tensor(array, dtype=CTYPE) if DEVICE == 'gpu': tensor = tensor.gpu() # pragma: no cover # size = np.prod(np.array(tensor.get_shape().as_list())) N = int(math.log2(size(tensor))) tensor =...
python
def astensor(array: TensorLike) -> BKTensor: """Convert to product tensor""" tensor = tf.convert_to_tensor(array, dtype=CTYPE) if DEVICE == 'gpu': tensor = tensor.gpu() # pragma: no cover # size = np.prod(np.array(tensor.get_shape().as_list())) N = int(math.log2(size(tensor))) tensor =...
[ "def", "astensor", "(", "array", ":", "TensorLike", ")", "->", "BKTensor", ":", "tensor", "=", "tf", ".", "convert_to_tensor", "(", "array", ",", "dtype", "=", "CTYPE", ")", "if", "DEVICE", "==", "'gpu'", ":", "tensor", "=", "tensor", ".", "gpu", "(", ...
Convert to product tensor
[ "Convert", "to", "product", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/eagerbk.py#L60-L70
train
rigetti/quantumflow
quantumflow/circuits.py
count_operations
def count_operations(elements: Iterable[Operation]) \ -> Dict[Type[Operation], int]: """Return a count of different operation types given a colelction of operations, such as a Circuit or DAGCircuit """ op_count: Dict[Type[Operation], int] = defaultdict(int) for elem in elements: op_c...
python
def count_operations(elements: Iterable[Operation]) \ -> Dict[Type[Operation], int]: """Return a count of different operation types given a colelction of operations, such as a Circuit or DAGCircuit """ op_count: Dict[Type[Operation], int] = defaultdict(int) for elem in elements: op_c...
[ "def", "count_operations", "(", "elements", ":", "Iterable", "[", "Operation", "]", ")", "->", "Dict", "[", "Type", "[", "Operation", "]", ",", "int", "]", ":", "op_count", ":", "Dict", "[", "Type", "[", "Operation", "]", ",", "int", "]", "=", "defau...
Return a count of different operation types given a colelction of operations, such as a Circuit or DAGCircuit
[ "Return", "a", "count", "of", "different", "operation", "types", "given", "a", "colelction", "of", "operations", "such", "as", "a", "Circuit", "or", "DAGCircuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L141-L149
train
rigetti/quantumflow
quantumflow/circuits.py
map_gate
def map_gate(gate: Gate, args: Sequence[Qubits]) -> Circuit: """Applies the same gate all input qubits in the argument list. >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]]) >>> print(circ) H(0) H(1) H(2) """ circ = Circuit() for qubits in args: circ += gate.relabel(qubits)...
python
def map_gate(gate: Gate, args: Sequence[Qubits]) -> Circuit: """Applies the same gate all input qubits in the argument list. >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]]) >>> print(circ) H(0) H(1) H(2) """ circ = Circuit() for qubits in args: circ += gate.relabel(qubits)...
[ "def", "map_gate", "(", "gate", ":", "Gate", ",", "args", ":", "Sequence", "[", "Qubits", "]", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "for", "qubits", "in", "args", ":", "circ", "+=", "gate", ".", "relabel", "(", "qubits", ")"...
Applies the same gate all input qubits in the argument list. >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]]) >>> print(circ) H(0) H(1) H(2)
[ "Applies", "the", "same", "gate", "all", "input", "qubits", "in", "the", "argument", "list", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L152-L167
train
rigetti/quantumflow
quantumflow/circuits.py
qft_circuit
def qft_circuit(qubits: Qubits) -> Circuit: """Returns the Quantum Fourier Transform circuit""" # Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py N = len(qubits) circ = Circuit() for n0 in range(N): q0 = qubits[n0] circ += H(q0) for n1 in range(n0+1, N): ...
python
def qft_circuit(qubits: Qubits) -> Circuit: """Returns the Quantum Fourier Transform circuit""" # Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py N = len(qubits) circ = Circuit() for n0 in range(N): q0 = qubits[n0] circ += H(q0) for n1 in range(n0+1, N): ...
[ "def", "qft_circuit", "(", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "N", "=", "len", "(", "qubits", ")", "circ", "=", "Circuit", "(", ")", "for", "n0", "in", "range", "(", "N", ")", ":", "q0", "=", "qubits", "[", "n0", "]", "circ", "...
Returns the Quantum Fourier Transform circuit
[ "Returns", "the", "Quantum", "Fourier", "Transform", "circuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L170-L184
train
rigetti/quantumflow
quantumflow/circuits.py
reversal_circuit
def reversal_circuit(qubits: Qubits) -> Circuit: """Returns a circuit to reverse qubits""" N = len(qubits) circ = Circuit() for n in range(N // 2): circ += SWAP(qubits[n], qubits[N-1-n]) return circ
python
def reversal_circuit(qubits: Qubits) -> Circuit: """Returns a circuit to reverse qubits""" N = len(qubits) circ = Circuit() for n in range(N // 2): circ += SWAP(qubits[n], qubits[N-1-n]) return circ
[ "def", "reversal_circuit", "(", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "N", "=", "len", "(", "qubits", ")", "circ", "=", "Circuit", "(", ")", "for", "n", "in", "range", "(", "N", "//", "2", ")", ":", "circ", "+=", "SWAP", "(", "qubit...
Returns a circuit to reverse qubits
[ "Returns", "a", "circuit", "to", "reverse", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L187-L193
train
rigetti/quantumflow
quantumflow/circuits.py
zyz_circuit
def zyz_circuit(t0: float, t1: float, t2: float, q0: Qubit) -> Circuit: """Circuit equivalent of 1-qubit ZYZ gate""" circ = Circuit() circ += TZ(t0, q0) circ += TY(t1, q0) circ += TZ(t2, q0) return circ
python
def zyz_circuit(t0: float, t1: float, t2: float, q0: Qubit) -> Circuit: """Circuit equivalent of 1-qubit ZYZ gate""" circ = Circuit() circ += TZ(t0, q0) circ += TY(t1, q0) circ += TZ(t2, q0) return circ
[ "def", "zyz_circuit", "(", "t0", ":", "float", ",", "t1", ":", "float", ",", "t2", ":", "float", ",", "q0", ":", "Qubit", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "circ", "+=", "TZ", "(", "t0", ",", "q0", ")", "circ", "+=", ...
Circuit equivalent of 1-qubit ZYZ gate
[ "Circuit", "equivalent", "of", "1", "-", "qubit", "ZYZ", "gate" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L260-L266
train
rigetti/quantumflow
quantumflow/circuits.py
phase_estimation_circuit
def phase_estimation_circuit(gate: Gate, outputs: Qubits) -> Circuit: """Returns a circuit for quantum phase estimation. The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To run the circuit, the eigenvector should be set on the gate qubits, and the output qubits should be in the zero state....
python
def phase_estimation_circuit(gate: Gate, outputs: Qubits) -> Circuit: """Returns a circuit for quantum phase estimation. The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To run the circuit, the eigenvector should be set on the gate qubits, and the output qubits should be in the zero state....
[ "def", "phase_estimation_circuit", "(", "gate", ":", "Gate", ",", "outputs", ":", "Qubits", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "circ", "+=", "map_gate", "(", "H", "(", ")", ",", "list", "(", "zip", "(", "outputs", ")", ")", ...
Returns a circuit for quantum phase estimation. The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To run the circuit, the eigenvector should be set on the gate qubits, and the output qubits should be in the zero state. After evolution and measurement, the output qubits will be (approximatel...
[ "Returns", "a", "circuit", "for", "quantum", "phase", "estimation", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L269-L303
train
rigetti/quantumflow
quantumflow/circuits.py
ghz_circuit
def ghz_circuit(qubits: Qubits) -> Circuit: """Returns a circuit that prepares a multi-qubit Bell state from the zero state. """ circ = Circuit() circ += H(qubits[0]) for q0 in range(0, len(qubits)-1): circ += CNOT(qubits[q0], qubits[q0+1]) return circ
python
def ghz_circuit(qubits: Qubits) -> Circuit: """Returns a circuit that prepares a multi-qubit Bell state from the zero state. """ circ = Circuit() circ += H(qubits[0]) for q0 in range(0, len(qubits)-1): circ += CNOT(qubits[q0], qubits[q0+1]) return circ
[ "def", "ghz_circuit", "(", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "circ", "+=", "H", "(", "qubits", "[", "0", "]", ")", "for", "q0", "in", "range", "(", "0", ",", "len", "(", "qubits", ")", "-", "1...
Returns a circuit that prepares a multi-qubit Bell state from the zero state.
[ "Returns", "a", "circuit", "that", "prepares", "a", "multi", "-", "qubit", "Bell", "state", "from", "the", "zero", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L359-L369
train
rigetti/quantumflow
quantumflow/circuits.py
Circuit.extend
def extend(self, other: Operation) -> None: """Append gates from circuit to the end of this circuit""" if isinstance(other, Circuit): self.elements.extend(other.elements) else: self.elements.extend([other])
python
def extend(self, other: Operation) -> None: """Append gates from circuit to the end of this circuit""" if isinstance(other, Circuit): self.elements.extend(other.elements) else: self.elements.extend([other])
[ "def", "extend", "(", "self", ",", "other", ":", "Operation", ")", "->", "None", ":", "if", "isinstance", "(", "other", ",", "Circuit", ")", ":", "self", ".", "elements", ".", "extend", "(", "other", ".", "elements", ")", "else", ":", "self", ".", ...
Append gates from circuit to the end of this circuit
[ "Append", "gates", "from", "circuit", "to", "the", "end", "of", "this", "circuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L53-L58
train
rigetti/quantumflow
quantumflow/circuits.py
Circuit.run
def run(self, ket: State = None) -> State: """ Apply the action of this circuit upon a state. If no initial state provided an initial zero state will be created. """ if ket is None: qubits = self.qubits ket = zero_state(qubits=qubits) for elem in...
python
def run(self, ket: State = None) -> State: """ Apply the action of this circuit upon a state. If no initial state provided an initial zero state will be created. """ if ket is None: qubits = self.qubits ket = zero_state(qubits=qubits) for elem in...
[ "def", "run", "(", "self", ",", "ket", ":", "State", "=", "None", ")", "->", "State", ":", "if", "ket", "is", "None", ":", "qubits", "=", "self", ".", "qubits", "ket", "=", "zero_state", "(", "qubits", "=", "qubits", ")", "for", "elem", "in", "se...
Apply the action of this circuit upon a state. If no initial state provided an initial zero state will be created.
[ "Apply", "the", "action", "of", "this", "circuit", "upon", "a", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L87-L99
train
rigetti/quantumflow
quantumflow/circuits.py
Circuit.asgate
def asgate(self) -> Gate: """ Return the action of this circuit as a gate """ gate = identity_gate(self.qubits) for elem in self.elements: gate = elem.asgate() @ gate return gate
python
def asgate(self) -> Gate: """ Return the action of this circuit as a gate """ gate = identity_gate(self.qubits) for elem in self.elements: gate = elem.asgate() @ gate return gate
[ "def", "asgate", "(", "self", ")", "->", "Gate", ":", "gate", "=", "identity_gate", "(", "self", ".", "qubits", ")", "for", "elem", "in", "self", ".", "elements", ":", "gate", "=", "elem", ".", "asgate", "(", ")", "@", "gate", "return", "gate" ]
Return the action of this circuit as a gate
[ "Return", "the", "action", "of", "this", "circuit", "as", "a", "gate" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L111-L118
train
rigetti/quantumflow
quantumflow/channels.py
join_channels
def join_channels(*channels: Channel) -> Channel: """Join two channels acting on different qubits into a single channel acting on all qubits""" vectors = [chan.vec for chan in channels] vec = reduce(outer_product, vectors) return Channel(vec.tensor, vec.qubits)
python
def join_channels(*channels: Channel) -> Channel: """Join two channels acting on different qubits into a single channel acting on all qubits""" vectors = [chan.vec for chan in channels] vec = reduce(outer_product, vectors) return Channel(vec.tensor, vec.qubits)
[ "def", "join_channels", "(", "*", "channels", ":", "Channel", ")", "->", "Channel", ":", "vectors", "=", "[", "chan", ".", "vec", "for", "chan", "in", "channels", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "return", "Channel", ...
Join two channels acting on different qubits into a single channel acting on all qubits
[ "Join", "two", "channels", "acting", "on", "different", "qubits", "into", "a", "single", "channel", "acting", "on", "all", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L170-L175
train
rigetti/quantumflow
quantumflow/channels.py
channel_to_kraus
def channel_to_kraus(chan: Channel) -> 'Kraus': """Convert a channel superoperator into a Kraus operator representation of the same channel.""" qubits = chan.qubits N = chan.qubit_nb choi = asarray(chan.choi()) evals, evecs = np.linalg.eig(choi) evecs = np.transpose(evecs) assert np.al...
python
def channel_to_kraus(chan: Channel) -> 'Kraus': """Convert a channel superoperator into a Kraus operator representation of the same channel.""" qubits = chan.qubits N = chan.qubit_nb choi = asarray(chan.choi()) evals, evecs = np.linalg.eig(choi) evecs = np.transpose(evecs) assert np.al...
[ "def", "channel_to_kraus", "(", "chan", ":", "Channel", ")", "->", "'Kraus'", ":", "qubits", "=", "chan", ".", "qubits", "N", "=", "chan", ".", "qubit_nb", "choi", "=", "asarray", "(", "chan", ".", "choi", "(", ")", ")", "evals", ",", "evecs", "=", ...
Convert a channel superoperator into a Kraus operator representation of the same channel.
[ "Convert", "a", "channel", "superoperator", "into", "a", "Kraus", "operator", "representation", "of", "the", "same", "channel", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L181-L203
train
rigetti/quantumflow
quantumflow/channels.py
Kraus.run
def run(self, ket: State) -> State: """Apply the action of this Kraus quantum operation upon a state""" res = [op.run(ket) for op in self.operators] probs = [asarray(ket.norm()) * w for ket, w in zip(res, self.weights)] probs = np.asarray(probs) probs /= np.sum(probs) new...
python
def run(self, ket: State) -> State: """Apply the action of this Kraus quantum operation upon a state""" res = [op.run(ket) for op in self.operators] probs = [asarray(ket.norm()) * w for ket, w in zip(res, self.weights)] probs = np.asarray(probs) probs /= np.sum(probs) new...
[ "def", "run", "(", "self", ",", "ket", ":", "State", ")", "->", "State", ":", "res", "=", "[", "op", ".", "run", "(", "ket", ")", "for", "op", "in", "self", ".", "operators", "]", "probs", "=", "[", "asarray", "(", "ket", ".", "norm", "(", ")...
Apply the action of this Kraus quantum operation upon a state
[ "Apply", "the", "action", "of", "this", "Kraus", "quantum", "operation", "upon", "a", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L70-L77
train
rigetti/quantumflow
quantumflow/channels.py
Kraus.evolve
def evolve(self, rho: Density) -> Density: """Apply the action of this Kraus quantum operation upon a density""" qubits = rho.qubits results = [op.evolve(rho) for op in self.operators] tensors = [rho.tensor * w for rho, w in zip(results, self.weights)] tensor = reduce(add, tensor...
python
def evolve(self, rho: Density) -> Density: """Apply the action of this Kraus quantum operation upon a density""" qubits = rho.qubits results = [op.evolve(rho) for op in self.operators] tensors = [rho.tensor * w for rho, w in zip(results, self.weights)] tensor = reduce(add, tensor...
[ "def", "evolve", "(", "self", ",", "rho", ":", "Density", ")", "->", "Density", ":", "qubits", "=", "rho", ".", "qubits", "results", "=", "[", "op", ".", "evolve", "(", "rho", ")", "for", "op", "in", "self", ".", "operators", "]", "tensors", "=", ...
Apply the action of this Kraus quantum operation upon a density
[ "Apply", "the", "action", "of", "this", "Kraus", "quantum", "operation", "upon", "a", "density" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L79-L85
train
rigetti/quantumflow
quantumflow/channels.py
Kraus.H
def H(self) -> 'Kraus': """Return the complex conjugate of this Kraus operation""" operators = [op.H for op in self.operators] return Kraus(operators, self.weights)
python
def H(self) -> 'Kraus': """Return the complex conjugate of this Kraus operation""" operators = [op.H for op in self.operators] return Kraus(operators, self.weights)
[ "def", "H", "(", "self", ")", "->", "'Kraus'", ":", "operators", "=", "[", "op", ".", "H", "for", "op", "in", "self", ".", "operators", "]", "return", "Kraus", "(", "operators", ",", "self", ".", "weights", ")" ]
Return the complex conjugate of this Kraus operation
[ "Return", "the", "complex", "conjugate", "of", "this", "Kraus", "operation" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L103-L106
train
rigetti/quantumflow
quantumflow/channels.py
UnitaryMixture.asgate
def asgate(self) -> Gate: """Return one of the composite Kraus operators at random with the appropriate weights""" return np.random.choice(self.operators, p=self.weights)
python
def asgate(self) -> Gate: """Return one of the composite Kraus operators at random with the appropriate weights""" return np.random.choice(self.operators, p=self.weights)
[ "def", "asgate", "(", "self", ")", "->", "Gate", ":", "return", "np", ".", "random", ".", "choice", "(", "self", ".", "operators", ",", "p", "=", "self", ".", "weights", ")" ]
Return one of the composite Kraus operators at random with the appropriate weights
[ "Return", "one", "of", "the", "composite", "Kraus", "operators", "at", "random", "with", "the", "appropriate", "weights" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L119-L122
train
rigetti/quantumflow
quantumflow/visualization.py
_display_layers
def _display_layers(circ: Circuit, qubits: Qubits) -> Circuit: """Separate a circuit into groups of gates that do not visually overlap""" N = len(qubits) qubit_idx = dict(zip(qubits, range(N))) gate_layers = DAGCircuit(circ).layers() layers = [] lcirc = Circuit() layers.append(lcirc) un...
python
def _display_layers(circ: Circuit, qubits: Qubits) -> Circuit: """Separate a circuit into groups of gates that do not visually overlap""" N = len(qubits) qubit_idx = dict(zip(qubits, range(N))) gate_layers = DAGCircuit(circ).layers() layers = [] lcirc = Circuit() layers.append(lcirc) un...
[ "def", "_display_layers", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "N", "=", "len", "(", "qubits", ")", "qubit_idx", "=", "dict", "(", "zip", "(", "qubits", ",", "range", "(", "N", ")", ")", ")", "gate_l...
Separate a circuit into groups of gates that do not visually overlap
[ "Separate", "a", "circuit", "into", "groups", "of", "gates", "that", "do", "not", "visually", "overlap" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L235-L261
train
rigetti/quantumflow
quantumflow/visualization.py
render_latex
def render_latex(latex: str) -> PIL.Image: # pragma: no cover """ Convert a single page LaTeX document into an image. To display the returned image, `img.show()` Required external dependencies: `pdflatex` (with `qcircuit` package), and `poppler` (for `pdftocairo`). Args: A LaTeX...
python
def render_latex(latex: str) -> PIL.Image: # pragma: no cover """ Convert a single page LaTeX document into an image. To display the returned image, `img.show()` Required external dependencies: `pdflatex` (with `qcircuit` package), and `poppler` (for `pdftocairo`). Args: A LaTeX...
[ "def", "render_latex", "(", "latex", ":", "str", ")", "->", "PIL", ".", "Image", ":", "tmpfilename", "=", "'circ'", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmpdirname", ":", "tmppath", "=", "os", ".", "path", ".", "join", "(", "...
Convert a single page LaTeX document into an image. To display the returned image, `img.show()` Required external dependencies: `pdflatex` (with `qcircuit` package), and `poppler` (for `pdftocairo`). Args: A LaTeX document as a string. Returns: A PIL Image Raises: O...
[ "Convert", "a", "single", "page", "LaTeX", "document", "into", "an", "image", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L264-L305
train
rigetti/quantumflow
quantumflow/visualization.py
circuit_to_image
def circuit_to_image(circ: Circuit, qubits: Qubits = None) -> PIL.Image: # pragma: no cover """Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubi...
python
def circuit_to_image(circ: Circuit, qubits: Qubits = None) -> PIL.Image: # pragma: no cover """Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubi...
[ "def", "circuit_to_image", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", "=", "None", ")", "->", "PIL", ".", "Image", ":", "latex", "=", "circuit_to_latex", "(", "circ", ",", "qubits", ")", "img", "=", "render_latex", "(", "latex", ")", "r...
Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubit list to specify qubit order Returns: Returns: A PIL Image (Use img.show() to display) Raises: ...
[ "Create", "an", "image", "of", "a", "quantum", "circuit", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L308-L327
train
rigetti/quantumflow
quantumflow/visualization.py
_latex_format
def _latex_format(obj: Any) -> str: """Format an object as a latex string.""" if isinstance(obj, float): try: return sympy.latex(symbolize(obj)) except ValueError: return "{0:.4g}".format(obj) return str(obj)
python
def _latex_format(obj: Any) -> str: """Format an object as a latex string.""" if isinstance(obj, float): try: return sympy.latex(symbolize(obj)) except ValueError: return "{0:.4g}".format(obj) return str(obj)
[ "def", "_latex_format", "(", "obj", ":", "Any", ")", "->", "str", ":", "if", "isinstance", "(", "obj", ",", "float", ")", ":", "try", ":", "return", "sympy", ".", "latex", "(", "symbolize", "(", "obj", ")", ")", "except", "ValueError", ":", "return",...
Format an object as a latex string.
[ "Format", "an", "object", "as", "a", "latex", "string", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L332-L340
train
rigetti/quantumflow
examples/eager_fit_gate.py
fit_zyz
def fit_zyz(target_gate): """ Tensorflow eager mode example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ assert bk.BACKEND == 'eager' tf = bk.TL tfe = bk.tfe steps = 4000 dev = '/gpu:0' if bk.DEVICE == '...
python
def fit_zyz(target_gate): """ Tensorflow eager mode example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ assert bk.BACKEND == 'eager' tf = bk.TL tfe = bk.tfe steps = 4000 dev = '/gpu:0' if bk.DEVICE == '...
[ "def", "fit_zyz", "(", "target_gate", ")", ":", "assert", "bk", ".", "BACKEND", "==", "'eager'", "tf", "=", "bk", ".", "TL", "tfe", "=", "bk", ".", "tfe", "steps", "=", "4000", "dev", "=", "'/gpu:0'", "if", "bk", ".", "DEVICE", "==", "'gpu'", "else...
Tensorflow eager mode example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate.
[ "Tensorflow", "eager", "mode", "example", ".", "Given", "an", "arbitrary", "one", "-", "qubit", "gate", "use", "gradient", "descent", "to", "find", "corresponding", "parameters", "of", "a", "universal", "ZYZ", "gate", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/eager_fit_gate.py#L21-L60
train
rigetti/quantumflow
quantumflow/meta.py
print_versions
def print_versions(file: typing.TextIO = None) -> None: """ Print version strings of currently installed dependencies ``> python -m quantumflow.meta`` Args: file: Output stream. Defaults to stdout. """ print('** QuantumFlow dependencies (> python -m quantumflow.meta) **') print(...
python
def print_versions(file: typing.TextIO = None) -> None: """ Print version strings of currently installed dependencies ``> python -m quantumflow.meta`` Args: file: Output stream. Defaults to stdout. """ print('** QuantumFlow dependencies (> python -m quantumflow.meta) **') print(...
[ "def", "print_versions", "(", "file", ":", "typing", ".", "TextIO", "=", "None", ")", "->", "None", ":", "print", "(", "'** QuantumFlow dependencies (> python -m quantumflow.meta) **'", ")", "print", "(", "'quantumflow \\t'", ",", "qf", ".", "__version__", ",", "f...
Print version strings of currently installed dependencies ``> python -m quantumflow.meta`` Args: file: Output stream. Defaults to stdout.
[ "Print", "version", "strings", "of", "currently", "installed", "dependencies" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/meta.py#L21-L40
train
rigetti/quantumflow
examples/tensorflow_fit_gate.py
fit_zyz
def fit_zyz(target_gate): """ Tensorflow example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ assert bk.BACKEND == 'tensorflow' tf = bk.TL steps = 4000 t = tf.get_variable('t', [3]) gate = qf.ZYZ(t[0], t[1],...
python
def fit_zyz(target_gate): """ Tensorflow example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ assert bk.BACKEND == 'tensorflow' tf = bk.TL steps = 4000 t = tf.get_variable('t', [3]) gate = qf.ZYZ(t[0], t[1],...
[ "def", "fit_zyz", "(", "target_gate", ")", ":", "assert", "bk", ".", "BACKEND", "==", "'tensorflow'", "tf", "=", "bk", ".", "TL", "steps", "=", "4000", "t", "=", "tf", ".", "get_variable", "(", "'t'", ",", "[", "3", "]", ")", "gate", "=", "qf", "...
Tensorflow example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate.
[ "Tensorflow", "example", ".", "Given", "an", "arbitrary", "one", "-", "qubit", "gate", "use", "gradient", "descent", "to", "find", "corresponding", "parameters", "of", "a", "universal", "ZYZ", "gate", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/tensorflow_fit_gate.py#L20-L50
train
rigetti/quantumflow
quantumflow/decompositions.py
zyz_decomposition
def zyz_decomposition(gate: Gate) -> Circuit: """ Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate. """ if gate.qubit_nb != 1: raise ValueError('Expected 1-qubit gate') q, = gate.qubits U = asarray(gate.asoperator()) U /= np.linalg.det(U) ** (1/2) # SU(2) if ab...
python
def zyz_decomposition(gate: Gate) -> Circuit: """ Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate. """ if gate.qubit_nb != 1: raise ValueError('Expected 1-qubit gate') q, = gate.qubits U = asarray(gate.asoperator()) U /= np.linalg.det(U) ** (1/2) # SU(2) if ab...
[ "def", "zyz_decomposition", "(", "gate", ":", "Gate", ")", "->", "Circuit", ":", "if", "gate", ".", "qubit_nb", "!=", "1", ":", "raise", "ValueError", "(", "'Expected 1-qubit gate'", ")", "q", ",", "=", "gate", ".", "qubits", "U", "=", "asarray", "(", ...
Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate.
[ "Returns", "the", "Euler", "Z", "-", "Y", "-", "Z", "decomposition", "of", "a", "local", "1", "-", "qubit", "gate", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L65-L108
train
rigetti/quantumflow
quantumflow/decompositions.py
kronecker_decomposition
def kronecker_decomposition(gate: Gate) -> Circuit: """ Decompose a 2-qubit unitary composed of two 1-qubit local gates. Uses the "Nearest Kronecker Product" algorithm. Will give erratic results if the gate is not the direct product of two 1-qubit gates. """ # An alternative approach would be t...
python
def kronecker_decomposition(gate: Gate) -> Circuit: """ Decompose a 2-qubit unitary composed of two 1-qubit local gates. Uses the "Nearest Kronecker Product" algorithm. Will give erratic results if the gate is not the direct product of two 1-qubit gates. """ # An alternative approach would be t...
[ "def", "kronecker_decomposition", "(", "gate", ":", "Gate", ")", "->", "Circuit", ":", "if", "gate", ".", "qubit_nb", "!=", "2", ":", "raise", "ValueError", "(", "'Expected 2-qubit gate'", ")", "U", "=", "asarray", "(", "gate", ".", "asoperator", "(", ")",...
Decompose a 2-qubit unitary composed of two 1-qubit local gates. Uses the "Nearest Kronecker Product" algorithm. Will give erratic results if the gate is not the direct product of two 1-qubit gates.
[ "Decompose", "a", "2", "-", "qubit", "unitary", "composed", "of", "two", "1", "-", "qubit", "local", "gates", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L111-L150
train
rigetti/quantumflow
quantumflow/decompositions.py
canonical_coords
def canonical_coords(gate: Gate) -> Sequence[float]: """Returns the canonical coordinates of a 2-qubit gate""" circ = canonical_decomposition(gate) gate = circ.elements[6] # type: ignore params = [gate.params[key] for key in ('tx', 'ty', 'tz')] return params
python
def canonical_coords(gate: Gate) -> Sequence[float]: """Returns the canonical coordinates of a 2-qubit gate""" circ = canonical_decomposition(gate) gate = circ.elements[6] # type: ignore params = [gate.params[key] for key in ('tx', 'ty', 'tz')] return params
[ "def", "canonical_coords", "(", "gate", ":", "Gate", ")", "->", "Sequence", "[", "float", "]", ":", "circ", "=", "canonical_decomposition", "(", "gate", ")", "gate", "=", "circ", ".", "elements", "[", "6", "]", "params", "=", "[", "gate", ".", "params"...
Returns the canonical coordinates of a 2-qubit gate
[ "Returns", "the", "canonical", "coordinates", "of", "a", "2", "-", "qubit", "gate" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L153-L158
train
rigetti/quantumflow
quantumflow/decompositions.py
_eig_complex_symmetric
def _eig_complex_symmetric(M: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Diagonalize a complex symmetric matrix. The eigenvalues are complex, and the eigenvectors form an orthogonal matrix. Returns: eigenvalues, eigenvectors """ if not np.allclose(M, M.transpose()): raise np....
python
def _eig_complex_symmetric(M: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Diagonalize a complex symmetric matrix. The eigenvalues are complex, and the eigenvectors form an orthogonal matrix. Returns: eigenvalues, eigenvectors """ if not np.allclose(M, M.transpose()): raise np....
[ "def", "_eig_complex_symmetric", "(", "M", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np", ".", "ndarray", "]", ":", "if", "not", "np", ".", "allclose", "(", "M", ",", "M", ".", "transpose", "(", ")", ")", ":"...
Diagonalize a complex symmetric matrix. The eigenvalues are complex, and the eigenvectors form an orthogonal matrix. Returns: eigenvalues, eigenvectors
[ "Diagonalize", "a", "complex", "symmetric", "matrix", ".", "The", "eigenvalues", "are", "complex", "and", "the", "eigenvectors", "form", "an", "orthogonal", "matrix", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L262-L309
train
rigetti/quantumflow
examples/qaoa_maxcut.py
maxcut_qaoa
def maxcut_qaoa( graph, steps=DEFAULT_STEPS, learning_rate=LEARNING_RATE, verbose=False): """QAOA Maxcut using tensorflow""" if not isinstance(graph, nx.Graph): graph = nx.from_edgelist(graph) init_scale = 0.01 init_bias = 0.5 init_beta = normal(loc=init_bi...
python
def maxcut_qaoa( graph, steps=DEFAULT_STEPS, learning_rate=LEARNING_RATE, verbose=False): """QAOA Maxcut using tensorflow""" if not isinstance(graph, nx.Graph): graph = nx.from_edgelist(graph) init_scale = 0.01 init_bias = 0.5 init_beta = normal(loc=init_bi...
[ "def", "maxcut_qaoa", "(", "graph", ",", "steps", "=", "DEFAULT_STEPS", ",", "learning_rate", "=", "LEARNING_RATE", ",", "verbose", "=", "False", ")", ":", "if", "not", "isinstance", "(", "graph", ",", "nx", ".", "Graph", ")", ":", "graph", "=", "nx", ...
QAOA Maxcut using tensorflow
[ "QAOA", "Maxcut", "using", "tensorflow" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/qaoa_maxcut.py#L37-L87
train
rigetti/quantumflow
quantumflow/gates.py
identity_gate
def identity_gate(qubits: Union[int, Qubits]) -> Gate: """Returns the K-qubit identity gate""" _, qubits = qubits_count_tuple(qubits) return I(*qubits)
python
def identity_gate(qubits: Union[int, Qubits]) -> Gate: """Returns the K-qubit identity gate""" _, qubits = qubits_count_tuple(qubits) return I(*qubits)
[ "def", "identity_gate", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "Gate", ":", "_", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "return", "I", "(", "*", "qubits", ")" ]
Returns the K-qubit identity gate
[ "Returns", "the", "K", "-", "qubit", "identity", "gate" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L57-L60
train
rigetti/quantumflow
quantumflow/gates.py
join_gates
def join_gates(*gates: Gate) -> Gate: """Direct product of two gates. Qubit count is the sum of each gate's bit count.""" vectors = [gate.vec for gate in gates] vec = reduce(outer_product, vectors) return Gate(vec.tensor, vec.qubits)
python
def join_gates(*gates: Gate) -> Gate: """Direct product of two gates. Qubit count is the sum of each gate's bit count.""" vectors = [gate.vec for gate in gates] vec = reduce(outer_product, vectors) return Gate(vec.tensor, vec.qubits)
[ "def", "join_gates", "(", "*", "gates", ":", "Gate", ")", "->", "Gate", ":", "vectors", "=", "[", "gate", ".", "vec", "for", "gate", "in", "gates", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "return", "Gate", "(", "vec", ...
Direct product of two gates. Qubit count is the sum of each gate's bit count.
[ "Direct", "product", "of", "two", "gates", ".", "Qubit", "count", "is", "the", "sum", "of", "each", "gate", "s", "bit", "count", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L63-L68
train
rigetti/quantumflow
quantumflow/gates.py
control_gate
def control_gate(control: Qubit, gate: Gate) -> Gate: """Return a controlled unitary gate. Given a gate acting on K qubits, return a new gate on K+1 qubits prepended with a control bit. """ if control in gate.qubits: raise ValueError('Gate and control qubits overlap') qubits = [control, *gate....
python
def control_gate(control: Qubit, gate: Gate) -> Gate: """Return a controlled unitary gate. Given a gate acting on K qubits, return a new gate on K+1 qubits prepended with a control bit. """ if control in gate.qubits: raise ValueError('Gate and control qubits overlap') qubits = [control, *gate....
[ "def", "control_gate", "(", "control", ":", "Qubit", ",", "gate", ":", "Gate", ")", "->", "Gate", ":", "if", "control", "in", "gate", ".", "qubits", ":", "raise", "ValueError", "(", "'Gate and control qubits overlap'", ")", "qubits", "=", "[", "control", "...
Return a controlled unitary gate. Given a gate acting on K qubits, return a new gate on K+1 qubits prepended with a control bit.
[ "Return", "a", "controlled", "unitary", "gate", ".", "Given", "a", "gate", "acting", "on", "K", "qubits", "return", "a", "new", "gate", "on", "K", "+", "1", "qubits", "prepended", "with", "a", "control", "bit", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L71-L83
train
rigetti/quantumflow
quantumflow/gates.py
conditional_gate
def conditional_gate(control: Qubit, gate0: Gate, gate1: Gate) -> Gate: """Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero, else do gate1 on 1""" assert gate0.qubits == gate1.qubits # FIXME tensor = join_gates(P0(control), gate0).tensor tensor += join_gates(P1(control), gate1...
python
def conditional_gate(control: Qubit, gate0: Gate, gate1: Gate) -> Gate: """Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero, else do gate1 on 1""" assert gate0.qubits == gate1.qubits # FIXME tensor = join_gates(P0(control), gate0).tensor tensor += join_gates(P1(control), gate1...
[ "def", "conditional_gate", "(", "control", ":", "Qubit", ",", "gate0", ":", "Gate", ",", "gate1", ":", "Gate", ")", "->", "Gate", ":", "assert", "gate0", ".", "qubits", "==", "gate1", ".", "qubits", "tensor", "=", "join_gates", "(", "P0", "(", "control...
Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero, else do gate1 on 1
[ "Return", "a", "conditional", "unitary", "gate", ".", "Do", "gate0", "on", "bit", "1", "if", "bit", "0", "is", "zero", "else", "do", "gate1", "on", "1" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L86-L94
train
rigetti/quantumflow
quantumflow/gates.py
print_gate
def print_gate(gate: Gate, ndigits: int = 2, file: TextIO = None) -> None: """Pretty print a gate tensor Args: gate: ndigits: file: Stream to which to write. Defaults to stdout """ N = gate.qubit_nb gate_tensor = gate.vec.asarray() lines = [] for index...
python
def print_gate(gate: Gate, ndigits: int = 2, file: TextIO = None) -> None: """Pretty print a gate tensor Args: gate: ndigits: file: Stream to which to write. Defaults to stdout """ N = gate.qubit_nb gate_tensor = gate.vec.asarray() lines = [] for index...
[ "def", "print_gate", "(", "gate", ":", "Gate", ",", "ndigits", ":", "int", "=", "2", ",", "file", ":", "TextIO", "=", "None", ")", "->", "None", ":", "N", "=", "gate", ".", "qubit_nb", "gate_tensor", "=", "gate", ".", "vec", ".", "asarray", "(", ...
Pretty print a gate tensor Args: gate: ndigits: file: Stream to which to write. Defaults to stdout
[ "Pretty", "print", "a", "gate", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L116-L134
train
rigetti/quantumflow
quantumflow/gates.py
random_gate
def random_gate(qubits: Union[int, Qubits]) -> Gate: r"""Returns a random unitary gate on K qubits. Ref: "How to generate random matrices from the classical compact groups" Francesco Mezzadri, math-ph/0609050 """ N, qubits = qubits_count_tuple(qubits) unitary = scipy.stats.unitary_g...
python
def random_gate(qubits: Union[int, Qubits]) -> Gate: r"""Returns a random unitary gate on K qubits. Ref: "How to generate random matrices from the classical compact groups" Francesco Mezzadri, math-ph/0609050 """ N, qubits = qubits_count_tuple(qubits) unitary = scipy.stats.unitary_g...
[ "def", "random_gate", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "Gate", ":", "r", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "unitary", "=", "scipy", ".", "stats", ".", "unitary_group", ".", "rvs", ...
r"""Returns a random unitary gate on K qubits. Ref: "How to generate random matrices from the classical compact groups" Francesco Mezzadri, math-ph/0609050
[ "r", "Returns", "a", "random", "unitary", "gate", "on", "K", "qubits", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L159-L168
train
VirusTotal/yara-python
setup.py
has_function
def has_function(function_name, libraries=None): """Checks if a given functions exists in the current platform.""" compiler = distutils.ccompiler.new_compiler() with muted(sys.stdout, sys.stderr): result = compiler.has_function( function_name, libraries=libraries) if os.path.exists('a.out'): os....
python
def has_function(function_name, libraries=None): """Checks if a given functions exists in the current platform.""" compiler = distutils.ccompiler.new_compiler() with muted(sys.stdout, sys.stderr): result = compiler.has_function( function_name, libraries=libraries) if os.path.exists('a.out'): os....
[ "def", "has_function", "(", "function_name", ",", "libraries", "=", "None", ")", ":", "compiler", "=", "distutils", ".", "ccompiler", ".", "new_compiler", "(", ")", "with", "muted", "(", "sys", ".", "stdout", ",", "sys", ".", "stderr", ")", ":", "result"...
Checks if a given functions exists in the current platform.
[ "Checks", "if", "a", "given", "functions", "exists", "in", "the", "current", "platform", "." ]
c3992bdc3a95d42e9df249ae92e726b74737e859
https://github.com/VirusTotal/yara-python/blob/c3992bdc3a95d42e9df249ae92e726b74737e859/setup.py#L80-L88
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_message
async def handle_agent_message(self, agent_addr, message): """Dispatch messages received from agents to the right handlers""" message_handlers = { AgentHello: self.handle_agent_hello, AgentJobStarted: self.handle_agent_job_started, AgentJobDone: self.handle_agent_job_...
python
async def handle_agent_message(self, agent_addr, message): """Dispatch messages received from agents to the right handlers""" message_handlers = { AgentHello: self.handle_agent_hello, AgentJobStarted: self.handle_agent_job_started, AgentJobDone: self.handle_agent_job_...
[ "async", "def", "handle_agent_message", "(", "self", ",", "agent_addr", ",", "message", ")", ":", "message_handlers", "=", "{", "AgentHello", ":", "self", ".", "handle_agent_hello", ",", "AgentJobStarted", ":", "self", ".", "handle_agent_job_started", ",", "AgentJ...
Dispatch messages received from agents to the right handlers
[ "Dispatch", "messages", "received", "from", "agents", "to", "the", "right", "handlers" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L59-L72
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_hello
async def handle_client_hello(self, client_addr, _: ClientHello): """ Handle an ClientHello message. Send available containers to the client """ self._logger.info("New client connected %s", client_addr) self._registered_clients.add(client_addr) await self.send_container_update_to_client(...
python
async def handle_client_hello(self, client_addr, _: ClientHello): """ Handle an ClientHello message. Send available containers to the client """ self._logger.info("New client connected %s", client_addr) self._registered_clients.add(client_addr) await self.send_container_update_to_client(...
[ "async", "def", "handle_client_hello", "(", "self", ",", "client_addr", ",", "_", ":", "ClientHello", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"New client connected %s\"", ",", "client_addr", ")", "self", ".", "_registered_clients", ".", "add", "(...
Handle an ClientHello message. Send available containers to the client
[ "Handle", "an", "ClientHello", "message", ".", "Send", "available", "containers", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L103-L107
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_ping
async def handle_client_ping(self, client_addr, _: Ping): """ Handle an Ping message. Pong the client """ await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong())
python
async def handle_client_ping(self, client_addr, _: Ping): """ Handle an Ping message. Pong the client """ await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong())
[ "async", "def", "handle_client_ping", "(", "self", ",", "client_addr", ",", "_", ":", "Ping", ")", ":", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_client_socket", ",", "client_addr", ",", "Pong", "(", ")", ")" ]
Handle an Ping message. Pong the client
[ "Handle", "an", "Ping", "message", ".", "Pong", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L109-L111
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_new_job
async def handle_client_new_job(self, client_addr, message: ClientNewJob): """ Handle an ClientNewJob message. Add a job to the queue and triggers an update """ self._logger.info("Adding a new job %s %s to the queue", client_addr, message.job_id) self._waiting_jobs[(client_addr, message.job_id)]...
python
async def handle_client_new_job(self, client_addr, message: ClientNewJob): """ Handle an ClientNewJob message. Add a job to the queue and triggers an update """ self._logger.info("Adding a new job %s %s to the queue", client_addr, message.job_id) self._waiting_jobs[(client_addr, message.job_id)]...
[ "async", "def", "handle_client_new_job", "(", "self", ",", "client_addr", ",", "message", ":", "ClientNewJob", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Adding a new job %s %s to the queue\"", ",", "client_addr", ",", "message", ".", "job_id", ")", ...
Handle an ClientNewJob message. Add a job to the queue and triggers an update
[ "Handle", "an", "ClientNewJob", "message", ".", "Add", "a", "job", "to", "the", "queue", "and", "triggers", "an", "update" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L113-L117
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_kill_job
async def handle_client_kill_job(self, client_addr, message: ClientKillJob): """ Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent. """ # Check if the job is not in the queue if (client_addr, message.job_id) in self._waiting_jobs: ...
python
async def handle_client_kill_job(self, client_addr, message: ClientKillJob): """ Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent. """ # Check if the job is not in the queue if (client_addr, message.job_id) in self._waiting_jobs: ...
[ "async", "def", "handle_client_kill_job", "(", "self", ",", "client_addr", ",", "message", ":", "ClientKillJob", ")", ":", "if", "(", "client_addr", ",", "message", ".", "job_id", ")", "in", "self", ".", "_waiting_jobs", ":", "del", "self", ".", "_waiting_jo...
Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent.
[ "Handle", "an", "ClientKillJob", "message", ".", "Remove", "a", "job", "from", "the", "waiting", "list", "or", "send", "the", "kill", "message", "to", "the", "right", "agent", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L119-L132
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_get_queue
async def handle_client_get_queue(self, client_addr, _: ClientGetQueue): """ Handles a ClientGetQueue message. Send back info about the job queue""" #jobs_running: a list of tuples in the form #(job_id, is_current_client_job, agent_name, info, launcher, started_at, max_end) jobs_running ...
python
async def handle_client_get_queue(self, client_addr, _: ClientGetQueue): """ Handles a ClientGetQueue message. Send back info about the job queue""" #jobs_running: a list of tuples in the form #(job_id, is_current_client_job, agent_name, info, launcher, started_at, max_end) jobs_running ...
[ "async", "def", "handle_client_get_queue", "(", "self", ",", "client_addr", ",", "_", ":", "ClientGetQueue", ")", ":", "jobs_running", "=", "list", "(", ")", "for", "backend_job_id", ",", "content", "in", "self", ".", "_job_running", ".", "items", "(", ")", ...
Handles a ClientGetQueue message. Send back info about the job queue
[ "Handles", "a", "ClientGetQueue", "message", ".", "Send", "back", "info", "about", "the", "job", "queue" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L134-L154
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.update_queue
async def update_queue(self): """ Send waiting jobs to available agents """ # For now, round-robin not_found_for_agent = [] while len(self._available_agents) > 0 and len(self._waiting_jobs) > 0: agent_addr = self._available_agents.pop(0) # Find ...
python
async def update_queue(self): """ Send waiting jobs to available agents """ # For now, round-robin not_found_for_agent = [] while len(self._available_agents) > 0 and len(self._waiting_jobs) > 0: agent_addr = self._available_agents.pop(0) # Find ...
[ "async", "def", "update_queue", "(", "self", ")", ":", "not_found_for_agent", "=", "[", "]", "while", "len", "(", "self", ".", "_available_agents", ")", ">", "0", "and", "len", "(", "self", ".", "_waiting_jobs", ")", ">", "0", ":", "agent_addr", "=", "...
Send waiting jobs to available agents
[ "Send", "waiting", "jobs", "to", "available", "agents" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L156-L193
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_hello
async def handle_agent_hello(self, agent_addr, message: AgentHello): """ Handle an AgentAvailable message. Add agent_addr to the list of available agents """ self._logger.info("Agent %s (%s) said hello", agent_addr, message.friendly_name) if agent_addr in self._registered_agents...
python
async def handle_agent_hello(self, agent_addr, message: AgentHello): """ Handle an AgentAvailable message. Add agent_addr to the list of available agents """ self._logger.info("Agent %s (%s) said hello", agent_addr, message.friendly_name) if agent_addr in self._registered_agents...
[ "async", "def", "handle_agent_hello", "(", "self", ",", "agent_addr", ",", "message", ":", "AgentHello", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Agent %s (%s) said hello\"", ",", "agent_addr", ",", "message", ".", "friendly_name", ")", "if", "ag...
Handle an AgentAvailable message. Add agent_addr to the list of available agents
[ "Handle", "an", "AgentAvailable", "message", ".", "Add", "agent_addr", "to", "the", "list", "of", "available", "agents" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L195-L248
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_job_started
async def handle_agent_job_started(self, agent_addr, message: AgentJobStarted): """Handle an AgentJobStarted message. Send the data back to the client""" self._logger.debug("Job %s %s started on agent %s", message.job_id[0], message.job_id[1], agent_addr) await ZMQUtils.send_with_addr(self._clie...
python
async def handle_agent_job_started(self, agent_addr, message: AgentJobStarted): """Handle an AgentJobStarted message. Send the data back to the client""" self._logger.debug("Job %s %s started on agent %s", message.job_id[0], message.job_id[1], agent_addr) await ZMQUtils.send_with_addr(self._clie...
[ "async", "def", "handle_agent_job_started", "(", "self", ",", "agent_addr", ",", "message", ":", "AgentJobStarted", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Job %s %s started on agent %s\"", ",", "message", ".", "job_id", "[", "0", "]", ",", "me...
Handle an AgentJobStarted message. Send the data back to the client
[ "Handle", "an", "AgentJobStarted", "message", ".", "Send", "the", "data", "back", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L250-L253
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_job_done
async def handle_agent_job_done(self, agent_addr, message: AgentJobDone): """Handle an AgentJobDone message. Send the data back to the client, and start new job if needed""" if agent_addr in self._registered_agents: self._logger.info("Job %s %s finished on agent %s", message.job_id[0], mess...
python
async def handle_agent_job_done(self, agent_addr, message: AgentJobDone): """Handle an AgentJobDone message. Send the data back to the client, and start new job if needed""" if agent_addr in self._registered_agents: self._logger.info("Job %s %s finished on agent %s", message.job_id[0], mess...
[ "async", "def", "handle_agent_job_done", "(", "self", ",", "agent_addr", ",", "message", ":", "AgentJobDone", ")", ":", "if", "agent_addr", "in", "self", ".", "_registered_agents", ":", "self", ".", "_logger", ".", "info", "(", "\"Job %s %s finished on agent %s\""...
Handle an AgentJobDone message. Send the data back to the client, and start new job if needed
[ "Handle", "an", "AgentJobDone", "message", ".", "Send", "the", "data", "back", "to", "the", "client", "and", "start", "new", "job", "if", "needed" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L255-L277
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_job_ssh_debug
async def handle_agent_job_ssh_debug(self, _, message: AgentJobSSHDebug): """Handle an AgentJobSSHDebug message. Send the data back to the client""" await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobSSHDebug(message.job_id[1], message.host, message.port, ...
python
async def handle_agent_job_ssh_debug(self, _, message: AgentJobSSHDebug): """Handle an AgentJobSSHDebug message. Send the data back to the client""" await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobSSHDebug(message.job_id[1], message.host, message.port, ...
[ "async", "def", "handle_agent_job_ssh_debug", "(", "self", ",", "_", ",", "message", ":", "AgentJobSSHDebug", ")", ":", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_client_socket", ",", "message", ".", "job_id", "[", "0", "]", ",", "Backen...
Handle an AgentJobSSHDebug message. Send the data back to the client
[ "Handle", "an", "AgentJobSSHDebug", "message", ".", "Send", "the", "data", "back", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L279-L282
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend._do_ping
async def _do_ping(self): """ Ping the agents """ # the list() call here is needed, as we remove entries from _registered_agents! for agent_addr, friendly_name in list(self._registered_agents.items()): try: ping_count = self._ping_count.get(agent_addr, 0) ...
python
async def _do_ping(self): """ Ping the agents """ # the list() call here is needed, as we remove entries from _registered_agents! for agent_addr, friendly_name in list(self._registered_agents.items()): try: ping_count = self._ping_count.get(agent_addr, 0) ...
[ "async", "def", "_do_ping", "(", "self", ")", ":", "for", "agent_addr", ",", "friendly_name", "in", "list", "(", "self", ".", "_registered_agents", ".", "items", "(", ")", ")", ":", "try", ":", "ping_count", "=", "self", ".", "_ping_count", ".", "get", ...
Ping the agents
[ "Ping", "the", "agents" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L314-L339
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend._delete_agent
async def _delete_agent(self, agent_addr): """ Deletes an agent """ self._available_agents = [agent for agent in self._available_agents if agent != agent_addr] del self._registered_agents[agent_addr] await self._recover_jobs(agent_addr)
python
async def _delete_agent(self, agent_addr): """ Deletes an agent """ self._available_agents = [agent for agent in self._available_agents if agent != agent_addr] del self._registered_agents[agent_addr] await self._recover_jobs(agent_addr)
[ "async", "def", "_delete_agent", "(", "self", ",", "agent_addr", ")", ":", "self", ".", "_available_agents", "=", "[", "agent", "for", "agent", "in", "self", ".", "_available_agents", "if", "agent", "!=", "agent_addr", "]", "del", "self", ".", "_registered_a...
Deletes an agent
[ "Deletes", "an", "agent" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L341-L345
train
UCL-INGI/INGInious
inginious/backend/backend.py
Backend._recover_jobs
async def _recover_jobs(self, agent_addr): """ Recover the jobs sent to a crashed agent """ for (client_addr, job_id), (agent, job_msg, _) in reversed(list(self._job_running.items())): if agent == agent_addr: await ZMQUtils.send_with_addr(self._client_socket, client_addr, ...
python
async def _recover_jobs(self, agent_addr): """ Recover the jobs sent to a crashed agent """ for (client_addr, job_id), (agent, job_msg, _) in reversed(list(self._job_running.items())): if agent == agent_addr: await ZMQUtils.send_with_addr(self._client_socket, client_addr, ...
[ "async", "def", "_recover_jobs", "(", "self", ",", "agent_addr", ")", ":", "for", "(", "client_addr", ",", "job_id", ")", ",", "(", "agent", ",", "job_msg", ",", "_", ")", "in", "reversed", "(", "list", "(", "self", ".", "_job_running", ".", "items", ...
Recover the jobs sent to a crashed agent
[ "Recover", "the", "jobs", "sent", "to", "a", "crashed", "agent" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L347-L356
train
UCL-INGI/INGInious
inginious/frontend/accessible_time.py
parse_date
def parse_date(date, default=None): """ Parse a valid date """ if date == "": if default is not None: return default else: raise Exception("Unknown format for " + date) for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H...
python
def parse_date(date, default=None): """ Parse a valid date """ if date == "": if default is not None: return default else: raise Exception("Unknown format for " + date) for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H...
[ "def", "parse_date", "(", "date", ",", "default", "=", "None", ")", ":", "if", "date", "==", "\"\"", ":", "if", "default", "is", "not", "None", ":", "return", "default", "else", ":", "raise", "Exception", "(", "\"Unknown format for \"", "+", "date", ")",...
Parse a valid date
[ "Parse", "a", "valid", "date" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/accessible_time.py#L11-L25
train
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.GET
def GET(self): """ Handles GET request """ if self.user_manager.session_logged_in() or not self.app.allow_registration: raise web.notfound() error = False reset = None msg = "" data = web.input() if "activate" in data: msg, error = self.a...
python
def GET(self): """ Handles GET request """ if self.user_manager.session_logged_in() or not self.app.allow_registration: raise web.notfound() error = False reset = None msg = "" data = web.input() if "activate" in data: msg, error = self.a...
[ "def", "GET", "(", "self", ")", ":", "if", "self", ".", "user_manager", ".", "session_logged_in", "(", ")", "or", "not", "self", ".", "app", ".", "allow_registration", ":", "raise", "web", ".", "notfound", "(", ")", "error", "=", "False", "reset", "=",...
Handles GET request
[ "Handles", "GET", "request" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L20-L35
train
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.get_reset_data
def get_reset_data(self, data): """ Returns the user info to reset """ error = False reset = None msg = "" user = self.database.users.find_one({"reset": data["reset"]}) if user is None: error = True msg = "Invalid reset hash." else: ...
python
def get_reset_data(self, data): """ Returns the user info to reset """ error = False reset = None msg = "" user = self.database.users.find_one({"reset": data["reset"]}) if user is None: error = True msg = "Invalid reset hash." else: ...
[ "def", "get_reset_data", "(", "self", ",", "data", ")", ":", "error", "=", "False", "reset", "=", "None", "msg", "=", "\"\"", "user", "=", "self", ".", "database", ".", "users", ".", "find_one", "(", "{", "\"reset\"", ":", "data", "[", "\"reset\"", "...
Returns the user info to reset
[ "Returns", "the", "user", "info", "to", "reset" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L37-L49
train
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.register_user
def register_user(self, data): """ Parses input and register user """ error = False msg = "" email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\0...
python
def register_user(self, data): """ Parses input and register user """ error = False msg = "" email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\0...
[ "def", "register_user", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "email_re", "=", "re", ".", "compile", "(", "r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\"", "r'|^\"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\1...
Parses input and register user
[ "Parses", "input", "and", "register", "user" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L63-L117
train
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.lost_passwd
def lost_passwd(self, data): """ Send a reset link to user to recover its password """ error = False msg = "" # Check input format email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\0...
python
def lost_passwd(self, data): """ Send a reset link to user to recover its password """ error = False msg = "" # Check input format email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\0...
[ "def", "lost_passwd", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "email_re", "=", "re", ".", "compile", "(", "r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\"", "r'|^\"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177...
Send a reset link to user to recover its password
[ "Send", "a", "reset", "link", "to", "user", "to", "recover", "its", "password" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L119-L151
train
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.reset_passwd
def reset_passwd(self, data): """ Reset the user password """ error = False msg = "" # Check input format if len(data["passwd"]) < 6: error = True msg = _("Password too short.") elif data["passwd"] != data["passwd2"]: error = True ...
python
def reset_passwd(self, data): """ Reset the user password """ error = False msg = "" # Check input format if len(data["passwd"]) < 6: error = True msg = _("Password too short.") elif data["passwd"] != data["passwd2"]: error = True ...
[ "def", "reset_passwd", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "if", "len", "(", "data", "[", "\"passwd\"", "]", ")", "<", "6", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Password too short.\"", ")", ...
Reset the user password
[ "Reset", "the", "user", "password" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L153-L177
train
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.POST
def POST(self): """ Handles POST request """ if self.user_manager.session_logged_in() or not self.app.allow_registration: raise web.notfound() reset = None msg = "" error = False data = web.input() if "register" in data: msg, error = self....
python
def POST(self): """ Handles POST request """ if self.user_manager.session_logged_in() or not self.app.allow_registration: raise web.notfound() reset = None msg = "" error = False data = web.input() if "register" in data: msg, error = self....
[ "def", "POST", "(", "self", ")", ":", "if", "self", ".", "user_manager", ".", "session_logged_in", "(", ")", "or", "not", "self", ".", "app", ".", "allow_registration", ":", "raise", "web", ".", "notfound", "(", ")", "reset", "=", "None", "msg", "=", ...
Handles POST request
[ "Handles", "POST", "request" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L179-L199
train
UCL-INGI/INGInious
inginious/common/task_factory.py
TaskFactory.get_readable_tasks
def get_readable_tasks(self, course): """ Returns the list of all available tasks in a course """ course_fs = self._filesystem.from_subfolder(course.get_id()) tasks = [ task[0:len(task)-1] # remove trailing / for task in course_fs.list(folders=True, files=False, recursiv...
python
def get_readable_tasks(self, course): """ Returns the list of all available tasks in a course """ course_fs = self._filesystem.from_subfolder(course.get_id()) tasks = [ task[0:len(task)-1] # remove trailing / for task in course_fs.list(folders=True, files=False, recursiv...
[ "def", "get_readable_tasks", "(", "self", ",", "course", ")", ":", "course_fs", "=", "self", ".", "_filesystem", ".", "from_subfolder", "(", "course", ".", "get_id", "(", ")", ")", "tasks", "=", "[", "task", "[", "0", ":", "len", "(", "task", ")", "-...
Returns the list of all available tasks in a course
[ "Returns", "the", "list", "of", "all", "available", "tasks", "in", "a", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L122-L129
train
UCL-INGI/INGInious
inginious/common/task_factory.py
TaskFactory._task_file_exists
def _task_file_exists(self, task_fs): """ Returns true if a task file exists in this directory """ for filename in ["task.{}".format(ext) for ext in self.get_available_task_file_extensions()]: if task_fs.exists(filename): return True return False
python
def _task_file_exists(self, task_fs): """ Returns true if a task file exists in this directory """ for filename in ["task.{}".format(ext) for ext in self.get_available_task_file_extensions()]: if task_fs.exists(filename): return True return False
[ "def", "_task_file_exists", "(", "self", ",", "task_fs", ")", ":", "for", "filename", "in", "[", "\"task.{}\"", ".", "format", "(", "ext", ")", "for", "ext", "in", "self", ".", "get_available_task_file_extensions", "(", ")", "]", ":", "if", "task_fs", ".",...
Returns true if a task file exists in this directory
[ "Returns", "true", "if", "a", "task", "file", "exists", "in", "this", "directory" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L131-L136
train
UCL-INGI/INGInious
inginious/common/task_factory.py
TaskFactory.delete_all_possible_task_files
def delete_all_possible_task_files(self, courseid, taskid): """ Deletes all possibles task files in directory, to allow to change the format """ if not id_checker(courseid): raise InvalidNameException("Course with invalid name: " + courseid) if not id_checker(taskid): rai...
python
def delete_all_possible_task_files(self, courseid, taskid): """ Deletes all possibles task files in directory, to allow to change the format """ if not id_checker(courseid): raise InvalidNameException("Course with invalid name: " + courseid) if not id_checker(taskid): rai...
[ "def", "delete_all_possible_task_files", "(", "self", ",", "courseid", ",", "taskid", ")", ":", "if", "not", "id_checker", "(", "courseid", ")", ":", "raise", "InvalidNameException", "(", "\"Course with invalid name: \"", "+", "courseid", ")", "if", "not", "id_che...
Deletes all possibles task files in directory, to allow to change the format
[ "Deletes", "all", "possibles", "task", "files", "in", "directory", "to", "allow", "to", "change", "the", "format" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L138-L149
train
UCL-INGI/INGInious
inginious/frontend/plugins/auth/saml2_auth.py
prepare_request
def prepare_request(settings): """ Prepare SAML request """ # Set the ACS url and binding method settings["sp"]["assertionConsumerService"] = { "url": web.ctx.homedomain + web.ctx.homepath + "/auth/callback/" + settings["id"], "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" ...
python
def prepare_request(settings): """ Prepare SAML request """ # Set the ACS url and binding method settings["sp"]["assertionConsumerService"] = { "url": web.ctx.homedomain + web.ctx.homepath + "/auth/callback/" + settings["id"], "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" ...
[ "def", "prepare_request", "(", "settings", ")", ":", "settings", "[", "\"sp\"", "]", "[", "\"assertionConsumerService\"", "]", "=", "{", "\"url\"", ":", "web", ".", "ctx", ".", "homedomain", "+", "web", ".", "ctx", ".", "homepath", "+", "\"/auth/callback/\""...
Prepare SAML request
[ "Prepare", "SAML", "request" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/auth/saml2_auth.py#L98-L119
train
UCL-INGI/INGInious
inginious/common/filesystems/provider.py
FileSystemProvider._checkpath
def _checkpath(self, path): """ Checks that a given path is valid. If it's not, raises NotFoundException """ if path.startswith("/") or ".." in path or path.strip() != path: raise NotFoundException()
python
def _checkpath(self, path): """ Checks that a given path is valid. If it's not, raises NotFoundException """ if path.startswith("/") or ".." in path or path.strip() != path: raise NotFoundException()
[ "def", "_checkpath", "(", "self", ",", "path", ")", ":", "if", "path", ".", "startswith", "(", "\"/\"", ")", "or", "\"..\"", "in", "path", "or", "path", ".", "strip", "(", ")", "!=", "path", ":", "raise", "NotFoundException", "(", ")" ]
Checks that a given path is valid. If it's not, raises NotFoundException
[ "Checks", "that", "a", "given", "path", "is", "valid", ".", "If", "it", "s", "not", "raises", "NotFoundException" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/filesystems/provider.py#L41-L44
train
UCL-INGI/INGInious
inginious/frontend/pages/api/courses.py
APICourses.API_GET
def API_GET(self, courseid=None): # pylint: disable=arguments-differ """ List courses available to the connected client. Returns a dict in the form :: { "courseid1": { "name": "Name of the course", #th...
python
def API_GET(self, courseid=None): # pylint: disable=arguments-differ """ List courses available to the connected client. Returns a dict in the form :: { "courseid1": { "name": "Name of the course", #th...
[ "def", "API_GET", "(", "self", ",", "courseid", "=", "None", ")", ":", "output", "=", "[", "]", "if", "courseid", "is", "None", ":", "courses", "=", "self", ".", "course_factory", ".", "get_all_courses", "(", ")", "else", ":", "try", ":", "courses", ...
List courses available to the connected client. Returns a dict in the form :: { "courseid1": { "name": "Name of the course", #the name of the course "require_password": False, #indicates if t...
[ "List", "courses", "available", "to", "the", "connected", "client", ".", "Returns", "a", "dict", "in", "the", "form" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/courses.py#L16-L67
train
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
_api_convert_output
def _api_convert_output(return_value): """ Convert the output to what the client asks """ content_type = web.ctx.environ.get('CONTENT_TYPE', 'text/json') if "text/json" in content_type: web.header('Content-Type', 'text/json; charset=utf-8') return json.dumps(return_value) if "text/html"...
python
def _api_convert_output(return_value): """ Convert the output to what the client asks """ content_type = web.ctx.environ.get('CONTENT_TYPE', 'text/json') if "text/json" in content_type: web.header('Content-Type', 'text/json; charset=utf-8') return json.dumps(return_value) if "text/html"...
[ "def", "_api_convert_output", "(", "return_value", ")", ":", "content_type", "=", "web", ".", "ctx", ".", "environ", ".", "get", "(", "'CONTENT_TYPE'", ",", "'text/json'", ")", "if", "\"text/json\"", "in", "content_type", ":", "web", ".", "header", "(", "'Co...
Convert the output to what the client asks
[ "Convert", "the", "output", "to", "what", "the", "client", "asks" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L163-L182
train
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIPage._handle_api
def _handle_api(self, handler, handler_args, handler_kwargs): """ Handle call to subclasses and convert the output to an appropriate value """ try: status_code, return_value = handler(*handler_args, **handler_kwargs) except APIError as error: return error.send() ...
python
def _handle_api(self, handler, handler_args, handler_kwargs): """ Handle call to subclasses and convert the output to an appropriate value """ try: status_code, return_value = handler(*handler_args, **handler_kwargs) except APIError as error: return error.send() ...
[ "def", "_handle_api", "(", "self", ",", "handler", ",", "handler_args", ",", "handler_kwargs", ")", ":", "try", ":", "status_code", ",", "return_value", "=", "handler", "(", "*", "handler_args", ",", "**", "handler_kwargs", ")", "except", "APIError", "as", "...
Handle call to subclasses and convert the output to an appropriate value
[ "Handle", "call", "to", "subclasses", "and", "convert", "the", "output", "to", "an", "appropriate", "value" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L47-L55
train
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIPage._guess_available_methods
def _guess_available_methods(self): """ Guess the method implemented by the subclass""" available_methods = [] for m in ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]: self_method = getattr(type(self), "API_{}".format(m)) super_method = getattr(APIPage, "API...
python
def _guess_available_methods(self): """ Guess the method implemented by the subclass""" available_methods = [] for m in ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]: self_method = getattr(type(self), "API_{}".format(m)) super_method = getattr(APIPage, "API...
[ "def", "_guess_available_methods", "(", "self", ")", ":", "available_methods", "=", "[", "]", "for", "m", "in", "[", "\"GET\"", ",", "\"POST\"", ",", "\"PUT\"", ",", "\"DELETE\"", ",", "\"PATCH\"", ",", "\"HEAD\"", ",", "\"OPTIONS\"", "]", ":", "self_method"...
Guess the method implemented by the subclass
[ "Guess", "the", "method", "implemented", "by", "the", "subclass" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L57-L65
train
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIAuthenticatedPage._verify_authentication
def _verify_authentication(self, handler, args, kwargs): """ Verify that the user is authenticated """ if not self.user_manager.session_logged_in(): raise APIForbidden() return handler(*args, **kwargs)
python
def _verify_authentication(self, handler, args, kwargs): """ Verify that the user is authenticated """ if not self.user_manager.session_logged_in(): raise APIForbidden() return handler(*args, **kwargs)
[ "def", "_verify_authentication", "(", "self", ",", "handler", ",", "args", ",", "kwargs", ")", ":", "if", "not", "self", ".", "user_manager", ".", "session_logged_in", "(", ")", ":", "raise", "APIForbidden", "(", ")", "return", "handler", "(", "*", "args",...
Verify that the user is authenticated
[ "Verify", "that", "the", "user", "is", "authenticated" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L109-L113
train
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIError.send
def send(self): """ Send the API Exception to the client """ web.ctx.status = _convert_http_status(self.status_code) return _api_convert_output(self.return_value)
python
def send(self): """ Send the API Exception to the client """ web.ctx.status = _convert_http_status(self.status_code) return _api_convert_output(self.return_value)
[ "def", "send", "(", "self", ")", ":", "web", ".", "ctx", ".", "status", "=", "_convert_http_status", "(", "self", ".", "status_code", ")", "return", "_api_convert_output", "(", "self", ".", "return_value", ")" ]
Send the API Exception to the client
[ "Send", "the", "API", "Exception", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L124-L127
train
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._job_done_callback
def _job_done_callback(self, submissionid, task, result, grade, problems, tests, custom, state, archive, stdout, stderr, newsub=True): """ Callback called by Client when a job is done. Updates the submission in the database with the data returned after the completion of the job """ submission = ...
python
def _job_done_callback(self, submissionid, task, result, grade, problems, tests, custom, state, archive, stdout, stderr, newsub=True): """ Callback called by Client when a job is done. Updates the submission in the database with the data returned after the completion of the job """ submission = ...
[ "def", "_job_done_callback", "(", "self", ",", "submissionid", ",", "task", ",", "result", ",", "grade", ",", "problems", ",", "tests", ",", "custom", ",", "state", ",", "archive", ",", "stdout", ",", "stderr", ",", "newsub", "=", "True", ")", ":", "su...
Callback called by Client when a job is done. Updates the submission in the database with the data returned after the completion of the job
[ "Callback", "called", "by", "Client", "when", "a", "job", "is", "done", ".", "Updates", "the", "submission", "in", "the", "database", "with", "the", "data", "returned", "after", "the", "completion", "of", "the", "job" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L46-L93
train
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._before_submission_insertion
def _before_submission_insertion(self, task, inputdata, debug, obj): """ Called before any new submission is inserted into the database. Allows you to modify obj, the new document that will be inserted into the database. Should be overridden in subclasses. :param task: Task related to t...
python
def _before_submission_insertion(self, task, inputdata, debug, obj): """ Called before any new submission is inserted into the database. Allows you to modify obj, the new document that will be inserted into the database. Should be overridden in subclasses. :param task: Task related to t...
[ "def", "_before_submission_insertion", "(", "self", ",", "task", ",", "inputdata", ",", "debug", ",", "obj", ")", ":", "username", "=", "self", ".", "_user_manager", ".", "session_username", "(", ")", "if", "task", ".", "is_group_task", "(", ")", "and", "n...
Called before any new submission is inserted into the database. Allows you to modify obj, the new document that will be inserted into the database. Should be overridden in subclasses. :param task: Task related to the submission :param inputdata: input of the student :param debug: True, ...
[ "Called", "before", "any", "new", "submission", "is", "inserted", "into", "the", "database", ".", "Allows", "you", "to", "modify", "obj", "the", "new", "document", "that", "will", "be", "inserted", "into", "the", "database", ".", "Should", "be", "overridden"...
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L95-L129
train
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.get_submission
def get_submission(self, submissionid, user_check=True): """ Get a submission from the database """ sub = self._database.submissions.find_one({'_id': ObjectId(submissionid)}) if user_check and not self.user_is_submission_owner(sub): return None return sub
python
def get_submission(self, submissionid, user_check=True): """ Get a submission from the database """ sub = self._database.submissions.find_one({'_id': ObjectId(submissionid)}) if user_check and not self.user_is_submission_owner(sub): return None return sub
[ "def", "get_submission", "(", "self", ",", "submissionid", ",", "user_check", "=", "True", ")", ":", "sub", "=", "self", ".", "_database", ".", "submissions", ".", "find_one", "(", "{", "'_id'", ":", "ObjectId", "(", "submissionid", ")", "}", ")", "if", ...
Get a submission from the database
[ "Get", "a", "submission", "from", "the", "database" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L208-L213
train
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._delete_exceeding_submissions
def _delete_exceeding_submissions(self, username, task, max_submissions_bound=-1): """ Deletes exceeding submissions from the database, to keep the database relatively small """ if max_submissions_bound <= 0: max_submissions = task.get_stored_submissions() elif task.get_stored_submi...
python
def _delete_exceeding_submissions(self, username, task, max_submissions_bound=-1): """ Deletes exceeding submissions from the database, to keep the database relatively small """ if max_submissions_bound <= 0: max_submissions = task.get_stored_submissions() elif task.get_stored_submi...
[ "def", "_delete_exceeding_submissions", "(", "self", ",", "username", ",", "task", ",", "max_submissions_bound", "=", "-", "1", ")", ":", "if", "max_submissions_bound", "<=", "0", ":", "max_submissions", "=", "task", ".", "get_stored_submissions", "(", ")", "eli...
Deletes exceeding submissions from the database, to keep the database relatively small
[ "Deletes", "exceeding", "submissions", "from", "the", "database", "to", "keep", "the", "database", "relatively", "small" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L284-L337
train
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.is_done
def is_done(self, submissionid_or_submission, user_check=True): """ Tells if a submission is done and its result is available """ # TODO: not a very nice way to avoid too many database call. Should be refactored. if isinstance(submissionid_or_submission, dict): submission = submissio...
python
def is_done(self, submissionid_or_submission, user_check=True): """ Tells if a submission is done and its result is available """ # TODO: not a very nice way to avoid too many database call. Should be refactored. if isinstance(submissionid_or_submission, dict): submission = submissio...
[ "def", "is_done", "(", "self", ",", "submissionid_or_submission", ",", "user_check", "=", "True", ")", ":", "if", "isinstance", "(", "submissionid_or_submission", ",", "dict", ")", ":", "submission", "=", "submissionid_or_submission", "else", ":", "submission", "=...
Tells if a submission is done and its result is available
[ "Tells", "if", "a", "submission", "is", "done", "and", "its", "result", "is", "available" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L379-L388
train
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.user_is_submission_owner
def user_is_submission_owner(self, submission): """ Returns true if the current user is the owner of this jobid, false else """ if not self._user_manager.session_logged_in(): raise Exception("A user must be logged in to verify if he owns a jobid") return self._user_manager.session_u...
python
def user_is_submission_owner(self, submission): """ Returns true if the current user is the owner of this jobid, false else """ if not self._user_manager.session_logged_in(): raise Exception("A user must be logged in to verify if he owns a jobid") return self._user_manager.session_u...
[ "def", "user_is_submission_owner", "(", "self", ",", "submission", ")", ":", "if", "not", "self", ".", "_user_manager", ".", "session_logged_in", "(", ")", ":", "raise", "Exception", "(", "\"A user must be logged in to verify if he owns a jobid\"", ")", "return", "sel...
Returns true if the current user is the owner of this jobid, false else
[ "Returns", "true", "if", "the", "current", "user", "is", "the", "owner", "of", "this", "jobid", "false", "else" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L404-L409
train
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.get_user_submissions
def get_user_submissions(self, task): """ Get all the user's submissions for a given task """ if not self._user_manager.session_logged_in(): raise Exception("A user must be logged in to get his submissions") cursor = self._database.submissions.find({"username": self._user_manager.se...
python
def get_user_submissions(self, task): """ Get all the user's submissions for a given task """ if not self._user_manager.session_logged_in(): raise Exception("A user must be logged in to get his submissions") cursor = self._database.submissions.find({"username": self._user_manager.se...
[ "def", "get_user_submissions", "(", "self", ",", "task", ")", ":", "if", "not", "self", ".", "_user_manager", ".", "session_logged_in", "(", ")", ":", "raise", "Exception", "(", "\"A user must be logged in to get his submissions\"", ")", "cursor", "=", "self", "."...
Get all the user's submissions for a given task
[ "Get", "all", "the", "user", "s", "submissions", "for", "a", "given", "task" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L411-L419
train
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.get_user_last_submissions
def get_user_last_submissions(self, limit=5, request=None): """ Get last submissions of a user """ if request is None: request = {} request.update({"username": self._user_manager.session_username()}) # Before, submissions were first sorted by submission date, then grouped ...
python
def get_user_last_submissions(self, limit=5, request=None): """ Get last submissions of a user """ if request is None: request = {} request.update({"username": self._user_manager.session_username()}) # Before, submissions were first sorted by submission date, then grouped ...
[ "def", "get_user_last_submissions", "(", "self", ",", "limit", "=", "5", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "request", "=", "{", "}", "request", ".", "update", "(", "{", "\"username\"", ":", "self", ".", "_user_m...
Get last submissions of a user
[ "Get", "last", "submissions", "of", "a", "user" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L421-L465
train