query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Launch the migration of a snapshot_uuid between 2 GlanceConnection regions in "streaming" mode | def migration_from_uuid(glance_source: GlanceConnection, glance_destination: GlanceConnection, snapshot_uuid: str,
snapshot_name_destination: str, disk_format: str = "qcow2", container_format: str = "bare"):
data = glance_source.connection.images.data(snapshot_uuid)
pipe_filename = Named... | [
"def migration(glance_source: GlanceConnection, glance_destination: GlanceConnection, snapshot_name_source: str,\n snapshot_name_destination: str, disk_format: str = \"qcow2\", container_format: str = \"bare\"):\n try:\n snapshot_uuid = get_snapshot_id_from_glance(glance_source, snapshot_name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Configure nginx, will trigger letsencrypt setup if required | def setup():
print(cyan('Configuring nginx on {}'.format(env.stage)))
context = {
'ssl_letsencrypt': False,
'ssl_with_dhparam': False,
'ssl_cert': None,
'ssl_key': None,
}
if ctx('ssl.letsencrypt'):
execute('letsencrypt.setup')
elif ctx('ssl.key') and ctx('ss... | [
"def setup_nginx():\n sudo('rm -f /etc/nginx/sites-enabled/default')\n put('files/nginx/adage-nginx.conf',\n '/etc/nginx/sites-enabled/', use_sudo=True)\n sudo('/etc/init.d/nginx restart')",
"def setup_nginx():\n put(\n \"{0}/nginx/sites-available/nagios\".format(env.CONFIG.NAGIOS_CFG_DI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Convert a list of lists into a DomainMatrix | def from_list(cls, rows, domain):
nrows = len(rows)
ncols = 0 if not nrows else len(rows[0])
conv = lambda e: domain(*e) if isinstance(e, tuple) else domain(e)
domain_rows = [[conv(e) for e in row] for row in rows]
return DomainMatrix(domain_rows, (nrows, ncols), domain) | [
"def from_list_sympy(cls, nrows, ncols, rows, **kwargs):\n assert len(rows) == nrows\n assert all(len(row) == ncols for row in rows)\n\n items_sympy = [_sympify(item) for row in rows for item in row]\n\n domain, items_domain = cls.get_domain(items_sympy, **kwargs)\n\n domain_rows ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Convert a list of lists of Expr into a DomainMatrix using construct_domain | def from_list_sympy(cls, nrows, ncols, rows, **kwargs):
assert len(rows) == nrows
assert all(len(row) == ncols for row in rows)
items_sympy = [_sympify(item) for row in rows for item in row]
domain, items_domain = cls.get_domain(items_sympy, **kwargs)
domain_rows = [[items_dom... | [
"def from_list(cls, rows, domain):\n nrows = len(rows)\n ncols = 0 if not nrows else len(rows[0])\n conv = lambda e: domain(*e) if isinstance(e, tuple) else domain(e)\n domain_rows = [[conv(e) for e in row] for row in rows]\n return DomainMatrix(domain_rows, (nrows, ncols), domain... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Returns a DomainMatrix with the appropriate field Returns ======= DomainMatrix DomainMatrix with the appropriate field Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.to_field() DomainMatr... | def to_field(self):
K = self.domain.get_field()
return self.convert_to(K) | [
"def convert_to(self, domain):\n if domain == self.domain:\n return self.copy()\n elif domain == QQ and self.domain == ZZ:\n return self._new(flint.fmpq_mat(self.rep), self.shape, domain)\n elif domain == ZZ and self.domain == QQ:\n # XXX: python-flint has no fm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a sparse DomainMatrix representation of self. Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ) >>> A.rep [[1, 0], [0, 2]] >>> B = A.to_sparse() >>> B.rep | def to_sparse(self):
if self.rep.fmt == 'sparse':
return self
return self.from_rep(self.rep.to_sdm()) | [
"def to_sparse(self):\n from divisi2.sparse import SparseMatrix\n return SparseMatrix(self, self.row_labels, self.col_labels)",
"def to_Matrix(self):\n from sympy.matrices.dense import MutableDenseMatrix\n\n # XXX: If the internal representation of RepMatrix changes then this\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert matrices to a common domain | def _unify_domain(cls, *matrices):
domains = {matrix.domain for matrix in matrices}
if len(domains) == 1:
return matrices
domain = reduce(lambda x, y: x.unify(y), domains)
return tuple(matrix.convert_to(domain) for matrix in matrices) | [
"def task4_onedimarray(matrix):\n return matrix.flatten()",
"def get_matrix(nodes, space='world'):\n nodes = _process_nodes(nodes)\n matrices = list()\n world = space == 'world'\n \n for node in nodes:\n mat = cmds.xform(node, query=True, matrix=True, worldSpace=world, objectSpace=not wor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert matrices to the same format. If all matrices have the same format, then return unmodified. Otherwise convert both to the preferred format given as fmt which should be 'dense' or 'sparse'. | def _unify_fmt(cls, *matrices, fmt=None):
formats = {matrix.rep.fmt for matrix in matrices}
if len(formats) == 1:
return matrices
if fmt == 'sparse':
return tuple(matrix.to_sparse() for matrix in matrices)
elif fmt == 'dense':
return tuple(matrix.to_de... | [
"def get_all_formats(matrix):\n other_formats = [\n matrix.todense(),\n matrix.todense().tolist(),\n matrix.todense().astype(np.float),\n matrix.tocoo(),\n matrix.tocsc(),\n matrix.todia(),\n matrix.todok(),\n matrix.tolil(),\n torch.tensor(matrix.to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unifies the domains and the format of self and other matrices. | def unify(self, *others, fmt=None):
matrices = (self,) + others
matrices = DomainMatrix._unify_domain(*matrices)
if fmt is not None:
matrices = DomainMatrix._unify_fmt(*matrices, fmt=fmt)
return matrices | [
"def _set_domains(self, domains):\n\n #resort and reshape data according to mirror transforms\n O = self.orientation_from_basis(self.basis_from_domains(domains))\n I = np.argsort(O, axis=1) #sort along transform axis\n mdim = len(np.unique(O[0])) #number of orientations encount... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Convert DomainMatrix to Matrix Returns ======= Matrix MutableDenseMatrix for the DomainMatrix Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.to_Matrix() Matrix([ [1, 2], [3, 4]]) See Also... | def to_Matrix(self):
from sympy.matrices.dense import MutableDenseMatrix
# XXX: If the internal representation of RepMatrix changes then this
# might need to be changed also.
if self.domain in (ZZ, QQ, EXRAW):
if self.rep.fmt == "sparse":
rep = self.copy()
... | [
"def toMatrix(self):\n l = []\n for i in range(self.rows):\n c = []\n l.append(c)\n for j in range(self.cols):\n if (i, j) in self.mat:\n c.append(self[i, j])\n else:\n c.append(0)\n return Matr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Number of nonzero elements in the matrix. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DM >>> A = DM([[1, 0], [0, 4]], ZZ) >>> A.nnz() 2 | def nnz(self):
return self.rep.nnz() | [
"def get_nnz(A):\n\n if isspmatrix(A):\n return A.nnz\n else:\n return A.shape[0] * A.shape[1]",
"def get_num_nonzeros(self):\n return CPX_PROC.getnumnz(self._env._e, self._cplex._lp)",
"def count_nonzero(tensor):\n raise NotImplementedError",
"def count_nonzero(a):\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the matrix is diagonal. Can return true for nonsquare matrices. A matrix is diagonal if ``M[i,j] == 0`` whenever ``i != j``. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DM >>> M = DM([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(1)]], ZZ) >>> M.is_diagonal True See Also ======== is_upper is_lo... | def is_diagonal(self):
return self.rep.is_diagonal() | [
"def is_diagonal(self):\n for i in xrange(self.rows):\n for j in xrange(self.cols):\n if i != j and self[i, j] != 0:\n return False\n return True",
"def is_diagonal(mat: np.ndarray) -> bool:\n if not is_square(mat):\n return False\n i, j = ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Vertically stack the given matrices. | def vstack(A, *B):
A, *B = A.unify(*B, fmt='dense')
return DomainMatrix.from_rep(A.rep.vstack(*(Bk.rep for Bk in B))) | [
"def stack_transformations(affine_matrices, t):\n affine_matrices_stacked = torch.zeros(affine_matrices.size(), dtype=torch.float32)\n affine_matrices_stacked[t] = affine_matrices[t]\n for i in reversed(range(t)):\n affine_matrices_stacked[i] = torch.matmul(torch.inverse(affine_matri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the strongly connected components of a DomainMatrix Explanation =========== A square matrix can be considered as the adjacency matrix for a directed graph where the row and column indices are the vertices. In this graph if there is an edge from vertex ``i`` to vertex ``j`` if ``M[i, j]`` is nonzero. This routin... | def scc(self):
if not self.is_square:
raise DMNonSquareMatrixError('Matrix must be square for scc')
return self.rep.scc() | [
"def findStronglyConnectedComponents(matrix):\r\n pathMatrix = []\r\n for i in range(len(matrix)):\r\n pathMatrix.append(bfs(matrix, i))\r\n\r\n components = []\r\n\r\n alreadyBelongs = [0]*len(matrix)\r\n for i in range(len(matrix)):\r\n if alreadyBelongs[i] > 0:\r\n continu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clear denominators, but keep the domain unchanged. Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DM >>> A = DM([[(1,2), (1,3)], [(1,4), (1,5)]], QQ) >>> den, Anum = A.clear_denoms() >>> den.to_sympy() 60 >>> Anum.to_Matrix() Matrix([ [30, 20], [15, 12]]) >>> den A == Anum True The nume... | def clear_denoms(self, convert=False):
elems0, data = self.to_flat_nz()
K0 = self.domain
K1 = K0.get_ring() if K0.has_assoc_Ring else K0
den, elems1 = dup_clear_denoms(elems0, K0, K1, convert=convert)
if convert:
Kden, Knum = K1, K1
else:
Kden, ... | [
"def clear_denoms(f, convert=False):\n coeff, F = dmp_clear_denoms(f.rep, f.lev, f.dom, convert=convert)\n return coeff, f.per(F)",
"def cancel_denom_elementwise(self, denom):\n K = self.domain\n M = self\n\n if K.is_zero(denom):\n raise ZeroDivisionError('denominator... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cancel factors between a matrix and a denominator. Returns a matrix and denominator on lowest terms. Requires ``gcd`` in the ground domain. | def cancel_denom(self, denom):
M = self
K = self.domain
if K.is_zero(denom):
raise ZeroDivisionError('denominator is zero')
elif K.is_one(denom):
return (M.copy(), denom)
elements, data = M.to_flat_nz()
# First canonicalize the denominator (e.g.... | [
"def cancel_denom_elementwise(self, denom):\n K = self.domain\n M = self\n\n if K.is_zero(denom):\n raise ZeroDivisionError('denominator is zero')\n elif K.is_one(denom):\n M_numers = M.copy()\n M_denoms = M.ones(M.shape, M.domain)\n return (M_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cancel factors between the elements of a matrix and a denominator. Returns a matrix of numerators and matrix of denominators. Requires ``gcd`` in the ground domain. Examples ======== >>> from sympy.polys.matrices import DM >>> from sympy import ZZ >>> M = DM([[2, 3], [4, 12]], ZZ) >>> denom = ZZ(6) >>> numers, denoms =... | def cancel_denom_elementwise(self, denom):
K = self.domain
M = self
if K.is_zero(denom):
raise ZeroDivisionError('denominator is zero')
elif K.is_one(denom):
M_numers = M.copy()
M_denoms = M.ones(M.shape, M.domain)
return (M_numers, M_deno... | [
"def cancel_denom(self, denom):\n M = self\n K = self.domain\n\n if K.is_zero(denom):\n raise ZeroDivisionError('denominator is zero')\n elif K.is_one(denom):\n return (M.copy(), denom)\n\n elements, data = M.to_flat_nz()\n\n # First canonicalize the d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Returns the columnspace for the DomainMatrix Returns ======= DomainMatrix The columns of this matrix form a basis for the columnspace. Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(1), QQ(1)], ... [QQ(2), QQ(2)]], (2, 2), QQ) >>> A.colum... | def columnspace(self):
if not self.domain.is_Field:
raise DMNotAField('Not a field')
rref, pivots = self.rref()
rows, cols = self.shape
return self.extract(range(rows), pivots) | [
"def columnspace(M):\r\n v = orth(M)\r\n if (v.size == 0):\r\n return [np.zeros((M.shape[0],), dtype = int)]\r\n else:\r\n return v",
"def matrix_space(self):\n return self._matrix_space",
"def _columnspace(M, simplify=False):\n\n reduced, pivots = M.echelon_form(simplify=simpli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Returns the rowspace for the DomainMatrix Returns ======= DomainMatrix The rows of this matrix form a basis for the rowspace. Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(1), QQ(1)], ... [QQ(2), QQ(2)]], (2, 2), QQ) >>> A.rowspace() Dom... | def rowspace(self):
if not self.domain.is_Field:
raise DMNotAField('Not a field')
rref, pivots = self.rref()
rows, cols = self.shape
return self.extract(range(len(pivots)), range(cols)) | [
"def matrix_space(self):\n return self._matrix_space",
"def _rowspace(M, simplify=False):\n\n reduced, pivots = M.echelon_form(simplify=simplify, with_pivots=True)\n\n return [reduced.row(i) for i in range(len(pivots))]",
"def Stirling1Matrix(dim):\r\n mat_space = MatrixSpace(CombinatorialScalar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Returns the nullspace for the DomainMatrix Returns ======= DomainMatrix The rows of this matrix form a basis for the nullspace. Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DM >>> A = DM([ ... [QQ(2), QQ(2)], ... [QQ(4), QQ(4)]], QQ) >>> A.nullspace() DomainMatrix([[1, 1]], (1, 2... | def nullspace(self, divide_last=False):
A = self
K = A.domain
if divide_last and not K.is_Field:
raise DMNotAField("Cannot normalize vectors over a non-field")
if divide_last:
A_rref, pivots = A.rref()
else:
A_rref, den, pivots = A.rref_den()... | [
"def nullspace(self):\n # Code to compute nullspace using flint:\n #\n # V, nullity = self.rep.nullspace()\n # V_dfm = self._new_rep(V)._extract(range(self.rows), range(nullity))\n #\n # XXX: That gives the nullspace but does not give us nonpivots. So we\n # use the ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute nullspace from rref and pivots. The domain of the matrix can be any domain. The matrix must be in reduced row echelon form already. Otherwise the | def nullspace_from_rref(self, pivots=None):
null_rep, nonpivots = self.rep.nullspace_from_rref(pivots)
return self.from_rep(null_rep) | [
"def sdm_nullspace_from_rref(A, one, ncols, pivots, nonzero_cols):\n nonpivots = sorted(set(range(ncols)) - set(pivots))\n\n K = []\n for j in nonpivots:\n Kj = {j:one}\n for i in nonzero_cols.get(j, ()):\n Kj[pivots[i]] = -A[i][j]\n K.append(Kj)\n\n return K, nonpivots",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Solve matrix equation $Ax = b$ using fractionfree RREF Solves the matrix equation $Ax = b$ for $x$ and returns the solution as a numerator/denominator pair. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DM >>> A = DM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], ZZ) >>> b = DM([[ZZ(5)], [ZZ(6)]], ... | def solve_den_rref(self, b):
A = self
m, n = A.shape
bm, bn = b.shape
if m != bm:
raise DMShapeError("Matrix equation shape mismatch.")
if m < n:
raise DMShapeError("Underdetermined matrix equation.")
Aaug = A.hstack(b)
Aaug_rref, denom,... | [
"def __rationalize_num_den(num: ndarray, den: ndarray):\n\n # if this function is called, it means there is at least one irrational value in den\n # two cases\n # case 1\n if len(den) == 1:\n num = __reduce_linear(linears_product(num, array([[1, den[0, 1], den[0, 2] - 1]])))\n den = array(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the polynomial $p$ such that $p(A) = adj(A)$ and also the determinant of $A$. Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DM >>> A = DM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], QQ) >>> p, detA = A.adj_poly_det() >>> p [1, 5] >>> p_A = A.eval_poly(p) >>> p_A DomainMatrix([[4, 2], [3, ... | def adj_poly_det(self, cp=None):
# Cayley-Hamilton says that a matrix satisfies its own minimal
# polynomial
#
# p[0]*A^n + p[1]*A^(n-1) + ... + p[n]*I = 0
#
# with p[0]=1 and p[n]=(-1)^n*det(A) or
#
# det(A)*I = -(-1)^n*(p[0]*A^(n-1) + p[1]*A^(n-2) +... | [
"def eval_poly(self, p):\n A = self\n m, n = A.shape\n\n if m != n:\n raise DMNonSquareMatrixError(\"Matrix must be square\")\n\n if not p:\n return self.zeros(self.shape, self.domain)\n elif len(p) == 1:\n return p[0] * self.eye(self.shape, self.d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluate polynomial function of a matrix $p(A)$. Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DM >>> A = DM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], QQ) >>> p = [QQ(1), QQ(2), QQ(3)] >>> p_A = A.eval_poly(p) >>> p_A DomainMatrix([[12, 14], [21, 33]], (2, 2), QQ) >>> p_A == p[0]A2 + p[1]A + p... | def eval_poly(self, p):
A = self
m, n = A.shape
if m != n:
raise DMNonSquareMatrixError("Matrix must be square")
if not p:
return self.zeros(self.shape, self.domain)
elif len(p) == 1:
return p[0] * self.eye(self.shape, self.domain)
#... | [
"def eval_poly_mul(self, p, B):\n A = self\n m, n = A.shape\n mb, nb = B.shape\n\n if m != n:\n raise DMNonSquareMatrixError(\"Matrix must be square\")\n\n if mb != n:\n raise DMShapeError(\"Matrices are not aligned\")\n\n if A.domain != B.domain:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Evaluate polynomial matrix product $p(A) \times B$. Evaluate the polynomial matrix product $p(A) \times B$ using Horner's method without creating the matrix $p(A)$ explicitly. If $B$ is a column matrix then this method will only use matrixvector multiplies and no matrixmatrix multiplies are needed. If $B$ is squar... | def eval_poly_mul(self, p, B):
A = self
m, n = A.shape
mb, nb = B.shape
if m != n:
raise DMNonSquareMatrixError("Matrix must be square")
if mb != n:
raise DMShapeError("Matrices are not aligned")
if A.domain != B.domain:
raise DMDoma... | [
"def mul(self, a, b):\n\n # We classically think about polynomial multiplication as:\n #\n # (a_3 x^3 + a_2 x^2 + a_1 x + a_0) * (b_3 x^3 + b_2 x^2 + b_1 x + b_0) as\n # (a_3 x^3 + a_2 x^2 + a_1 x + a_0) * b_3 x^3 +\n # (a_3 x^3 + a_2 x^2 + a_1 x + a_0) * b_2 x^2 +\n # (a_3 x^3 + a_2 x^2 + a_1 x... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Returns Lower and Upper decomposition of the DomainMatrix Returns ======= (L, U, exchange) L, U are Lower and Upper decomposition of the DomainMatrix, exchange is the list of indices of rows exchanged in the decomposition. Raises ====== ValueError If the domain of DomainMatrix not a Field Examples ======== >>> fro... | def lu(self):
if not self.domain.is_Field:
raise DMNotAField('Not a field')
L, U, swaps = self.rep.lu()
return self.from_rep(L), self.from_rep(U), swaps | [
"def decomposeLU(self):\n self.check_square()\n\n N = self.rows\n L = make_matrix(N, N)\n U = make_matrix(N, N)\n A = self #for more math friendly notation\n\n\n for j in range(N):\n L[j, j] = 1.0 #Doolittle factorization\n\n #e.g., if you are in colum... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Characteristic polynomial of a square matrix. Computes the characteristic polynomial in a fully expanded form using division free arithmetic. If a factorization of the characteristic polynomial is needed then it is more efficient to call | def charpoly(self):
M = self
K = M.domain
factors = M.charpoly_factor_blocks()
cp = [K.one]
for f, mult in factors:
for _ in range(mult):
cp = dup_mul(cp, f, K)
return cp | [
"def CharacteristicPolynomial(mol, mat=...): # -> ndarray:\n ...",
"def characteristic_polynomial(self):\n return self.matrix().characteristic_polynomial()",
"def evaluate_polynomial(tropical_matrix, coefficient_list):\n identity_matrix = get_identity_matrix(tropical_matrix.get_dimension())\n su... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Return diagonal matrix with entries from ``diagonal``. Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import ZZ >>> DomainMatrix.diag([ZZ(5), ZZ(6)], ZZ) | def diag(cls, diagonal, domain, shape=None):
if shape is None:
N = len(diagonal)
shape = (N, N)
return cls.from_rep(SDM.diag(diagonal, domain, shape)) | [
"def task6_diagonal(matrix):\n return np.diagonal(matrix)",
"def diagonal(matrix):\n if sp.sparse.issparse(matrix):\n diag = np.array(matrix.diagonal())\n else:\n diag = np.diagonal(matrix).copy()\n return diag",
"def get_diagonal(matrix):\n print('*' * 55)\n print('use list comp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a zero DomainMatrix of size shape, belonging to the specified domain Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> DomainMatrix.zeros((2, 3), QQ) DomainMatrix({}, (2, 3), QQ) | def zeros(cls, shape, domain, *, fmt='sparse'):
return cls.from_rep(SDM.zeros(shape, domain)) | [
"def empty(shape):\n return EigenMatrix(np.zeros(shape))",
"def zeros(shape, dtype=float):\n if not mathutil.is_shape(shape, ndim=2):\n raise ValueError(\"invalid shape\")\n\n sc = SparkContext.getOrCreate()\n\n nelem = 0\n\n rdd = sc.emptyRDD()\n\n return Matrix(rdd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a DomainMatrix of 1s, of size shape, belonging to the specified domain Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> DomainMatrix.ones((2,3), QQ) DomainMatrix([[1, 1, 1], [1, 1, 1]], (2, 3), QQ) | def ones(cls, shape, domain):
return cls.from_rep(DDM.ones(shape, domain).to_dfm_or_ddm()) | [
"def ones(cls, size:(int,int)) -> 'Matrix': #note single quotes because this is the class, itself and has not been completely defined yet.\n N = size[0]\n M = size[1]\n assert N > 0 and M > 0, \"N and M must be positive.\"\n return cls([[1 for col in range(M)] for row in range(N)])",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collect repeating factors and sort. >>> from sympy.polys.matrices.domainmatrix import _collect_factors >>> _collect_factors([([1, 2], 2), ([1, 4], 3), ([1, 2], 5)]) [([1, 4], 3), ([1, 2], 7)] | def _collect_factors(factors_list):
factors = Counter()
for factor, exponent in factors_list:
factors[tuple(factor)] += exponent
factors_list = [(list(f), e) for f, e in factors.items()]
return _sort_factors(factors_list) | [
"def factors(self):\n fs = []\n for factorlist in self._factors.values():\n fs.extend(factorlist)\n return fs",
"def sorted_factors(self):\n if not hasattr(self, \"_sorted_factors\"):\n self._sorted_factors = {}\n for expr in self.graded_dict:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read XML file, , and return the XML tree and root As this is a test script, errors will throw exceptions. | def read_xml_file(filename):
###############################################################################
with __FILE_OPEN(filename) as file_:
tree = ET.parse(file_)
root = tree.getroot()
# End with
return tree, root | [
"def read_xml(fname):\n tree = ET.parse(fname)\n root = tree.getroot()\n\n return tree, root",
"def get_xml_tree(filename):\n\n try:\n return ET.parse(filename)\n except IOError:\n print \"The file {} was not found.\".format(filename)\n return None\n except ET.ParseError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a good registry with only variables validates. Check that generate_registry_data.py generates good Fortran and metadata files | def test_good_simple_registry(self):
# Setup test
filename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_simple.xml")
out_source_name = "physics_types_simple"
in_source = os.path.join(_SAMPLE_FILES_DIR, out_source_name + '.F90')
in_meta = os.path.join(_SAMPLE_FILES_DIR, out_source_... | [
"def test_good_complete_registry(self):\n\n # Setup test\n filename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_complete.xml\")\n out_source_name = \"physics_types_complete\"\n in_source = os.path.join(_SAMPLE_FILES_DIR, out_source_name + '.F90')\n in_meta = os.path.join(_SAMPLE_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test code and metadata generation from a good registry with a DDT. Check that generate_registry_data.py generates good Fortran and metadata files. Check that the DDT contains the proper information depending on dycore | def test_good_ddt_registry(self):
# Setup test
filename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_ddt.xml")
out_name = "physics_types_ddt"
for dycore in ['fv', 'eul', 'se']:
out_source_name = out_name + '_' + dycore + '.F90'
out_meta_name = out_name + '_' + dyco... | [
"def test_good_ddt_registry2(self):\n # Setup test\n filename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_ddt2.xml\")\n out_name = \"physics_types_ddt2\"\n out_source_name = out_name + '.F90'\n out_meta_name = out_name + '.meta'\n in_source = os.path.join(_SAMPLE_FILES_DIR... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test code and metadata generation from a good registry with DDTs with extends and bindC attributes. Check that generate_registry_data.py generates good Fortran and metadata files. Check that the DDT contains the proper information depending on dycore | def test_good_ddt_registry2(self):
# Setup test
filename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_ddt2.xml")
out_name = "physics_types_ddt2"
out_source_name = out_name + '.F90'
out_meta_name = out_name + '.meta'
in_source = os.path.join(_SAMPLE_FILES_DIR, out_source_na... | [
"def test_good_ddt_registry(self):\n # Setup test\n filename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_ddt.xml\")\n out_name = \"physics_types_ddt\"\n for dycore in ['fv', 'eul', 'se']:\n out_source_name = out_name + '_' + dycore + '.F90'\n out_meta_name = out_na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test code and metadata generation from a good registry with DDTs containing an "Array" variable with multiple internal Array elements Check that generate_registry_data.py generates good Fortran and metadata files. Check that the DDT contains the proper information and the initialization code has the correct array calls | def test_good_array(self):
# Setup test
filename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_ddt_array.xml")
out_name = "physics_types_ddt_array"
out_source_name = out_name + '.F90'
out_meta_name = out_name + '.meta'
in_source = os.path.join(_SAMPLE_FILES_DIR, out_source_... | [
"def test_good_ddt_registry2(self):\n # Setup test\n filename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_ddt2.xml\")\n out_name = \"physics_types_ddt2\"\n out_source_name = out_name + '.F90'\n out_meta_name = out_name + '.meta'\n in_source = os.path.join(_SAMPLE_FILES_DIR... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test code and metadata generation from a good registry with a DDT and a metadata file. Check that generate_registry_data.py generates good Fortran and metadata files. Check that the DDT contains the proper information for the SE dycore | def test_good_metadata_file_registry(self):
# Setup test
filename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_mf.xml")
out_name = "physics_types_ddt"
in_source = os.path.join(_SAMPLE_FILES_DIR, out_name + '_se.F90')
in_meta = os.path.join(_SAMPLE_FILES_DIR, out_name + '_se.meta')... | [
"def test_good_ddt_registry(self):\n # Setup test\n filename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_ddt.xml\")\n out_name = \"physics_types_ddt\"\n for dycore in ['fv', 'eul', 'se']:\n out_source_name = out_name + '_' + dycore + '.F90'\n out_meta_name = out_na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform the same test as "test_good_metadata_file_registry", except with the metadata file located elsewhere, and the "src_root" input variable set accordingly. | def test_diff_src_root_metadata_file_registry(self):
# Setup test
filename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_mf.xml")
out_name = "physics_types_ddt"
in_source = os.path.join(_SAMPLE_FILES_DIR, out_name + '_se.F90')
in_meta = os.path.join(_SAMPLE_FILES_DIR, out_name + '_... | [
"def test_no_metadata_file_registry(self):\n # Setup test\n infilename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_mf.xml\")\n filename = os.path.join(_TMP_DIR, \"reg_no_mf.xml\")\n out_source_name = \"physics_types_no_mf\"\n out_source = out_source_name + '.F90'\n out_met... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a registry file present in the 'SourceMods' directory is correctly used over the standard input registry file. | def test_SourceMods_metadata_file_registry(self):
# Setup test
filename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_mf.xml")
out_name = "physics_types_ddt"
in_source = os.path.join(_SAMPLE_FILES_DIR, out_name + '_se.F90')
in_meta = os.path.join(_SAMPLE_FILES_DIR, out_name + '_se.... | [
"def test_good_simple_registry(self):\n # Setup test\n filename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_simple.xml\")\n out_source_name = \"physics_types_simple\"\n in_source = os.path.join(_SAMPLE_FILES_DIR, out_source_name + '.F90')\n in_meta = os.path.join(_SAMPLE_FILES_DI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a good registry with variables, metadata files, DDTs, Arrays, and parameters validates, i.e. try and test everything at once. Check that generate_registry_data.py generates good Fortran and metadata files with all of the proper code features. | def test_good_complete_registry(self):
# Setup test
filename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_complete.xml")
out_source_name = "physics_types_complete"
in_source = os.path.join(_SAMPLE_FILES_DIR, out_source_name + '.F90')
in_meta = os.path.join(_SAMPLE_FILES_DIR, out_... | [
"def test_good_simple_registry(self):\n # Setup test\n filename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_simple.xml\")\n out_source_name = \"physics_types_simple\"\n in_source = os.path.join(_SAMPLE_FILES_DIR, out_source_name + '.F90')\n in_meta = os.path.join(_SAMPLE_FILES_DI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test code and metadata generation from a good registry with a nonexistent metadata file. Check that generate_registry_data.py raises the correct error. | def test_no_metadata_file_registry(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_mf.xml")
filename = os.path.join(_TMP_DIR, "reg_no_mf.xml")
out_source_name = "physics_types_no_mf"
out_source = out_source_name + '.F90'
out_meta_name = out_sour... | [
"def test_good_metadata_file_registry(self):\n # Setup test\n filename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_mf.xml\")\n out_name = \"physics_types_ddt\"\n in_source = os.path.join(_SAMPLE_FILES_DIR, out_name + '_se.F90')\n in_meta = os.path.join(_SAMPLE_FILES_DIR, out_name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a bad version number. Check that it does not validate and does not generate any Fortran or metadata files | def test_bad_registry_version(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_simple.xml")
filename = os.path.join(_TMP_DIR, "reg_bad_version.xml")
out_source_name = "physics_types_bad_ver"
out_source = os.path.join(_TMP_DIR, out_source_name + '.F90')
... | [
"def test_invalid_version(self, version):\n with pytest.raises((ValueError, TypeError), match=\"Invalid version number\"):\n XIRProgram(version=version)",
"def test_registry(self):\n validate_registry()",
"def test_version_control_invalid(self):\n versions = ('Thirteen', '-1', -1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a missing standard name. Check that it does not validate and does not generate any Fortran or metadata files | def test_missing_standard_name(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_simple.xml")
filename = os.path.join(_TMP_DIR, "reg_no_std_name.xml")
out_source_name = "physics_types_no_std_name"
out_source = os.path.join(_TMP_DIR, out_source_name + '.F9... | [
"def test_registry(self):\n validate_registry()",
"def test_no_metadata_file_registry(self):\n # Setup test\n infilename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_mf.xml\")\n filename = os.path.join(_TMP_DIR, \"reg_no_mf.xml\")\n out_source_name = \"physics_types_no_mf\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a variable with bad dimensions. Check that it does not validate and does not generate any Fortran or metadata files | def test_bad_dimensions(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_simple.xml")
filename = os.path.join(_TMP_DIR, "reg_bad_dimensions.xml")
out_source_name = "physics_types_bad_dimensions"
out_source = os.path.join(_TMP_DIR, out_source_name + '.F90... | [
"def test_unknown_dimensions(self):\n # Setup test\n infilename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_simple.xml\")\n filename = os.path.join(_TMP_DIR, \"reg_unknown_dimension.xml\")\n out_source_name = \"physics_types_unknown_dimension\"\n out_source = os.path.join(_TMP_DI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a variable with an unknown dimension. Check that it does not validate and does not generate any Fortran or metadata files | def test_unknown_dimensions(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_simple.xml")
filename = os.path.join(_TMP_DIR, "reg_unknown_dimension.xml")
out_source_name = "physics_types_unknown_dimension"
out_source = os.path.join(_TMP_DIR, out_source_na... | [
"def test_bad_dimensions(self):\n # Setup test\n infilename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_simple.xml\")\n filename = os.path.join(_TMP_DIR, \"reg_bad_dimensions.xml\")\n out_source_name = \"physics_types_bad_dimensions\"\n out_source = os.path.join(_TMP_DIR, out_sou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a parameter with no initial value. Check that it does not validate and does not generate any Fortran or metadata files | def test_no_init_value(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_simple.xml")
filename = os.path.join(_TMP_DIR, "reg_no_init_value.xml")
out_source_name = "physics_types_no_init_value"
out_source = os.path.join(_TMP_DIR, out_source_name + '.F90')
... | [
"def test_registry(self):\n validate_registry()",
"def test_registry_param_type() -> None:\n r: Registry = Registry()\n assert r._default_kwarg is None\n with pytest.raises(ValueError, match=\"kwarg parameter cannot be blank\"):\n Registry(kwarg='')\n with pytest.raises(TypeError):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a duplicate DDT type. Check that it raises an exception and does not generate any Fortran or metadata files | def test_duplicate_type(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_ddt.xml")
filename = os.path.join(_TMP_DIR, "reg_dup_ddt.xml")
out_source_name = "physics_types_dup_ddt"
out_source = os.path.join(_TMP_DIR, out_source_name + '.F90')
out_me... | [
"def test_good_ddt_registry2(self):\n # Setup test\n filename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_ddt2.xml\")\n out_name = \"physics_types_ddt2\"\n out_source_name = out_name + '.F90'\n out_meta_name = out_name + '.meta'\n in_source = os.path.join(_SAMPLE_FILES_DIR... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a DDT variable that has a kind attribute. Check that it raises an exception and does not generate any Fortran or metadata files | def test_ddt_with_kind(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_ddt.xml")
filename = os.path.join(_TMP_DIR, "reg_ddt_with_kind.xml")
out_source_name = "physics_types_ddt_with_kind"
out_source = os.path.join(_TMP_DIR, out_source_name + '.F90')
... | [
"def test_ddt_with_unknown_type(self):\n # Setup test\n infilename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_ddt.xml\")\n filename = os.path.join(_TMP_DIR, \"reg_ddt_var_unknown.xml\")\n out_source_name = \"physics_types_ddt_var_unknown_type\"\n out_source = os.path.join(_TMP_D... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a DDT variable of unknown type. Check that it raises an exception and does not generate any Fortran or metadata files | def test_ddt_with_unknown_type(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_ddt.xml")
filename = os.path.join(_TMP_DIR, "reg_ddt_var_unknown.xml")
out_source_name = "physics_types_ddt_var_unknown_type"
out_source = os.path.join(_TMP_DIR, out_source_n... | [
"def test_good_ddt_registry(self):\n # Setup test\n filename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_ddt.xml\")\n out_name = \"physics_types_ddt\"\n for dycore in ['fv', 'eul', 'se']:\n out_source_name = out_name + '_' + dycore + '.F90'\n out_meta_name = out_na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a DDT which extends an unknown type attributes. Check that it raises an exception and does not generate any Fortran or metadata files | def test_ddt_with_unknown_extends(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_ddt.xml")
filename = os.path.join(_TMP_DIR, "reg_ddt_unknown_extends.xml")
out_source_name = "physics_types_ddt_unknown_extends"
out_source = os.path.join(_TMP_DIR, out_so... | [
"def test_ddt_with_unknown_type(self):\n # Setup test\n infilename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_ddt.xml\")\n filename = os.path.join(_TMP_DIR, \"reg_ddt_var_unknown.xml\")\n out_source_name = \"physics_types_ddt_var_unknown_type\"\n out_source = os.path.join(_TMP_D... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a DDT with both the extends and bindC attributes. Check that it raises an exception and does not generate any Fortran or metadata files | def test_ddt_with_incompatible_attr(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_ddt2.xml")
filename = os.path.join(_TMP_DIR, "reg_ddt_incompatible_attributes.xml")
out_source_name = "physics_types_ddt_incompatible_attributes"
out_source = os.path.jo... | [
"def test_good_ddt_registry(self):\n # Setup test\n filename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_ddt.xml\")\n out_name = \"physics_types_ddt\"\n for dycore in ['fv', 'eul', 'se']:\n out_source_name = out_name + '_' + dycore + '.F90'\n out_meta_name = out_na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a duplicate local name. Check that it raises an exception and does not generate any Fortran or metadata files | def test_duplicate_local_name(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_simple.xml")
filename = os.path.join(_TMP_DIR, "reg_duplicate_local_name.xml")
out_source_name = "physics_types_duplicate_local_name"
out_source = os.path.join(_TMP_DIR, out_s... | [
"def test_duplicate_standard_name(self):\n # Setup test\n infilename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_simple.xml\")\n filename = os.path.join(_TMP_DIR, \"reg_duplicate_standard_name.xml\")\n out_source_name = \"physics_types_duplicate_standard_name\"\n out_source = os.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a registry with a duplicate standard name. Check that it raises an exception and does not generate any Fortran or metadata files | def test_duplicate_standard_name(self):
# Setup test
infilename = os.path.join(_SAMPLE_FILES_DIR, "reg_good_simple.xml")
filename = os.path.join(_TMP_DIR, "reg_duplicate_standard_name.xml")
out_source_name = "physics_types_duplicate_standard_name"
out_source = os.path.join(_TMP_D... | [
"def test_missing_standard_name(self):\n # Setup test\n infilename = os.path.join(_SAMPLE_FILES_DIR, \"reg_good_simple.xml\")\n filename = os.path.join(_TMP_DIR, \"reg_no_std_name.xml\")\n out_source_name = \"physics_types_no_std_name\"\n out_source = os.path.join(_TMP_DIR, out_so... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates day 2 test data | def day2_data():
test_data = []
test_data.append([5, 1, 9, 5])
test_data.append([7, 5, 3])
test_data.append([2, 4, 6, 8])
return test_data | [
"def day2part2_data():\n test_data = []\n test_data.append([5, 9, 2, 8])\n test_data.append([9, 4, 7, 3])\n test_data.append([3, 8, 6, 5])\n return test_data",
"def test_factory_methods(self):\n\n DatumTest.create_data()",
"def create_test_episodes(self, n_episodes):",
"def test_create_r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates day 2 test data | def day2part2_data():
test_data = []
test_data.append([5, 9, 2, 8])
test_data.append([9, 4, 7, 3])
test_data.append([3, 8, 6, 5])
return test_data | [
"def day2_data():\n test_data = []\n test_data.append([5, 1, 9, 5])\n test_data.append([7, 5, 3])\n test_data.append([2, 4, 6, 8])\n return test_data",
"def test_factory_methods(self):\n\n DatumTest.create_data()",
"def create_test_episodes(self, n_episodes):",
"def test_create_run(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint which is used to have the number of condominium of a specific company | def number_condominium_company_business(id_company):
number_condominium_company_bus = requests.get('http://127.0.0.1:5050/{}/number_condominium'.format(id_company), headers={"Content-Type": "application/json"})
data = json.loads(number_condominium_company_bus.text)
if 'counter' in data and data.get('status... | [
"def number_condominium_all_business():\n\n number_condominium_bus = requests.get('http://127.0.0.1:5050/number_condominium', headers={\"Content-Type\": \"application/json\"})\n data = json.loads(number_condominium_bus.text)\n if 'counter' in data and data.get('status', '') == 'OK':\n response = {\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint which is used to have the number of condominium of a specific technician | def number_condominium_all_business():
number_condominium_bus = requests.get('http://127.0.0.1:5050/number_condominium', headers={"Content-Type": "application/json"})
data = json.loads(number_condominium_bus.text)
if 'counter' in data and data.get('status', '') == 'OK':
response = {
"me... | [
"def getCountInstitutionByEtat(self, institutionEtat):",
"def getCountAllInstitution(self):",
"def getCounterIn_nat(type_dev, adr_sw, adr_port):\n\tpass",
"def get_total_requests_number(self):",
"def test_get_resource_license_resource_count_by_moid(self):\n pass",
"def count(cls, client) :\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the mean rate and the mean PNSR associated to the compression of the RGB digits via an entropy autoencoder. An image of the RGB digits after being compressed via the entropy autoencoder is saved. | def compute_rate_psnr(reference_uint8, mean_training, std_training, entropy_ae,
bin_width, nb_vertically, path_to_reconstruction):
# The function `svhn.svhn.preprocess_svhn` checks
# that `reference_uint8.dtype` is equal to `numpy.uint8`
# and `reference_uint8.ndim` is equal to 2.
... | [
"def compute_rate_psnr(luminances_uint8, path_to_before_hevc, path_to_after_hevc, path_to_cfg,\n path_to_bitstream, qp, path_to_storage, list_rotation, positions_top_left):\n # If `luminances_uint8.ndim` is not equal to 3,\n # the unpacking below raises a `ValueError` exception.\n (nb_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain batch of training examples from a list of tasks | def _generate_batch(self, tasks: List):
x_batch = np.stack([np.random.uniform(low=self.domain_bounds[0], high=self.domain_bounds[1], size=(self.inner_update_k, 1)) for _ in range(len(tasks))])
y_batch = np.stack([[tasks[t](x) for x in x_batch[t]] for t in range(len(tasks))])
return x_batch, y_b... | [
"def gen_multitask_batches(tasks, train):\n iterator_id = 0\n all_batches = []\n for task_id, iterator in tasks:\n if train:\n iterator.dataset.train()\n else:\n iterator.dataset.eval()\n\n for batch in iterator:\n al... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If using fixed validation this method returns a set of tasks that are equally spread across the task distribution space. | def _get_fixed_validation_tasks(self):
# mesh of equally partitioned state space
if self.task_type == 'sin3d':
amplitude_spectrum, phase_spectrum, frequency_spectrum = np.mgrid[
self.amplitude_bounds[0]:self.amplitude_bounds[1]:self.validation_block_sizes[0],
... | [
"def _constraints_task_spread(self):\n # encourage scheduling a chunk for every 24 hours\n diag = util.blockdiag(self.num_timeslots, incr=tutil.SLOTS_PER_DAY)\n slots = diag.shape[0]\n\n def rule(model, p, j):\n \"\"\"\n For spread-activated tasks, this rule is used... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produces plot of priority queue (losses or counts) Discrete vs continuous, 2d heatmap vs 3d. | def visualise_priority_queue(self, feature='losses'):
if type(self._queue) == np.ndarray:
if len(self._queue.shape) == 2:
fig = plt.figure()
if feature == 'losses':
plt.imshow(self._queue)
elif feature == 'counts':
... | [
"def visualise_priority_queue(self, feature='losses'):\n if type(self.queue) == np.ndarray:\n if len(self.queue.shape) == 2:\n fig = plt.figure()\n if feature == 'losses':\n plt.imshow(self.queue)\n elif feature == 'counts':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produces probability distribution plot of losses in the priority queue | def visualise_priority_queue_loss_distribution(self):
all_losses = self._queue.flatten()
hist, bin_edges = np.histogram(all_losses, bins=int(0.1 * len(all_losses)))
bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
fig = plt.figure()
plt.plot(bin_centers, hist)
return ... | [
"def visualise_priority_queue_loss_distribution(self):\n all_losses = self.queue.flatten()\n\n hist, bin_edges = np.histogram(all_losses, bins=int(0.1 * len(all_losses)))\n bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2\n\n fig = plt.figure()\n plt.plot(bin_centers, hist)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the goal of hero current position. | def check_goal(self):
hero = self.objects[0]
others = self.objects[1:]
for other in others:
if other.x == hero.x and other.y == hero.y:
self.objects.remove(other)
if other.reward == 1:
self.objects.append(GameObject(self.__new_posi... | [
"def check_at_goal(self, currentLocation):\n pass",
"def at_goal(self):\n return self.distance_from_goal < self.robot.wheels.base_length/2",
"def checkGoal(self):\n # -- It is not included for simplifity --#\n if self.reward_cumulative != None:\n x = round((abs(self.reward... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates list dict from parsing list Key refers to the asserted index (key_ind), value by default takes all the indexes (including the key index) | def create_dict_from_list(parse_list, key_ind, *val_inds):
parse_dict=defaultdict(list)
for string in parse_list:
if not val_inds:
parse_dict[string[key_ind]]=string
else:
parse_dict[string[key_ind]]=[string[i] for i in range(len(string)) if i in val_inds]
return(pars... | [
"def index_label_reader(index_list):\n index_dict = OrderedDict()\n for doc_id, doc_pos in index_list:\n doc_pos = doc_pos.split(\" \")\n temp_dict = []\n for i in doc_pos:\n # (global_instance_idx, token_idx, sense)\n pair = i.split(\":\")\n temp_dict.app... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads csv file and returns list without header by default If headless argument is false, parses the whole file | def read_csv_to_list(in_file, headless=True, delim='\t'):
ret_list=list()
with open(in_file,'r') as csv_file:
my_reader = csv.reader(csv_file, delimiter=delim)
if headless:
next(my_reader)
for row in my_reader:
ret_list.append(list(row))
return(ret_list) | [
"def read_csv_file(self):\n pass",
"def fread_csv(fp, delim = ','):\n \n data = []\n line = fp.readline()\n while line != \"\":\n if line[0] != '#' and not empty_line_p(line):\n data.append(parse_line(line, delim))\n line = fp.readline()\n return data",
"def _read_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A universal function for writing lists to csvfiles If input is list of lists uses writerows function else iteratively writes If strings for header are specified, writes header to the output, saves headless table otherwise | def write_csv(row_list,out_name,*header_strings : str):
with open(out_name,'w',newline='') as result_file:
wr = csv.writer(result_file, delimiter='\t')
if header_strings:
wr.writerow([name for name in header_strings])
if type(row_list[0]) is list:
wr.writerows(row_lis... | [
"def csv_writer(list_,csv_name):\n with open(csv_name,\"wb\") as outfile:\n csv_writer = csv.writer(outfile)\n for element in list_:\n csv_writer.writerow(element)",
"def CSVWriter (iterable, outLoc, header=\"\", ):\n if not iterable:\n print (\"nothing to write\")\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subscribe a subscription actor | def subscribe(self, subscription):
try:
if isinstance(subscription, Subscription):
sub = Subscribe(subscription, self.__pool, self.myAddress)
self.send(self.__pool, sub)
except Exception:
handle_actor_system_fail() | [
"def subscribe(self, subject):\n pass",
"def subscribe(self, *args):\n return self.write(u'SUBSCRIBE', *args)",
"def subscribeMember(member):",
"def subscribeAuthenticatedMember():",
"def subscribe(self, channel, **kwargs):\n pass",
"def psubscribe(self, *args):\n return self.w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DeSubscribe a subscription actor | def desubscribe(self, subscription):
try:
if isinstance(subscription, Subscription):
sub = DeSubscribe(subscription, self.__pool, self.myAddress)
self.send(self.__pool, sub)
except Exception:
handle_actor_system_fail() | [
"def unsubscribe(self, subject):\n pass",
"def unsubscribe(self, *args):\n return self.write(u'UNSUBSCRIBE', *args)",
"def unsubscribe(self, subscriber):\n self._observers.remove(subscriber)",
"def unsubscribe(self):\n pass # pragma: no cover",
"def unsubscribe(callback):\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the drop policy | def set_drop_policy(self, msg, sender):
payload = msg.payload
if isinstance(payload, str):
self.drop_policy = payload | [
"def setDropThreshold(self, dropThreshold): # real signature unknown; restored from __doc__\n pass",
"def packet_drop_rate(self, drop_rate):\n\n if drop_rate < 0 or drop_rate > 1:\n raise Exception('Packet drop rate should be between 0 and 1')\n\n if not (isinstance(drop_rate, int)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve comments from local database. | def get_comments():
conn = pymongo.Connection("localhost",27017)
db = conn["paperDB"]
infoDB = db.infoDB
record = infoDB.find_one()
return record['comment'] | [
"def get_comments(self):\n print(\"\\nReading posts currently in database\")\n print(\"---------------------------------------\")\n \n res = requests.get(API_COMMENT_URL)\n self.comments.extend(res.json())\n\n print(\"{} comments read from database successfully\".format(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a blog from local database. | def get_blog():
conn = pymongo.Connection("localhost",27017)
db = conn["paperDB"]
infoDB = db.infoDB
record = infoDB.find_one()
del record['_id']
del record['comment'] # reserve space
# Since there's only one blog per page, use namedtuple
blog = namedtuple('Blog', record.keys())(*reco... | [
"def get(self, id):\n blog = get_a_blog(id)\n if not blog:\n api.abort(404)\n else:\n return blog",
"def GetById(id):\n return Blog.query.get(int(id))",
"def get_blog(id):\n key = KEY_BLOG_PREFIX + str(id)\n blog = RedisHelper.get_cache(key)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the pixel at x, y to be of colour colour (default 1 = black ink). Any colour value other than 0 (white paper) is taken to be 1 (black ink). | def set(self, x, y, colour=1):
inkCol = None
if colour == 0:
# self.__draw.setink(bitmap._pixelWhite)
inkCol = bitmap._pixelWhite
else:
# self.__draw.setink(bitmap._pixelBlack)
inkCol = bitmap._pixelBlack
self.__draw.point((x, y), fill=ink... | [
"def setPixel (self, x, y, colour):\r\n self.image [y][x] = colour",
"def set_green(self, x, y, newval):\n self.__check_dimensions(x, y)\n return self.pixels[(x, y)].set_green(newval)",
"def set_pixel(self, x, y, color):\n self._data[y][x] = color",
"def set_red(self, x, y, newval)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write this bitmap to a file with the given filename. File type is deduced from the extension (exception if it can't be figured out). | def write(self, filename):
self.__image.save(filename) | [
"def save(self, filename):\n \n path, name = os.path.split(filename)\n ext = name.split(\".\")[-1]\n _tkExec(self.image.write, filename, format=ext)",
"def save_image(self, filename):\n if filename[-4:] != '.pkl':\n filename + '.pkl'\n with open(filename, 'wb')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a new bitmap, twice as big linearly, by pixelcoding every pixel of bmp into a grid of 4 pixels. Pixelcoding means translating each pixel into a grid of pixels in a clever way which is the core idea of visual cryptography. Read the poster for more on that. | def pixelcode(self):
maxX, maxY = self.size()
result = bitmap((2*maxX, 2*maxY))
for x in range(maxX):
for y in range(maxY):
pixel = self.get(x,y)
result.set(2*x,2*y, pixel)
result.set(2*x,2*y+1, not pixel)
result.set(2*... | [
"def bitmap(img, profundidad=8):\n img_shape = img.shape\n\n assert len(img_shape)==2, \"Utilizar una imagen en grises, o solo pasar un sólo canal.\"\n\n bit_maps = []\n\n for i in np.arange(profundidad):\n new_map = np.zeros((img_shape[0], img_shape[1]))\n for x in np.arange(img_shape[0])... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply the boolean operation 'operation' (a binary function of two integers returning an integer) to the list of bitmaps in 'bitmaps' | def boolean(operation, bitmaps):
maxX, maxY = size = bitmaps[0].size()
result = bitmap(size)
for x in range(maxX):
for y in range(maxY):
pixel = bitmaps[0].get(x,y)
for b in bitmaps[1:]:
pixel = apply(operation, (pixel, b.get(x,y)))
result.set(x,y... | [
"def apply(masks: Sequence[int], value: int) -> Iterator[int]:\n return ((value & mask) for mask in masks)",
"def test_apply_flags():\n true_value = dqflags.pixel['HOT'] + dqflags.pixel['DO_NOT_USE']\n\n print(true_value)\n\n badmap = np.zeros((10, 10), dtype=np.int)\n true_map = np.zeros((10, 10),... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take a size (2tuple of x and y) and return a bitmap of that size filled with random pixels. WARNING! THE CODE HERE IS ONLY FOR DEMONSTRATION PURPOSES, SINCE IT CALLS THE STANDARD PYTHON RANDOM NUMBER GENERATOR, which is fine for statistics but not good enough for crypto. For real use, substitute this with really random... | def randomBitmap(size):
b = bitmap(size)
xmax, ymax = size
for x in xrange(xmax):
for y in xrange(ymax):
b.set(x, y, random.randint(0,1))
return b | [
"def random_image(x, y, out):\n\n pixels = []\n for pixel in range(0, x*y):\n pixels.append(random_pixel())\n\n new_image(x, y, out, pixels)",
"def generateRandomImage(size, lims=[0,255]):\n a,b = lims\n image_array = (b-a)*np.random.random(size) + a\n image = sitk.GetImageFromArray(image... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take a plaintext bitmap and, optionally, a supposedly random pad of the same size (one will be made up on the spot if not supplied). Return a 2tuple containing the large pixelcoded versions of ciphertext and pad. | def encrypt(rawPlaintext, rawPad = None):
# The raw versions are the same size as the original rawPlaintext
if not rawPad:
rawPad = randomBitmap(rawPlaintext.size())
rawCiphertext = XOR(rawPlaintext, rawPad)
# The final versions are linearly twice as big due to pixelcoding
ciphertext = raw... | [
"def testEncryptDecrypt(root):\n\n plaintext = bitmap(\"vck.gif\")\n ciphertext, pad = encrypt(plaintext)\n decryptedResult = decrypt(ciphertext, pad)\n\n v1 = plaintext.view(root, \"plaintext\")\n v2 = pad.view(root, \"pad (pixelcoded)\")\n v3 = ciphertext.view(root, \"ciphertext (pixelcoded)\")\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute the supplied function. The function may create new windows by calling bitmap.view() or by making instances of viewer, but it must return a list of any such windows it makes. The point of this wrapper is merely to shield the caller away from the quirks of initialising Tkinter, running its main loop and ensuring ... | def mainApp(function):
root = Tkinter.Tk()
quit = Tkinter.Button(root, text="Quit", command=root.quit)
quit.pack()
Tkinter.Wm.title(root, "VCK main")
windows = function(root)
root.update()
root.mainloop() | [
"def invoke(function):\n def inner(*args, **kwargs):\n if Thread.CurrentThread.ManagedThreadId != _main_id:\n return root.Dispatcher.BeginInvoke(lambda: function(*args, **kwargs))\n return function(*args, **kwargs)\n return inner",
"def _showView(self, win, fn=None):\n raise ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take a function f(x,y) that accepts a position in the moonfield and returns an integer value. Fill every cell in the moonfield with the value returned by the filler (taken modulo mod). | def fill(self, filler):
for x in range(self.__xmax):
for y in range(self.__ymax):
self.__data[(x,y)] = filler(x,y) % self.mod | [
"def fill(self, func=lambda: random().getdigits(1), diag=None):\n for y,x in self.coords(diag):\n self.store(y,x, func())",
"def mod(i):\r\n return i % NUM_PIXELS",
"def __mod__(self,integer):\n return Coords(self.x % integer, self.y % integer)",
"def fill_tiles(tiles, fill_func):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fill the moonfield with random values in the range min..max | def randomFill(self, low=0, high=mod-1):
def randomFiller(x,y, low=low, high=high):
return random.randint(low, high)
self.fill(randomFiller) | [
"def fill_random(self,low,high):\n\n for i in range(self.size):\n\n # HIGH + 1 is used because the number in the\n # argument for the largest possible random number\n # is excluded.\n self.data[i] = random.randrange(RANGE_LOW, RANGE_HIGH + 1)",
"def real_rand(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take a canvas and render the moonfield on it. The radius of the halfmoons must be specified in canvas units. | def renderOnCanvas(self, canvas, radius=moonfieldViewer.R):
for x in range(self.__xmax):
for y in range(self.__ymax):
# Make the halfmoon at x,y
canvas.create_arc(
radius*2*x, radius*2*y, radius*2*(x+1)-1, radius*2*(y+1)-1,
sta... | [
"def draw_scene(canvas, scene_left, scene_top, scene_right, scene_bottom):\r\n # Call your functions here, such as draw_sky, draw_ground,\r\n # draw_snowman, draw_tree, draw_shrub, etc.\r\n ## tree_left = scene_left + 500\r\n ## tree_top = scene_top + 100\r\n ## tree_height = 150\r\n ## draw_pine_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a moonfield obtained by rebuilding the one that had been dumped to the given file. | def moonfield_undump(filename):
return pickle.load(open(filename)) | [
"def from_dem(file, verbose=False):\n import subprocess, os\n from uuid import uuid4\n jarCall = list(REP_DEM_JARBASE)\n jarCall[-2] = file\n if not os.path.exists(OPTIONS.JB.SCRATCH): os.makedirs(OPTIONS.JB.SCRATCH)\n jarCall[-1] = os.path.abspath(os.path.join(OPTIONS.JB.S... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a cryptograph. Take a monochrome image (the filename of a | def makeCryptograph(imageFile, codedFile="coded.tif", dumpFile="media/rawpad.pbm"):
print(os.getcwd())
pad = bitmap(dumpFile)
plaintext = bitmap(imageFile)
ciphertext = XOR(pad, plaintext)
expandedCiphertext = ciphertext.pixelcode()
expandedCiphertext.write(codedFile)
return expandedCipherte... | [
"def makeCryptographG(root, image, codedFile=\"coded.ps\", dumpFile=\"rawpad.mfd\"):\n\n pad = moonfield_undump(dumpFile)\n ciphertext = pad.imageComplement(image)\n v = ciphertext.view(root)\n v.psprint(codedFile)\n return ciphertext, v",
"def decrypt_your_message():\n\n a = []\n keys = []\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a cryptograph. Take an image (either a PIL image of type "L" or a filename) and a file with a dump of a raw pad moonfield | def makeCryptographG(root, image, codedFile="coded.ps", dumpFile="rawpad.mfd"):
pad = moonfield_undump(dumpFile)
ciphertext = pad.imageComplement(image)
v = ciphertext.view(root)
v.psprint(codedFile)
return ciphertext, v | [
"def makeCryptograph(imageFile, codedFile=\"coded.tif\", dumpFile=\"media/rawpad.pbm\"):\n print(os.getcwd())\n pad = bitmap(dumpFile)\n plaintext = bitmap(imageFile)\n ciphertext = XOR(pad, plaintext)\n expandedCiphertext = ciphertext.pixelcode()\n expandedCiphertext.write(codedFile)\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Not for spies, really, just for cute demos. Take a greyscale image (either an "L" image object or a filename) and produce two postscript files of halfmoons that, when superimposed, will yield the image. Return a quadruple made of the two shares and two viewers showing them. | def splitImageG(root, image, shareFile1="share1.ps", shareFile2="share2.ps"):
if type(image) == type(""):
image = Image.open(image).convert("L")
p, v1 = makePadG(root, image.size, shareFile1)
c, v2 = makeCryptographG(root, image, shareFile2)
return p, c, v1, v2 | [
"def exchange():\n img_1 = cv2.imread('src/lena.jpg', cv2.IMREAD_GRAYSCALE)\n img_2 = cv2.imread('src/bowl.tiff', cv2.IMREAD_GRAYSCALE)\n\n amp_1, angle_1 = get_amplitude_angle(img_1)\n amp_2, angle_2 = get_amplitude_angle(img_2)\n\n dst_1 = reconstuct_image(amp_1, angle_2)\n dst_2 = reconstuct_im... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encrypt a monochrome image and decrypt it, showing the results on screen (work in memory, don't save to files). | def testEncryptDecrypt(root):
plaintext = bitmap("vck.gif")
ciphertext, pad = encrypt(plaintext)
decryptedResult = decrypt(ciphertext, pad)
v1 = plaintext.view(root, "plaintext")
v2 = pad.view(root, "pad (pixelcoded)")
v3 = ciphertext.view(root, "ciphertext (pixelcoded)")
v4 = decryptedRes... | [
"def decrypt_your_message():\n\n a = []\n keys = []\n img = Image.open(input(\"path to image: \"))\n\n pix = img.load()\n f = open(input('path to keys: '), 'r')\n\n fw = open('new_image.png', 'r+b')\n img_code = str(fw.read())\n\n fl = open('code_img.txt', 'w')\n flw = fl.write(img_code)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Demonstrate the boolean operations available in VCK by combining an image (vck.tif must be in the current directory) with a diagonal cross. | def testBooleanOps(root):
letters = bitmap("vck.tif")
v1 = letters.view(root, "vck")
cross = bitmap(letters.size())
xmax, ymax = cross.size()
r = ymax*1.0/xmax
for x in range(xmax):
cross.set(x, x*r)
cross.set(x, x*r+1)
cross.set(x, x*r-1)
cross.set(x, ymax-x*r)... | [
"def createComposite(self):\n\n success = False\n msg = 'Placeholder'\n\n #########################################\n ## PLACE YOUR CODE BETWEEN THESE LINES ##\n #########################################'\n cIn = self._images['colIn']\n bIn = self._images['backIn']\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split a greyscale image into two shares (postscript files). | def testSplitImageG(root):
p, c, v1, v2 = splitImageG(root, "guido.tif")
p.renderOnCanvas(v2.canvas())
v2.psprint("guido-decrypted.ps")
return v2 | [
"def splitImageG(root, image, shareFile1=\"share1.ps\", shareFile2=\"share2.ps\"):\n\n if type(image) == type(\"\"):\n image = Image.open(image).convert(\"L\")\n p, v1 = makePadG(root, image.size, shareFile1)\n c, v2 = makeCryptographG(root, image, shareFile2)\n return p, c, v1, v2",
"def split... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that packrat parsing was enabled | def test_enable_pyparsing_packrat_parsing():
import pyparsing
assert pyparsing.ParserElement._packratEnabled is True | [
"def test_package_json_jetpack():\n err = _do_test(MockXPI({'bootstrap.js': '', 'package.json': ''}))\n assert not err.errors\n assert not err.warnings\n assert not err.notices\n assert err.metadata.get('is_jetpack') is True",
"def test_pretagged():\n nlp = stanza.Pipeline(lang='en', dir=TEST_MO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that pyparsing._trim_arity has been replaced | def test_disable_pyparsing_arity_trimming():
import pyparsing
import dice.utilities
assert pyparsing._trim_arity is dice.utilities._trim_arity | [
"def test_disable_pyparsing_arity_trimming_works():\n for func in [lambda a: None, lambda a, b: None, lambda a, b, c, d: None]:\n element = Literal('test').setParseAction(func)\n with raises(TypeError):\n element.parseString('test')",
"def test_WhitespaceTokenizer():",
"def test_eval... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that arity trimming has been disabled and parse actions with the wrong number of arguments will raise TypeErrors | def test_disable_pyparsing_arity_trimming_works():
for func in [lambda a: None, lambda a, b: None, lambda a, b, c, d: None]:
element = Literal('test').setParseAction(func)
with raises(TypeError):
element.parseString('test') | [
"def test_disable_pyparsing_arity_trimming():\n import pyparsing\n import dice.utilities\n assert pyparsing._trim_arity is dice.utilities._trim_arity",
"def test_parser_dispatch(self):\n valid_cmds = 'A L |R V Z c b T a l'.split()\n for cmd in valid_cmds:\n parser = self.base.pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get authorization header for user using the passed client. | def get_authorization_header(client, user):
# obtain authorization token
response = client.post(
reverse('token-obtain'),
data={'username': user.username, 'password': user.raw_password},
content_type='application/json'
)
token = response.json()['access']
return {'HTTP_AUTHORI... | [
"def get_access_header(client, user):\n\n response = client.post(\n reverse('token-obtain'),\n data={'username': user.username, 'password': user.raw_password},\n headers={'Content-type': 'application/json'}\n )\n token = response.json()['access']\n return {'HTTP_AUTHORIZATION': f'Be... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open the file and return the docx document. | def get_docx_document(docx_file: str) -> docx.Document:
if os.path.isfile(docx_file):
return docx.Document(docx_file)
else:
logging.error("Could not find file at: " + str(docx_file))
return docx.Document() | [
"def return_doc_object(filename):\n return docx.Document(filename)",
"def extract_content_from_document(self, filename):\n ext = os.path.splitext(filename)[1]\n if ext == '.docx':\n with open(filename, \"rb\") as f:\n html = mammoth.convert_to_html(f).value\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rename output file replacing placeholders from meta dict (edition, component, language, version). | def rename_output_file(file_type: str, style: str, meta: Dict[str, str]) -> str:
args_output_file: str = convert_vars.args.outputfile
logging.debug(f" --- args_output_file = {args_output_file}")
if args_output_file:
# Output file is specified as an argument
if os.path.isabs(args_output_file)... | [
"def rename(self, current_suffix: str):\n os.rename(os.path.join(self.full_output_path, f\"{current_suffix}.py\"),\n os.path.join(self.full_output_path, f\"{self.dir_name}.py\"))\n os.rename(os.path.join(self.full_output_path, f\"{current_suffix}_test.py\"),\n os.path... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace the text in the docx document. | def replace_docx_inline_text(doc: docx.Document, data: Dict[str, str]) -> docx.Document:
logging.debug(" --- starting docx_replace")
if convert_vars.making_template:
replacement_values = sort_keys_longest_to_shortest(data)
else:
replacement_values = list(data.items())
paragraphs = get_... | [
"def replace_content(self, text):\n closing_tag = self.get_closing_tag()\n element = XmlDocElement(text)\n element.set_previous(self)\n element.set_next(closing_tag)\n self.set_next(element)\n closing_tag.set_previous(element)",
"def replace_text(self, text):\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Zip all the files recursively from path into zip_filename (excluding root path) | def zip_dir(path: str, zip_filename: str) -> None:
with zipfile.ZipFile(zip_filename, "w", zipfile.ZIP_DEFLATED) as zip_file:
for root, dirs, files in os.walk(path):
for file in files:
f = os.path.join(root, file)
zip_file.write(f, f[len(path) :]) | [
"def zip_dir(path):\n file_out = BytesIO()\n with zipfile.ZipFile(file_out, \"w\", zipfile.ZIP_DEFLATED) as ziph:\n for root, _, files in os.walk(path):\n for file in files:\n _add_file_to_zip(\n ziph,\n os.path.join(root, file),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fetch the top k similar parameters as argument indices | def fetch_top_k(vect, mat, k):
resultant = np.dot(mat, vect)
arglist = np.argsort(resultant)
arglist = arglist[-1:(-1 - k):-1]
return arglist, resultant | [
"def _extract_topk(alist, k):\r\n scores = [t.score for t in alist]\r\n indices = np.argsort(alist)[:k]\r\n return [alist[idx] for idx in indices]",
"def get_top_k_indices(arr, k=1):\n\n return arr.argsort()[-k:][::-1]",
"def top_k_predictions(pred,k):\n return [np.argsort... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query available sources for sequence details. Overwrite method in subclasses to fetch data. | def _query_sequence_sources(self):
pass | [
"def _query_sequence_sources(self):\n if self.uniprot_id:\n self._query_uniprot()\n elif self.ncbi_id:\n self._query_ncbi()\n if \"mutations\" in self.metadata.keys():\n mutations = self.metadata[\"mutations\"].split()\n del self.metadata[\"mutations\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete all elements between first and last positions including bounds. Optionally, provide an additional insert that shell be placed at the position of the deletion. | def delete(self, first, last, insert=""):
assert all(new in self.ALPHABET for new in insert)
if first < 1 or last > len(self.sequence):
raise ValueError(f"Deletion {first}-{last} out of bounds for given sequence.")
self.sequence = f"{self.sequence[: first - 1]}{insert}{self.sequence[... | [
"def delete(self, *args):\n def _delete(begin, end=None):\n _proc.deldblanno(self._env._e, self._cplex._lp, begin, end)\n _aux.delete_set_by_range(_delete, self._conv, self.get_num(), *args)",
"def delete_points_in_range(self, start: float, end: float) -> None:\r\n ...",
"def del... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert a sequence at the given position. | def insert(self, position, insert):
assert all(new in self.ALPHABET for new in insert)
if position < 1 or position - 1 > len(self.sequence):
raise ValueError(f"Insertion position {position} out of bonds for given sequence.")
self.sequence = f"{self.sequence[: position - 1]}{insert}{s... | [
"def insert_position(seq, position, frame):\n seq[\"launch\"] = position\n seq.keyframe_insert(data_path='[\"launch\"]', frame=frame)",
"def insert_at(sequence, index, element):\n # ... and the rest is up to you\n\n new_sequence = sequence[:index] + element + sequence[index:]\n return new_sequence"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |