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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
toumorokoshi/transmute-core
transmute_core/swagger/__init__.py
SwaggerSpec.add_func
def add_func(self, transmute_func, transmute_context): """ add a transmute function's swagger definition to the spec """ swagger_path = transmute_func.get_swagger_path(transmute_context) for p in transmute_func.paths: self.add_path(p, swagger_path)
python
def add_func(self, transmute_func, transmute_context): """ add a transmute function's swagger definition to the spec """ swagger_path = transmute_func.get_swagger_path(transmute_context) for p in transmute_func.paths: self.add_path(p, swagger_path)
[ "def", "add_func", "(", "self", ",", "transmute_func", ",", "transmute_context", ")", ":", "swagger_path", "=", "transmute_func", ".", "get_swagger_path", "(", "transmute_context", ")", "for", "p", "in", "transmute_func", ".", "paths", ":", "self", ".", "add_pat...
add a transmute function's swagger definition to the spec
[ "add", "a", "transmute", "function", "s", "swagger", "definition", "to", "the", "spec" ]
a2c26625d5d8bab37e00038f9d615a26167fc7f4
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/swagger/__init__.py#L53-L57
train
47,600
toumorokoshi/transmute-core
transmute_core/swagger/__init__.py
SwaggerSpec.add_path
def add_path(self, path, path_item): """ for a given path, add the path items. """ if path not in self._swagger: self._swagger[path] = path_item else: for method, definition in path_item.items(): if definition is not None: setattr(self._swagger[path], method, definition)
python
def add_path(self, path, path_item): """ for a given path, add the path items. """ if path not in self._swagger: self._swagger[path] = path_item else: for method, definition in path_item.items(): if definition is not None: setattr(self._swagger[path], method, definition)
[ "def", "add_path", "(", "self", ",", "path", ",", "path_item", ")", ":", "if", "path", "not", "in", "self", ".", "_swagger", ":", "self", ".", "_swagger", "[", "path", "]", "=", "path_item", "else", ":", "for", "method", ",", "definition", "in", "pat...
for a given path, add the path items.
[ "for", "a", "given", "path", "add", "the", "path", "items", "." ]
a2c26625d5d8bab37e00038f9d615a26167fc7f4
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/swagger/__init__.py#L59-L66
train
47,601
toumorokoshi/transmute-core
transmute_core/swagger/__init__.py
SwaggerSpec.swagger_definition
def swagger_definition(self, base_path=None, **kwargs): """ return a valid swagger spec, with the values passed. """ return Swagger( { "info": Info( { key: kwargs.get(key, self.DEFAULT_INFO.get(key)) for key in Info.fields.keys() if key in kwargs or key in self.DEFAULT_INFO } ), "paths": self.paths, "swagger": "2.0", "basePath": base_path, } ).to_primitive()
python
def swagger_definition(self, base_path=None, **kwargs): """ return a valid swagger spec, with the values passed. """ return Swagger( { "info": Info( { key: kwargs.get(key, self.DEFAULT_INFO.get(key)) for key in Info.fields.keys() if key in kwargs or key in self.DEFAULT_INFO } ), "paths": self.paths, "swagger": "2.0", "basePath": base_path, } ).to_primitive()
[ "def", "swagger_definition", "(", "self", ",", "base_path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Swagger", "(", "{", "\"info\"", ":", "Info", "(", "{", "key", ":", "kwargs", ".", "get", "(", "key", ",", "self", ".", "DEFAULT_INF...
return a valid swagger spec, with the values passed.
[ "return", "a", "valid", "swagger", "spec", "with", "the", "values", "passed", "." ]
a2c26625d5d8bab37e00038f9d615a26167fc7f4
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/swagger/__init__.py#L76-L93
train
47,602
agoragames/chai
chai/spy.py
Spy._call_spy
def _call_spy(self, *args, **kwargs): ''' Wrapper to call the spied-on function. Operates similar to Expectation.test. ''' if self._spy_side_effect: if self._spy_side_effect_args or self._spy_side_effect_kwargs: self._spy_side_effect( *self._spy_side_effect_args, **self._spy_side_effect_kwargs) else: self._spy_side_effect(*args, **kwargs) return_value = self._stub.call_orig(*args, **kwargs) if self._spy_return: self._spy_return(return_value) return return_value
python
def _call_spy(self, *args, **kwargs): ''' Wrapper to call the spied-on function. Operates similar to Expectation.test. ''' if self._spy_side_effect: if self._spy_side_effect_args or self._spy_side_effect_kwargs: self._spy_side_effect( *self._spy_side_effect_args, **self._spy_side_effect_kwargs) else: self._spy_side_effect(*args, **kwargs) return_value = self._stub.call_orig(*args, **kwargs) if self._spy_return: self._spy_return(return_value) return return_value
[ "def", "_call_spy", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_spy_side_effect", ":", "if", "self", ".", "_spy_side_effect_args", "or", "self", ".", "_spy_side_effect_kwargs", ":", "self", ".", "_spy_side_effect", ...
Wrapper to call the spied-on function. Operates similar to Expectation.test.
[ "Wrapper", "to", "call", "the", "spied", "-", "on", "function", ".", "Operates", "similar", "to", "Expectation", ".", "test", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/spy.py#L24-L41
train
47,603
agoragames/chai
chai/spy.py
Spy.side_effect
def side_effect(self, func, *args, **kwargs): ''' Wrap side effects for spies. ''' self._spy_side_effect = func self._spy_side_effect_args = args self._spy_side_effect_kwargs = kwargs return self
python
def side_effect(self, func, *args, **kwargs): ''' Wrap side effects for spies. ''' self._spy_side_effect = func self._spy_side_effect_args = args self._spy_side_effect_kwargs = kwargs return self
[ "def", "side_effect", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_spy_side_effect", "=", "func", "self", ".", "_spy_side_effect_args", "=", "args", "self", ".", "_spy_side_effect_kwargs", "=", "kwargs", "re...
Wrap side effects for spies.
[ "Wrap", "side", "effects", "for", "spies", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/spy.py#L43-L50
train
47,604
LCAV/pylocus
pylocus/opt_space.py
guess_rank
def guess_rank(M_E): '''Guess the rank of the incomplete matrix ''' n, m = M_E.shape epsilon = np.count_nonzero(M_E) / np.sqrt(m * n) _, S0, _ = svds_descending(M_E, min(100, max(M_E.shape) - 1)) S0 = np.diag(S0) S1 = S0[:-1] - S0[1:] S1_ = S1 / np.mean(S1[-10:]) r1 = 0 lam = 0.05 cost = [None] * len(S1_) while r1 <= 0: for idx in range(len(S1_)): cost[idx] = lam * max(S1_[idx:]) + idx i2 = np.argmin(cost) r1 = np.max(i2) lam += 0.05 cost = [None] * (len(S0) - 1) for idx in range(len(S0) - 1): cost[idx] = (S0[idx + 1] + np.sqrt(idx * epsilon) * S0[0] / epsilon) / S0[idx] i2 = np.argmin(cost) r2 = np.max(i2 + 1) r = max([r1, r2]) return r
python
def guess_rank(M_E): '''Guess the rank of the incomplete matrix ''' n, m = M_E.shape epsilon = np.count_nonzero(M_E) / np.sqrt(m * n) _, S0, _ = svds_descending(M_E, min(100, max(M_E.shape) - 1)) S0 = np.diag(S0) S1 = S0[:-1] - S0[1:] S1_ = S1 / np.mean(S1[-10:]) r1 = 0 lam = 0.05 cost = [None] * len(S1_) while r1 <= 0: for idx in range(len(S1_)): cost[idx] = lam * max(S1_[idx:]) + idx i2 = np.argmin(cost) r1 = np.max(i2) lam += 0.05 cost = [None] * (len(S0) - 1) for idx in range(len(S0) - 1): cost[idx] = (S0[idx + 1] + np.sqrt(idx * epsilon) * S0[0] / epsilon) / S0[idx] i2 = np.argmin(cost) r2 = np.max(i2 + 1) r = max([r1, r2]) return r
[ "def", "guess_rank", "(", "M_E", ")", ":", "n", ",", "m", "=", "M_E", ".", "shape", "epsilon", "=", "np", ".", "count_nonzero", "(", "M_E", ")", "/", "np", ".", "sqrt", "(", "m", "*", "n", ")", "_", ",", "S0", ",", "_", "=", "svds_descending", ...
Guess the rank of the incomplete matrix
[ "Guess", "the", "rank", "of", "the", "incomplete", "matrix" ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L147-L174
train
47,605
LCAV/pylocus
pylocus/opt_space.py
F_t
def F_t(X, Y, S, M_E, E, m0, rho): ''' Compute the distortion ''' r = X.shape[1] out1 = (((np.dot(np.dot(X, S), Y.T) - M_E) * E)**2).sum() / 2 out2 = rho * G(Y, m0, r) out3 = rho * G(X, m0, r) return out1 + out2 + out3
python
def F_t(X, Y, S, M_E, E, m0, rho): ''' Compute the distortion ''' r = X.shape[1] out1 = (((np.dot(np.dot(X, S), Y.T) - M_E) * E)**2).sum() / 2 out2 = rho * G(Y, m0, r) out3 = rho * G(X, m0, r) return out1 + out2 + out3
[ "def", "F_t", "(", "X", ",", "Y", ",", "S", ",", "M_E", ",", "E", ",", "m0", ",", "rho", ")", ":", "r", "=", "X", ".", "shape", "[", "1", "]", "out1", "=", "(", "(", "(", "np", ".", "dot", "(", "np", ".", "dot", "(", "X", ",", "S", ...
Compute the distortion
[ "Compute", "the", "distortion" ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L177-L184
train
47,606
LCAV/pylocus
pylocus/opt_space.py
getoptS
def getoptS(X, Y, M_E, E): ''' Find Sopt given X, Y ''' n, r = X.shape C = np.dot(np.dot(X.T, M_E), Y) C = C.flatten() A = np.zeros((r * r, r * r)) for i in range(r): for j in range(r): ind = j * r + i temp = np.dot( np.dot(X.T, np.dot(X[:, i, None], Y[:, j, None].T) * E), Y) A[:, ind] = temp.flatten() S = np.linalg.solve(A, C) return np.reshape(S, (r, r)).T
python
def getoptS(X, Y, M_E, E): ''' Find Sopt given X, Y ''' n, r = X.shape C = np.dot(np.dot(X.T, M_E), Y) C = C.flatten() A = np.zeros((r * r, r * r)) for i in range(r): for j in range(r): ind = j * r + i temp = np.dot( np.dot(X.T, np.dot(X[:, i, None], Y[:, j, None].T) * E), Y) A[:, ind] = temp.flatten() S = np.linalg.solve(A, C) return np.reshape(S, (r, r)).T
[ "def", "getoptS", "(", "X", ",", "Y", ",", "M_E", ",", "E", ")", ":", "n", ",", "r", "=", "X", ".", "shape", "C", "=", "np", ".", "dot", "(", "np", ".", "dot", "(", "X", ".", "T", ",", "M_E", ")", ",", "Y", ")", "C", "=", "C", ".", ...
Find Sopt given X, Y
[ "Find", "Sopt", "given", "X", "Y" ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L222-L239
train
47,607
LCAV/pylocus
pylocus/opt_space.py
getoptT
def getoptT(X, W, Y, Z, S, M_E, E, m0, rho): ''' Perform line search ''' iter_max = 20 norm2WZ = np.linalg.norm(W, ord='fro')**2 + np.linalg.norm(Z, ord='fro')**2 f = np.zeros(iter_max + 1) f[0] = F_t(X, Y, S, M_E, E, m0, rho) t = -1e-1 for i in range(iter_max): f[i + 1] = F_t(X + t * W, Y + t * Z, S, M_E, E, m0, rho) if f[i + 1] - f[0] <= 0.5 * t * norm2WZ: return t t /= 2 return t
python
def getoptT(X, W, Y, Z, S, M_E, E, m0, rho): ''' Perform line search ''' iter_max = 20 norm2WZ = np.linalg.norm(W, ord='fro')**2 + np.linalg.norm(Z, ord='fro')**2 f = np.zeros(iter_max + 1) f[0] = F_t(X, Y, S, M_E, E, m0, rho) t = -1e-1 for i in range(iter_max): f[i + 1] = F_t(X + t * W, Y + t * Z, S, M_E, E, m0, rho) if f[i + 1] - f[0] <= 0.5 * t * norm2WZ: return t t /= 2 return t
[ "def", "getoptT", "(", "X", ",", "W", ",", "Y", ",", "Z", ",", "S", ",", "M_E", ",", "E", ",", "m0", ",", "rho", ")", ":", "iter_max", "=", "20", "norm2WZ", "=", "np", ".", "linalg", ".", "norm", "(", "W", ",", "ord", "=", "'fro'", ")", "...
Perform line search
[ "Perform", "line", "search" ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L242-L257
train
47,608
LCAV/pylocus
pylocus/mds.py
MDS
def MDS(D, dim, method='simple', theta=False): """ recover points from euclidean distance matrix using classic MDS algorithm. """ N = D.shape[0] if method == 'simple': d1 = D[0, :] # buf_ = d1 * np.ones([1, N]).T + (np.ones([N, 1]) * d1).T buf_ = np.broadcast_to(d1, D.shape) + np.broadcast_to(d1[:, np.newaxis], D.shape) np.subtract(D, buf_, out=buf_) G = buf_ # G = (D - d1 * np.ones([1, N]).T - (np.ones([N, 1]) * d1).T) elif method == 'advanced': # s1T = np.vstack([np.ones([1, N]), np.zeros([N - 1, N])]) s1T = np.zeros_like(D) s1T[0, :] = 1 np.subtract(np.identity(N), s1T, out = s1T) G = np.dot(np.dot(s1T.T, D), s1T) elif method == 'geometric': J = np.identity(N) + np.full((N, N), -1.0 / float(N)) G = np.dot(np.dot(J, D), J) else: print('Unknown method {} in MDS'.format(method)) G *= -0.5 factor, u = eigendecomp(G, dim) if (theta): return theta_from_eigendecomp(factor, u) else: return x_from_eigendecomp(factor, u, dim)
python
def MDS(D, dim, method='simple', theta=False): """ recover points from euclidean distance matrix using classic MDS algorithm. """ N = D.shape[0] if method == 'simple': d1 = D[0, :] # buf_ = d1 * np.ones([1, N]).T + (np.ones([N, 1]) * d1).T buf_ = np.broadcast_to(d1, D.shape) + np.broadcast_to(d1[:, np.newaxis], D.shape) np.subtract(D, buf_, out=buf_) G = buf_ # G = (D - d1 * np.ones([1, N]).T - (np.ones([N, 1]) * d1).T) elif method == 'advanced': # s1T = np.vstack([np.ones([1, N]), np.zeros([N - 1, N])]) s1T = np.zeros_like(D) s1T[0, :] = 1 np.subtract(np.identity(N), s1T, out = s1T) G = np.dot(np.dot(s1T.T, D), s1T) elif method == 'geometric': J = np.identity(N) + np.full((N, N), -1.0 / float(N)) G = np.dot(np.dot(J, D), J) else: print('Unknown method {} in MDS'.format(method)) G *= -0.5 factor, u = eigendecomp(G, dim) if (theta): return theta_from_eigendecomp(factor, u) else: return x_from_eigendecomp(factor, u, dim)
[ "def", "MDS", "(", "D", ",", "dim", ",", "method", "=", "'simple'", ",", "theta", "=", "False", ")", ":", "N", "=", "D", ".", "shape", "[", "0", "]", "if", "method", "==", "'simple'", ":", "d1", "=", "D", "[", "0", ",", ":", "]", "# buf_ = d1...
recover points from euclidean distance matrix using classic MDS algorithm.
[ "recover", "points", "from", "euclidean", "distance", "matrix", "using", "classic", "MDS", "algorithm", "." ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/mds.py#L22-L48
train
47,609
LCAV/pylocus
pylocus/mds.py
superMDS
def superMDS(X0, N, d, **kwargs): """ Find the set of points from an edge kernel. """ Om = kwargs.get('Om', None) dm = kwargs.get('dm', None) if Om is not None and dm is not None: KE = kwargs.get('KE', None) if KE is not None: print('superMDS: KE and Om, dm given. Continuing with Om, dm') factor, u = eigendecomp(Om, d) uhat = u[:, :d] lambdahat = np.diag(factor[:d]) diag_dm = np.diag(dm) Vhat = np.dot(diag_dm, np.dot(uhat, lambdahat)) elif Om is None or dm is None: KE = kwargs.get('KE', None) if KE is None: raise NameError('Either KE or Om and dm have to be given.') factor, u = eigendecomp(KE, d) lambda_ = np.diag(factor) Vhat = np.dot(u, lambda_)[:, :d] C_inv = -np.eye(N) C_inv[0, 0] = 1.0 C_inv[:, 0] = 1.0 b = np.zeros((C_inv.shape[1], d)) b[0, :] = X0 b[1:, :] = Vhat[:N - 1, :] Xhat = np.dot(C_inv, b) return Xhat, Vhat
python
def superMDS(X0, N, d, **kwargs): """ Find the set of points from an edge kernel. """ Om = kwargs.get('Om', None) dm = kwargs.get('dm', None) if Om is not None and dm is not None: KE = kwargs.get('KE', None) if KE is not None: print('superMDS: KE and Om, dm given. Continuing with Om, dm') factor, u = eigendecomp(Om, d) uhat = u[:, :d] lambdahat = np.diag(factor[:d]) diag_dm = np.diag(dm) Vhat = np.dot(diag_dm, np.dot(uhat, lambdahat)) elif Om is None or dm is None: KE = kwargs.get('KE', None) if KE is None: raise NameError('Either KE or Om and dm have to be given.') factor, u = eigendecomp(KE, d) lambda_ = np.diag(factor) Vhat = np.dot(u, lambda_)[:, :d] C_inv = -np.eye(N) C_inv[0, 0] = 1.0 C_inv[:, 0] = 1.0 b = np.zeros((C_inv.shape[1], d)) b[0, :] = X0 b[1:, :] = Vhat[:N - 1, :] Xhat = np.dot(C_inv, b) return Xhat, Vhat
[ "def", "superMDS", "(", "X0", ",", "N", ",", "d", ",", "*", "*", "kwargs", ")", ":", "Om", "=", "kwargs", ".", "get", "(", "'Om'", ",", "None", ")", "dm", "=", "kwargs", ".", "get", "(", "'dm'", ",", "None", ")", "if", "Om", "is", "not", "N...
Find the set of points from an edge kernel.
[ "Find", "the", "set", "of", "points", "from", "an", "edge", "kernel", "." ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/mds.py#L51-L80
train
47,610
LCAV/pylocus
pylocus/mds.py
iterativeEMDS
def iterativeEMDS(X0, N, d, C, b, max_it=10, print_out=False, **kwargs): """ Find the set of points from an edge kernel with geometric constraints, using iterative projection """ from pylocus.basics import mse, projection KE = kwargs.get('KE', None) KE_projected = KE.copy() d = len(X0) for i in range(max_it): # projection on constraints KE_projected, cost, __ = projection(KE_projected, C, b) rank = np.linalg.matrix_rank(KE_projected) # rank 2 decomposition Xhat_KE, Vhat_KE = superMDS(X0, N, d, KE=KE_projected) KE_projected = Vhat_KE.dot(Vhat_KE.T) error = mse(C.dot(KE_projected), b) if (print_out): print('cost={:2.2e},error={:2.2e}, rank={}'.format( cost, error, rank)) if cost < 1e-20 and error < 1e-20 and rank == d: if (print_out): print('converged after {} iterations'.format(i)) return Xhat_KE, Vhat_KE print('iterativeMDS did not converge!') return None, None
python
def iterativeEMDS(X0, N, d, C, b, max_it=10, print_out=False, **kwargs): """ Find the set of points from an edge kernel with geometric constraints, using iterative projection """ from pylocus.basics import mse, projection KE = kwargs.get('KE', None) KE_projected = KE.copy() d = len(X0) for i in range(max_it): # projection on constraints KE_projected, cost, __ = projection(KE_projected, C, b) rank = np.linalg.matrix_rank(KE_projected) # rank 2 decomposition Xhat_KE, Vhat_KE = superMDS(X0, N, d, KE=KE_projected) KE_projected = Vhat_KE.dot(Vhat_KE.T) error = mse(C.dot(KE_projected), b) if (print_out): print('cost={:2.2e},error={:2.2e}, rank={}'.format( cost, error, rank)) if cost < 1e-20 and error < 1e-20 and rank == d: if (print_out): print('converged after {} iterations'.format(i)) return Xhat_KE, Vhat_KE print('iterativeMDS did not converge!') return None, None
[ "def", "iterativeEMDS", "(", "X0", ",", "N", ",", "d", ",", "C", ",", "b", ",", "max_it", "=", "10", ",", "print_out", "=", "False", ",", "*", "*", "kwargs", ")", ":", "from", "pylocus", ".", "basics", "import", "mse", ",", "projection", "KE", "=...
Find the set of points from an edge kernel with geometric constraints, using iterative projection
[ "Find", "the", "set", "of", "points", "from", "an", "edge", "kernel", "with", "geometric", "constraints", "using", "iterative", "projection" ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/mds.py#L83-L109
train
47,611
LCAV/pylocus
pylocus/mds.py
relaxedEMDS
def relaxedEMDS(X0, N, d, C, b, KE, print_out=False, lamda=10): """ Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation. """ E = C.shape[1] X = Variable((E, E), PSD=True) constraints = [C[i, :] * X == b[i] for i in range(C.shape[0])] obj = Minimize(trace(X) + lamda * norm(KE - X)) prob = Problem(obj, constraints) try: # CVXOPT is more accurate than SCS, even though slower. total_cost = prob.solve(solver='CVXOPT', verbose=print_out) except: try: print('CVXOPT with default cholesky failed. Trying kktsolver...') # kktsolver is more robust than default (cholesky), even though slower. total_cost = prob.solve( solver='CVXOPT', verbose=print_out, kktsolver="robust") except: try: print('CVXOPT with robust kktsovler failed. Trying SCS...') # SCS is fast and robust, but inaccurate (last choice). total_cost = prob.solve(solver='SCS', verbose=print_out) except: print('SCS and CVXOPT solver with default and kktsolver failed .') if print_out: print('status:', prob.status) Xhat_KE, Vhat_KE = superMDS(X0, N, d, KE=X.value) return Xhat_KE, Vhat_KE
python
def relaxedEMDS(X0, N, d, C, b, KE, print_out=False, lamda=10): """ Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation. """ E = C.shape[1] X = Variable((E, E), PSD=True) constraints = [C[i, :] * X == b[i] for i in range(C.shape[0])] obj = Minimize(trace(X) + lamda * norm(KE - X)) prob = Problem(obj, constraints) try: # CVXOPT is more accurate than SCS, even though slower. total_cost = prob.solve(solver='CVXOPT', verbose=print_out) except: try: print('CVXOPT with default cholesky failed. Trying kktsolver...') # kktsolver is more robust than default (cholesky), even though slower. total_cost = prob.solve( solver='CVXOPT', verbose=print_out, kktsolver="robust") except: try: print('CVXOPT with robust kktsovler failed. Trying SCS...') # SCS is fast and robust, but inaccurate (last choice). total_cost = prob.solve(solver='SCS', verbose=print_out) except: print('SCS and CVXOPT solver with default and kktsolver failed .') if print_out: print('status:', prob.status) Xhat_KE, Vhat_KE = superMDS(X0, N, d, KE=X.value) return Xhat_KE, Vhat_KE
[ "def", "relaxedEMDS", "(", "X0", ",", "N", ",", "d", ",", "C", ",", "b", ",", "KE", ",", "print_out", "=", "False", ",", "lamda", "=", "10", ")", ":", "E", "=", "C", ".", "shape", "[", "1", "]", "X", "=", "Variable", "(", "(", "E", ",", "...
Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation.
[ "Find", "the", "set", "of", "points", "from", "an", "edge", "kernel", "with", "geometric", "constraints", "using", "convex", "rank", "relaxation", "." ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/mds.py#L112-L142
train
47,612
LCAV/pylocus
pylocus/mds.py
signedMDS
def signedMDS(cdm, W=None): """ Find the set of points from a cdm. """ N = cdm.shape[0] D_sym = (cdm - cdm.T) D_sym /= 2 if W is None: x_est = np.mean(D_sym, axis=1) x_est -= np.min(x_est) return x_est W_sub = W[1:, 1:] sum_W = np.sum(W[1:, :], axis=1) # A = np.eye(N, N-1, k=-1) - W_sub.astype(np.int) / sum_W[:, None] A = np.eye(N - 1) - W_sub.astype(np.int) / 1. / sum_W[:, None] d = (np.sum(D_sym[1:, :] * W[1:, :], axis=1) / 1. / sum_W) x_est = np.linalg.lstsq(A, d)[0] x_est = np.r_[[0], x_est] x_est -= np.min(x_est) return x_est, A, np.linalg.pinv(A)
python
def signedMDS(cdm, W=None): """ Find the set of points from a cdm. """ N = cdm.shape[0] D_sym = (cdm - cdm.T) D_sym /= 2 if W is None: x_est = np.mean(D_sym, axis=1) x_est -= np.min(x_est) return x_est W_sub = W[1:, 1:] sum_W = np.sum(W[1:, :], axis=1) # A = np.eye(N, N-1, k=-1) - W_sub.astype(np.int) / sum_W[:, None] A = np.eye(N - 1) - W_sub.astype(np.int) / 1. / sum_W[:, None] d = (np.sum(D_sym[1:, :] * W[1:, :], axis=1) / 1. / sum_W) x_est = np.linalg.lstsq(A, d)[0] x_est = np.r_[[0], x_est] x_est -= np.min(x_est) return x_est, A, np.linalg.pinv(A)
[ "def", "signedMDS", "(", "cdm", ",", "W", "=", "None", ")", ":", "N", "=", "cdm", ".", "shape", "[", "0", "]", "D_sym", "=", "(", "cdm", "-", "cdm", ".", "T", ")", "D_sym", "/=", "2", "if", "W", "is", "None", ":", "x_est", "=", "np", ".", ...
Find the set of points from a cdm.
[ "Find", "the", "set", "of", "points", "from", "a", "cdm", "." ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/mds.py#L145-L170
train
47,613
agoragames/chai
chai/stub.py
_stub_attr
def _stub_attr(obj, attr_name): ''' Stub an attribute of an object. Will return an existing stub if there already is one. ''' # Annoying circular reference requires importing here. Would like to see # this cleaned up. @AW from .mock import Mock # Check to see if this a property, this check is only for when dealing # with an instance. getattr will work for classes. is_property = False if not inspect.isclass(obj) and not inspect.ismodule(obj): # It's possible that the attribute is defined after initialization, and # so is not on the class itself. attr = getattr(obj.__class__, attr_name, None) if isinstance(attr, property): is_property = True if not is_property: attr = getattr(obj, attr_name) # Return an existing stub if isinstance(attr, Stub): return attr # If a Mock object, stub its __call__ if isinstance(attr, Mock): return stub(attr.__call__) if isinstance(attr, property): return StubProperty(obj, attr_name) # Sadly, builtin functions and methods have the same type, so we have to # use the same stub class even though it's a bit ugly if inspect.ismodule(obj) and isinstance(attr, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType)): return StubFunction(obj, attr_name) # In python3 unbound methods are treated as functions with no reference # back to the parent class and no im_* fields. We can still make unbound # methods work by passing these through to the stub if inspect.isclass(obj) and isinstance(attr, types.FunctionType): return StubUnboundMethod(obj, attr_name) # I thought that types.UnboundMethodType differentiated these cases but # apparently not. if isinstance(attr, types.MethodType): # Handle differently if unbound because it's an implicit "any instance" if getattr(attr, 'im_self', None) is None: # Handle the python3 case and py2 filter if hasattr(attr, '__self__'): if attr.__self__ is not None: return StubMethod(obj, attr_name) if sys.version_info.major == 2: return StubUnboundMethod(attr) else: return StubMethod(obj, attr_name) if isinstance(attr, (types.BuiltinFunctionType, types.BuiltinMethodType)): return StubFunction(obj, attr_name) # What an absurd type this is .... if type(attr).__name__ == 'method-wrapper': return StubMethodWrapper(attr) # This is also slot_descriptor if type(attr).__name__ == 'wrapper_descriptor': return StubWrapperDescriptor(obj, attr_name) raise UnsupportedStub( "can't stub %s(%s) of %s", attr_name, type(attr), obj)
python
def _stub_attr(obj, attr_name): ''' Stub an attribute of an object. Will return an existing stub if there already is one. ''' # Annoying circular reference requires importing here. Would like to see # this cleaned up. @AW from .mock import Mock # Check to see if this a property, this check is only for when dealing # with an instance. getattr will work for classes. is_property = False if not inspect.isclass(obj) and not inspect.ismodule(obj): # It's possible that the attribute is defined after initialization, and # so is not on the class itself. attr = getattr(obj.__class__, attr_name, None) if isinstance(attr, property): is_property = True if not is_property: attr = getattr(obj, attr_name) # Return an existing stub if isinstance(attr, Stub): return attr # If a Mock object, stub its __call__ if isinstance(attr, Mock): return stub(attr.__call__) if isinstance(attr, property): return StubProperty(obj, attr_name) # Sadly, builtin functions and methods have the same type, so we have to # use the same stub class even though it's a bit ugly if inspect.ismodule(obj) and isinstance(attr, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType)): return StubFunction(obj, attr_name) # In python3 unbound methods are treated as functions with no reference # back to the parent class and no im_* fields. We can still make unbound # methods work by passing these through to the stub if inspect.isclass(obj) and isinstance(attr, types.FunctionType): return StubUnboundMethod(obj, attr_name) # I thought that types.UnboundMethodType differentiated these cases but # apparently not. if isinstance(attr, types.MethodType): # Handle differently if unbound because it's an implicit "any instance" if getattr(attr, 'im_self', None) is None: # Handle the python3 case and py2 filter if hasattr(attr, '__self__'): if attr.__self__ is not None: return StubMethod(obj, attr_name) if sys.version_info.major == 2: return StubUnboundMethod(attr) else: return StubMethod(obj, attr_name) if isinstance(attr, (types.BuiltinFunctionType, types.BuiltinMethodType)): return StubFunction(obj, attr_name) # What an absurd type this is .... if type(attr).__name__ == 'method-wrapper': return StubMethodWrapper(attr) # This is also slot_descriptor if type(attr).__name__ == 'wrapper_descriptor': return StubWrapperDescriptor(obj, attr_name) raise UnsupportedStub( "can't stub %s(%s) of %s", attr_name, type(attr), obj)
[ "def", "_stub_attr", "(", "obj", ",", "attr_name", ")", ":", "# Annoying circular reference requires importing here. Would like to see", "# this cleaned up. @AW", "from", ".", "mock", "import", "Mock", "# Check to see if this a property, this check is only for when dealing", "# with ...
Stub an attribute of an object. Will return an existing stub if there already is one.
[ "Stub", "an", "attribute", "of", "an", "object", ".", "Will", "return", "an", "existing", "stub", "if", "there", "already", "is", "one", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L32-L105
train
47,614
agoragames/chai
chai/stub.py
_stub_obj
def _stub_obj(obj): ''' Stub an object directly. ''' # Annoying circular reference requires importing here. Would like to see # this cleaned up. @AW from .mock import Mock # Return an existing stub if isinstance(obj, Stub): return obj # If a Mock object, stub its __call__ if isinstance(obj, Mock): return stub(obj.__call__) # If passed-in a type, assume that we're going to stub out the creation. # See StubNew for the awesome sauce. # if isinstance(obj, types.TypeType): if hasattr(types, 'TypeType') and isinstance(obj, types.TypeType): return StubNew(obj) elif hasattr(__builtins__, 'type') and \ isinstance(obj, __builtins__.type): return StubNew(obj) elif inspect.isclass(obj): return StubNew(obj) # I thought that types.UnboundMethodType differentiated these cases but # apparently not. if isinstance(obj, types.MethodType): # Handle differently if unbound because it's an implicit "any instance" if getattr(obj, 'im_self', None) is None: # Handle the python3 case and py2 filter if hasattr(obj, '__self__'): if obj.__self__ is not None: return StubMethod(obj) if sys.version_info.major == 2: return StubUnboundMethod(obj) else: return StubMethod(obj) # These aren't in the types library if type(obj).__name__ == 'method-wrapper': return StubMethodWrapper(obj) if type(obj).__name__ == 'wrapper_descriptor': raise UnsupportedStub( "must call stub(obj,'%s') for slot wrapper on %s", obj.__name__, obj.__objclass__.__name__) # (Mostly) Lastly, look for properties. # First look for the situation where there's a reference back to the # property. prop = obj if isinstance(getattr(obj, '__self__', None), property): obj = prop.__self__ # Once we've found a property, we have to figure out how to reference # back to the owning class. This is a giant pain and we have to use gc # to find out where it comes from. This code is dense but resolves to # something like this: # >>> gc.get_referrers( foo.x ) # [{'__dict__': <attribute '__dict__' of 'foo' objects>, # 'x': <property object at 0x7f68c99a16d8>, # '__module__': '__main__', # '__weakref__': <attribute '__weakref__' of 'foo' objects>, # '__doc__': None}] if isinstance(obj, property): klass, attr = None, None for ref in gc.get_referrers(obj): if klass and attr: break if isinstance(ref, dict) and ref.get('prop', None) is obj: klass = getattr( ref.get('__dict__', None), '__objclass__', None) for name, val in getattr(klass, '__dict__', {}).items(): if val is obj: attr = name break # In the case of PyPy, we have to check all types that refer to # the property, and see if any of their attrs are the property elif isinstance(ref, type): # Use dir as a means to quickly walk through the class tree for name in dir(ref): if getattr(ref, name) == obj: klass = ref attr = name break if klass and attr: rval = stub(klass, attr) if prop != obj: return stub(rval, prop.__name__) return rval # If a function and it has an associated module, we can mock directly. # Note that this *must* be after properties, otherwise it conflicts with # stubbing out the deleter methods and such # Sadly, builtin functions and methods have the same type, so we have to # use the same stub class even though it's a bit ugly if isinstance(obj, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType)) and hasattr(obj, '__module__'): return StubFunction(obj) raise UnsupportedStub("can't stub %s", obj)
python
def _stub_obj(obj): ''' Stub an object directly. ''' # Annoying circular reference requires importing here. Would like to see # this cleaned up. @AW from .mock import Mock # Return an existing stub if isinstance(obj, Stub): return obj # If a Mock object, stub its __call__ if isinstance(obj, Mock): return stub(obj.__call__) # If passed-in a type, assume that we're going to stub out the creation. # See StubNew for the awesome sauce. # if isinstance(obj, types.TypeType): if hasattr(types, 'TypeType') and isinstance(obj, types.TypeType): return StubNew(obj) elif hasattr(__builtins__, 'type') and \ isinstance(obj, __builtins__.type): return StubNew(obj) elif inspect.isclass(obj): return StubNew(obj) # I thought that types.UnboundMethodType differentiated these cases but # apparently not. if isinstance(obj, types.MethodType): # Handle differently if unbound because it's an implicit "any instance" if getattr(obj, 'im_self', None) is None: # Handle the python3 case and py2 filter if hasattr(obj, '__self__'): if obj.__self__ is not None: return StubMethod(obj) if sys.version_info.major == 2: return StubUnboundMethod(obj) else: return StubMethod(obj) # These aren't in the types library if type(obj).__name__ == 'method-wrapper': return StubMethodWrapper(obj) if type(obj).__name__ == 'wrapper_descriptor': raise UnsupportedStub( "must call stub(obj,'%s') for slot wrapper on %s", obj.__name__, obj.__objclass__.__name__) # (Mostly) Lastly, look for properties. # First look for the situation where there's a reference back to the # property. prop = obj if isinstance(getattr(obj, '__self__', None), property): obj = prop.__self__ # Once we've found a property, we have to figure out how to reference # back to the owning class. This is a giant pain and we have to use gc # to find out where it comes from. This code is dense but resolves to # something like this: # >>> gc.get_referrers( foo.x ) # [{'__dict__': <attribute '__dict__' of 'foo' objects>, # 'x': <property object at 0x7f68c99a16d8>, # '__module__': '__main__', # '__weakref__': <attribute '__weakref__' of 'foo' objects>, # '__doc__': None}] if isinstance(obj, property): klass, attr = None, None for ref in gc.get_referrers(obj): if klass and attr: break if isinstance(ref, dict) and ref.get('prop', None) is obj: klass = getattr( ref.get('__dict__', None), '__objclass__', None) for name, val in getattr(klass, '__dict__', {}).items(): if val is obj: attr = name break # In the case of PyPy, we have to check all types that refer to # the property, and see if any of their attrs are the property elif isinstance(ref, type): # Use dir as a means to quickly walk through the class tree for name in dir(ref): if getattr(ref, name) == obj: klass = ref attr = name break if klass and attr: rval = stub(klass, attr) if prop != obj: return stub(rval, prop.__name__) return rval # If a function and it has an associated module, we can mock directly. # Note that this *must* be after properties, otherwise it conflicts with # stubbing out the deleter methods and such # Sadly, builtin functions and methods have the same type, so we have to # use the same stub class even though it's a bit ugly if isinstance(obj, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType)) and hasattr(obj, '__module__'): return StubFunction(obj) raise UnsupportedStub("can't stub %s", obj)
[ "def", "_stub_obj", "(", "obj", ")", ":", "# Annoying circular reference requires importing here. Would like to see", "# this cleaned up. @AW", "from", ".", "mock", "import", "Mock", "# Return an existing stub", "if", "isinstance", "(", "obj", ",", "Stub", ")", ":", "retu...
Stub an object directly.
[ "Stub", "an", "object", "directly", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L108-L212
train
47,615
agoragames/chai
chai/stub.py
Stub.unmet_expectations
def unmet_expectations(self): ''' Assert that all expectations on the stub have been met. ''' unmet = [] for exp in self._expectations: if not exp.closed(with_counts=True): unmet.append(ExpectationNotSatisfied(exp)) return unmet
python
def unmet_expectations(self): ''' Assert that all expectations on the stub have been met. ''' unmet = [] for exp in self._expectations: if not exp.closed(with_counts=True): unmet.append(ExpectationNotSatisfied(exp)) return unmet
[ "def", "unmet_expectations", "(", "self", ")", ":", "unmet", "=", "[", "]", "for", "exp", "in", "self", ".", "_expectations", ":", "if", "not", "exp", ".", "closed", "(", "with_counts", "=", "True", ")", ":", "unmet", ".", "append", "(", "ExpectationNo...
Assert that all expectations on the stub have been met.
[ "Assert", "that", "all", "expectations", "on", "the", "stub", "have", "been", "met", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L238-L246
train
47,616
agoragames/chai
chai/stub.py
Stub.teardown
def teardown(self): ''' Clean up all expectations and restore the original attribute of the mocked object. ''' if not self._torn: self._expectations = [] self._torn = True self._teardown()
python
def teardown(self): ''' Clean up all expectations and restore the original attribute of the mocked object. ''' if not self._torn: self._expectations = [] self._torn = True self._teardown()
[ "def", "teardown", "(", "self", ")", ":", "if", "not", "self", ".", "_torn", ":", "self", ".", "_expectations", "=", "[", "]", "self", ".", "_torn", "=", "True", "self", ".", "_teardown", "(", ")" ]
Clean up all expectations and restore the original attribute of the mocked object.
[ "Clean", "up", "all", "expectations", "and", "restore", "the", "original", "attribute", "of", "the", "mocked", "object", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L248-L256
train
47,617
agoragames/chai
chai/stub.py
Stub.expect
def expect(self): ''' Add an expectation to this stub. Return the expectation. ''' exp = Expectation(self) self._expectations.append(exp) return exp
python
def expect(self): ''' Add an expectation to this stub. Return the expectation. ''' exp = Expectation(self) self._expectations.append(exp) return exp
[ "def", "expect", "(", "self", ")", ":", "exp", "=", "Expectation", "(", "self", ")", "self", ".", "_expectations", ".", "append", "(", "exp", ")", "return", "exp" ]
Add an expectation to this stub. Return the expectation.
[ "Add", "an", "expectation", "to", "this", "stub", ".", "Return", "the", "expectation", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L263-L269
train
47,618
agoragames/chai
chai/stub.py
Stub.spy
def spy(self): ''' Add a spy to this stub. Return the spy. ''' spy = Spy(self) self._expectations.append(spy) return spy
python
def spy(self): ''' Add a spy to this stub. Return the spy. ''' spy = Spy(self) self._expectations.append(spy) return spy
[ "def", "spy", "(", "self", ")", ":", "spy", "=", "Spy", "(", "self", ")", "self", ".", "_expectations", ".", "append", "(", "spy", ")", "return", "spy" ]
Add a spy to this stub. Return the spy.
[ "Add", "a", "spy", "to", "this", "stub", ".", "Return", "the", "spy", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L271-L277
train
47,619
agoragames/chai
chai/stub.py
StubMethod._teardown
def _teardown(self): ''' Put the original method back in place. This will also handle the special case when it putting back a class method. The following code snippet best describe why it fails using settar, the class method would be replaced with a bound method not a class method. >>> class Example(object): ... @classmethod ... def a_classmethod(self): ... pass ... >>> Example.__dict__['a_classmethod'] <classmethod object at 0x7f5e6c298be8> >>> orig = getattr(Example, 'a_classmethod') >>> orig <bound method type.a_classmethod of <class '__main__.Example'>> >>> setattr(Example, 'a_classmethod', orig) >>> Example.__dict__['a_classmethod'] <bound method type.a_classmethod of <class '__main__.Example'>> The only way to figure out if this is a class method is to check and see if the bound method im_self is a class, if so then we need to wrap the function object (im_func) with class method before setting it back on the class. ''' # Figure out if this is a class method and we're unstubbing it on the # class to which it belongs. This addresses an edge case where a # module can expose a method of an instance. e.g gevent. if hasattr(self._obj, '__self__') and \ inspect.isclass(self._obj.__self__) and \ self._obj.__self__ is self._instance: setattr( self._instance, self._attr, classmethod(self._obj.__func__)) elif hasattr(self._obj, 'im_self') and \ inspect.isclass(self._obj.im_self) and \ self._obj.im_self is self._instance: # Wrap it and set it back on the class setattr(self._instance, self._attr, classmethod(self._obj.im_func)) else: setattr(self._instance, self._attr, self._obj)
python
def _teardown(self): ''' Put the original method back in place. This will also handle the special case when it putting back a class method. The following code snippet best describe why it fails using settar, the class method would be replaced with a bound method not a class method. >>> class Example(object): ... @classmethod ... def a_classmethod(self): ... pass ... >>> Example.__dict__['a_classmethod'] <classmethod object at 0x7f5e6c298be8> >>> orig = getattr(Example, 'a_classmethod') >>> orig <bound method type.a_classmethod of <class '__main__.Example'>> >>> setattr(Example, 'a_classmethod', orig) >>> Example.__dict__['a_classmethod'] <bound method type.a_classmethod of <class '__main__.Example'>> The only way to figure out if this is a class method is to check and see if the bound method im_self is a class, if so then we need to wrap the function object (im_func) with class method before setting it back on the class. ''' # Figure out if this is a class method and we're unstubbing it on the # class to which it belongs. This addresses an edge case where a # module can expose a method of an instance. e.g gevent. if hasattr(self._obj, '__self__') and \ inspect.isclass(self._obj.__self__) and \ self._obj.__self__ is self._instance: setattr( self._instance, self._attr, classmethod(self._obj.__func__)) elif hasattr(self._obj, 'im_self') and \ inspect.isclass(self._obj.im_self) and \ self._obj.im_self is self._instance: # Wrap it and set it back on the class setattr(self._instance, self._attr, classmethod(self._obj.im_func)) else: setattr(self._instance, self._attr, self._obj)
[ "def", "_teardown", "(", "self", ")", ":", "# Figure out if this is a class method and we're unstubbing it on the", "# class to which it belongs. This addresses an edge case where a", "# module can expose a method of an instance. e.g gevent.", "if", "hasattr", "(", "self", ".", "_obj", ...
Put the original method back in place. This will also handle the special case when it putting back a class method. The following code snippet best describe why it fails using settar, the class method would be replaced with a bound method not a class method. >>> class Example(object): ... @classmethod ... def a_classmethod(self): ... pass ... >>> Example.__dict__['a_classmethod'] <classmethod object at 0x7f5e6c298be8> >>> orig = getattr(Example, 'a_classmethod') >>> orig <bound method type.a_classmethod of <class '__main__.Example'>> >>> setattr(Example, 'a_classmethod', orig) >>> Example.__dict__['a_classmethod'] <bound method type.a_classmethod of <class '__main__.Example'>> The only way to figure out if this is a class method is to check and see if the bound method im_self is a class, if so then we need to wrap the function object (im_func) with class method before setting it back on the class.
[ "Put", "the", "original", "method", "back", "in", "place", ".", "This", "will", "also", "handle", "the", "special", "case", "when", "it", "putting", "back", "a", "class", "method", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L422-L464
train
47,620
agoragames/chai
chai/stub.py
StubFunction._teardown
def _teardown(self): ''' Replace the original method. ''' if not self._was_object_method: setattr(self._instance, self._attr, self._obj) else: delattr(self._instance, self._attr)
python
def _teardown(self): ''' Replace the original method. ''' if not self._was_object_method: setattr(self._instance, self._attr, self._obj) else: delattr(self._instance, self._attr)
[ "def", "_teardown", "(", "self", ")", ":", "if", "not", "self", ".", "_was_object_method", ":", "setattr", "(", "self", ".", "_instance", ",", "self", ".", "_attr", ",", "self", ".", "_obj", ")", "else", ":", "delattr", "(", "self", ".", "_instance", ...
Replace the original method.
[ "Replace", "the", "original", "method", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L518-L525
train
47,621
agoragames/chai
chai/stub.py
StubNew._teardown
def _teardown(self): ''' Overload so that we can clear out the cache after a test run. ''' # __new__ is a super-special case in that even when stubbing a class # which implements its own __new__ and subclasses object, the # "Class.__new__" reference is a staticmethod and not a method (or # function). That confuses the "was_object_method" logic in # StubFunction which then fails to delattr and from then on the class # is corrupted. So skip that teardown and use a __new__-specific case. setattr(self._instance, self._attr, staticmethod(self._new)) StubNew._cache.pop(self._type)
python
def _teardown(self): ''' Overload so that we can clear out the cache after a test run. ''' # __new__ is a super-special case in that even when stubbing a class # which implements its own __new__ and subclasses object, the # "Class.__new__" reference is a staticmethod and not a method (or # function). That confuses the "was_object_method" logic in # StubFunction which then fails to delattr and from then on the class # is corrupted. So skip that teardown and use a __new__-specific case. setattr(self._instance, self._attr, staticmethod(self._new)) StubNew._cache.pop(self._type)
[ "def", "_teardown", "(", "self", ")", ":", "# __new__ is a super-special case in that even when stubbing a class", "# which implements its own __new__ and subclasses object, the", "# \"Class.__new__\" reference is a staticmethod and not a method (or", "# function). That confuses the \"was_object_m...
Overload so that we can clear out the cache after a test run.
[ "Overload", "so", "that", "we", "can", "clear", "out", "the", "cache", "after", "a", "test", "run", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L576-L587
train
47,622
d0ugal/python-rfxcom
rfxcom/transport/asyncio.py
AsyncioTransport._setup
def _setup(self): """Performs the RFXtrx initialisation protocol in a Future. Currently this is the rough workflow of the interactions with the RFXtrx. We also do a few extra things - flush the buffer, and attach readers/writers to the asyncio loop. 1. Write a RESET packet (write all zeros) 2. Wait at least 50ms and less than 9000ms 3. Write the STATUS packet to verify the device is up. 4. Receive status response 5. Write the MODE packet to enable or disabled the required protocols. """ self.log.info("Adding reader to prepare to receive.") self.loop.add_reader(self.dev.fd, self.read) self.log.info("Flushing the RFXtrx buffer.") self.flushSerialInput() self.log.info("Writing the reset packet to the RFXtrx. (blocking)") yield from self.sendRESET() self.log.info("Wating 0.4s") yield from asyncio.sleep(0.4) self.log.info("Write the status packet (blocking)") yield from self.sendSTATUS() # TODO receive status response, compare it with the needed MODE and # request a new MODE if required. Currently MODE is always sent. self.log.info("Adding mode packet to the write queue (blocking)") yield from self.sendMODE()
python
def _setup(self): """Performs the RFXtrx initialisation protocol in a Future. Currently this is the rough workflow of the interactions with the RFXtrx. We also do a few extra things - flush the buffer, and attach readers/writers to the asyncio loop. 1. Write a RESET packet (write all zeros) 2. Wait at least 50ms and less than 9000ms 3. Write the STATUS packet to verify the device is up. 4. Receive status response 5. Write the MODE packet to enable or disabled the required protocols. """ self.log.info("Adding reader to prepare to receive.") self.loop.add_reader(self.dev.fd, self.read) self.log.info("Flushing the RFXtrx buffer.") self.flushSerialInput() self.log.info("Writing the reset packet to the RFXtrx. (blocking)") yield from self.sendRESET() self.log.info("Wating 0.4s") yield from asyncio.sleep(0.4) self.log.info("Write the status packet (blocking)") yield from self.sendSTATUS() # TODO receive status response, compare it with the needed MODE and # request a new MODE if required. Currently MODE is always sent. self.log.info("Adding mode packet to the write queue (blocking)") yield from self.sendMODE()
[ "def", "_setup", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "\"Adding reader to prepare to receive.\"", ")", "self", ".", "loop", ".", "add_reader", "(", "self", ".", "dev", ".", "fd", ",", "self", ".", "read", ")", "self", ".", "log"...
Performs the RFXtrx initialisation protocol in a Future. Currently this is the rough workflow of the interactions with the RFXtrx. We also do a few extra things - flush the buffer, and attach readers/writers to the asyncio loop. 1. Write a RESET packet (write all zeros) 2. Wait at least 50ms and less than 9000ms 3. Write the STATUS packet to verify the device is up. 4. Receive status response 5. Write the MODE packet to enable or disabled the required protocols.
[ "Performs", "the", "RFXtrx", "initialisation", "protocol", "in", "a", "Future", "." ]
2eb87f85e5f5a04d00f32f25e0f010edfefbde0d
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/transport/asyncio.py#L23-L55
train
47,623
d0ugal/python-rfxcom
rfxcom/transport/asyncio.py
AsyncioTransport.do_callback
def do_callback(self, pkt): """Add the callback to the event loop, we use call soon because we just want it to be called at some point, but don't care when particularly. """ callback, parser = self.get_callback_parser(pkt) if asyncio.iscoroutinefunction(callback): self.loop.call_soon_threadsafe(self._do_async_callback, callback, parser) else: self.loop.call_soon(callback, parser)
python
def do_callback(self, pkt): """Add the callback to the event loop, we use call soon because we just want it to be called at some point, but don't care when particularly. """ callback, parser = self.get_callback_parser(pkt) if asyncio.iscoroutinefunction(callback): self.loop.call_soon_threadsafe(self._do_async_callback, callback, parser) else: self.loop.call_soon(callback, parser)
[ "def", "do_callback", "(", "self", ",", "pkt", ")", ":", "callback", ",", "parser", "=", "self", ".", "get_callback_parser", "(", "pkt", ")", "if", "asyncio", ".", "iscoroutinefunction", "(", "callback", ")", ":", "self", ".", "loop", ".", "call_soon_threa...
Add the callback to the event loop, we use call soon because we just want it to be called at some point, but don't care when particularly.
[ "Add", "the", "callback", "to", "the", "event", "loop", "we", "use", "call", "soon", "because", "we", "just", "want", "it", "to", "be", "called", "at", "some", "point", "but", "don", "t", "care", "when", "particularly", "." ]
2eb87f85e5f5a04d00f32f25e0f010edfefbde0d
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/transport/asyncio.py#L73-L83
train
47,624
d0ugal/python-rfxcom
rfxcom/transport/asyncio.py
AsyncioTransport.read
def read(self): """We have been called to read! As a consumer, continue to read for the length of the packet and then pass to the callback. """ data = self.dev.read() if len(data) == 0: self.log.warning("READ : Nothing received") return if data == b'\x00': self.log.warning("READ : Empty packet (Got \\x00)") return pkt = bytearray(data) data = self.dev.read(pkt[0]) pkt.extend(bytearray(data)) self.log.info("READ : %s" % self.format_packet(pkt)) self.do_callback(pkt) return pkt
python
def read(self): """We have been called to read! As a consumer, continue to read for the length of the packet and then pass to the callback. """ data = self.dev.read() if len(data) == 0: self.log.warning("READ : Nothing received") return if data == b'\x00': self.log.warning("READ : Empty packet (Got \\x00)") return pkt = bytearray(data) data = self.dev.read(pkt[0]) pkt.extend(bytearray(data)) self.log.info("READ : %s" % self.format_packet(pkt)) self.do_callback(pkt) return pkt
[ "def", "read", "(", "self", ")", ":", "data", "=", "self", ".", "dev", ".", "read", "(", ")", "if", "len", "(", "data", ")", "==", "0", ":", "self", ".", "log", ".", "warning", "(", "\"READ : Nothing received\"", ")", "return", "if", "data", "==", ...
We have been called to read! As a consumer, continue to read for the length of the packet and then pass to the callback.
[ "We", "have", "been", "called", "to", "read!", "As", "a", "consumer", "continue", "to", "read", "for", "the", "length", "of", "the", "packet", "and", "then", "pass", "to", "the", "callback", "." ]
2eb87f85e5f5a04d00f32f25e0f010edfefbde0d
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/transport/asyncio.py#L93-L114
train
47,625
zencoder/zencoder-py
zencoder/core.py
HTTPBackend.delete
def delete(self, url, params=None): """ Executes an HTTP DELETE request for the given URL. ``params`` should be a dictionary """ response = self.http.delete(url, params=params, **self.requests_params) return self.process(response)
python
def delete(self, url, params=None): """ Executes an HTTP DELETE request for the given URL. ``params`` should be a dictionary """ response = self.http.delete(url, params=params, **self.requests_params) return self.process(response)
[ "def", "delete", "(", "self", ",", "url", ",", "params", "=", "None", ")", ":", "response", "=", "self", ".", "http", ".", "delete", "(", "url", ",", "params", "=", "params", ",", "*", "*", "self", ".", "requests_params", ")", "return", "self", "."...
Executes an HTTP DELETE request for the given URL. ``params`` should be a dictionary
[ "Executes", "an", "HTTP", "DELETE", "request", "for", "the", "given", "URL", "." ]
9d762e33e2bb2edadb0e5da0bb80a61e27636426
https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L82-L90
train
47,626
zencoder/zencoder-py
zencoder/core.py
HTTPBackend.get
def get(self, url, data=None): """ Executes an HTTP GET request for the given URL. ``data`` should be a dictionary of url parameters """ response = self.http.get(url, headers=self.headers, params=data, **self.requests_params) return self.process(response)
python
def get(self, url, data=None): """ Executes an HTTP GET request for the given URL. ``data`` should be a dictionary of url parameters """ response = self.http.get(url, headers=self.headers, params=data, **self.requests_params) return self.process(response)
[ "def", "get", "(", "self", ",", "url", ",", "data", "=", "None", ")", ":", "response", "=", "self", ".", "http", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "headers", ",", "params", "=", "data", ",", "*", "*", "self", ".", "reque...
Executes an HTTP GET request for the given URL. ``data`` should be a dictionary of url parameters
[ "Executes", "an", "HTTP", "GET", "request", "for", "the", "given", "URL", "." ]
9d762e33e2bb2edadb0e5da0bb80a61e27636426
https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L92-L101
train
47,627
zencoder/zencoder-py
zencoder/core.py
HTTPBackend.post
def post(self, url, body=None): """ Executes an HTTP POST request for the given URL. """ response = self.http.post(url, headers=self.headers, data=body, **self.requests_params) return self.process(response)
python
def post(self, url, body=None): """ Executes an HTTP POST request for the given URL. """ response = self.http.post(url, headers=self.headers, data=body, **self.requests_params) return self.process(response)
[ "def", "post", "(", "self", ",", "url", ",", "body", "=", "None", ")", ":", "response", "=", "self", ".", "http", ".", "post", "(", "url", ",", "headers", "=", "self", ".", "headers", ",", "data", "=", "body", ",", "*", "*", "self", ".", "reque...
Executes an HTTP POST request for the given URL.
[ "Executes", "an", "HTTP", "POST", "request", "for", "the", "given", "URL", "." ]
9d762e33e2bb2edadb0e5da0bb80a61e27636426
https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L103-L110
train
47,628
zencoder/zencoder-py
zencoder/core.py
HTTPBackend.put
def put(self, url, data=None, body=None): """ Executes an HTTP PUT request for the given URL. """ response = self.http.put(url, headers=self.headers, data=body, params=data, **self.requests_params) return self.process(response)
python
def put(self, url, data=None, body=None): """ Executes an HTTP PUT request for the given URL. """ response = self.http.put(url, headers=self.headers, data=body, params=data, **self.requests_params) return self.process(response)
[ "def", "put", "(", "self", ",", "url", ",", "data", "=", "None", ",", "body", "=", "None", ")", ":", "response", "=", "self", ".", "http", ".", "put", "(", "url", ",", "headers", "=", "self", ".", "headers", ",", "data", "=", "body", ",", "para...
Executes an HTTP PUT request for the given URL.
[ "Executes", "an", "HTTP", "PUT", "request", "for", "the", "given", "URL", "." ]
9d762e33e2bb2edadb0e5da0bb80a61e27636426
https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L112-L120
train
47,629
zencoder/zencoder-py
zencoder/core.py
HTTPBackend.process
def process(self, response): """ Returns HTTP backend agnostic ``Response`` data. """ try: code = response.status_code # 204 - No Content if code == 204: body = None # add an error message to 402 errors elif code == 402: body = { "message": "Payment Required", "status": "error" } else: body = response.json() return Response(code, body, response.content, response) except ValueError: raise ZencoderResponseError(response, response.content)
python
def process(self, response): """ Returns HTTP backend agnostic ``Response`` data. """ try: code = response.status_code # 204 - No Content if code == 204: body = None # add an error message to 402 errors elif code == 402: body = { "message": "Payment Required", "status": "error" } else: body = response.json() return Response(code, body, response.content, response) except ValueError: raise ZencoderResponseError(response, response.content)
[ "def", "process", "(", "self", ",", "response", ")", ":", "try", ":", "code", "=", "response", ".", "status_code", "# 204 - No Content", "if", "code", "==", "204", ":", "body", "=", "None", "# add an error message to 402 errors", "elif", "code", "==", "402", ...
Returns HTTP backend agnostic ``Response`` data.
[ "Returns", "HTTP", "backend", "agnostic", "Response", "data", "." ]
9d762e33e2bb2edadb0e5da0bb80a61e27636426
https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L122-L142
train
47,630
zencoder/zencoder-py
zencoder/core.py
Account.create
def create(self, email, tos=1, options=None): """ Creates an account with Zencoder, no API Key necessary. https://app.zencoder.com/docs/api/accounts/create """ data = {'email': email, 'terms_of_service': str(tos)} if options: data.update(options) return self.post(self.base_url, body=json.dumps(data))
python
def create(self, email, tos=1, options=None): """ Creates an account with Zencoder, no API Key necessary. https://app.zencoder.com/docs/api/accounts/create """ data = {'email': email, 'terms_of_service': str(tos)} if options: data.update(options) return self.post(self.base_url, body=json.dumps(data))
[ "def", "create", "(", "self", ",", "email", ",", "tos", "=", "1", ",", "options", "=", "None", ")", ":", "data", "=", "{", "'email'", ":", "email", ",", "'terms_of_service'", ":", "str", "(", "tos", ")", "}", "if", "options", ":", "data", ".", "u...
Creates an account with Zencoder, no API Key necessary. https://app.zencoder.com/docs/api/accounts/create
[ "Creates", "an", "account", "with", "Zencoder", "no", "API", "Key", "necessary", "." ]
9d762e33e2bb2edadb0e5da0bb80a61e27636426
https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L230-L241
train
47,631
zencoder/zencoder-py
zencoder/core.py
Job.list
def list(self, page=1, per_page=50): """ Lists Jobs. https://app.zencoder.com/docs/api/jobs/list """ data = {"page": page, "per_page": per_page} return self.get(self.base_url, data=data)
python
def list(self, page=1, per_page=50): """ Lists Jobs. https://app.zencoder.com/docs/api/jobs/list """ data = {"page": page, "per_page": per_page} return self.get(self.base_url, data=data)
[ "def", "list", "(", "self", ",", "page", "=", "1", ",", "per_page", "=", "50", ")", ":", "data", "=", "{", "\"page\"", ":", "page", ",", "\"per_page\"", ":", "per_page", "}", "return", "self", ".", "get", "(", "self", ".", "base_url", ",", "data", ...
Lists Jobs. https://app.zencoder.com/docs/api/jobs/list
[ "Lists", "Jobs", "." ]
9d762e33e2bb2edadb0e5da0bb80a61e27636426
https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L352-L360
train
47,632
zencoder/zencoder-py
zencoder/core.py
Job.resubmit
def resubmit(self, job_id): """ Resubmits the given ``job_id``. https://app.zencoder.com/docs/api/jobs/resubmit """ url = self.base_url + '/%s/resubmit' % str(job_id) return self.put(url)
python
def resubmit(self, job_id): """ Resubmits the given ``job_id``. https://app.zencoder.com/docs/api/jobs/resubmit """ url = self.base_url + '/%s/resubmit' % str(job_id) return self.put(url)
[ "def", "resubmit", "(", "self", ",", "job_id", ")", ":", "url", "=", "self", ".", "base_url", "+", "'/%s/resubmit'", "%", "str", "(", "job_id", ")", "return", "self", ".", "put", "(", "url", ")" ]
Resubmits the given ``job_id``. https://app.zencoder.com/docs/api/jobs/resubmit
[ "Resubmits", "the", "given", "job_id", "." ]
9d762e33e2bb2edadb0e5da0bb80a61e27636426
https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L378-L385
train
47,633
zencoder/zencoder-py
zencoder/core.py
Job.cancel
def cancel(self, job_id): """ Cancels the given ``job_id``. https://app.zencoder.com/docs/api/jobs/cancel """ if self.version == 'v1': verb = self.get else: verb = self.put url = self.base_url + '/%s/cancel' % str(job_id) return verb(url)
python
def cancel(self, job_id): """ Cancels the given ``job_id``. https://app.zencoder.com/docs/api/jobs/cancel """ if self.version == 'v1': verb = self.get else: verb = self.put url = self.base_url + '/%s/cancel' % str(job_id) return verb(url)
[ "def", "cancel", "(", "self", ",", "job_id", ")", ":", "if", "self", ".", "version", "==", "'v1'", ":", "verb", "=", "self", ".", "get", "else", ":", "verb", "=", "self", ".", "put", "url", "=", "self", ".", "base_url", "+", "'/%s/cancel'", "%", ...
Cancels the given ``job_id``. https://app.zencoder.com/docs/api/jobs/cancel
[ "Cancels", "the", "given", "job_id", "." ]
9d762e33e2bb2edadb0e5da0bb80a61e27636426
https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L387-L399
train
47,634
zencoder/zencoder-py
zencoder/core.py
Report.minutes
def minutes(self, start_date=None, end_date=None, grouping=None): """ Gets a detailed Report of encoded minutes and billable minutes for a date range. **Warning**: ``start_date`` and ``end_date`` must be ``datetime.date`` objects. Example:: import datetime start = datetime.date(2012, 12, 31) end = datetime.today() data = z.report.minutes(start, end) https://app.zencoder.com/docs/api/reports/minutes """ data = self.__format(start_date, end_date) url = self.base_url + '/minutes' return self.get(url, data=data)
python
def minutes(self, start_date=None, end_date=None, grouping=None): """ Gets a detailed Report of encoded minutes and billable minutes for a date range. **Warning**: ``start_date`` and ``end_date`` must be ``datetime.date`` objects. Example:: import datetime start = datetime.date(2012, 12, 31) end = datetime.today() data = z.report.minutes(start, end) https://app.zencoder.com/docs/api/reports/minutes """ data = self.__format(start_date, end_date) url = self.base_url + '/minutes' return self.get(url, data=data)
[ "def", "minutes", "(", "self", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "grouping", "=", "None", ")", ":", "data", "=", "self", ".", "__format", "(", "start_date", ",", "end_date", ")", "url", "=", "self", ".", "base_url", "...
Gets a detailed Report of encoded minutes and billable minutes for a date range. **Warning**: ``start_date`` and ``end_date`` must be ``datetime.date`` objects. Example:: import datetime start = datetime.date(2012, 12, 31) end = datetime.today() data = z.report.minutes(start, end) https://app.zencoder.com/docs/api/reports/minutes
[ "Gets", "a", "detailed", "Report", "of", "encoded", "minutes", "and", "billable", "minutes", "for", "a", "date", "range", "." ]
9d762e33e2bb2edadb0e5da0bb80a61e27636426
https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L442-L462
train
47,635
toumorokoshi/transmute-core
transmute_core/frameworks/flask/route.py
route
def route(app_or_blueprint, context=default_context, **kwargs): """ attach a transmute route. """ def decorator(fn): fn = describe(**kwargs)(fn) transmute_func = TransmuteFunction(fn) routes, handler = create_routes_and_handler(transmute_func, context) for r in routes: # push swagger info. if not hasattr(app_or_blueprint, SWAGGER_ATTR_NAME): setattr(app_or_blueprint, SWAGGER_ATTR_NAME, SwaggerSpec()) swagger_obj = getattr(app_or_blueprint, SWAGGER_ATTR_NAME) swagger_obj.add_func(transmute_func, context) app_or_blueprint.route(r, methods=transmute_func.methods)(handler) return handler return decorator
python
def route(app_or_blueprint, context=default_context, **kwargs): """ attach a transmute route. """ def decorator(fn): fn = describe(**kwargs)(fn) transmute_func = TransmuteFunction(fn) routes, handler = create_routes_and_handler(transmute_func, context) for r in routes: # push swagger info. if not hasattr(app_or_blueprint, SWAGGER_ATTR_NAME): setattr(app_or_blueprint, SWAGGER_ATTR_NAME, SwaggerSpec()) swagger_obj = getattr(app_or_blueprint, SWAGGER_ATTR_NAME) swagger_obj.add_func(transmute_func, context) app_or_blueprint.route(r, methods=transmute_func.methods)(handler) return handler return decorator
[ "def", "route", "(", "app_or_blueprint", ",", "context", "=", "default_context", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "fn", ")", ":", "fn", "=", "describe", "(", "*", "*", "kwargs", ")", "(", "fn", ")", "transmute_func", "=", "...
attach a transmute route.
[ "attach", "a", "transmute", "route", "." ]
a2c26625d5d8bab37e00038f9d615a26167fc7f4
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/flask/route.py#L9-L23
train
47,636
agoragames/chai
chai/chai.py
ChaiBase.stub
def stub(self, obj, attr=None): ''' Stub an object. If attr is not None, will attempt to stub that attribute on the object. Only required for modules and other rare cases where we can't determine the binding from the object. ''' s = stub(obj, attr) if s not in self._stubs: self._stubs.append(s) return s
python
def stub(self, obj, attr=None): ''' Stub an object. If attr is not None, will attempt to stub that attribute on the object. Only required for modules and other rare cases where we can't determine the binding from the object. ''' s = stub(obj, attr) if s not in self._stubs: self._stubs.append(s) return s
[ "def", "stub", "(", "self", ",", "obj", ",", "attr", "=", "None", ")", ":", "s", "=", "stub", "(", "obj", ",", "attr", ")", "if", "s", "not", "in", "self", ".", "_stubs", ":", "self", ".", "_stubs", ".", "append", "(", "s", ")", "return", "s"...
Stub an object. If attr is not None, will attempt to stub that attribute on the object. Only required for modules and other rare cases where we can't determine the binding from the object.
[ "Stub", "an", "object", ".", "If", "attr", "is", "not", "None", "will", "attempt", "to", "stub", "that", "attribute", "on", "the", "object", ".", "Only", "required", "for", "modules", "and", "other", "rare", "cases", "where", "we", "can", "t", "determine...
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/chai.py#L207-L216
train
47,637
agoragames/chai
chai/chai.py
ChaiBase.mock
def mock(self, obj=None, attr=None, **kwargs): ''' Return a mock object. ''' rval = Mock(**kwargs) if obj is not None and attr is not None: rval._object = obj rval._attr = attr if hasattr(obj, attr): orig = getattr(obj, attr) self._mocks.append((obj, attr, orig)) setattr(obj, attr, rval) else: self._mocks.append((obj, attr)) setattr(obj, attr, rval) return rval
python
def mock(self, obj=None, attr=None, **kwargs): ''' Return a mock object. ''' rval = Mock(**kwargs) if obj is not None and attr is not None: rval._object = obj rval._attr = attr if hasattr(obj, attr): orig = getattr(obj, attr) self._mocks.append((obj, attr, orig)) setattr(obj, attr, rval) else: self._mocks.append((obj, attr)) setattr(obj, attr, rval) return rval
[ "def", "mock", "(", "self", ",", "obj", "=", "None", ",", "attr", "=", "None", ",", "*", "*", "kwargs", ")", ":", "rval", "=", "Mock", "(", "*", "*", "kwargs", ")", "if", "obj", "is", "not", "None", "and", "attr", "is", "not", "None", ":", "r...
Return a mock object.
[ "Return", "a", "mock", "object", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/chai.py#L232-L248
train
47,638
paylogic/halogen
halogen/vnd/error.py
Error.from_validation_exception
def from_validation_exception(cls, exception, **kwargs): """Create an error from validation exception.""" errors = [] def flatten(error, path=""): if isinstance(error, halogen.exceptions.ValidationError): if not path.endswith("/"): path += "/" if error.attr is not None: path += error.attr elif error.index is not None: path += six.text_type(error.index) for e in error.errors: flatten(e, path) else: message = error if isinstance(error, Exception): try: message = error.message except AttributeError: message = six.text_type(error) # TODO: i18n errors.append(Error(message=message, path=path)) flatten(exception) message = kwargs.pop("message", "Validation error.") return cls(message=message, errors=sorted(errors, key=lambda error: error.path or ""), **kwargs)
python
def from_validation_exception(cls, exception, **kwargs): """Create an error from validation exception.""" errors = [] def flatten(error, path=""): if isinstance(error, halogen.exceptions.ValidationError): if not path.endswith("/"): path += "/" if error.attr is not None: path += error.attr elif error.index is not None: path += six.text_type(error.index) for e in error.errors: flatten(e, path) else: message = error if isinstance(error, Exception): try: message = error.message except AttributeError: message = six.text_type(error) # TODO: i18n errors.append(Error(message=message, path=path)) flatten(exception) message = kwargs.pop("message", "Validation error.") return cls(message=message, errors=sorted(errors, key=lambda error: error.path or ""), **kwargs)
[ "def", "from_validation_exception", "(", "cls", ",", "exception", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "[", "]", "def", "flatten", "(", "error", ",", "path", "=", "\"\"", ")", ":", "if", "isinstance", "(", "error", ",", "halogen", ".", "...
Create an error from validation exception.
[ "Create", "an", "error", "from", "validation", "exception", "." ]
2dec0a67c506d02d1f51915fa7163f59764a0bde
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/vnd/error.py#L26-L53
train
47,639
toumorokoshi/transmute-core
transmute_core/frameworks/aiohttp/url_dispatcher.py
TransmuteUrlDispatcher.add_transmute_route
def add_transmute_route(self, *args): """ two formats are accepted, for transmute routes. One allows for a more traditional aiohttp syntax, while the other allows for a flask-like variant. .. code-block:: python # if the path and method are not added in describe. add_transmute_route("GET", "/route", fn) # if the path and method are already added in describe add_transmute_route(fn) """ if len(args) == 1: fn = args[0] elif len(args) == 3: methods, paths, fn = args fn = describe(methods=methods, paths=paths)(fn) else: raise ValueError( "expected one or three arguments for add_transmute_route!" ) add_route(self._app, fn, context=self._transmute_context)
python
def add_transmute_route(self, *args): """ two formats are accepted, for transmute routes. One allows for a more traditional aiohttp syntax, while the other allows for a flask-like variant. .. code-block:: python # if the path and method are not added in describe. add_transmute_route("GET", "/route", fn) # if the path and method are already added in describe add_transmute_route(fn) """ if len(args) == 1: fn = args[0] elif len(args) == 3: methods, paths, fn = args fn = describe(methods=methods, paths=paths)(fn) else: raise ValueError( "expected one or three arguments for add_transmute_route!" ) add_route(self._app, fn, context=self._transmute_context)
[ "def", "add_transmute_route", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "fn", "=", "args", "[", "0", "]", "elif", "len", "(", "args", ")", "==", "3", ":", "methods", ",", "paths", ",", "fn", "=", ...
two formats are accepted, for transmute routes. One allows for a more traditional aiohttp syntax, while the other allows for a flask-like variant. .. code-block:: python # if the path and method are not added in describe. add_transmute_route("GET", "/route", fn) # if the path and method are already added in describe add_transmute_route(fn)
[ "two", "formats", "are", "accepted", "for", "transmute", "routes", ".", "One", "allows", "for", "a", "more", "traditional", "aiohttp", "syntax", "while", "the", "other", "allows", "for", "a", "flask", "-", "like", "variant", "." ]
a2c26625d5d8bab37e00038f9d615a26167fc7f4
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/aiohttp/url_dispatcher.py#L33-L57
train
47,640
toumorokoshi/transmute-core
transmute_core/object_serializers/cattrs_serializer/__init__.py
CattrsSerializer.can_handle
def can_handle(self, cls): """ this will theoretically be compatible with everything, as cattrs can handle many basic types as well. """ # cattrs uses a Singledispatch like function # under the hood. f = self._cattrs_converter._structure_func.dispatch(cls) return f != self._cattrs_converter._structure_default
python
def can_handle(self, cls): """ this will theoretically be compatible with everything, as cattrs can handle many basic types as well. """ # cattrs uses a Singledispatch like function # under the hood. f = self._cattrs_converter._structure_func.dispatch(cls) return f != self._cattrs_converter._structure_default
[ "def", "can_handle", "(", "self", ",", "cls", ")", ":", "# cattrs uses a Singledispatch like function", "# under the hood.", "f", "=", "self", ".", "_cattrs_converter", ".", "_structure_func", ".", "dispatch", "(", "cls", ")", "return", "f", "!=", "self", ".", "...
this will theoretically be compatible with everything, as cattrs can handle many basic types as well.
[ "this", "will", "theoretically", "be", "compatible", "with", "everything", "as", "cattrs", "can", "handle", "many", "basic", "types", "as", "well", "." ]
a2c26625d5d8bab37e00038f9d615a26167fc7f4
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/object_serializers/cattrs_serializer/__init__.py#L17-L25
train
47,641
toumorokoshi/transmute-core
transmute_core/object_serializers/cattrs_serializer/__init__.py
CattrsSerializer.load
def load(self, model, value): """ Converts unstructured data into structured data, recursively. """ try: return self._cattrs_converter.structure(value, model) except (ValueError, TypeError) as e: raise SerializationException(str(e))
python
def load(self, model, value): """ Converts unstructured data into structured data, recursively. """ try: return self._cattrs_converter.structure(value, model) except (ValueError, TypeError) as e: raise SerializationException(str(e))
[ "def", "load", "(", "self", ",", "model", ",", "value", ")", ":", "try", ":", "return", "self", ".", "_cattrs_converter", ".", "structure", "(", "value", ",", "model", ")", "except", "(", "ValueError", ",", "TypeError", ")", "as", "e", ":", "raise", ...
Converts unstructured data into structured data, recursively.
[ "Converts", "unstructured", "data", "into", "structured", "data", "recursively", "." ]
a2c26625d5d8bab37e00038f9d615a26167fc7f4
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/object_serializers/cattrs_serializer/__init__.py#L27-L34
train
47,642
inveniosoftware/invenio-previewer
invenio_previewer/utils.py
detect_encoding
def detect_encoding(fp, default=None): """Detect the cahracter encoding of a file. :param fp: Open Python file pointer. :param default: Fallback encoding to use. :returns: The detected encoding. .. note:: The file pointer is returned at its original read position. """ init_pos = fp.tell() try: sample = fp.read( current_app.config.get('PREVIEWER_CHARDET_BYTES', 1024)) # Result contains 'confidence' and 'encoding' result = cchardet.detect(sample) threshold = current_app.config.get('PREVIEWER_CHARDET_CONFIDENCE', 0.9) if result.get('confidence', 0) > threshold: return result.get('encoding', default) else: return default except Exception: current_app.logger.warning('Encoding detection failed.', exc_info=True) return default finally: fp.seek(init_pos)
python
def detect_encoding(fp, default=None): """Detect the cahracter encoding of a file. :param fp: Open Python file pointer. :param default: Fallback encoding to use. :returns: The detected encoding. .. note:: The file pointer is returned at its original read position. """ init_pos = fp.tell() try: sample = fp.read( current_app.config.get('PREVIEWER_CHARDET_BYTES', 1024)) # Result contains 'confidence' and 'encoding' result = cchardet.detect(sample) threshold = current_app.config.get('PREVIEWER_CHARDET_CONFIDENCE', 0.9) if result.get('confidence', 0) > threshold: return result.get('encoding', default) else: return default except Exception: current_app.logger.warning('Encoding detection failed.', exc_info=True) return default finally: fp.seek(init_pos)
[ "def", "detect_encoding", "(", "fp", ",", "default", "=", "None", ")", ":", "init_pos", "=", "fp", ".", "tell", "(", ")", "try", ":", "sample", "=", "fp", ".", "read", "(", "current_app", ".", "config", ".", "get", "(", "'PREVIEWER_CHARDET_BYTES'", ","...
Detect the cahracter encoding of a file. :param fp: Open Python file pointer. :param default: Fallback encoding to use. :returns: The detected encoding. .. note:: The file pointer is returned at its original read position.
[ "Detect", "the", "cahracter", "encoding", "of", "a", "file", "." ]
558fd22e0f29cc8cd7a6999abd4febcf6b248c49
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/utils.py#L15-L39
train
47,643
paylogic/halogen
halogen/types.py
Type.deserialize
def deserialize(self, value, **kwargs): """Deserialization of value. :return: Deserialized value. :raises: :class:`halogen.exception.ValidationError` exception if value is not valid. """ for validator in self.validators: validator.validate(value, **kwargs) return value
python
def deserialize(self, value, **kwargs): """Deserialization of value. :return: Deserialized value. :raises: :class:`halogen.exception.ValidationError` exception if value is not valid. """ for validator in self.validators: validator.validate(value, **kwargs) return value
[ "def", "deserialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "for", "validator", "in", "self", ".", "validators", ":", "validator", ".", "validate", "(", "value", ",", "*", "*", "kwargs", ")", "return", "value" ]
Deserialization of value. :return: Deserialized value. :raises: :class:`halogen.exception.ValidationError` exception if value is not valid.
[ "Deserialization", "of", "value", "." ]
2dec0a67c506d02d1f51915fa7163f59764a0bde
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L29-L38
train
47,644
paylogic/halogen
halogen/types.py
Type.is_type
def is_type(value): """Determine if value is an instance or subclass of the class Type.""" if isinstance(value, type): return issubclass(value, Type) return isinstance(value, Type)
python
def is_type(value): """Determine if value is an instance or subclass of the class Type.""" if isinstance(value, type): return issubclass(value, Type) return isinstance(value, Type)
[ "def", "is_type", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "type", ")", ":", "return", "issubclass", "(", "value", ",", "Type", ")", "return", "isinstance", "(", "value", ",", "Type", ")" ]
Determine if value is an instance or subclass of the class Type.
[ "Determine", "if", "value", "is", "an", "instance", "or", "subclass", "of", "the", "class", "Type", "." ]
2dec0a67c506d02d1f51915fa7163f59764a0bde
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L41-L45
train
47,645
paylogic/halogen
halogen/types.py
List.serialize
def serialize(self, value, **kwargs): """Serialize every item of the list.""" return [self.item_type.serialize(val, **kwargs) for val in value]
python
def serialize(self, value, **kwargs): """Serialize every item of the list.""" return [self.item_type.serialize(val, **kwargs) for val in value]
[ "def", "serialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "return", "[", "self", ".", "item_type", ".", "serialize", "(", "val", ",", "*", "*", "kwargs", ")", "for", "val", "in", "value", "]" ]
Serialize every item of the list.
[ "Serialize", "every", "item", "of", "the", "list", "." ]
2dec0a67c506d02d1f51915fa7163f59764a0bde
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L61-L63
train
47,646
paylogic/halogen
halogen/types.py
List.deserialize
def deserialize(self, value, **kwargs): """Deserialize every item of the list.""" if self.allow_scalar and not isinstance(value, (list, tuple)): value = [value] value = super(List, self).deserialize(value) result = [] errors = [] for index, val in enumerate(value): try: result.append(self.item_type.deserialize(val, **kwargs)) except ValidationError as exc: exc.index = index errors.append(exc) if errors: raise ValidationError(errors) return result
python
def deserialize(self, value, **kwargs): """Deserialize every item of the list.""" if self.allow_scalar and not isinstance(value, (list, tuple)): value = [value] value = super(List, self).deserialize(value) result = [] errors = [] for index, val in enumerate(value): try: result.append(self.item_type.deserialize(val, **kwargs)) except ValidationError as exc: exc.index = index errors.append(exc) if errors: raise ValidationError(errors) return result
[ "def", "deserialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "allow_scalar", "and", "not", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "value", "=", "[", "value", "]", "value"...
Deserialize every item of the list.
[ "Deserialize", "every", "item", "of", "the", "list", "." ]
2dec0a67c506d02d1f51915fa7163f59764a0bde
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L65-L81
train
47,647
paylogic/halogen
halogen/types.py
ISOUTCDateTime.format_as_utc
def format_as_utc(self, value): """Format UTC times.""" if isinstance(value, datetime.datetime): if value.tzinfo is not None: value = value.astimezone(pytz.UTC) value = value.replace(microsecond=0) return value.isoformat().replace('+00:00', 'Z')
python
def format_as_utc(self, value): """Format UTC times.""" if isinstance(value, datetime.datetime): if value.tzinfo is not None: value = value.astimezone(pytz.UTC) value = value.replace(microsecond=0) return value.isoformat().replace('+00:00', 'Z')
[ "def", "format_as_utc", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "if", "value", ".", "tzinfo", "is", "not", "None", ":", "value", "=", "value", ".", "astimezone", "(", "pytz", ...
Format UTC times.
[ "Format", "UTC", "times", "." ]
2dec0a67c506d02d1f51915fa7163f59764a0bde
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L110-L116
train
47,648
paylogic/halogen
halogen/types.py
Amount.amount_object_to_dict
def amount_object_to_dict(self, amount): """Return the dictionary representation of an Amount object. Amount object must have amount and currency properties and as_tuple method which will return (currency, amount) and as_quantized method to quantize amount property. :param amount: instance of Amount object :return: dict with amount and currency keys. """ currency, amount = ( amount.as_quantized(digits=2).as_tuple() if not isinstance(amount, dict) else (amount["currency"], amount["amount"]) ) if currency not in self.currencies: raise ValueError(self.err_unknown_currency.format(currency=currency)) return { "amount": str(amount), "currency": str(currency), }
python
def amount_object_to_dict(self, amount): """Return the dictionary representation of an Amount object. Amount object must have amount and currency properties and as_tuple method which will return (currency, amount) and as_quantized method to quantize amount property. :param amount: instance of Amount object :return: dict with amount and currency keys. """ currency, amount = ( amount.as_quantized(digits=2).as_tuple() if not isinstance(amount, dict) else (amount["currency"], amount["amount"]) ) if currency not in self.currencies: raise ValueError(self.err_unknown_currency.format(currency=currency)) return { "amount": str(amount), "currency": str(currency), }
[ "def", "amount_object_to_dict", "(", "self", ",", "amount", ")", ":", "currency", ",", "amount", "=", "(", "amount", ".", "as_quantized", "(", "digits", "=", "2", ")", ".", "as_tuple", "(", ")", "if", "not", "isinstance", "(", "amount", ",", "dict", ")...
Return the dictionary representation of an Amount object. Amount object must have amount and currency properties and as_tuple method which will return (currency, amount) and as_quantized method to quantize amount property. :param amount: instance of Amount object :return: dict with amount and currency keys.
[ "Return", "the", "dictionary", "representation", "of", "an", "Amount", "object", "." ]
2dec0a67c506d02d1f51915fa7163f59764a0bde
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L205-L225
train
47,649
paylogic/halogen
halogen/types.py
Amount.deserialize
def deserialize(self, value, **kwargs): """Deserialize the amount. :param value: Amount in CURRENCYAMOUNT or {"currency": CURRENCY, "amount": AMOUNT} format. For example EUR35.50 or {"currency": "EUR", "amount": "35.50"} :return: A paylogic Amount object. :raises ValidationError: when amount can"t be deserialzied :raises ValidationError: when amount has more than 2 decimal places """ if value is None: return None if isinstance(value, six.string_types): currency = value[:3] amount = value[3:] elif isinstance(value, dict): if set(value.keys()) != set(("currency", "amount")): raise ValueError("Amount object has to have currency and amount fields.") amount = value["amount"] currency = value["currency"] else: raise ValueError("Value cannot be parsed to Amount.") if currency not in self.currencies: raise ValueError(self.err_unknown_currency.format(currency=currency)) try: amount = decimal.Decimal(amount).normalize() except decimal.InvalidOperation: raise ValueError(u"'{amount}' cannot be parsed to decimal.".format(amount=amount)) if amount.as_tuple().exponent < - 2: raise ValueError(u"'{amount}' has more than 2 decimal places.".format(amount=amount)) value = self.amount_class(currency=currency, amount=amount) return super(Amount, self).deserialize(value)
python
def deserialize(self, value, **kwargs): """Deserialize the amount. :param value: Amount in CURRENCYAMOUNT or {"currency": CURRENCY, "amount": AMOUNT} format. For example EUR35.50 or {"currency": "EUR", "amount": "35.50"} :return: A paylogic Amount object. :raises ValidationError: when amount can"t be deserialzied :raises ValidationError: when amount has more than 2 decimal places """ if value is None: return None if isinstance(value, six.string_types): currency = value[:3] amount = value[3:] elif isinstance(value, dict): if set(value.keys()) != set(("currency", "amount")): raise ValueError("Amount object has to have currency and amount fields.") amount = value["amount"] currency = value["currency"] else: raise ValueError("Value cannot be parsed to Amount.") if currency not in self.currencies: raise ValueError(self.err_unknown_currency.format(currency=currency)) try: amount = decimal.Decimal(amount).normalize() except decimal.InvalidOperation: raise ValueError(u"'{amount}' cannot be parsed to decimal.".format(amount=amount)) if amount.as_tuple().exponent < - 2: raise ValueError(u"'{amount}' has more than 2 decimal places.".format(amount=amount)) value = self.amount_class(currency=currency, amount=amount) return super(Amount, self).deserialize(value)
[ "def", "deserialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "currency", "=", "value", "[", ":", ...
Deserialize the amount. :param value: Amount in CURRENCYAMOUNT or {"currency": CURRENCY, "amount": AMOUNT} format. For example EUR35.50 or {"currency": "EUR", "amount": "35.50"} :return: A paylogic Amount object. :raises ValidationError: when amount can"t be deserialzied :raises ValidationError: when amount has more than 2 decimal places
[ "Deserialize", "the", "amount", "." ]
2dec0a67c506d02d1f51915fa7163f59764a0bde
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L238-L274
train
47,650
toumorokoshi/transmute-core
transmute_core/frameworks/aiohttp/route.py
add_route
def add_route(app, fn, context=default_context): """ a decorator that adds a transmute route to the application. """ transmute_func = TransmuteFunction( fn, args_not_from_request=["request"] ) handler = create_handler(transmute_func, context=context) get_swagger_spec(app).add_func(transmute_func, context) for p in transmute_func.paths: aiohttp_path = _convert_to_aiohttp_path(p) resource = app.router.add_resource(aiohttp_path) for method in transmute_func.methods: resource.add_route(method, handler)
python
def add_route(app, fn, context=default_context): """ a decorator that adds a transmute route to the application. """ transmute_func = TransmuteFunction( fn, args_not_from_request=["request"] ) handler = create_handler(transmute_func, context=context) get_swagger_spec(app).add_func(transmute_func, context) for p in transmute_func.paths: aiohttp_path = _convert_to_aiohttp_path(p) resource = app.router.add_resource(aiohttp_path) for method in transmute_func.methods: resource.add_route(method, handler)
[ "def", "add_route", "(", "app", ",", "fn", ",", "context", "=", "default_context", ")", ":", "transmute_func", "=", "TransmuteFunction", "(", "fn", ",", "args_not_from_request", "=", "[", "\"request\"", "]", ")", "handler", "=", "create_handler", "(", "transmu...
a decorator that adds a transmute route to the application.
[ "a", "decorator", "that", "adds", "a", "transmute", "route", "to", "the", "application", "." ]
a2c26625d5d8bab37e00038f9d615a26167fc7f4
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/aiohttp/route.py#L6-L21
train
47,651
inveniosoftware/invenio-previewer
invenio_previewer/views.py
preview
def preview(pid, record, template=None, **kwargs): """Preview file for given record. Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration: .. code-block:: python RECORDS_UI_ENDPOINTS = dict( recid=dict( # ... route='/records/<pid_value/preview/<path:filename>', view_imp='invenio_previewer.views.preview', record_class='invenio_records_files.api:Record', ) ) """ # Get file from record fileobj = current_previewer.record_file_factory( pid, record, request.view_args.get( 'filename', request.args.get('filename', type=str)) ) if not fileobj: abort(404) # Try to see if specific previewer is requested? try: file_previewer = fileobj['previewer'] except KeyError: file_previewer = None # Find a suitable previewer fileobj = PreviewFile(pid, record, fileobj) for plugin in current_previewer.iter_previewers( previewers=[file_previewer] if file_previewer else None): if plugin.can_preview(fileobj): try: return plugin.preview(fileobj) except Exception: current_app.logger.warning( ('Preview failed for {key}, in {pid_type}:{pid_value}' .format(key=fileobj.file.key, pid_type=fileobj.pid.pid_type, pid_value=fileobj.pid.pid_value)), exc_info=True) return default.preview(fileobj)
python
def preview(pid, record, template=None, **kwargs): """Preview file for given record. Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration: .. code-block:: python RECORDS_UI_ENDPOINTS = dict( recid=dict( # ... route='/records/<pid_value/preview/<path:filename>', view_imp='invenio_previewer.views.preview', record_class='invenio_records_files.api:Record', ) ) """ # Get file from record fileobj = current_previewer.record_file_factory( pid, record, request.view_args.get( 'filename', request.args.get('filename', type=str)) ) if not fileobj: abort(404) # Try to see if specific previewer is requested? try: file_previewer = fileobj['previewer'] except KeyError: file_previewer = None # Find a suitable previewer fileobj = PreviewFile(pid, record, fileobj) for plugin in current_previewer.iter_previewers( previewers=[file_previewer] if file_previewer else None): if plugin.can_preview(fileobj): try: return plugin.preview(fileobj) except Exception: current_app.logger.warning( ('Preview failed for {key}, in {pid_type}:{pid_value}' .format(key=fileobj.file.key, pid_type=fileobj.pid.pid_type, pid_value=fileobj.pid.pid_value)), exc_info=True) return default.preview(fileobj)
[ "def", "preview", "(", "pid", ",", "record", ",", "template", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Get file from record", "fileobj", "=", "current_previewer", ".", "record_file_factory", "(", "pid", ",", "record", ",", "request", ".", "view_arg...
Preview file for given record. Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration: .. code-block:: python RECORDS_UI_ENDPOINTS = dict( recid=dict( # ... route='/records/<pid_value/preview/<path:filename>', view_imp='invenio_previewer.views.preview', record_class='invenio_records_files.api:Record', ) )
[ "Preview", "file", "for", "given", "record", "." ]
558fd22e0f29cc8cd7a6999abd4febcf6b248c49
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/views.py#L28-L72
train
47,652
inveniosoftware/invenio-previewer
examples/app.py
fixtures
def fixtures(): """Command for working with test data.""" temp_path = os.path.join(os.path.dirname(__file__), 'temp') demo_files_path = os.path.join(os.path.dirname(__file__), 'demo_files') # Create location loc = Location(name='local', uri=temp_path, default=True) db.session.add(loc) db.session.commit() # Example files from the data folder demo_files = ( 'markdown.md', 'csvfile.csv', 'zipfile.zip', 'jsonfile.json', 'xmlfile.xml', 'notebook.ipynb', 'jpgfile.jpg', 'pngfile.png', ) rec_uuid = uuid4() provider = RecordIdProvider.create(object_type='rec', object_uuid=rec_uuid) data = { 'pid_value': provider.pid.pid_value, } record = Record.create(data, id_=rec_uuid) bucket = Bucket.create() RecordsBuckets.create(record=record.model, bucket=bucket) # Add files to the record for f in demo_files: with open(os.path.join(demo_files_path, f), 'rb') as fp: record.files[f] = fp record.files.flush() record.commit() db.session.commit()
python
def fixtures(): """Command for working with test data.""" temp_path = os.path.join(os.path.dirname(__file__), 'temp') demo_files_path = os.path.join(os.path.dirname(__file__), 'demo_files') # Create location loc = Location(name='local', uri=temp_path, default=True) db.session.add(loc) db.session.commit() # Example files from the data folder demo_files = ( 'markdown.md', 'csvfile.csv', 'zipfile.zip', 'jsonfile.json', 'xmlfile.xml', 'notebook.ipynb', 'jpgfile.jpg', 'pngfile.png', ) rec_uuid = uuid4() provider = RecordIdProvider.create(object_type='rec', object_uuid=rec_uuid) data = { 'pid_value': provider.pid.pid_value, } record = Record.create(data, id_=rec_uuid) bucket = Bucket.create() RecordsBuckets.create(record=record.model, bucket=bucket) # Add files to the record for f in demo_files: with open(os.path.join(demo_files_path, f), 'rb') as fp: record.files[f] = fp record.files.flush() record.commit() db.session.commit()
[ "def", "fixtures", "(", ")", ":", "temp_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'temp'", ")", "demo_files_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ...
Command for working with test data.
[ "Command", "for", "working", "with", "test", "data", "." ]
558fd22e0f29cc8cd7a6999abd4febcf6b248c49
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/examples/app.py#L87-L126
train
47,653
inveniosoftware/invenio-previewer
invenio_previewer/extensions/mistune.py
render
def render(file): """Render HTML from Markdown file content.""" with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') result = mistune.markdown(fp.read().decode(encoding)) return result
python
def render(file): """Render HTML from Markdown file content.""" with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') result = mistune.markdown(fp.read().decode(encoding)) return result
[ "def", "render", "(", "file", ")", ":", "with", "file", ".", "open", "(", ")", "as", "fp", ":", "encoding", "=", "detect_encoding", "(", "fp", ",", "default", "=", "'utf-8'", ")", "result", "=", "mistune", ".", "markdown", "(", "fp", ".", "read", "...
Render HTML from Markdown file content.
[ "Render", "HTML", "from", "Markdown", "file", "content", "." ]
558fd22e0f29cc8cd7a6999abd4febcf6b248c49
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/mistune.py#L21-L26
train
47,654
paylogic/halogen
halogen/validators.py
Length.validate
def validate(self, value): """Validate the length of a list. :param value: List of values. :raises: :class:`halogen.exception.ValidationError` exception when length of the list is less than minimum or greater than maximum. """ try: length = len(value) except TypeError: length = 0 if self.min_length is not None: min_length = self.min_length() if callable(self.min_length) else self.min_length if length < min_length: raise exceptions.ValidationError(self.min_err.format(min_length)) if self.max_length is not None: max_length = self.max_length() if callable(self.max_length) else self.max_length if length > max_length: raise exceptions.ValidationError(self.max_err.format(max_length))
python
def validate(self, value): """Validate the length of a list. :param value: List of values. :raises: :class:`halogen.exception.ValidationError` exception when length of the list is less than minimum or greater than maximum. """ try: length = len(value) except TypeError: length = 0 if self.min_length is not None: min_length = self.min_length() if callable(self.min_length) else self.min_length if length < min_length: raise exceptions.ValidationError(self.min_err.format(min_length)) if self.max_length is not None: max_length = self.max_length() if callable(self.max_length) else self.max_length if length > max_length: raise exceptions.ValidationError(self.max_err.format(max_length))
[ "def", "validate", "(", "self", ",", "value", ")", ":", "try", ":", "length", "=", "len", "(", "value", ")", "except", "TypeError", ":", "length", "=", "0", "if", "self", ".", "min_length", "is", "not", "None", ":", "min_length", "=", "self", ".", ...
Validate the length of a list. :param value: List of values. :raises: :class:`halogen.exception.ValidationError` exception when length of the list is less than minimum or greater than maximum.
[ "Validate", "the", "length", "of", "a", "list", "." ]
2dec0a67c506d02d1f51915fa7163f59764a0bde
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/validators.py#L92-L113
train
47,655
dhondta/tinyscript
tinyscript/parser.py
__get_calls_from_parser
def __get_calls_from_parser(proxy_parser, real_parser): """ This actually executes the calls registered in the ProxyArgumentParser. :param proxy_parser: ProxyArgumentParser instance :param real_parser: ArgumentParser instance """ __parsers[proxy_parser] = real_parser for method, safe, args, kwargs, proxy_subparser in proxy_parser.calls: args = (__proxy_to_real_parser(v) for v in args) kwargs = {k: __proxy_to_real_parser(v) for k, v in kwargs.items()} real_subparser = getattr(real_parser, method)(*args, **kwargs) if real_subparser is not None: __get_calls_from_parser(proxy_subparser, real_subparser)
python
def __get_calls_from_parser(proxy_parser, real_parser): """ This actually executes the calls registered in the ProxyArgumentParser. :param proxy_parser: ProxyArgumentParser instance :param real_parser: ArgumentParser instance """ __parsers[proxy_parser] = real_parser for method, safe, args, kwargs, proxy_subparser in proxy_parser.calls: args = (__proxy_to_real_parser(v) for v in args) kwargs = {k: __proxy_to_real_parser(v) for k, v in kwargs.items()} real_subparser = getattr(real_parser, method)(*args, **kwargs) if real_subparser is not None: __get_calls_from_parser(proxy_subparser, real_subparser)
[ "def", "__get_calls_from_parser", "(", "proxy_parser", ",", "real_parser", ")", ":", "__parsers", "[", "proxy_parser", "]", "=", "real_parser", "for", "method", ",", "safe", ",", "args", ",", "kwargs", ",", "proxy_subparser", "in", "proxy_parser", ".", "calls", ...
This actually executes the calls registered in the ProxyArgumentParser. :param proxy_parser: ProxyArgumentParser instance :param real_parser: ArgumentParser instance
[ "This", "actually", "executes", "the", "calls", "registered", "in", "the", "ProxyArgumentParser", "." ]
624a0718db698899e7bc3ba6ac694baed251e81d
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/parser.py#L28-L41
train
47,656
dhondta/tinyscript
tinyscript/parser.py
__proxy_to_real_parser
def __proxy_to_real_parser(value): """ This recursively converts ProxyArgumentParser instances to actual parsers. Use case: defining subparsers with a parent >>> [...] >>> parser.add_argument(...) # argument common to all subparsers >>> subparsers = parser.add_subparsers() >>> subparsers.add_parser(..., parents=[parent]) ^ this is an instance of ProxyArgumentParser and must be converted to an actual parser instance :param value: a value coming from args or kwargs aimed to an actual parser """ if isinstance(value, ProxyArgumentParser): return __parsers[value] elif any(isinstance(value, t) for t in [list, tuple]): new_value = [] for subvalue in iter(value): new_value.append(__proxy_to_real_parser(subvalue)) return new_value return value
python
def __proxy_to_real_parser(value): """ This recursively converts ProxyArgumentParser instances to actual parsers. Use case: defining subparsers with a parent >>> [...] >>> parser.add_argument(...) # argument common to all subparsers >>> subparsers = parser.add_subparsers() >>> subparsers.add_parser(..., parents=[parent]) ^ this is an instance of ProxyArgumentParser and must be converted to an actual parser instance :param value: a value coming from args or kwargs aimed to an actual parser """ if isinstance(value, ProxyArgumentParser): return __parsers[value] elif any(isinstance(value, t) for t in [list, tuple]): new_value = [] for subvalue in iter(value): new_value.append(__proxy_to_real_parser(subvalue)) return new_value return value
[ "def", "__proxy_to_real_parser", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "ProxyArgumentParser", ")", ":", "return", "__parsers", "[", "value", "]", "elif", "any", "(", "isinstance", "(", "value", ",", "t", ")", "for", "t", "in", "[...
This recursively converts ProxyArgumentParser instances to actual parsers. Use case: defining subparsers with a parent >>> [...] >>> parser.add_argument(...) # argument common to all subparsers >>> subparsers = parser.add_subparsers() >>> subparsers.add_parser(..., parents=[parent]) ^ this is an instance of ProxyArgumentParser and must be converted to an actual parser instance :param value: a value coming from args or kwargs aimed to an actual parser
[ "This", "recursively", "converts", "ProxyArgumentParser", "instances", "to", "actual", "parsers", "." ]
624a0718db698899e7bc3ba6ac694baed251e81d
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/parser.py#L44-L66
train
47,657
LCAV/pylocus
pylocus/basics.py
mse
def mse(x, xhat): """ Calcualte mse between vector or matrix x and xhat """ buf_ = x - xhat np.square(buf_, out=buf_) # square in-place sum_ = np.sum(buf_) sum_ /= x.size # divide in-place return sum_
python
def mse(x, xhat): """ Calcualte mse between vector or matrix x and xhat """ buf_ = x - xhat np.square(buf_, out=buf_) # square in-place sum_ = np.sum(buf_) sum_ /= x.size # divide in-place return sum_
[ "def", "mse", "(", "x", ",", "xhat", ")", ":", "buf_", "=", "x", "-", "xhat", "np", ".", "square", "(", "buf_", ",", "out", "=", "buf_", ")", "# square in-place", "sum_", "=", "np", ".", "sum", "(", "buf_", ")", "sum_", "/=", "x", ".", "size", ...
Calcualte mse between vector or matrix x and xhat
[ "Calcualte", "mse", "between", "vector", "or", "matrix", "x", "and", "xhat" ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics.py#L6-L12
train
47,658
LCAV/pylocus
pylocus/basics.py
low_rank_approximation
def low_rank_approximation(A, r): """ Returns approximation of A of rank r in least-squares sense.""" try: u, s, v = np.linalg.svd(A, full_matrices=False) except np.linalg.LinAlgError as e: print('Matrix:', A) print('Matrix rank:', np.linalg.matrix_rank(A)) raise Ar = np.zeros((len(u), len(v)), dtype=u.dtype) buf_ = np.empty_like(Ar) sc_vec_ = np.empty((v.shape[1],), dtype=v.dtype) for i in range(r): np.multiply(v[i], s[i], out=sc_vec_) np.outer(u[:, i], sc_vec_, out=buf_) Ar += buf_ return Ar
python
def low_rank_approximation(A, r): """ Returns approximation of A of rank r in least-squares sense.""" try: u, s, v = np.linalg.svd(A, full_matrices=False) except np.linalg.LinAlgError as e: print('Matrix:', A) print('Matrix rank:', np.linalg.matrix_rank(A)) raise Ar = np.zeros((len(u), len(v)), dtype=u.dtype) buf_ = np.empty_like(Ar) sc_vec_ = np.empty((v.shape[1],), dtype=v.dtype) for i in range(r): np.multiply(v[i], s[i], out=sc_vec_) np.outer(u[:, i], sc_vec_, out=buf_) Ar += buf_ return Ar
[ "def", "low_rank_approximation", "(", "A", ",", "r", ")", ":", "try", ":", "u", ",", "s", ",", "v", "=", "np", ".", "linalg", ".", "svd", "(", "A", ",", "full_matrices", "=", "False", ")", "except", "np", ".", "linalg", ".", "LinAlgError", "as", ...
Returns approximation of A of rank r in least-squares sense.
[ "Returns", "approximation", "of", "A", "of", "rank", "r", "in", "least", "-", "squares", "sense", "." ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics.py#L28-L44
train
47,659
LCAV/pylocus
pylocus/basics.py
eigendecomp
def eigendecomp(G, d): """ Computes sorted eigendecomposition of G. :param G: Matrix :param d: rank :return factor: vector of square root d of eigenvalues (biggest to smallest). :return u: matrix with colums equal to the normalized eigenvectors corresponding to sorted eigenvalues. """ N = G.shape[0] lamda, u = np.linalg.eig(G) # test decomposition of G. #G_hat = np.dot(np.dot(u, np.diag(lamda)), u.T) #assert np.linalg.norm(G_hat - G) < 1e-10, 'decomposition not exact: err {}'.format(np.linalg.norm(G_hat - G)) # sort the eigenvalues in decreasing order lamda = np.real(lamda) indices = np.argsort(lamda)[::-1] lamda_sorted = lamda[indices] assert (lamda_sorted[ :d] > -1e-10).all(), "{} not all positive!".format(lamda_sorted[:d]) u = u[:, indices] factor = np.empty((N,), dtype=lamda.dtype) np.sqrt(lamda_sorted[:d], out=factor[0:d]) factor[d:] = 0.0 return factor, np.real(u)
python
def eigendecomp(G, d): """ Computes sorted eigendecomposition of G. :param G: Matrix :param d: rank :return factor: vector of square root d of eigenvalues (biggest to smallest). :return u: matrix with colums equal to the normalized eigenvectors corresponding to sorted eigenvalues. """ N = G.shape[0] lamda, u = np.linalg.eig(G) # test decomposition of G. #G_hat = np.dot(np.dot(u, np.diag(lamda)), u.T) #assert np.linalg.norm(G_hat - G) < 1e-10, 'decomposition not exact: err {}'.format(np.linalg.norm(G_hat - G)) # sort the eigenvalues in decreasing order lamda = np.real(lamda) indices = np.argsort(lamda)[::-1] lamda_sorted = lamda[indices] assert (lamda_sorted[ :d] > -1e-10).all(), "{} not all positive!".format(lamda_sorted[:d]) u = u[:, indices] factor = np.empty((N,), dtype=lamda.dtype) np.sqrt(lamda_sorted[:d], out=factor[0:d]) factor[d:] = 0.0 return factor, np.real(u)
[ "def", "eigendecomp", "(", "G", ",", "d", ")", ":", "N", "=", "G", ".", "shape", "[", "0", "]", "lamda", ",", "u", "=", "np", ".", "linalg", ".", "eig", "(", "G", ")", "# test decomposition of G.", "#G_hat = np.dot(np.dot(u, np.diag(lamda)), u.T)", "#asser...
Computes sorted eigendecomposition of G. :param G: Matrix :param d: rank :return factor: vector of square root d of eigenvalues (biggest to smallest). :return u: matrix with colums equal to the normalized eigenvectors corresponding to sorted eigenvalues.
[ "Computes", "sorted", "eigendecomposition", "of", "G", "." ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics.py#L62-L89
train
47,660
LCAV/pylocus
pylocus/basics.py
projection
def projection(x, A, b): """ Returns the vector xhat closest to x in 2-norm, satisfying A.xhat =b. :param x: vector :param A, b: matrix and array characterizing the constraints on x (A.x = b) :return x_hat: optimum angle vector, minimizing cost. :return cost: least square error of xhat, x :return constraints_error: mse of constraint. :rtype: (numpy.ndarray, float, float) """ A_pseudoinv = pseudo_inverse(A) tmp_ = A.dot(x) tmp_ -= b x_hat = A_pseudoinv.dot(tmp_) np.subtract(x, x_hat, out=x_hat) cost = mse(x_hat, x) A.dot(x_hat, out=tmp_) constraints_error = mse(tmp_, b) return x_hat, cost, constraints_error
python
def projection(x, A, b): """ Returns the vector xhat closest to x in 2-norm, satisfying A.xhat =b. :param x: vector :param A, b: matrix and array characterizing the constraints on x (A.x = b) :return x_hat: optimum angle vector, minimizing cost. :return cost: least square error of xhat, x :return constraints_error: mse of constraint. :rtype: (numpy.ndarray, float, float) """ A_pseudoinv = pseudo_inverse(A) tmp_ = A.dot(x) tmp_ -= b x_hat = A_pseudoinv.dot(tmp_) np.subtract(x, x_hat, out=x_hat) cost = mse(x_hat, x) A.dot(x_hat, out=tmp_) constraints_error = mse(tmp_, b) return x_hat, cost, constraints_error
[ "def", "projection", "(", "x", ",", "A", ",", "b", ")", ":", "A_pseudoinv", "=", "pseudo_inverse", "(", "A", ")", "tmp_", "=", "A", ".", "dot", "(", "x", ")", "tmp_", "-=", "b", "x_hat", "=", "A_pseudoinv", ".", "dot", "(", "tmp_", ")", "np", "...
Returns the vector xhat closest to x in 2-norm, satisfying A.xhat =b. :param x: vector :param A, b: matrix and array characterizing the constraints on x (A.x = b) :return x_hat: optimum angle vector, minimizing cost. :return cost: least square error of xhat, x :return constraints_error: mse of constraint. :rtype: (numpy.ndarray, float, float)
[ "Returns", "the", "vector", "xhat", "closest", "to", "x", "in", "2", "-", "norm", "satisfying", "A", ".", "xhat", "=", "b", "." ]
c56a38c251d8a435caf4641a8ae6027ecba2c8c6
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics.py#L143-L163
train
47,661
agoragames/chai
chai/comparators.py
build_comparators
def build_comparators(*values_or_types): ''' All of the comparators that can be used for arguments. ''' comparators = [] for item in values_or_types: if isinstance(item, Comparator): comparators.append(item) elif isinstance(item, type): # If you are passing around a type you will have to build a Equals # comparator comparators.append(Any(IsA(item), Is(item))) else: comparators.append(Equals(item)) return comparators
python
def build_comparators(*values_or_types): ''' All of the comparators that can be used for arguments. ''' comparators = [] for item in values_or_types: if isinstance(item, Comparator): comparators.append(item) elif isinstance(item, type): # If you are passing around a type you will have to build a Equals # comparator comparators.append(Any(IsA(item), Is(item))) else: comparators.append(Equals(item)) return comparators
[ "def", "build_comparators", "(", "*", "values_or_types", ")", ":", "comparators", "=", "[", "]", "for", "item", "in", "values_or_types", ":", "if", "isinstance", "(", "item", ",", "Comparator", ")", ":", "comparators", ".", "append", "(", "item", ")", "eli...
All of the comparators that can be used for arguments.
[ "All", "of", "the", "comparators", "that", "can", "be", "used", "for", "arguments", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/comparators.py#L9-L23
train
47,662
toumorokoshi/transmute-core
ubuild.py
changelog
def changelog(build): """ create a changelog """ build.packages.install("gitchangelog") changelog_text = subprocess.check_output(["gitchangelog", "HEAD...v0.2.9"]) with open(os.path.join(build.root, "CHANGELOG"), "wb+") as fh: fh.write(changelog_text)
python
def changelog(build): """ create a changelog """ build.packages.install("gitchangelog") changelog_text = subprocess.check_output(["gitchangelog", "HEAD...v0.2.9"]) with open(os.path.join(build.root, "CHANGELOG"), "wb+") as fh: fh.write(changelog_text)
[ "def", "changelog", "(", "build", ")", ":", "build", ".", "packages", ".", "install", "(", "\"gitchangelog\"", ")", "changelog_text", "=", "subprocess", ".", "check_output", "(", "[", "\"gitchangelog\"", ",", "\"HEAD...v0.2.9\"", "]", ")", "with", "open", "(",...
create a changelog
[ "create", "a", "changelog" ]
a2c26625d5d8bab37e00038f9d615a26167fc7f4
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/ubuild.py#L50-L55
train
47,663
agoragames/chai
chai/expectation.py
Expectation.args
def args(self, *args, **kwargs): """ Creates a ArgumentsExpectationRule and adds it to the expectation """ self._any_args = False self._arguments_rule.set_args(*args, **kwargs) return self
python
def args(self, *args, **kwargs): """ Creates a ArgumentsExpectationRule and adds it to the expectation """ self._any_args = False self._arguments_rule.set_args(*args, **kwargs) return self
[ "def", "args", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_any_args", "=", "False", "self", ".", "_arguments_rule", ".", "set_args", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self" ]
Creates a ArgumentsExpectationRule and adds it to the expectation
[ "Creates", "a", "ArgumentsExpectationRule", "and", "adds", "it", "to", "the", "expectation" ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/expectation.py#L139-L145
train
47,664
agoragames/chai
chai/expectation.py
Expectation.return_value
def return_value(self): """ Returns the value for this expectation or raises the proper exception. """ if self._raises: # Handle exceptions if inspect.isclass(self._raises): raise self._raises() else: raise self._raises else: if isinstance(self._returns, tuple): return tuple([x.value if isinstance(x, Variable) else x for x in self._returns]) return self._returns.value if isinstance(self._returns, Variable) \ else self._returns
python
def return_value(self): """ Returns the value for this expectation or raises the proper exception. """ if self._raises: # Handle exceptions if inspect.isclass(self._raises): raise self._raises() else: raise self._raises else: if isinstance(self._returns, tuple): return tuple([x.value if isinstance(x, Variable) else x for x in self._returns]) return self._returns.value if isinstance(self._returns, Variable) \ else self._returns
[ "def", "return_value", "(", "self", ")", ":", "if", "self", ".", "_raises", ":", "# Handle exceptions", "if", "inspect", ".", "isclass", "(", "self", ".", "_raises", ")", ":", "raise", "self", ".", "_raises", "(", ")", "else", ":", "raise", "self", "."...
Returns the value for this expectation or raises the proper exception.
[ "Returns", "the", "value", "for", "this", "expectation", "or", "raises", "the", "proper", "exception", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/expectation.py#L226-L241
train
47,665
agoragames/chai
chai/expectation.py
Expectation.match
def match(self, *args, **kwargs): """ Check the if these args match this expectation. """ return self._any_args or \ self._arguments_rule.validate(*args, **kwargs)
python
def match(self, *args, **kwargs): """ Check the if these args match this expectation. """ return self._any_args or \ self._arguments_rule.validate(*args, **kwargs)
[ "def", "match", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_any_args", "or", "self", ".", "_arguments_rule", ".", "validate", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Check the if these args match this expectation.
[ "Check", "the", "if", "these", "args", "match", "this", "expectation", "." ]
8148d7b7754226b0d1cabfc2af10cd912612abdc
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/expectation.py#L265-L270
train
47,666
inveniosoftware/invenio-previewer
invenio_previewer/ext.py
_InvenioPreviewerState.record_file_factory
def record_file_factory(self): """Load default record file factory.""" try: get_distribution('invenio-records-files') from invenio_records_files.utils import record_file_factory default = record_file_factory except DistributionNotFound: def default(pid, record, filename): return None return load_or_import_from_config( 'PREVIEWER_RECORD_FILE_FACOTRY', app=self.app, default=default, )
python
def record_file_factory(self): """Load default record file factory.""" try: get_distribution('invenio-records-files') from invenio_records_files.utils import record_file_factory default = record_file_factory except DistributionNotFound: def default(pid, record, filename): return None return load_or_import_from_config( 'PREVIEWER_RECORD_FILE_FACOTRY', app=self.app, default=default, )
[ "def", "record_file_factory", "(", "self", ")", ":", "try", ":", "get_distribution", "(", "'invenio-records-files'", ")", "from", "invenio_records_files", ".", "utils", "import", "record_file_factory", "default", "=", "record_file_factory", "except", "DistributionNotFound...
Load default record file factory.
[ "Load", "default", "record", "file", "factory", "." ]
558fd22e0f29cc8cd7a6999abd4febcf6b248c49
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/ext.py#L57-L71
train
47,667
inveniosoftware/invenio-previewer
invenio_previewer/ext.py
_InvenioPreviewerState.register_previewer
def register_previewer(self, name, previewer): """Register a previewer in the system.""" if name in self.previewers: assert name not in self.previewers, \ "Previewer with same name already registered" self.previewers[name] = previewer if hasattr(previewer, 'previewable_extensions'): self._previewable_extensions |= set( previewer.previewable_extensions)
python
def register_previewer(self, name, previewer): """Register a previewer in the system.""" if name in self.previewers: assert name not in self.previewers, \ "Previewer with same name already registered" self.previewers[name] = previewer if hasattr(previewer, 'previewable_extensions'): self._previewable_extensions |= set( previewer.previewable_extensions)
[ "def", "register_previewer", "(", "self", ",", "name", ",", "previewer", ")", ":", "if", "name", "in", "self", ".", "previewers", ":", "assert", "name", "not", "in", "self", ".", "previewers", ",", "\"Previewer with same name already registered\"", "self", ".", ...
Register a previewer in the system.
[ "Register", "a", "previewer", "in", "the", "system", "." ]
558fd22e0f29cc8cd7a6999abd4febcf6b248c49
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/ext.py#L81-L89
train
47,668
inveniosoftware/invenio-previewer
invenio_previewer/ext.py
_InvenioPreviewerState.iter_previewers
def iter_previewers(self, previewers=None): """Get previewers ordered by PREVIEWER_PREVIEWERS_ORDER.""" if self.entry_point_group is not None: self.load_entry_point_group(self.entry_point_group) self.entry_point_group = None previewers = previewers or \ self.app.config.get('PREVIEWER_PREFERENCE', []) for item in previewers: if item in self.previewers: yield self.previewers[item]
python
def iter_previewers(self, previewers=None): """Get previewers ordered by PREVIEWER_PREVIEWERS_ORDER.""" if self.entry_point_group is not None: self.load_entry_point_group(self.entry_point_group) self.entry_point_group = None previewers = previewers or \ self.app.config.get('PREVIEWER_PREFERENCE', []) for item in previewers: if item in self.previewers: yield self.previewers[item]
[ "def", "iter_previewers", "(", "self", ",", "previewers", "=", "None", ")", ":", "if", "self", ".", "entry_point_group", "is", "not", "None", ":", "self", ".", "load_entry_point_group", "(", "self", ".", "entry_point_group", ")", "self", ".", "entry_point_grou...
Get previewers ordered by PREVIEWER_PREVIEWERS_ORDER.
[ "Get", "previewers", "ordered", "by", "PREVIEWER_PREVIEWERS_ORDER", "." ]
558fd22e0f29cc8cd7a6999abd4febcf6b248c49
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/ext.py#L96-L107
train
47,669
howl-anderson/MicroTokenizer
MicroTokenizer/errors.py
add_codes
def add_codes(err_cls): """Add error codes to string messages via class attribute names.""" class ErrorsWithCodes(object): def __getattribute__(self, code): msg = getattr(err_cls, code) return '[{code}] {msg}'.format(code=code, msg=msg) return ErrorsWithCodes()
python
def add_codes(err_cls): """Add error codes to string messages via class attribute names.""" class ErrorsWithCodes(object): def __getattribute__(self, code): msg = getattr(err_cls, code) return '[{code}] {msg}'.format(code=code, msg=msg) return ErrorsWithCodes()
[ "def", "add_codes", "(", "err_cls", ")", ":", "class", "ErrorsWithCodes", "(", "object", ")", ":", "def", "__getattribute__", "(", "self", ",", "code", ")", ":", "msg", "=", "getattr", "(", "err_cls", ",", "code", ")", "return", "'[{code}] {msg}'", ".", ...
Add error codes to string messages via class attribute names.
[ "Add", "error", "codes", "to", "string", "messages", "via", "class", "attribute", "names", "." ]
41bbe9c31d202b4f751ad5201d343ad1123b42b5
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/errors.py#L9-L15
train
47,670
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
is_package
def is_package(name): """Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not. """ name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False
python
def is_package(name): """Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not. """ name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False
[ "def", "is_package", "(", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "# compare package name against lowercase name", "packages", "=", "pkg_resources", ".", "working_set", ".", "by_key", ".", "keys", "(", ")", "for", "package", "in", "packa...
Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not.
[ "Check", "if", "string", "maps", "to", "a", "package", "installed", "via", "pip", "." ]
41bbe9c31d202b4f751ad5201d343ad1123b42b5
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L159-L170
train
47,671
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
read_json
def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f)
python
def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f)
[ "def", "read_json", "(", "location", ")", ":", "location", "=", "ensure_path", "(", "location", ")", "with", "location", ".", "open", "(", "'r'", ",", "encoding", "=", "'utf8'", ")", "as", "f", ":", "return", "ujson", ".", "load", "(", "f", ")" ]
Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content.
[ "Open", "and", "load", "JSON", "from", "file", "." ]
41bbe9c31d202b4f751ad5201d343ad1123b42b5
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L311-L319
train
47,672
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
print_table
def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table))
python
def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table))
[ "def", "print_table", "(", "data", ",", "title", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "list", "(", "data", ".", "items", "(", ")", ")", "tpl_row", "=", "' {:<15}'", "*", "len", "(", "data", ...
Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above.
[ "Print", "data", "in", "table", "format", "." ]
41bbe9c31d202b4f751ad5201d343ad1123b42b5
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L355-L367
train
47,673
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
_wrap
def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text. """ indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False)
python
def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text. """ indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False)
[ "def", "_wrap", "(", "text", ",", "wrap_max", "=", "80", ",", "indent", "=", "4", ")", ":", "indent", "=", "indent", "*", "' '", "wrap_width", "=", "wrap_max", "-", "len", "(", "indent", ")", "if", "isinstance", "(", "text", ",", "Path", ")", ":", ...
Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text.
[ "Wrap", "text", "at", "given", "width", "using", "textwrap", "module", "." ]
41bbe9c31d202b4f751ad5201d343ad1123b42b5
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L405-L419
train
47,674
howl-anderson/MicroTokenizer
MicroTokenizer/compat.py
normalize_string_keys
def normalize_string_keys(old): """Given a dictionary, make sure keys are unicode strings, not bytes.""" new = {} for key, value in old.items(): if isinstance(key, bytes_): new[key.decode('utf8')] = value else: new[key] = value return new
python
def normalize_string_keys(old): """Given a dictionary, make sure keys are unicode strings, not bytes.""" new = {} for key, value in old.items(): if isinstance(key, bytes_): new[key.decode('utf8')] = value else: new[key] = value return new
[ "def", "normalize_string_keys", "(", "old", ")", ":", "new", "=", "{", "}", "for", "key", ",", "value", "in", "old", ".", "items", "(", ")", ":", "if", "isinstance", "(", "key", ",", "bytes_", ")", ":", "new", "[", "key", ".", "decode", "(", "'ut...
Given a dictionary, make sure keys are unicode strings, not bytes.
[ "Given", "a", "dictionary", "make", "sure", "keys", "are", "unicode", "strings", "not", "bytes", "." ]
41bbe9c31d202b4f751ad5201d343ad1123b42b5
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/compat.py#L78-L86
train
47,675
howl-anderson/MicroTokenizer
MicroTokenizer/compat.py
locale_escape
def locale_escape(string, errors='replace'): ''' Mangle non-supported characters, for savages with ascii terminals. ''' encoding = locale.getpreferredencoding() string = string.encode(encoding, errors).decode('utf8') return string
python
def locale_escape(string, errors='replace'): ''' Mangle non-supported characters, for savages with ascii terminals. ''' encoding = locale.getpreferredencoding() string = string.encode(encoding, errors).decode('utf8') return string
[ "def", "locale_escape", "(", "string", ",", "errors", "=", "'replace'", ")", ":", "encoding", "=", "locale", ".", "getpreferredencoding", "(", ")", "string", "=", "string", ".", "encode", "(", "encoding", ",", "errors", ")", ".", "decode", "(", "'utf8'", ...
Mangle non-supported characters, for savages with ascii terminals.
[ "Mangle", "non", "-", "supported", "characters", "for", "savages", "with", "ascii", "terminals", "." ]
41bbe9c31d202b4f751ad5201d343ad1123b42b5
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/compat.py#L102-L108
train
47,676
aparrish/pronouncingpy
pronouncing/__init__.py
parse_cmu
def parse_cmu(cmufh): """Parses an incoming file handle as a CMU pronouncing dictionary file. (Most end-users of this module won't need to call this function explicitly, as it's called internally by the :func:`init_cmu` function.) :param cmufh: a filehandle with CMUdict-formatted data :returns: a list of 2-tuples pairing a word with its phones (as a string) """ pronunciations = list() for line in cmufh: line = line.strip().decode('utf-8') if line.startswith(';'): continue word, phones = line.split(" ", 1) pronunciations.append((word.split('(', 1)[0].lower(), phones)) return pronunciations
python
def parse_cmu(cmufh): """Parses an incoming file handle as a CMU pronouncing dictionary file. (Most end-users of this module won't need to call this function explicitly, as it's called internally by the :func:`init_cmu` function.) :param cmufh: a filehandle with CMUdict-formatted data :returns: a list of 2-tuples pairing a word with its phones (as a string) """ pronunciations = list() for line in cmufh: line = line.strip().decode('utf-8') if line.startswith(';'): continue word, phones = line.split(" ", 1) pronunciations.append((word.split('(', 1)[0].lower(), phones)) return pronunciations
[ "def", "parse_cmu", "(", "cmufh", ")", ":", "pronunciations", "=", "list", "(", ")", "for", "line", "in", "cmufh", ":", "line", "=", "line", ".", "strip", "(", ")", ".", "decode", "(", "'utf-8'", ")", "if", "line", ".", "startswith", "(", "';'", ")...
Parses an incoming file handle as a CMU pronouncing dictionary file. (Most end-users of this module won't need to call this function explicitly, as it's called internally by the :func:`init_cmu` function.) :param cmufh: a filehandle with CMUdict-formatted data :returns: a list of 2-tuples pairing a word with its phones (as a string)
[ "Parses", "an", "incoming", "file", "handle", "as", "a", "CMU", "pronouncing", "dictionary", "file", "." ]
09467fa9407d7d87cb0998ee3cb09db4dcc9571a
https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L17-L33
train
47,677
aparrish/pronouncingpy
pronouncing/__init__.py
init_cmu
def init_cmu(filehandle=None): """Initialize the module's pronunciation data. This function is called automatically the first time you attempt to use another function in the library that requires loading the pronunciation data from disk. You can call this function manually to control when and how the pronunciation data is loaded (e.g., you're using this module in a web application and want to load the data asynchronously). :param filehandle: a filehandle with CMUdict-formatted data :returns: None """ global pronunciations, lookup, rhyme_lookup if pronunciations is None: if filehandle is None: filehandle = cmudict.dict_stream() pronunciations = parse_cmu(filehandle) filehandle.close() lookup = collections.defaultdict(list) for word, phones in pronunciations: lookup[word].append(phones) rhyme_lookup = collections.defaultdict(list) for word, phones in pronunciations: rp = rhyming_part(phones) if rp is not None: rhyme_lookup[rp].append(word)
python
def init_cmu(filehandle=None): """Initialize the module's pronunciation data. This function is called automatically the first time you attempt to use another function in the library that requires loading the pronunciation data from disk. You can call this function manually to control when and how the pronunciation data is loaded (e.g., you're using this module in a web application and want to load the data asynchronously). :param filehandle: a filehandle with CMUdict-formatted data :returns: None """ global pronunciations, lookup, rhyme_lookup if pronunciations is None: if filehandle is None: filehandle = cmudict.dict_stream() pronunciations = parse_cmu(filehandle) filehandle.close() lookup = collections.defaultdict(list) for word, phones in pronunciations: lookup[word].append(phones) rhyme_lookup = collections.defaultdict(list) for word, phones in pronunciations: rp = rhyming_part(phones) if rp is not None: rhyme_lookup[rp].append(word)
[ "def", "init_cmu", "(", "filehandle", "=", "None", ")", ":", "global", "pronunciations", ",", "lookup", ",", "rhyme_lookup", "if", "pronunciations", "is", "None", ":", "if", "filehandle", "is", "None", ":", "filehandle", "=", "cmudict", ".", "dict_stream", "...
Initialize the module's pronunciation data. This function is called automatically the first time you attempt to use another function in the library that requires loading the pronunciation data from disk. You can call this function manually to control when and how the pronunciation data is loaded (e.g., you're using this module in a web application and want to load the data asynchronously). :param filehandle: a filehandle with CMUdict-formatted data :returns: None
[ "Initialize", "the", "module", "s", "pronunciation", "data", "." ]
09467fa9407d7d87cb0998ee3cb09db4dcc9571a
https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L36-L61
train
47,678
aparrish/pronouncingpy
pronouncing/__init__.py
rhyming_part
def rhyming_part(phones): """Get the "rhyming part" of a string with CMUdict phones. "Rhyming part" here means everything from the vowel in the stressed syllable nearest the end of the word up to the end of the word. .. doctest:: >>> import pronouncing >>> phones = pronouncing.phones_for_word("purple") >>> pronouncing.rhyming_part(phones[0]) 'ER1 P AH0 L' :param phones: a string containing space-separated CMUdict phones :returns: a string with just the "rhyming part" of those phones """ phones_list = phones.split() for i in range(len(phones_list) - 1, 0, -1): if phones_list[i][-1] in '12': return ' '.join(phones_list[i:]) return phones
python
def rhyming_part(phones): """Get the "rhyming part" of a string with CMUdict phones. "Rhyming part" here means everything from the vowel in the stressed syllable nearest the end of the word up to the end of the word. .. doctest:: >>> import pronouncing >>> phones = pronouncing.phones_for_word("purple") >>> pronouncing.rhyming_part(phones[0]) 'ER1 P AH0 L' :param phones: a string containing space-separated CMUdict phones :returns: a string with just the "rhyming part" of those phones """ phones_list = phones.split() for i in range(len(phones_list) - 1, 0, -1): if phones_list[i][-1] in '12': return ' '.join(phones_list[i:]) return phones
[ "def", "rhyming_part", "(", "phones", ")", ":", "phones_list", "=", "phones", ".", "split", "(", ")", "for", "i", "in", "range", "(", "len", "(", "phones_list", ")", "-", "1", ",", "0", ",", "-", "1", ")", ":", "if", "phones_list", "[", "i", "]",...
Get the "rhyming part" of a string with CMUdict phones. "Rhyming part" here means everything from the vowel in the stressed syllable nearest the end of the word up to the end of the word. .. doctest:: >>> import pronouncing >>> phones = pronouncing.phones_for_word("purple") >>> pronouncing.rhyming_part(phones[0]) 'ER1 P AH0 L' :param phones: a string containing space-separated CMUdict phones :returns: a string with just the "rhyming part" of those phones
[ "Get", "the", "rhyming", "part", "of", "a", "string", "with", "CMUdict", "phones", "." ]
09467fa9407d7d87cb0998ee3cb09db4dcc9571a
https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L135-L155
train
47,679
aparrish/pronouncingpy
pronouncing/__init__.py
search
def search(pattern): """Get words whose pronunciation matches a regular expression. This function Searches the CMU dictionary for pronunciations matching a given regular expression. (Word boundary anchors are automatically added before and after the pattern.) .. doctest:: >>> import pronouncing >>> 'interpolate' in pronouncing.search('ER1 P AH0') True :param pattern: a string containing a regular expression :returns: a list of matching words """ init_cmu() regexp = re.compile(r"\b" + pattern + r"\b") return [word for word, phones in pronunciations if regexp.search(phones)]
python
def search(pattern): """Get words whose pronunciation matches a regular expression. This function Searches the CMU dictionary for pronunciations matching a given regular expression. (Word boundary anchors are automatically added before and after the pattern.) .. doctest:: >>> import pronouncing >>> 'interpolate' in pronouncing.search('ER1 P AH0') True :param pattern: a string containing a regular expression :returns: a list of matching words """ init_cmu() regexp = re.compile(r"\b" + pattern + r"\b") return [word for word, phones in pronunciations if regexp.search(phones)]
[ "def", "search", "(", "pattern", ")", ":", "init_cmu", "(", ")", "regexp", "=", "re", ".", "compile", "(", "r\"\\b\"", "+", "pattern", "+", "r\"\\b\"", ")", "return", "[", "word", "for", "word", ",", "phones", "in", "pronunciations", "if", "regexp", "....
Get words whose pronunciation matches a regular expression. This function Searches the CMU dictionary for pronunciations matching a given regular expression. (Word boundary anchors are automatically added before and after the pattern.) .. doctest:: >>> import pronouncing >>> 'interpolate' in pronouncing.search('ER1 P AH0') True :param pattern: a string containing a regular expression :returns: a list of matching words
[ "Get", "words", "whose", "pronunciation", "matches", "a", "regular", "expression", "." ]
09467fa9407d7d87cb0998ee3cb09db4dcc9571a
https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L158-L178
train
47,680
aparrish/pronouncingpy
pronouncing/__init__.py
search_stresses
def search_stresses(pattern): """Get words whose stress pattern matches a regular expression. This function is a special case of :func:`search` that searches only the stress patterns of each pronunciation in the dictionary. You can get stress patterns for a word using the :func:`stresses_for_word` function. .. doctest:: >>> import pronouncing >>> pronouncing.search_stresses('020120') ['gubernatorial'] :param pattern: a string containing a regular expression :returns: a list of matching words """ init_cmu() regexp = re.compile(pattern) return [word for word, phones in pronunciations if regexp.search(stresses(phones))]
python
def search_stresses(pattern): """Get words whose stress pattern matches a regular expression. This function is a special case of :func:`search` that searches only the stress patterns of each pronunciation in the dictionary. You can get stress patterns for a word using the :func:`stresses_for_word` function. .. doctest:: >>> import pronouncing >>> pronouncing.search_stresses('020120') ['gubernatorial'] :param pattern: a string containing a regular expression :returns: a list of matching words """ init_cmu() regexp = re.compile(pattern) return [word for word, phones in pronunciations if regexp.search(stresses(phones))]
[ "def", "search_stresses", "(", "pattern", ")", ":", "init_cmu", "(", ")", "regexp", "=", "re", ".", "compile", "(", "pattern", ")", "return", "[", "word", "for", "word", ",", "phones", "in", "pronunciations", "if", "regexp", ".", "search", "(", "stresses...
Get words whose stress pattern matches a regular expression. This function is a special case of :func:`search` that searches only the stress patterns of each pronunciation in the dictionary. You can get stress patterns for a word using the :func:`stresses_for_word` function. .. doctest:: >>> import pronouncing >>> pronouncing.search_stresses('020120') ['gubernatorial'] :param pattern: a string containing a regular expression :returns: a list of matching words
[ "Get", "words", "whose", "stress", "pattern", "matches", "a", "regular", "expression", "." ]
09467fa9407d7d87cb0998ee3cb09db4dcc9571a
https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L181-L201
train
47,681
aparrish/pronouncingpy
pronouncing/__init__.py
rhymes
def rhymes(word): """Get words rhyming with a given word. This function may return an empty list if no rhyming words are found in the dictionary, or if the word you pass to the function is itself not found in the dictionary. .. doctest:: >>> import pronouncing >>> pronouncing.rhymes("conditioner") ['commissioner', 'parishioner', 'petitioner', 'practitioner'] :param word: a word :returns: a list of rhyming words """ phones = phones_for_word(word) combined_rhymes = [] if phones: for element in phones: combined_rhymes.append([w for w in rhyme_lookup.get(rhyming_part( element), []) if w != word]) combined_rhymes = list(chain.from_iterable(combined_rhymes)) unique_combined_rhymes = sorted(set(combined_rhymes)) return unique_combined_rhymes else: return []
python
def rhymes(word): """Get words rhyming with a given word. This function may return an empty list if no rhyming words are found in the dictionary, or if the word you pass to the function is itself not found in the dictionary. .. doctest:: >>> import pronouncing >>> pronouncing.rhymes("conditioner") ['commissioner', 'parishioner', 'petitioner', 'practitioner'] :param word: a word :returns: a list of rhyming words """ phones = phones_for_word(word) combined_rhymes = [] if phones: for element in phones: combined_rhymes.append([w for w in rhyme_lookup.get(rhyming_part( element), []) if w != word]) combined_rhymes = list(chain.from_iterable(combined_rhymes)) unique_combined_rhymes = sorted(set(combined_rhymes)) return unique_combined_rhymes else: return []
[ "def", "rhymes", "(", "word", ")", ":", "phones", "=", "phones_for_word", "(", "word", ")", "combined_rhymes", "=", "[", "]", "if", "phones", ":", "for", "element", "in", "phones", ":", "combined_rhymes", ".", "append", "(", "[", "w", "for", "w", "in",...
Get words rhyming with a given word. This function may return an empty list if no rhyming words are found in the dictionary, or if the word you pass to the function is itself not found in the dictionary. .. doctest:: >>> import pronouncing >>> pronouncing.rhymes("conditioner") ['commissioner', 'parishioner', 'petitioner', 'practitioner'] :param word: a word :returns: a list of rhyming words
[ "Get", "words", "rhyming", "with", "a", "given", "word", "." ]
09467fa9407d7d87cb0998ee3cb09db4dcc9571a
https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L204-L230
train
47,682
OSSOS/MOP
src/ossos/core/ossos/gui/views/imageview.py
ImageViewManager.set_ds9
def set_ds9(self, level="PREF"): """ Set the default values on the ds9 display. """ self.set_zoom() ds9_settings = config.read("DS9."+level) for key in ds9_settings.keys(): value = ds9_settings[key] cmd = key.replace("_", " ") self.ds9.set("{} {}".format(cmd, value))
python
def set_ds9(self, level="PREF"): """ Set the default values on the ds9 display. """ self.set_zoom() ds9_settings = config.read("DS9."+level) for key in ds9_settings.keys(): value = ds9_settings[key] cmd = key.replace("_", " ") self.ds9.set("{} {}".format(cmd, value))
[ "def", "set_ds9", "(", "self", ",", "level", "=", "\"PREF\"", ")", ":", "self", ".", "set_zoom", "(", ")", "ds9_settings", "=", "config", ".", "read", "(", "\"DS9.\"", "+", "level", ")", "for", "key", "in", "ds9_settings", ".", "keys", "(", ")", ":",...
Set the default values on the ds9 display.
[ "Set", "the", "default", "values", "on", "the", "ds9", "display", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/views/imageview.py#L29-L38
train
47,683
OSSOS/MOP
src/ossos/core/ossos/cadc.py
cfht_megacam_tap_query
def cfht_megacam_tap_query(ra_deg=180.0, dec_deg=0.0, width=1, height=1, date=None): """Do a query of the CADC Megacam table. Get all observations inside the box (right now it turns width/height into a radius, should not do this). @rtype : Table @param ra_deg: center of search region, in degrees @param dec_deg: center of search region in degrees @param width: width of search region in degrees @param height: height of search region in degrees @param date: ISO format date string. Query will be +/- 0.5 days from date given. """ radius = min(90, max(width, height) / 2.0) query = ("SELECT " "COORD1(CENTROID(Plane.position_bounds)) AS RAJ2000," "COORD2(CENTROID(Plane.position_bounds)) AS DEJ2000," "target_name " "FROM " "caom2.Observation as o " "JOIN caom2.Plane as Plane on o.obsID=Plane.obsID " "WHERE o.collection = 'CFHT' " "AND o.instrument_name = 'MegaPrime' " "AND INTERSECTS( CIRCLE('ICRS', %f, %f, %f), Plane.position_bounds ) = 1") query = query % (ra_deg, dec_deg, radius) if date is not None: mjd = Time(date, scale='utc').mjd query += " AND Plane.time_bounds_lower <= {} AND {} <= Plane.time_bounds_upper ".format(mjd+0.5, mjd-0.5) data = {"QUERY": query, "REQUEST": "doQuery", "LANG": "ADQL", "FORMAT": "votable"} url = "http://www.cadc.hia.nrc.gc.ca/tap/sync" warnings.simplefilter('ignore') ff = StringIO(requests.get(url, params=data).content) ff.seek(0) table = votable.parse(ff).get_first_table().to_table() assert isinstance(table, Table) return table
python
def cfht_megacam_tap_query(ra_deg=180.0, dec_deg=0.0, width=1, height=1, date=None): """Do a query of the CADC Megacam table. Get all observations inside the box (right now it turns width/height into a radius, should not do this). @rtype : Table @param ra_deg: center of search region, in degrees @param dec_deg: center of search region in degrees @param width: width of search region in degrees @param height: height of search region in degrees @param date: ISO format date string. Query will be +/- 0.5 days from date given. """ radius = min(90, max(width, height) / 2.0) query = ("SELECT " "COORD1(CENTROID(Plane.position_bounds)) AS RAJ2000," "COORD2(CENTROID(Plane.position_bounds)) AS DEJ2000," "target_name " "FROM " "caom2.Observation as o " "JOIN caom2.Plane as Plane on o.obsID=Plane.obsID " "WHERE o.collection = 'CFHT' " "AND o.instrument_name = 'MegaPrime' " "AND INTERSECTS( CIRCLE('ICRS', %f, %f, %f), Plane.position_bounds ) = 1") query = query % (ra_deg, dec_deg, radius) if date is not None: mjd = Time(date, scale='utc').mjd query += " AND Plane.time_bounds_lower <= {} AND {} <= Plane.time_bounds_upper ".format(mjd+0.5, mjd-0.5) data = {"QUERY": query, "REQUEST": "doQuery", "LANG": "ADQL", "FORMAT": "votable"} url = "http://www.cadc.hia.nrc.gc.ca/tap/sync" warnings.simplefilter('ignore') ff = StringIO(requests.get(url, params=data).content) ff.seek(0) table = votable.parse(ff).get_first_table().to_table() assert isinstance(table, Table) return table
[ "def", "cfht_megacam_tap_query", "(", "ra_deg", "=", "180.0", ",", "dec_deg", "=", "0.0", ",", "width", "=", "1", ",", "height", "=", "1", ",", "date", "=", "None", ")", ":", "radius", "=", "min", "(", "90", ",", "max", "(", "width", ",", "height",...
Do a query of the CADC Megacam table. Get all observations inside the box (right now it turns width/height into a radius, should not do this). @rtype : Table @param ra_deg: center of search region, in degrees @param dec_deg: center of search region in degrees @param width: width of search region in degrees @param height: height of search region in degrees @param date: ISO format date string. Query will be +/- 0.5 days from date given.
[ "Do", "a", "query", "of", "the", "CADC", "Megacam", "table", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/cadc.py#L11-L55
train
47,684
JohnVinyard/zounds
zounds/spectral/tfrepresentation.py
FrequencyDimension.validate
def validate(self, size): """ Ensure that the size of the dimension matches the number of bands in the scale Raises: ValueError: when the dimension size and number of bands don't match """ msg = 'scale and array size must match, ' \ 'but were scale: {self.scale.n_bands}, array size: {size}' if size != len(self.scale): raise ValueError(msg.format(**locals()))
python
def validate(self, size): """ Ensure that the size of the dimension matches the number of bands in the scale Raises: ValueError: when the dimension size and number of bands don't match """ msg = 'scale and array size must match, ' \ 'but were scale: {self.scale.n_bands}, array size: {size}' if size != len(self.scale): raise ValueError(msg.format(**locals()))
[ "def", "validate", "(", "self", ",", "size", ")", ":", "msg", "=", "'scale and array size must match, '", "'but were scale: {self.scale.n_bands}, array size: {size}'", "if", "size", "!=", "len", "(", "self", ".", "scale", ")", ":", "raise", "ValueError", "(", "msg"...
Ensure that the size of the dimension matches the number of bands in the scale Raises: ValueError: when the dimension size and number of bands don't match
[ "Ensure", "that", "the", "size", "of", "the", "dimension", "matches", "the", "number", "of", "bands", "in", "the", "scale" ]
337b3f98753d09eaab1c72dcd37bb852a3fa5ac6
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/tfrepresentation.py#L57-L69
train
47,685
JohnVinyard/zounds
zounds/basic/audiograph.py
resampled
def resampled( chunksize_bytes=DEFAULT_CHUNK_SIZE, resample_to=SR44100(), store_resampled=False): """ Create a basic processing pipeline that can resample all incoming audio to a normalized sampling rate for downstream processing, and store a convenient, compressed version for playback :param chunksize_bytes: The number of bytes from the raw stream to process at once :param resample_to: The new, normalized sampling rate :return: A simple processing pipeline """ class Resampled(BaseModel): meta = JSONFeature( MetaData, store=True, encoder=AudioMetaDataEncoder) raw = ByteStreamFeature( ByteStream, chunksize=chunksize_bytes, needs=meta, store=False) ogg = OggVorbisFeature( OggVorbis, needs=raw, store=True) pcm = AudioSamplesFeature( AudioStream, needs=raw, store=False) resampled = AudioSamplesFeature( Resampler, needs=pcm, samplerate=resample_to, store=store_resampled) return Resampled
python
def resampled( chunksize_bytes=DEFAULT_CHUNK_SIZE, resample_to=SR44100(), store_resampled=False): """ Create a basic processing pipeline that can resample all incoming audio to a normalized sampling rate for downstream processing, and store a convenient, compressed version for playback :param chunksize_bytes: The number of bytes from the raw stream to process at once :param resample_to: The new, normalized sampling rate :return: A simple processing pipeline """ class Resampled(BaseModel): meta = JSONFeature( MetaData, store=True, encoder=AudioMetaDataEncoder) raw = ByteStreamFeature( ByteStream, chunksize=chunksize_bytes, needs=meta, store=False) ogg = OggVorbisFeature( OggVorbis, needs=raw, store=True) pcm = AudioSamplesFeature( AudioStream, needs=raw, store=False) resampled = AudioSamplesFeature( Resampler, needs=pcm, samplerate=resample_to, store=store_resampled) return Resampled
[ "def", "resampled", "(", "chunksize_bytes", "=", "DEFAULT_CHUNK_SIZE", ",", "resample_to", "=", "SR44100", "(", ")", ",", "store_resampled", "=", "False", ")", ":", "class", "Resampled", "(", "BaseModel", ")", ":", "meta", "=", "JSONFeature", "(", "MetaData", ...
Create a basic processing pipeline that can resample all incoming audio to a normalized sampling rate for downstream processing, and store a convenient, compressed version for playback :param chunksize_bytes: The number of bytes from the raw stream to process at once :param resample_to: The new, normalized sampling rate :return: A simple processing pipeline
[ "Create", "a", "basic", "processing", "pipeline", "that", "can", "resample", "all", "incoming", "audio", "to", "a", "normalized", "sampling", "rate", "for", "downstream", "processing", "and", "store", "a", "convenient", "compressed", "version", "for", "playback" ]
337b3f98753d09eaab1c72dcd37bb852a3fa5ac6
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/basic/audiograph.py#L22-L65
train
47,686
JohnVinyard/zounds
zounds/basic/audiograph.py
audio_graph
def audio_graph( chunksize_bytes=DEFAULT_CHUNK_SIZE, resample_to=SR44100(), store_fft=False): """ Produce a base class suitable as a starting point for many audio processing pipelines. This class resamples all audio to a common sampling rate, and produces a bark band spectrogram from overlapping short-time fourier transform frames. It also compresses the audio into ogg vorbis format for compact storage. """ band = FrequencyBand(20, resample_to.nyquist) class AudioGraph(BaseModel): meta = JSONFeature( MetaData, store=True, encoder=AudioMetaDataEncoder) raw = ByteStreamFeature( ByteStream, chunksize=chunksize_bytes, needs=meta, store=False) ogg = OggVorbisFeature( OggVorbis, needs=raw, store=True) pcm = AudioSamplesFeature( AudioStream, needs=raw, store=False) resampled = AudioSamplesFeature( Resampler, needs=pcm, samplerate=resample_to, store=False) windowed = ArrayWithUnitsFeature( SlidingWindow, needs=resampled, wscheme=HalfLapped(), wfunc=OggVorbisWindowingFunc(), store=False) dct = ArrayWithUnitsFeature( DCT, needs=windowed, store=True) fft = ArrayWithUnitsFeature( FFT, needs=windowed, store=store_fft) bark = ArrayWithUnitsFeature( BarkBands, needs=fft, frequency_band=band, store=True) centroid = ArrayWithUnitsFeature( SpectralCentroid, needs=bark, store=True) chroma = ArrayWithUnitsFeature( Chroma, needs=fft, frequency_band=band, store=True) bfcc = ArrayWithUnitsFeature( BFCC, needs=fft, store=True) return AudioGraph
python
def audio_graph( chunksize_bytes=DEFAULT_CHUNK_SIZE, resample_to=SR44100(), store_fft=False): """ Produce a base class suitable as a starting point for many audio processing pipelines. This class resamples all audio to a common sampling rate, and produces a bark band spectrogram from overlapping short-time fourier transform frames. It also compresses the audio into ogg vorbis format for compact storage. """ band = FrequencyBand(20, resample_to.nyquist) class AudioGraph(BaseModel): meta = JSONFeature( MetaData, store=True, encoder=AudioMetaDataEncoder) raw = ByteStreamFeature( ByteStream, chunksize=chunksize_bytes, needs=meta, store=False) ogg = OggVorbisFeature( OggVorbis, needs=raw, store=True) pcm = AudioSamplesFeature( AudioStream, needs=raw, store=False) resampled = AudioSamplesFeature( Resampler, needs=pcm, samplerate=resample_to, store=False) windowed = ArrayWithUnitsFeature( SlidingWindow, needs=resampled, wscheme=HalfLapped(), wfunc=OggVorbisWindowingFunc(), store=False) dct = ArrayWithUnitsFeature( DCT, needs=windowed, store=True) fft = ArrayWithUnitsFeature( FFT, needs=windowed, store=store_fft) bark = ArrayWithUnitsFeature( BarkBands, needs=fft, frequency_band=band, store=True) centroid = ArrayWithUnitsFeature( SpectralCentroid, needs=bark, store=True) chroma = ArrayWithUnitsFeature( Chroma, needs=fft, frequency_band=band, store=True) bfcc = ArrayWithUnitsFeature( BFCC, needs=fft, store=True) return AudioGraph
[ "def", "audio_graph", "(", "chunksize_bytes", "=", "DEFAULT_CHUNK_SIZE", ",", "resample_to", "=", "SR44100", "(", ")", ",", "store_fft", "=", "False", ")", ":", "band", "=", "FrequencyBand", "(", "20", ",", "resample_to", ".", "nyquist", ")", "class", "Audio...
Produce a base class suitable as a starting point for many audio processing pipelines. This class resamples all audio to a common sampling rate, and produces a bark band spectrogram from overlapping short-time fourier transform frames. It also compresses the audio into ogg vorbis format for compact storage.
[ "Produce", "a", "base", "class", "suitable", "as", "a", "starting", "point", "for", "many", "audio", "processing", "pipelines", ".", "This", "class", "resamples", "all", "audio", "to", "a", "common", "sampling", "rate", "and", "produces", "a", "bark", "band"...
337b3f98753d09eaab1c72dcd37bb852a3fa5ac6
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/basic/audiograph.py#L179-L260
train
47,687
playpauseandstop/rororo
rororo/timedelta.py
str_to_timedelta
def str_to_timedelta(value: str, fmt: str = None) -> Optional[datetime.timedelta]: """ Convert string value to timedelta instance according to the given format. If format not set function tries to load timedelta using default ``TIMEDELTA_FORMAT`` and then both of magic "full" formats. You should also specify list of formats and function tries to convert to timedelta using each of formats in list. First matched format would return the converted timedelta instance. If user specified format, but function cannot convert string to new timedelta instance - ``ValueError`` would be raised. But if user did not specify the format, function would be fail silently and return ``None`` as result. :param value: String representation of timedelta. :param fmt: Format to use for conversion. """ def timedelta_kwargs(data: DictStrInt) -> DictStrInt: """ Convert day_hours, hour_minutes, minute_seconds, week_days and weeks to timedelta seconds. """ seconds = data.get('seconds', 0) seconds += data.get('day_hours', 0) * 3600 seconds += data.pop('hour_minutes', 0) * 60 seconds += data.pop('minute_seconds', 0) seconds += data.pop('week_days', 0) * SECONDS_PER_DAY seconds += data.pop('weeks', 0) * SECONDS_PER_WEEK data.update({'seconds': seconds}) return data if not isinstance(value, str): raise ValueError( 'Value should be a "str" instance. You use {0}.' .format(type(value))) user_fmt = fmt if isinstance(fmt, (list, tuple)): formats = list(fmt) elif fmt is None: formats = [TIMEDELTA_FORMAT, 'F', 'f'] else: formats = [fmt] locale_data = { 'days_label': '({0}|{1})'.format('day', 'days'), 'short_days_label': 'd', 'short_week_days_label': 'd', 'short_weeks_label': 'w', 'week_days_label': '({0}|{1})'.format('day', 'days'), 'weeks_label': '({0}|{1})'.format('week', 'weeks'), } regexps = [] for item in formats: processed = r'^' for part in item: if part in TIMEDELTA_FORMATS: part = TIMEDELTA_FORMATS[part][1] % locale_data else: part = re.escape(part) processed += part processed += r'$' regexps.append(processed) for regexp in regexps: timedelta_re = re.compile(regexp) matched = timedelta_re.match(value) if matched: data = { key: to_int(value) or 0 for key, value in matched.groupdict().items()} return datetime.timedelta(**timedelta_kwargs(data)) if user_fmt: raise ValueError( 'Cannot convert {0!r} to timedelta instance, using {1!r} format.' .format(value, user_fmt)) return None
python
def str_to_timedelta(value: str, fmt: str = None) -> Optional[datetime.timedelta]: """ Convert string value to timedelta instance according to the given format. If format not set function tries to load timedelta using default ``TIMEDELTA_FORMAT`` and then both of magic "full" formats. You should also specify list of formats and function tries to convert to timedelta using each of formats in list. First matched format would return the converted timedelta instance. If user specified format, but function cannot convert string to new timedelta instance - ``ValueError`` would be raised. But if user did not specify the format, function would be fail silently and return ``None`` as result. :param value: String representation of timedelta. :param fmt: Format to use for conversion. """ def timedelta_kwargs(data: DictStrInt) -> DictStrInt: """ Convert day_hours, hour_minutes, minute_seconds, week_days and weeks to timedelta seconds. """ seconds = data.get('seconds', 0) seconds += data.get('day_hours', 0) * 3600 seconds += data.pop('hour_minutes', 0) * 60 seconds += data.pop('minute_seconds', 0) seconds += data.pop('week_days', 0) * SECONDS_PER_DAY seconds += data.pop('weeks', 0) * SECONDS_PER_WEEK data.update({'seconds': seconds}) return data if not isinstance(value, str): raise ValueError( 'Value should be a "str" instance. You use {0}.' .format(type(value))) user_fmt = fmt if isinstance(fmt, (list, tuple)): formats = list(fmt) elif fmt is None: formats = [TIMEDELTA_FORMAT, 'F', 'f'] else: formats = [fmt] locale_data = { 'days_label': '({0}|{1})'.format('day', 'days'), 'short_days_label': 'd', 'short_week_days_label': 'd', 'short_weeks_label': 'w', 'week_days_label': '({0}|{1})'.format('day', 'days'), 'weeks_label': '({0}|{1})'.format('week', 'weeks'), } regexps = [] for item in formats: processed = r'^' for part in item: if part in TIMEDELTA_FORMATS: part = TIMEDELTA_FORMATS[part][1] % locale_data else: part = re.escape(part) processed += part processed += r'$' regexps.append(processed) for regexp in regexps: timedelta_re = re.compile(regexp) matched = timedelta_re.match(value) if matched: data = { key: to_int(value) or 0 for key, value in matched.groupdict().items()} return datetime.timedelta(**timedelta_kwargs(data)) if user_fmt: raise ValueError( 'Cannot convert {0!r} to timedelta instance, using {1!r} format.' .format(value, user_fmt)) return None
[ "def", "str_to_timedelta", "(", "value", ":", "str", ",", "fmt", ":", "str", "=", "None", ")", "->", "Optional", "[", "datetime", ".", "timedelta", "]", ":", "def", "timedelta_kwargs", "(", "data", ":", "DictStrInt", ")", "->", "DictStrInt", ":", "\"\"\"...
Convert string value to timedelta instance according to the given format. If format not set function tries to load timedelta using default ``TIMEDELTA_FORMAT`` and then both of magic "full" formats. You should also specify list of formats and function tries to convert to timedelta using each of formats in list. First matched format would return the converted timedelta instance. If user specified format, but function cannot convert string to new timedelta instance - ``ValueError`` would be raised. But if user did not specify the format, function would be fail silently and return ``None`` as result. :param value: String representation of timedelta. :param fmt: Format to use for conversion.
[ "Convert", "string", "value", "to", "timedelta", "instance", "according", "to", "the", "given", "format", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/timedelta.py#L66-L152
train
47,688
playpauseandstop/rororo
rororo/timedelta.py
timedelta_average
def timedelta_average(*values: datetime.timedelta) -> datetime.timedelta: r"""Compute the arithmetic mean for timedeltas list. :param \*values: Timedelta instances to process. """ if isinstance(values[0], (list, tuple)): values = values[0] return sum(values, datetime.timedelta()) // len(values)
python
def timedelta_average(*values: datetime.timedelta) -> datetime.timedelta: r"""Compute the arithmetic mean for timedeltas list. :param \*values: Timedelta instances to process. """ if isinstance(values[0], (list, tuple)): values = values[0] return sum(values, datetime.timedelta()) // len(values)
[ "def", "timedelta_average", "(", "*", "values", ":", "datetime", ".", "timedelta", ")", "->", "datetime", ".", "timedelta", ":", "if", "isinstance", "(", "values", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "values", "=", "values", ...
r"""Compute the arithmetic mean for timedeltas list. :param \*values: Timedelta instances to process.
[ "r", "Compute", "the", "arithmetic", "mean", "for", "timedeltas", "list", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/timedelta.py#L155-L162
train
47,689
playpauseandstop/rororo
rororo/timedelta.py
timedelta_div
def timedelta_div(first: datetime.timedelta, second: datetime.timedelta) -> Optional[float]: """Implement divison for timedelta instances. :param first: First timedelta instance. :param second: Second timedelta instance. """ first_seconds = timedelta_seconds(first) second_seconds = timedelta_seconds(second) if not second_seconds: return None return first_seconds / second_seconds
python
def timedelta_div(first: datetime.timedelta, second: datetime.timedelta) -> Optional[float]: """Implement divison for timedelta instances. :param first: First timedelta instance. :param second: Second timedelta instance. """ first_seconds = timedelta_seconds(first) second_seconds = timedelta_seconds(second) if not second_seconds: return None return first_seconds / second_seconds
[ "def", "timedelta_div", "(", "first", ":", "datetime", ".", "timedelta", ",", "second", ":", "datetime", ".", "timedelta", ")", "->", "Optional", "[", "float", "]", ":", "first_seconds", "=", "timedelta_seconds", "(", "first", ")", "second_seconds", "=", "ti...
Implement divison for timedelta instances. :param first: First timedelta instance. :param second: Second timedelta instance.
[ "Implement", "divison", "for", "timedelta", "instances", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/timedelta.py#L165-L178
train
47,690
playpauseandstop/rororo
rororo/timedelta.py
timedelta_seconds
def timedelta_seconds(value: datetime.timedelta) -> int: """Return full number of seconds from timedelta. By default, Python returns only one day seconds, not all timedelta seconds. :param value: Timedelta instance. """ return SECONDS_PER_DAY * value.days + value.seconds
python
def timedelta_seconds(value: datetime.timedelta) -> int: """Return full number of seconds from timedelta. By default, Python returns only one day seconds, not all timedelta seconds. :param value: Timedelta instance. """ return SECONDS_PER_DAY * value.days + value.seconds
[ "def", "timedelta_seconds", "(", "value", ":", "datetime", ".", "timedelta", ")", "->", "int", ":", "return", "SECONDS_PER_DAY", "*", "value", ".", "days", "+", "value", ".", "seconds" ]
Return full number of seconds from timedelta. By default, Python returns only one day seconds, not all timedelta seconds. :param value: Timedelta instance.
[ "Return", "full", "number", "of", "seconds", "from", "timedelta", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/timedelta.py#L181-L188
train
47,691
playpauseandstop/rororo
rororo/timedelta.py
timedelta_to_str
def timedelta_to_str(value: datetime.timedelta, fmt: str = None) -> str: """Display the timedelta formatted according to the given string. You should use global setting ``TIMEDELTA_FORMAT`` to specify default format to this function there (like ``DATE_FORMAT`` for builtin ``date`` template filter). Default value for ``TIMEDELTA_FORMAT`` is ``'G:i'``. Format uses the same policy as Django ``date`` template filter or PHP ``date`` function with several differences. Available format strings: +------------------+-----------------------------+------------------------+ | Format character | Description | Example output | +==================+=============================+========================+ | ``a`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``A`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``b`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``B`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``c`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``d`` | Total days, 2 digits with | ``'01'``, ``'41'`` | | | leading zeros. Do not | | | | combine with ``w`` format. | | +------------------+-----------------------------+------------------------+ | ``D`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``f`` | Magic "full" format with | ``'2w 4d 1:28:07'`` | | | short labels. | | +------------------+-----------------------------+------------------------+ | ``F`` | Magic "full" format with | ``'2 weeks, 4 days, | | | normal labels. | 1:28:07'`` | +------------------+-----------------------------+------------------------+ | ``g`` | Day, not total, hours | ``'0'`` to ``'23'`` | | | without leading zeros. To | | | | use with ``d``, ``j``, or | | | | ``w``. | | +------------------+-----------------------------+------------------------+ | ``G`` | Total hours without | ``'1'``, ``'433'`` | | | leading zeros. Do not | | | | combine with ``g`` or | | | | ``h`` formats. | | +------------------+-----------------------------+------------------------+ | ``h`` | Day, not total, hours with | ``'00'`` to ``'23'`` | | | leading zeros. To use with | | | | ``d`` or ``w``. | | +------------------+-----------------------------+------------------------+ | ``H`` | Total hours with leading | ``'01', ``'433'`` | | | zeros. Do not combine with | | | | ``g`` or ``h`` formats. | | +------------------+-----------------------------+------------------------+ | ``i`` | Hour, not total, minutes, 2 | ``00`` to ``'59'`` | | | digits with leading zeros | | | | To use with ``g``, ``G``, | | | | ``h`` or ``H`` formats. | | +------------------+-----------------------------+------------------------+ | ``I`` | Total minutes, 2 digits or | ``'01'``, ``'433'`` | | | more with leading zeros. Do | | | | not combine with ``i`` | | | | format. | | +------------------+-----------------------------+------------------------+ | ``j`` | Total days, one or 2 digits | ``'1'``, ``'41'`` | | | without leading zeros. Do | | | | not combine with ``w`` | | | | format. | | +------------------+-----------------------------+------------------------+ | ``J`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``l`` | Days long label. | ``'day'`` or | | | Pluralized and localized. | ``'days'`` | +------------------+-----------------------------+------------------------+ | ``L`` | Weeks long label. | ``'week'`` or | | | Pluralized and localized. | ``'weeks'`` | +------------------+-----------------------------+------------------------+ | ``m`` | Week days long label. | ``'day'`` or | | | Pluralized and localized. | ``'days'`` | +------------------+-----------------------------+------------------------+ | ``M`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``n`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``N`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``O`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``P`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``r`` | Standart Python timedelta | ``'18 d 1:28:07'`` | | | representation with short | | | | labels. | | +------------------+-----------------------------+------------------------+ | ``R`` | Standart Python timedelta | ``'18 days, 1:28:07'`` | | | representation with normal | | | | labels. | | +------------------+-----------------------------+------------------------+ | ``s`` | Minute, not total, seconds, | ``'00'`` to ``'59'`` | | | 2 digits with leading | | | | zeros. To use with ``i`` or | | | | ``I``. | | +------------------+-----------------------------+------------------------+ | ``S`` | Total seconds. 2 digits or | ``'00'``, ``'433'`` | | | more with leading zeros. Do | | | | not combine with ``s`` | | | | format. | | +------------------+-----------------------------+------------------------+ | ``t`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``T`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``u`` | Second, not total, | ``0`` to ``999999`` | | | microseconds. | | +------------------+-----------------------------+------------------------+ | ``U`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``w`` | Week, not total, days, one | ``0`` to ``6`` | | | digit without leading | | | | zeros. To use with ``W``. | | +------------------+-----------------------------+------------------------+ | ``W`` | Total weeks, one or more | ``'1'``, ``'41'`` | | | digits without leading | | | | zeros. | | +------------------+-----------------------------+------------------------+ | ``y`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``Y`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``z`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``Z`` | Not implemented. | | +------------------+-----------------------------+------------------------+ For example, :: >>> import datetime >>> from rororo.timedelta import timedelta_to_str >>> delta = datetime.timedelta(seconds=99660) >>> timedelta_to_str(delta) ... '27:41' >>> timedelta_to_str(delta, 'r') ... '1d 3:41:00' >>> timedelta_to_str(delta, 'f') ... '1d 3:41' >>> timedelta_to_str(delta, 'W L, w l, H:i:s') ... '0 weeks, 1 day, 03:41:00' Couple words about magic "full" formats. These formats show weeks number with week label, days number with day label and seconds only if weeks number, days number or seconds greater that zero. For example, :: >>> import datetime >>> from rororo.timedelta import timedelta_to_str >>> delta = datetime.timedelta(hours=12) >>> timedelta_to_str(delta, 'f') ... '12:00' >>> timedelta_to_str(delta, 'F') ... '12:00' >>> delta = datetime.timedelta(hours=12, seconds=30) >>> timedelta_to_str(delta, 'f') ... '12:00:30' >>> timedelta_to_str(delta, 'F') ... '12:00:30' >>> delta = datetime.timedelta(hours=168) >>> timedelta_to_str(delta, 'f') ... '1w 0:00' >>> timedelta_to_str(delta, 'F') ... '1 week, 0:00' :param value: Timedelta instance to convert to string. :param fmt: Format to use for conversion. """ # Only ``datetime.timedelta`` instances allowed for this function if not isinstance(value, datetime.timedelta): raise ValueError( 'Value should be a "datetime.timedelta" instance. You use {0}.' .format(type(value))) # Generate total data days = value.days microseconds = value.microseconds seconds = timedelta_seconds(value) hours = seconds // 3600 minutes = seconds // 60 weeks = days // 7 # Generate collapsed data day_hours = hours - days * 24 hour_minutes = minutes - hours * 60 minute_seconds = seconds - minutes * 60 week_days = days - weeks * 7 days_label = 'day' if days % 10 == 1 else 'days' short_days_label = 'd' short_week_days_label = 'd' short_weeks_label = 'w' week_days_label = 'day' if week_days % 10 == 1 else 'days' weeks_label = 'week' if weeks % 10 == 1 else 'weeks' # Collect data data = locals() fmt = fmt or TIMEDELTA_FORMAT processed = '' for part in fmt: if part in TIMEDELTA_FORMATS: is_full_part = part in ('f', 'F') is_repr_part = part in ('r', 'R') part = TIMEDELTA_FORMATS[part][0] if is_full_part or is_repr_part: if is_repr_part and not days: part = part.replace('%(days)d', '') part = part.replace('%(days_label)s,', '') part = part.replace('%(short_days_label)s', '') if is_full_part and not minute_seconds: part = part.replace(':%(minute_seconds)02d', '') if is_full_part and not weeks: part = part.replace('%(weeks)d', '') part = part.replace('%(short_weeks_label)s', '') part = part.replace('%(weeks_label)s,', '') if is_full_part and not week_days: part = part.replace('%(week_days)d', '') part = part.replace('%(short_week_days_label)s', '') part = part.replace('%(week_days_label)s,', '') part = part.strip() part = ' '.join(part.split()) processed += part return processed % data
python
def timedelta_to_str(value: datetime.timedelta, fmt: str = None) -> str: """Display the timedelta formatted according to the given string. You should use global setting ``TIMEDELTA_FORMAT`` to specify default format to this function there (like ``DATE_FORMAT`` for builtin ``date`` template filter). Default value for ``TIMEDELTA_FORMAT`` is ``'G:i'``. Format uses the same policy as Django ``date`` template filter or PHP ``date`` function with several differences. Available format strings: +------------------+-----------------------------+------------------------+ | Format character | Description | Example output | +==================+=============================+========================+ | ``a`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``A`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``b`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``B`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``c`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``d`` | Total days, 2 digits with | ``'01'``, ``'41'`` | | | leading zeros. Do not | | | | combine with ``w`` format. | | +------------------+-----------------------------+------------------------+ | ``D`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``f`` | Magic "full" format with | ``'2w 4d 1:28:07'`` | | | short labels. | | +------------------+-----------------------------+------------------------+ | ``F`` | Magic "full" format with | ``'2 weeks, 4 days, | | | normal labels. | 1:28:07'`` | +------------------+-----------------------------+------------------------+ | ``g`` | Day, not total, hours | ``'0'`` to ``'23'`` | | | without leading zeros. To | | | | use with ``d``, ``j``, or | | | | ``w``. | | +------------------+-----------------------------+------------------------+ | ``G`` | Total hours without | ``'1'``, ``'433'`` | | | leading zeros. Do not | | | | combine with ``g`` or | | | | ``h`` formats. | | +------------------+-----------------------------+------------------------+ | ``h`` | Day, not total, hours with | ``'00'`` to ``'23'`` | | | leading zeros. To use with | | | | ``d`` or ``w``. | | +------------------+-----------------------------+------------------------+ | ``H`` | Total hours with leading | ``'01', ``'433'`` | | | zeros. Do not combine with | | | | ``g`` or ``h`` formats. | | +------------------+-----------------------------+------------------------+ | ``i`` | Hour, not total, minutes, 2 | ``00`` to ``'59'`` | | | digits with leading zeros | | | | To use with ``g``, ``G``, | | | | ``h`` or ``H`` formats. | | +------------------+-----------------------------+------------------------+ | ``I`` | Total minutes, 2 digits or | ``'01'``, ``'433'`` | | | more with leading zeros. Do | | | | not combine with ``i`` | | | | format. | | +------------------+-----------------------------+------------------------+ | ``j`` | Total days, one or 2 digits | ``'1'``, ``'41'`` | | | without leading zeros. Do | | | | not combine with ``w`` | | | | format. | | +------------------+-----------------------------+------------------------+ | ``J`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``l`` | Days long label. | ``'day'`` or | | | Pluralized and localized. | ``'days'`` | +------------------+-----------------------------+------------------------+ | ``L`` | Weeks long label. | ``'week'`` or | | | Pluralized and localized. | ``'weeks'`` | +------------------+-----------------------------+------------------------+ | ``m`` | Week days long label. | ``'day'`` or | | | Pluralized and localized. | ``'days'`` | +------------------+-----------------------------+------------------------+ | ``M`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``n`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``N`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``O`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``P`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``r`` | Standart Python timedelta | ``'18 d 1:28:07'`` | | | representation with short | | | | labels. | | +------------------+-----------------------------+------------------------+ | ``R`` | Standart Python timedelta | ``'18 days, 1:28:07'`` | | | representation with normal | | | | labels. | | +------------------+-----------------------------+------------------------+ | ``s`` | Minute, not total, seconds, | ``'00'`` to ``'59'`` | | | 2 digits with leading | | | | zeros. To use with ``i`` or | | | | ``I``. | | +------------------+-----------------------------+------------------------+ | ``S`` | Total seconds. 2 digits or | ``'00'``, ``'433'`` | | | more with leading zeros. Do | | | | not combine with ``s`` | | | | format. | | +------------------+-----------------------------+------------------------+ | ``t`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``T`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``u`` | Second, not total, | ``0`` to ``999999`` | | | microseconds. | | +------------------+-----------------------------+------------------------+ | ``U`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``w`` | Week, not total, days, one | ``0`` to ``6`` | | | digit without leading | | | | zeros. To use with ``W``. | | +------------------+-----------------------------+------------------------+ | ``W`` | Total weeks, one or more | ``'1'``, ``'41'`` | | | digits without leading | | | | zeros. | | +------------------+-----------------------------+------------------------+ | ``y`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``Y`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``z`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``Z`` | Not implemented. | | +------------------+-----------------------------+------------------------+ For example, :: >>> import datetime >>> from rororo.timedelta import timedelta_to_str >>> delta = datetime.timedelta(seconds=99660) >>> timedelta_to_str(delta) ... '27:41' >>> timedelta_to_str(delta, 'r') ... '1d 3:41:00' >>> timedelta_to_str(delta, 'f') ... '1d 3:41' >>> timedelta_to_str(delta, 'W L, w l, H:i:s') ... '0 weeks, 1 day, 03:41:00' Couple words about magic "full" formats. These formats show weeks number with week label, days number with day label and seconds only if weeks number, days number or seconds greater that zero. For example, :: >>> import datetime >>> from rororo.timedelta import timedelta_to_str >>> delta = datetime.timedelta(hours=12) >>> timedelta_to_str(delta, 'f') ... '12:00' >>> timedelta_to_str(delta, 'F') ... '12:00' >>> delta = datetime.timedelta(hours=12, seconds=30) >>> timedelta_to_str(delta, 'f') ... '12:00:30' >>> timedelta_to_str(delta, 'F') ... '12:00:30' >>> delta = datetime.timedelta(hours=168) >>> timedelta_to_str(delta, 'f') ... '1w 0:00' >>> timedelta_to_str(delta, 'F') ... '1 week, 0:00' :param value: Timedelta instance to convert to string. :param fmt: Format to use for conversion. """ # Only ``datetime.timedelta`` instances allowed for this function if not isinstance(value, datetime.timedelta): raise ValueError( 'Value should be a "datetime.timedelta" instance. You use {0}.' .format(type(value))) # Generate total data days = value.days microseconds = value.microseconds seconds = timedelta_seconds(value) hours = seconds // 3600 minutes = seconds // 60 weeks = days // 7 # Generate collapsed data day_hours = hours - days * 24 hour_minutes = minutes - hours * 60 minute_seconds = seconds - minutes * 60 week_days = days - weeks * 7 days_label = 'day' if days % 10 == 1 else 'days' short_days_label = 'd' short_week_days_label = 'd' short_weeks_label = 'w' week_days_label = 'day' if week_days % 10 == 1 else 'days' weeks_label = 'week' if weeks % 10 == 1 else 'weeks' # Collect data data = locals() fmt = fmt or TIMEDELTA_FORMAT processed = '' for part in fmt: if part in TIMEDELTA_FORMATS: is_full_part = part in ('f', 'F') is_repr_part = part in ('r', 'R') part = TIMEDELTA_FORMATS[part][0] if is_full_part or is_repr_part: if is_repr_part and not days: part = part.replace('%(days)d', '') part = part.replace('%(days_label)s,', '') part = part.replace('%(short_days_label)s', '') if is_full_part and not minute_seconds: part = part.replace(':%(minute_seconds)02d', '') if is_full_part and not weeks: part = part.replace('%(weeks)d', '') part = part.replace('%(short_weeks_label)s', '') part = part.replace('%(weeks_label)s,', '') if is_full_part and not week_days: part = part.replace('%(week_days)d', '') part = part.replace('%(short_week_days_label)s', '') part = part.replace('%(week_days_label)s,', '') part = part.strip() part = ' '.join(part.split()) processed += part return processed % data
[ "def", "timedelta_to_str", "(", "value", ":", "datetime", ".", "timedelta", ",", "fmt", ":", "str", "=", "None", ")", "->", "str", ":", "# Only ``datetime.timedelta`` instances allowed for this function", "if", "not", "isinstance", "(", "value", ",", "datetime", "...
Display the timedelta formatted according to the given string. You should use global setting ``TIMEDELTA_FORMAT`` to specify default format to this function there (like ``DATE_FORMAT`` for builtin ``date`` template filter). Default value for ``TIMEDELTA_FORMAT`` is ``'G:i'``. Format uses the same policy as Django ``date`` template filter or PHP ``date`` function with several differences. Available format strings: +------------------+-----------------------------+------------------------+ | Format character | Description | Example output | +==================+=============================+========================+ | ``a`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``A`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``b`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``B`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``c`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``d`` | Total days, 2 digits with | ``'01'``, ``'41'`` | | | leading zeros. Do not | | | | combine with ``w`` format. | | +------------------+-----------------------------+------------------------+ | ``D`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``f`` | Magic "full" format with | ``'2w 4d 1:28:07'`` | | | short labels. | | +------------------+-----------------------------+------------------------+ | ``F`` | Magic "full" format with | ``'2 weeks, 4 days, | | | normal labels. | 1:28:07'`` | +------------------+-----------------------------+------------------------+ | ``g`` | Day, not total, hours | ``'0'`` to ``'23'`` | | | without leading zeros. To | | | | use with ``d``, ``j``, or | | | | ``w``. | | +------------------+-----------------------------+------------------------+ | ``G`` | Total hours without | ``'1'``, ``'433'`` | | | leading zeros. Do not | | | | combine with ``g`` or | | | | ``h`` formats. | | +------------------+-----------------------------+------------------------+ | ``h`` | Day, not total, hours with | ``'00'`` to ``'23'`` | | | leading zeros. To use with | | | | ``d`` or ``w``. | | +------------------+-----------------------------+------------------------+ | ``H`` | Total hours with leading | ``'01', ``'433'`` | | | zeros. Do not combine with | | | | ``g`` or ``h`` formats. | | +------------------+-----------------------------+------------------------+ | ``i`` | Hour, not total, minutes, 2 | ``00`` to ``'59'`` | | | digits with leading zeros | | | | To use with ``g``, ``G``, | | | | ``h`` or ``H`` formats. | | +------------------+-----------------------------+------------------------+ | ``I`` | Total minutes, 2 digits or | ``'01'``, ``'433'`` | | | more with leading zeros. Do | | | | not combine with ``i`` | | | | format. | | +------------------+-----------------------------+------------------------+ | ``j`` | Total days, one or 2 digits | ``'1'``, ``'41'`` | | | without leading zeros. Do | | | | not combine with ``w`` | | | | format. | | +------------------+-----------------------------+------------------------+ | ``J`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``l`` | Days long label. | ``'day'`` or | | | Pluralized and localized. | ``'days'`` | +------------------+-----------------------------+------------------------+ | ``L`` | Weeks long label. | ``'week'`` or | | | Pluralized and localized. | ``'weeks'`` | +------------------+-----------------------------+------------------------+ | ``m`` | Week days long label. | ``'day'`` or | | | Pluralized and localized. | ``'days'`` | +------------------+-----------------------------+------------------------+ | ``M`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``n`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``N`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``O`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``P`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``r`` | Standart Python timedelta | ``'18 d 1:28:07'`` | | | representation with short | | | | labels. | | +------------------+-----------------------------+------------------------+ | ``R`` | Standart Python timedelta | ``'18 days, 1:28:07'`` | | | representation with normal | | | | labels. | | +------------------+-----------------------------+------------------------+ | ``s`` | Minute, not total, seconds, | ``'00'`` to ``'59'`` | | | 2 digits with leading | | | | zeros. To use with ``i`` or | | | | ``I``. | | +------------------+-----------------------------+------------------------+ | ``S`` | Total seconds. 2 digits or | ``'00'``, ``'433'`` | | | more with leading zeros. Do | | | | not combine with ``s`` | | | | format. | | +------------------+-----------------------------+------------------------+ | ``t`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``T`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``u`` | Second, not total, | ``0`` to ``999999`` | | | microseconds. | | +------------------+-----------------------------+------------------------+ | ``U`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``w`` | Week, not total, days, one | ``0`` to ``6`` | | | digit without leading | | | | zeros. To use with ``W``. | | +------------------+-----------------------------+------------------------+ | ``W`` | Total weeks, one or more | ``'1'``, ``'41'`` | | | digits without leading | | | | zeros. | | +------------------+-----------------------------+------------------------+ | ``y`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``Y`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``z`` | Not implemented. | | +------------------+-----------------------------+------------------------+ | ``Z`` | Not implemented. | | +------------------+-----------------------------+------------------------+ For example, :: >>> import datetime >>> from rororo.timedelta import timedelta_to_str >>> delta = datetime.timedelta(seconds=99660) >>> timedelta_to_str(delta) ... '27:41' >>> timedelta_to_str(delta, 'r') ... '1d 3:41:00' >>> timedelta_to_str(delta, 'f') ... '1d 3:41' >>> timedelta_to_str(delta, 'W L, w l, H:i:s') ... '0 weeks, 1 day, 03:41:00' Couple words about magic "full" formats. These formats show weeks number with week label, days number with day label and seconds only if weeks number, days number or seconds greater that zero. For example, :: >>> import datetime >>> from rororo.timedelta import timedelta_to_str >>> delta = datetime.timedelta(hours=12) >>> timedelta_to_str(delta, 'f') ... '12:00' >>> timedelta_to_str(delta, 'F') ... '12:00' >>> delta = datetime.timedelta(hours=12, seconds=30) >>> timedelta_to_str(delta, 'f') ... '12:00:30' >>> timedelta_to_str(delta, 'F') ... '12:00:30' >>> delta = datetime.timedelta(hours=168) >>> timedelta_to_str(delta, 'f') ... '1w 0:00' >>> timedelta_to_str(delta, 'F') ... '1 week, 0:00' :param value: Timedelta instance to convert to string. :param fmt: Format to use for conversion.
[ "Display", "the", "timedelta", "formatted", "according", "to", "the", "given", "string", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/timedelta.py#L191-L438
train
47,692
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.send_command
def send_command(self, cmd, params=None, raw=False): ''' Send command to foscam. ''' paramstr = '' if params: paramstr = urlencode(params) paramstr = '&' + paramstr if paramstr else '' cmdurl = 'http://%s/cgi-bin/CGIProxy.fcgi?usr=%s&pwd=%s&cmd=%s%s' % ( self.url, self.usr, self.pwd, cmd, paramstr, ) if self.ssl and ssl_enabled: cmdurl = cmdurl.replace('http:','https:') # Parse parameters from response string. if self.verbose: print ('Send Foscam command: %s' % cmdurl) try: raw_string = '' if self.ssl and ssl_enabled: gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # disable cert raw_string = urlopen(cmdurl,context=gcontext, timeout=5).read() else: raw_string = urlopen(cmdurl,timeout=5).read() if raw: if self.verbose: print ('Returning raw Foscam response: len=%d' % len(raw_string)) return FOSCAM_SUCCESS, raw_string root = ET.fromstring(raw_string) except: if self.verbose: print ('Foscam exception: ' + raw_string) return ERROR_FOSCAM_UNAVAILABLE, None code = ERROR_FOSCAM_UNKNOWN params = OrderedDict() for child in root.iter(): if child.tag == 'result': code = int(child.text) elif child.tag != 'CGI_Result': params[child.tag] = unquote(child.text) if self.verbose: print ('Received Foscam response: %s, %s' % (code, params)) return code, params
python
def send_command(self, cmd, params=None, raw=False): ''' Send command to foscam. ''' paramstr = '' if params: paramstr = urlencode(params) paramstr = '&' + paramstr if paramstr else '' cmdurl = 'http://%s/cgi-bin/CGIProxy.fcgi?usr=%s&pwd=%s&cmd=%s%s' % ( self.url, self.usr, self.pwd, cmd, paramstr, ) if self.ssl and ssl_enabled: cmdurl = cmdurl.replace('http:','https:') # Parse parameters from response string. if self.verbose: print ('Send Foscam command: %s' % cmdurl) try: raw_string = '' if self.ssl and ssl_enabled: gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # disable cert raw_string = urlopen(cmdurl,context=gcontext, timeout=5).read() else: raw_string = urlopen(cmdurl,timeout=5).read() if raw: if self.verbose: print ('Returning raw Foscam response: len=%d' % len(raw_string)) return FOSCAM_SUCCESS, raw_string root = ET.fromstring(raw_string) except: if self.verbose: print ('Foscam exception: ' + raw_string) return ERROR_FOSCAM_UNAVAILABLE, None code = ERROR_FOSCAM_UNKNOWN params = OrderedDict() for child in root.iter(): if child.tag == 'result': code = int(child.text) elif child.tag != 'CGI_Result': params[child.tag] = unquote(child.text) if self.verbose: print ('Received Foscam response: %s, %s' % (code, params)) return code, params
[ "def", "send_command", "(", "self", ",", "cmd", ",", "params", "=", "None", ",", "raw", "=", "False", ")", ":", "paramstr", "=", "''", "if", "params", ":", "paramstr", "=", "urlencode", "(", "params", ")", "paramstr", "=", "'&'", "+", "paramstr", "if...
Send command to foscam.
[ "Send", "command", "to", "foscam", "." ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L74-L122
train
47,693
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.set_port_info
def set_port_info(self, webport, mediaport, httpsport, onvifport, callback=None): ''' Set http port and media port of camera. ''' params = {'webPort' : webport, 'mediaPort' : mediaport, 'httpsPort' : httpsport, 'onvifPort' : onvifport, } return self.execute_command('setPortInfo', params, callback=callback)
python
def set_port_info(self, webport, mediaport, httpsport, onvifport, callback=None): ''' Set http port and media port of camera. ''' params = {'webPort' : webport, 'mediaPort' : mediaport, 'httpsPort' : httpsport, 'onvifPort' : onvifport, } return self.execute_command('setPortInfo', params, callback=callback)
[ "def", "set_port_info", "(", "self", ",", "webport", ",", "mediaport", ",", "httpsport", ",", "onvifport", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'webPort'", ":", "webport", ",", "'mediaPort'", ":", "mediaport", ",", "'httpsPort'", ":...
Set http port and media port of camera.
[ "Set", "http", "port", "and", "media", "port", "of", "camera", "." ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L172-L182
train
47,694
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.set_wifi_setting
def set_wifi_setting(self, ssid, psk, isenable, isusewifi, nettype, encryptype, authmode, keyformat, defaultkey, key1='', key2='', key3='', key4='', key1len=64, key2len=64, key3len=64, key4len=64, callback=None): ''' Set wifi config. Camera will not connect to AP unless you enject your cable. ''' params = {'isEnable' : isenable, 'isUseWifi' : isusewifi, 'ssid' : ssid, 'netType' : nettype, 'encryptType': encryptype, 'psk' : psk, 'authMode' : authmode, 'keyFormat' : keyformat, 'defaultKey' : defaultkey, 'key1' : key1, 'key2' : key2, 'key3' : key3, 'key4' : key4, 'key1Len' : key1len, 'key2Len' : key2len, 'key3Len' : key3len, 'key4Len' : key4len, } return self.execute_command('setWifiSetting', params, callback=callback)
python
def set_wifi_setting(self, ssid, psk, isenable, isusewifi, nettype, encryptype, authmode, keyformat, defaultkey, key1='', key2='', key3='', key4='', key1len=64, key2len=64, key3len=64, key4len=64, callback=None): ''' Set wifi config. Camera will not connect to AP unless you enject your cable. ''' params = {'isEnable' : isenable, 'isUseWifi' : isusewifi, 'ssid' : ssid, 'netType' : nettype, 'encryptType': encryptype, 'psk' : psk, 'authMode' : authmode, 'keyFormat' : keyformat, 'defaultKey' : defaultkey, 'key1' : key1, 'key2' : key2, 'key3' : key3, 'key4' : key4, 'key1Len' : key1len, 'key2Len' : key2len, 'key3Len' : key3len, 'key4Len' : key4len, } return self.execute_command('setWifiSetting', params, callback=callback)
[ "def", "set_wifi_setting", "(", "self", ",", "ssid", ",", "psk", ",", "isenable", ",", "isusewifi", ",", "nettype", ",", "encryptype", ",", "authmode", ",", "keyformat", ",", "defaultkey", ",", "key1", "=", "''", ",", "key2", "=", "''", ",", "key3", "=...
Set wifi config. Camera will not connect to AP unless you enject your cable.
[ "Set", "wifi", "config", ".", "Camera", "will", "not", "connect", "to", "AP", "unless", "you", "enject", "your", "cable", "." ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L200-L227
train
47,695
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.set_upnp_config
def set_upnp_config(self, isenable, callback=None): ''' Set UPnP config ''' params = {'isEnable': isenable} return self.execute_command('setUPnPConfig', params, callback=callback)
python
def set_upnp_config(self, isenable, callback=None): ''' Set UPnP config ''' params = {'isEnable': isenable} return self.execute_command('setUPnPConfig', params, callback=callback)
[ "def", "set_upnp_config", "(", "self", ",", "isenable", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'isEnable'", ":", "isenable", "}", "return", "self", ".", "execute_command", "(", "'setUPnPConfig'", ",", "params", ",", "callback", "=", "...
Set UPnP config
[ "Set", "UPnP", "config" ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L241-L246
train
47,696
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.set_ddns_config
def set_ddns_config(self, isenable, hostname, ddnsserver, user, password, callback=None): ''' Set DDNS config. ''' params = {'isEnable': isenable, 'hostName': hostname, 'ddnsServer': ddnsserver, 'user': user, 'password': password, } return self.execute_command('setDDNSConfig', params, callback=callback)
python
def set_ddns_config(self, isenable, hostname, ddnsserver, user, password, callback=None): ''' Set DDNS config. ''' params = {'isEnable': isenable, 'hostName': hostname, 'ddnsServer': ddnsserver, 'user': user, 'password': password, } return self.execute_command('setDDNSConfig', params, callback=callback)
[ "def", "set_ddns_config", "(", "self", ",", "isenable", ",", "hostname", ",", "ddnsserver", ",", "user", ",", "password", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'isEnable'", ":", "isenable", ",", "'hostName'", ":", "hostname", ",", ...
Set DDNS config.
[ "Set", "DDNS", "config", "." ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L254-L265
train
47,697
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.set_sub_stream_format
def set_sub_stream_format(self, format, callback=None): ''' Set the stream fromat of sub stream???? ''' params = {'format': format} return self.execute_command('setSubStreamFormat', params, callback=callback)
python
def set_sub_stream_format(self, format, callback=None): ''' Set the stream fromat of sub stream???? ''' params = {'format': format} return self.execute_command('setSubStreamFormat', params, callback=callback)
[ "def", "set_sub_stream_format", "(", "self", ",", "format", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'format'", ":", "format", "}", "return", "self", ".", "execute_command", "(", "'setSubStreamFormat'", ",", "params", ",", "callback", "="...
Set the stream fromat of sub stream????
[ "Set", "the", "stream", "fromat", "of", "sub", "stream????" ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L286-L292
train
47,698
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.set_main_video_stream_type
def set_main_video_stream_type(self, streamtype, callback=None): ''' Set the stream type of main stream ''' params = {'streamType': streamtype} return self.execute_command('setMainVideoStreamType', params, callback=callback)
python
def set_main_video_stream_type(self, streamtype, callback=None): ''' Set the stream type of main stream ''' params = {'streamType': streamtype} return self.execute_command('setMainVideoStreamType', params, callback=callback)
[ "def", "set_main_video_stream_type", "(", "self", ",", "streamtype", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'streamType'", ":", "streamtype", "}", "return", "self", ".", "execute_command", "(", "'setMainVideoStreamType'", ",", "params", ","...
Set the stream type of main stream
[ "Set", "the", "stream", "type", "of", "main", "stream" ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L300-L306
train
47,699