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
scot-dev/scot
scot/utils.py
cuthill_mckee
def cuthill_mckee(matrix): """Implementation of the Cuthill-McKee algorithm. Permute a symmetric binary matrix into a band matrix form with a small bandwidth. Parameters ---------- matrix : ndarray, dtype=bool, shape = [n, n] The matrix is internally converted to a symmetric matrix by sett...
python
def cuthill_mckee(matrix): """Implementation of the Cuthill-McKee algorithm. Permute a symmetric binary matrix into a band matrix form with a small bandwidth. Parameters ---------- matrix : ndarray, dtype=bool, shape = [n, n] The matrix is internally converted to a symmetric matrix by sett...
[ "def", "cuthill_mckee", "(", "matrix", ")", ":", "matrix", "=", "np", ".", "atleast_2d", "(", "matrix", ")", "n", ",", "m", "=", "matrix", ".", "shape", "assert", "(", "n", "==", "m", ")", "# make sure the matrix is really symmetric. This is equivalent to", "#...
Implementation of the Cuthill-McKee algorithm. Permute a symmetric binary matrix into a band matrix form with a small bandwidth. Parameters ---------- matrix : ndarray, dtype=bool, shape = [n, n] The matrix is internally converted to a symmetric matrix by setting each element [i,j] to True if ...
[ "Implementation", "of", "the", "Cuthill", "-", "McKee", "algorithm", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/utils.py#L32-L90
train
64,400
scot-dev/scot
scot/connectivity.py
connectivity
def connectivity(measure_names, b, c=None, nfft=512): """Calculate connectivity measures. Parameters ---------- measure_names : str or list of str Name(s) of the connectivity measure(s) to calculate. See :class:`Connectivity` for supported measures. b : array, shape (n_channels, n_c...
python
def connectivity(measure_names, b, c=None, nfft=512): """Calculate connectivity measures. Parameters ---------- measure_names : str or list of str Name(s) of the connectivity measure(s) to calculate. See :class:`Connectivity` for supported measures. b : array, shape (n_channels, n_c...
[ "def", "connectivity", "(", "measure_names", ",", "b", ",", "c", "=", "None", ",", "nfft", "=", "512", ")", ":", "con", "=", "Connectivity", "(", "b", ",", "c", ",", "nfft", ")", "try", ":", "return", "getattr", "(", "con", ",", "measure_names", ")...
Calculate connectivity measures. Parameters ---------- measure_names : str or list of str Name(s) of the connectivity measure(s) to calculate. See :class:`Connectivity` for supported measures. b : array, shape (n_channels, n_channels * model_order) VAR model coefficients. See :r...
[ "Calculate", "connectivity", "measures", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L16-L55
train
64,401
scot-dev/scot
scot/connectivity.py
Connectivity.Cinv
def Cinv(self): """Inverse of the noise covariance.""" try: return np.linalg.inv(self.c) except np.linalg.linalg.LinAlgError: print('Warning: non-invertible noise covariance matrix c.') return np.eye(self.c.shape[0])
python
def Cinv(self): """Inverse of the noise covariance.""" try: return np.linalg.inv(self.c) except np.linalg.linalg.LinAlgError: print('Warning: non-invertible noise covariance matrix c.') return np.eye(self.c.shape[0])
[ "def", "Cinv", "(", "self", ")", ":", "try", ":", "return", "np", ".", "linalg", ".", "inv", "(", "self", ".", "c", ")", "except", "np", ".", "linalg", ".", "linalg", ".", "LinAlgError", ":", "print", "(", "'Warning: non-invertible noise covariance matrix ...
Inverse of the noise covariance.
[ "Inverse", "of", "the", "noise", "covariance", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L147-L153
train
64,402
scot-dev/scot
scot/connectivity.py
Connectivity.A
def A(self): """Spectral VAR coefficients. .. math:: \mathbf{A}(f) = \mathbf{I} - \sum_{k=1}^{p} \mathbf{a}^{(k)} \mathrm{e}^{-2\pi f} """ return fft(np.dstack([np.eye(self.m), -self.b]), self.nfft * 2 - 1)[:, :, :self.nfft]
python
def A(self): """Spectral VAR coefficients. .. math:: \mathbf{A}(f) = \mathbf{I} - \sum_{k=1}^{p} \mathbf{a}^{(k)} \mathrm{e}^{-2\pi f} """ return fft(np.dstack([np.eye(self.m), -self.b]), self.nfft * 2 - 1)[:, :, :self.nfft]
[ "def", "A", "(", "self", ")", ":", "return", "fft", "(", "np", ".", "dstack", "(", "[", "np", ".", "eye", "(", "self", ".", "m", ")", ",", "-", "self", ".", "b", "]", ")", ",", "self", ".", "nfft", "*", "2", "-", "1", ")", "[", ":", ","...
Spectral VAR coefficients. .. math:: \mathbf{A}(f) = \mathbf{I} - \sum_{k=1}^{p} \mathbf{a}^{(k)} \mathrm{e}^{-2\pi f}
[ "Spectral", "VAR", "coefficients", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L156-L163
train
64,403
scot-dev/scot
scot/connectivity.py
Connectivity.S
def S(self): """Cross-spectral density. .. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f) """ if self.c is None: raise RuntimeError('Cross-spectral density requires noise ' 'covariance matrix c.') H = self.H() # ...
python
def S(self): """Cross-spectral density. .. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f) """ if self.c is None: raise RuntimeError('Cross-spectral density requires noise ' 'covariance matrix c.') H = self.H() # ...
[ "def", "S", "(", "self", ")", ":", "if", "self", ".", "c", "is", "None", ":", "raise", "RuntimeError", "(", "'Cross-spectral density requires noise '", "'covariance matrix c.'", ")", "H", "=", "self", ".", "H", "(", ")", "# TODO: can we do that more efficiently?",...
Cross-spectral density. .. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f)
[ "Cross", "-", "spectral", "density", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L174-L187
train
64,404
scot-dev/scot
scot/connectivity.py
Connectivity.G
def G(self): """Inverse cross-spectral density. .. math:: \mathbf{G}(f) = \mathbf{A}(f) \mathbf{C}^{-1} \mathbf{A}'(f) """ if self.c is None: raise RuntimeError('Inverse cross spectral density requires ' 'invertible noise covariance matrix c.')...
python
def G(self): """Inverse cross-spectral density. .. math:: \mathbf{G}(f) = \mathbf{A}(f) \mathbf{C}^{-1} \mathbf{A}'(f) """ if self.c is None: raise RuntimeError('Inverse cross spectral density requires ' 'invertible noise covariance matrix c.')...
[ "def", "G", "(", "self", ")", ":", "if", "self", ".", "c", "is", "None", ":", "raise", "RuntimeError", "(", "'Inverse cross spectral density requires '", "'invertible noise covariance matrix c.'", ")", "A", "=", "self", ".", "A", "(", ")", "# TODO: can we do that ...
Inverse cross-spectral density. .. math:: \mathbf{G}(f) = \mathbf{A}(f) \mathbf{C}^{-1} \mathbf{A}'(f)
[ "Inverse", "cross", "-", "spectral", "density", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L206-L218
train
64,405
scot-dev/scot
scot/connectivity.py
Connectivity.pCOH
def pCOH(self): """Partial coherence. .. math:: \mathrm{pCOH}_{ij}(f) = \\frac{G_{ij}(f)} {\sqrt{G_{ii}(f) G_{jj}(f)}} References ---------- P. J. Franaszczuk, K. J. Blinowska, M. Kowalczyk. The application of parametric m...
python
def pCOH(self): """Partial coherence. .. math:: \mathrm{pCOH}_{ij}(f) = \\frac{G_{ij}(f)} {\sqrt{G_{ii}(f) G_{jj}(f)}} References ---------- P. J. Franaszczuk, K. J. Blinowska, M. Kowalczyk. The application of parametric m...
[ "def", "pCOH", "(", "self", ")", ":", "G", "=", "self", ".", "G", "(", ")", "# TODO: can we do that more efficiently?", "return", "G", "/", "np", ".", "sqrt", "(", "np", ".", "einsum", "(", "'ii..., jj... ->ij...'", ",", "G", ",", "G", ")", ")" ]
Partial coherence. .. math:: \mathrm{pCOH}_{ij}(f) = \\frac{G_{ij}(f)} {\sqrt{G_{ii}(f) G_{jj}(f)}} References ---------- P. J. Franaszczuk, K. J. Blinowska, M. Kowalczyk. The application of parametric multichannel spectral estima...
[ "Partial", "coherence", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L256-L270
train
64,406
scot-dev/scot
scot/connectivity.py
Connectivity.PDC
def PDC(self): """Partial directed coherence. .. math:: \mathrm{PDC}_{ij}(f) = \\frac{A_{ij}(f)} {\sqrt{A_{:j}'(f) A_{:j}(f)}} References ---------- L. A. Baccalá, K. Sameshima. Partial directed coherence: a new concept in ...
python
def PDC(self): """Partial directed coherence. .. math:: \mathrm{PDC}_{ij}(f) = \\frac{A_{ij}(f)} {\sqrt{A_{:j}'(f) A_{:j}(f)}} References ---------- L. A. Baccalá, K. Sameshima. Partial directed coherence: a new concept in ...
[ "def", "PDC", "(", "self", ")", ":", "A", "=", "self", ".", "A", "(", ")", "return", "np", ".", "abs", "(", "A", "/", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "A", ".", "conj", "(", ")", "*", "A", ",", "axis", "=", "0", ",", "keep...
Partial directed coherence. .. math:: \mathrm{PDC}_{ij}(f) = \\frac{A_{ij}(f)} {\sqrt{A_{:j}'(f) A_{:j}(f)}} References ---------- L. A. Baccalá, K. Sameshima. Partial directed coherence: a new concept in neural structure determina...
[ "Partial", "directed", "coherence", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L273-L286
train
64,407
scot-dev/scot
scot/connectivity.py
Connectivity.ffPDC
def ffPDC(self): """Full frequency partial directed coherence. .. math:: \mathrm{ffPDC}_{ij}(f) = \\frac{A_{ij}(f)}{\sqrt{\sum_f A_{:j}'(f) A_{:j}(f)}} """ A = self.A() return np.abs(A * self.nfft / np.sqrt(np.sum(A.conj() * A, axis=(0, 2), ...
python
def ffPDC(self): """Full frequency partial directed coherence. .. math:: \mathrm{ffPDC}_{ij}(f) = \\frac{A_{ij}(f)}{\sqrt{\sum_f A_{:j}'(f) A_{:j}(f)}} """ A = self.A() return np.abs(A * self.nfft / np.sqrt(np.sum(A.conj() * A, axis=(0, 2), ...
[ "def", "ffPDC", "(", "self", ")", ":", "A", "=", "self", ".", "A", "(", ")", "return", "np", ".", "abs", "(", "A", "*", "self", ".", "nfft", "/", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "A", ".", "conj", "(", ")", "*", "A", ",", ...
Full frequency partial directed coherence. .. math:: \mathrm{ffPDC}_{ij}(f) = \\frac{A_{ij}(f)}{\sqrt{\sum_f A_{:j}'(f) A_{:j}(f)}}
[ "Full", "frequency", "partial", "directed", "coherence", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L305-L313
train
64,408
scot-dev/scot
scot/connectivity.py
Connectivity.PDCF
def PDCF(self): """Partial directed coherence factor. .. math:: \mathrm{PDCF}_{ij}(f) = \\frac{A_{ij}(f)}{\sqrt{A_{:j}'(f) \mathbf{C}^{-1} A_{:j}(f)}} References ---------- L. A. Baccalá, K. Sameshima. Partial directed coherence: a new concept in neural structur...
python
def PDCF(self): """Partial directed coherence factor. .. math:: \mathrm{PDCF}_{ij}(f) = \\frac{A_{ij}(f)}{\sqrt{A_{:j}'(f) \mathbf{C}^{-1} A_{:j}(f)}} References ---------- L. A. Baccalá, K. Sameshima. Partial directed coherence: a new concept in neural structur...
[ "def", "PDCF", "(", "self", ")", ":", "A", "=", "self", ".", "A", "(", ")", "# TODO: can we do that more efficiently?", "return", "np", ".", "abs", "(", "A", "/", "np", ".", "sqrt", "(", "np", ".", "einsum", "(", "'aj..., ab..., bj... ->j...'", ",", "A",...
Partial directed coherence factor. .. math:: \mathrm{PDCF}_{ij}(f) = \\frac{A_{ij}(f)}{\sqrt{A_{:j}'(f) \mathbf{C}^{-1} A_{:j}(f)}} References ---------- L. A. Baccalá, K. Sameshima. Partial directed coherence: a new concept in neural structure determination. Biol. Cybe...
[ "Partial", "directed", "coherence", "factor", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L316-L331
train
64,409
scot-dev/scot
scot/connectivity.py
Connectivity.GPDC
def GPDC(self): """Generalized partial directed coherence. .. math:: \mathrm{GPDC}_{ij}(f) = \\frac{|A_{ij}(f)|} {\sigma_i \sqrt{A_{:j}'(f) \mathrm{diag}(\mathbf{C})^{-1} A_{:j}(f)}} References ---------- L. Faes, S. Erla, G. Nollo. Measuring connectivity in linear ...
python
def GPDC(self): """Generalized partial directed coherence. .. math:: \mathrm{GPDC}_{ij}(f) = \\frac{|A_{ij}(f)|} {\sigma_i \sqrt{A_{:j}'(f) \mathrm{diag}(\mathbf{C})^{-1} A_{:j}(f)}} References ---------- L. Faes, S. Erla, G. Nollo. Measuring connectivity in linear ...
[ "def", "GPDC", "(", "self", ")", ":", "A", "=", "self", ".", "A", "(", ")", "tmp", "=", "A", "/", "np", ".", "sqrt", "(", "np", ".", "einsum", "(", "'aj..., a..., aj..., ii... ->ij...'", ",", "A", ".", "conj", "(", ")", ",", "1", "/", "np", "."...
Generalized partial directed coherence. .. math:: \mathrm{GPDC}_{ij}(f) = \\frac{|A_{ij}(f)|} {\sigma_i \sqrt{A_{:j}'(f) \mathrm{diag}(\mathbf{C})^{-1} A_{:j}(f)}} References ---------- L. Faes, S. Erla, G. Nollo. Measuring connectivity in linear multivariate processes:...
[ "Generalized", "partial", "directed", "coherence", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L334-L349
train
64,410
scot-dev/scot
scot/connectivity.py
Connectivity.DTF
def DTF(self): """Directed transfer function. .. math:: \mathrm{DTF}_{ij}(f) = \\frac{H_{ij}(f)} {\sqrt{H_{i:}(f) H_{i:}'(f)}} References ---------- M. J. Kaminski, K. J. Blinowska. A new method of the description of the in...
python
def DTF(self): """Directed transfer function. .. math:: \mathrm{DTF}_{ij}(f) = \\frac{H_{ij}(f)} {\sqrt{H_{i:}(f) H_{i:}'(f)}} References ---------- M. J. Kaminski, K. J. Blinowska. A new method of the description of the in...
[ "def", "DTF", "(", "self", ")", ":", "H", "=", "self", ".", "H", "(", ")", "return", "np", ".", "abs", "(", "H", "/", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "H", "*", "H", ".", "conj", "(", ")", ",", "axis", "=", "1", ",", "keep...
Directed transfer function. .. math:: \mathrm{DTF}_{ij}(f) = \\frac{H_{ij}(f)} {\sqrt{H_{i:}(f) H_{i:}'(f)}} References ---------- M. J. Kaminski, K. J. Blinowska. A new method of the description of the information flow in the brai...
[ "Directed", "transfer", "function", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L352-L365
train
64,411
scot-dev/scot
scot/connectivity.py
Connectivity.ffDTF
def ffDTF(self): """Full frequency directed transfer function. .. math:: \mathrm{ffDTF}_{ij}(f) = \\frac{H_{ij}(f)}{\sqrt{\sum_f H_{i:}(f) H_{i:}'(f)}} References ---------- A. Korzeniewska, M. Mańczak, M. Kaminski, K. J. Blinowska, S. Kasicki. Determi...
python
def ffDTF(self): """Full frequency directed transfer function. .. math:: \mathrm{ffDTF}_{ij}(f) = \\frac{H_{ij}(f)}{\sqrt{\sum_f H_{i:}(f) H_{i:}'(f)}} References ---------- A. Korzeniewska, M. Mańczak, M. Kaminski, K. J. Blinowska, S. Kasicki. Determi...
[ "def", "ffDTF", "(", "self", ")", ":", "H", "=", "self", ".", "H", "(", ")", "return", "np", ".", "abs", "(", "H", "*", "self", ".", "nfft", "/", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "H", "*", "H", ".", "conj", "(", ")", ",", ...
Full frequency directed transfer function. .. math:: \mathrm{ffDTF}_{ij}(f) = \\frac{H_{ij}(f)}{\sqrt{\sum_f H_{i:}(f) H_{i:}'(f)}} References ---------- A. Korzeniewska, M. Mańczak, M. Kaminski, K. J. Blinowska, S. Kasicki. Determination of information flow d...
[ "Full", "frequency", "directed", "transfer", "function", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L368-L383
train
64,412
scot-dev/scot
scot/connectivity.py
Connectivity.GDTF
def GDTF(self): """Generalized directed transfer function. .. math:: \mathrm{GPDC}_{ij}(f) = \\frac{\sigma_j |H_{ij}(f)|} {\sqrt{H_{i:}(f) \mathrm{diag}(\mathbf{C}) H_{i:}'(f)}} References ---------- L. Faes, S. Erla, G. Nollo. Measuring connectivity in linear ...
python
def GDTF(self): """Generalized directed transfer function. .. math:: \mathrm{GPDC}_{ij}(f) = \\frac{\sigma_j |H_{ij}(f)|} {\sqrt{H_{i:}(f) \mathrm{diag}(\mathbf{C}) H_{i:}'(f)}} References ---------- L. Faes, S. Erla, G. Nollo. Measuring connectivity in linear ...
[ "def", "GDTF", "(", "self", ")", ":", "H", "=", "self", ".", "H", "(", ")", "tmp", "=", "H", "/", "np", ".", "sqrt", "(", "np", ".", "einsum", "(", "'ia..., aa..., ia..., j... ->ij...'", ",", "H", ".", "conj", "(", ")", ",", "self", ".", "c", "...
Generalized directed transfer function. .. math:: \mathrm{GPDC}_{ij}(f) = \\frac{\sigma_j |H_{ij}(f)|} {\sqrt{H_{i:}(f) \mathrm{diag}(\mathbf{C}) H_{i:}'(f)}} References ---------- L. Faes, S. Erla, G. Nollo. Measuring connectivity in linear multivariate processes: ...
[ "Generalized", "directed", "transfer", "function", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L402-L418
train
64,413
kolypto/py-good
good/schema/errors.py
Invalid.enrich
def enrich(self, expected=None, provided=None, path=None, validator=None): """ Enrich this error with additional information. This works with both Invalid and MultipleInvalid (thanks to `Invalid` being iterable): in the latter case, the defaults are applied to all collected errors. The...
python
def enrich(self, expected=None, provided=None, path=None, validator=None): """ Enrich this error with additional information. This works with both Invalid and MultipleInvalid (thanks to `Invalid` being iterable): in the latter case, the defaults are applied to all collected errors. The...
[ "def", "enrich", "(", "self", ",", "expected", "=", "None", ",", "provided", "=", "None", ",", "path", "=", "None", ",", "validator", "=", "None", ")", ":", "for", "e", "in", "self", ":", "# defaults on fields", "if", "e", ".", "expected", "is", "Non...
Enrich this error with additional information. This works with both Invalid and MultipleInvalid (thanks to `Invalid` being iterable): in the latter case, the defaults are applied to all collected errors. The specified arguments are only set on `Invalid` errors which do not have any value on th...
[ "Enrich", "this", "error", "with", "additional", "information", "." ]
192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4
https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/schema/errors.py#L101-L150
train
64,414
kolypto/py-good
good/schema/errors.py
MultipleInvalid.flatten
def flatten(cls, errors): """ Unwind `MultipleErrors` to have a plain list of `Invalid` :type errors: list[Invalid|MultipleInvalid] :rtype: list[Invalid] """ ers = [] for e in errors: if isinstance(e, MultipleInvalid): ers.extend(cls.flatten(e...
python
def flatten(cls, errors): """ Unwind `MultipleErrors` to have a plain list of `Invalid` :type errors: list[Invalid|MultipleInvalid] :rtype: list[Invalid] """ ers = [] for e in errors: if isinstance(e, MultipleInvalid): ers.extend(cls.flatten(e...
[ "def", "flatten", "(", "cls", ",", "errors", ")", ":", "ers", "=", "[", "]", "for", "e", "in", "errors", ":", "if", "isinstance", "(", "e", ",", "MultipleInvalid", ")", ":", "ers", ".", "extend", "(", "cls", ".", "flatten", "(", "e", ".", "errors...
Unwind `MultipleErrors` to have a plain list of `Invalid` :type errors: list[Invalid|MultipleInvalid] :rtype: list[Invalid]
[ "Unwind", "MultipleErrors", "to", "have", "a", "plain", "list", "of", "Invalid" ]
192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4
https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/schema/errors.py#L208-L220
train
64,415
scot-dev/scot
scot/eegtopo/warp_layout.py
warp_locations
def warp_locations(locations, y_center=None, return_ellipsoid=False, verbose=False): """ Warp EEG electrode locations to spherical layout. EEG Electrodes are warped to a spherical layout in three steps: 1. An ellipsoid is least-squares-fitted to the electrode locations. 2. Electrodes are displa...
python
def warp_locations(locations, y_center=None, return_ellipsoid=False, verbose=False): """ Warp EEG electrode locations to spherical layout. EEG Electrodes are warped to a spherical layout in three steps: 1. An ellipsoid is least-squares-fitted to the electrode locations. 2. Electrodes are displa...
[ "def", "warp_locations", "(", "locations", ",", "y_center", "=", "None", ",", "return_ellipsoid", "=", "False", ",", "verbose", "=", "False", ")", ":", "locations", "=", "np", ".", "asarray", "(", "locations", ")", "if", "y_center", "is", "None", ":", "c...
Warp EEG electrode locations to spherical layout. EEG Electrodes are warped to a spherical layout in three steps: 1. An ellipsoid is least-squares-fitted to the electrode locations. 2. Electrodes are displaced to the nearest point on the ellipsoid's surface. 3. The ellipsoid is transformed ...
[ "Warp", "EEG", "electrode", "locations", "to", "spherical", "layout", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/eegtopo/warp_layout.py#L15-L68
train
64,416
scot-dev/scot
scot/eegtopo/warp_layout.py
_project_on_ellipsoid
def _project_on_ellipsoid(c, r, locations): """displace locations to the nearest point on ellipsoid surface""" p0 = locations - c # original locations l2 = 1 / np.sum(p0**2 / r**2, axis=1, keepdims=True) p = p0 * np.sqrt(l2) # initial approximation (projection of points towards center of ellipsoid) ...
python
def _project_on_ellipsoid(c, r, locations): """displace locations to the nearest point on ellipsoid surface""" p0 = locations - c # original locations l2 = 1 / np.sum(p0**2 / r**2, axis=1, keepdims=True) p = p0 * np.sqrt(l2) # initial approximation (projection of points towards center of ellipsoid) ...
[ "def", "_project_on_ellipsoid", "(", "c", ",", "r", ",", "locations", ")", ":", "p0", "=", "locations", "-", "c", "# original locations", "l2", "=", "1", "/", "np", ".", "sum", "(", "p0", "**", "2", "/", "r", "**", "2", ",", "axis", "=", "1", ","...
displace locations to the nearest point on ellipsoid surface
[ "displace", "locations", "to", "the", "nearest", "point", "on", "ellipsoid", "surface" ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/eegtopo/warp_layout.py#L96-L107
train
64,417
scot-dev/scot
scot/datatools.py
cut_segments
def cut_segments(x2d, tr, start, stop): """Cut continuous signal into segments. Parameters ---------- x2d : array, shape (m, n) Input data with m signals and n samples. tr : list of int Trigger positions. start : int Window start (offset relative to trigger). stop : ...
python
def cut_segments(x2d, tr, start, stop): """Cut continuous signal into segments. Parameters ---------- x2d : array, shape (m, n) Input data with m signals and n samples. tr : list of int Trigger positions. start : int Window start (offset relative to trigger). stop : ...
[ "def", "cut_segments", "(", "x2d", ",", "tr", ",", "start", ",", "stop", ")", ":", "if", "start", "!=", "int", "(", "start", ")", ":", "raise", "ValueError", "(", "\"start index must be an integer\"", ")", "if", "stop", "!=", "int", "(", "stop", ")", "...
Cut continuous signal into segments. Parameters ---------- x2d : array, shape (m, n) Input data with m signals and n samples. tr : list of int Trigger positions. start : int Window start (offset relative to trigger). stop : int Window end (offset relative to trig...
[ "Cut", "continuous", "signal", "into", "segments", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/datatools.py#L28-L68
train
64,418
scot-dev/scot
scot/datatools.py
cat_trials
def cat_trials(x3d): """Concatenate trials along time axis. Parameters ---------- x3d : array, shape (t, m, n) Segmented input data with t trials, m signals, and n samples. Returns ------- x2d : array, shape (m, t * n) Trials are concatenated along the second axis. See...
python
def cat_trials(x3d): """Concatenate trials along time axis. Parameters ---------- x3d : array, shape (t, m, n) Segmented input data with t trials, m signals, and n samples. Returns ------- x2d : array, shape (m, t * n) Trials are concatenated along the second axis. See...
[ "def", "cat_trials", "(", "x3d", ")", ":", "x3d", "=", "atleast_3d", "(", "x3d", ")", "t", "=", "x3d", ".", "shape", "[", "0", "]", "return", "np", ".", "concatenate", "(", "np", ".", "split", "(", "x3d", ",", "t", ",", "0", ")", ",", "axis", ...
Concatenate trials along time axis. Parameters ---------- x3d : array, shape (t, m, n) Segmented input data with t trials, m signals, and n samples. Returns ------- x2d : array, shape (m, t * n) Trials are concatenated along the second axis. See also -------- cut_s...
[ "Concatenate", "trials", "along", "time", "axis", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/datatools.py#L71-L97
train
64,419
scot-dev/scot
scot/datatools.py
dot_special
def dot_special(x2d, x3d): """Segment-wise dot product. This function calculates the dot product of x2d with each trial of x3d. Parameters ---------- x2d : array, shape (p, m) Input argument. x3d : array, shape (t, m, n) Segmented input data with t trials, m signals, and n samp...
python
def dot_special(x2d, x3d): """Segment-wise dot product. This function calculates the dot product of x2d with each trial of x3d. Parameters ---------- x2d : array, shape (p, m) Input argument. x3d : array, shape (t, m, n) Segmented input data with t trials, m signals, and n samp...
[ "def", "dot_special", "(", "x2d", ",", "x3d", ")", ":", "x3d", "=", "atleast_3d", "(", "x3d", ")", "x2d", "=", "np", ".", "atleast_2d", "(", "x2d", ")", "return", "np", ".", "concatenate", "(", "[", "x2d", ".", "dot", "(", "x3d", "[", "i", ",", ...
Segment-wise dot product. This function calculates the dot product of x2d with each trial of x3d. Parameters ---------- x2d : array, shape (p, m) Input argument. x3d : array, shape (t, m, n) Segmented input data with t trials, m signals, and n samples. The dot product with ...
[ "Segment", "-", "wise", "dot", "product", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/datatools.py#L100-L129
train
64,420
scot-dev/scot
scot/datatools.py
randomize_phase
def randomize_phase(data, random_state=None): """Phase randomization. This function randomizes the spectral phase of the input data along the last dimension. Parameters ---------- data : array Input array. Returns ------- out : array Array of same shape as data. ...
python
def randomize_phase(data, random_state=None): """Phase randomization. This function randomizes the spectral phase of the input data along the last dimension. Parameters ---------- data : array Input array. Returns ------- out : array Array of same shape as data. ...
[ "def", "randomize_phase", "(", "data", ",", "random_state", "=", "None", ")", ":", "rng", "=", "check_random_state", "(", "random_state", ")", "data", "=", "np", ".", "asarray", "(", "data", ")", "data_freq", "=", "np", ".", "fft", ".", "rfft", "(", "d...
Phase randomization. This function randomizes the spectral phase of the input data along the last dimension. Parameters ---------- data : array Input array. Returns ------- out : array Array of same shape as data. Notes ----- The algorithm randomizes the p...
[ "Phase", "randomization", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/datatools.py#L132-L175
train
64,421
scot-dev/scot
scot/datatools.py
acm
def acm(x, l): """Compute autocovariance matrix at lag l. This function calculates the autocovariance matrix of `x` at lag `l`. Parameters ---------- x : array, shape (n_trials, n_channels, n_samples) Signal data (2D or 3D for multiple trials) l : int Lag Returns -----...
python
def acm(x, l): """Compute autocovariance matrix at lag l. This function calculates the autocovariance matrix of `x` at lag `l`. Parameters ---------- x : array, shape (n_trials, n_channels, n_samples) Signal data (2D or 3D for multiple trials) l : int Lag Returns -----...
[ "def", "acm", "(", "x", ",", "l", ")", ":", "x", "=", "atleast_3d", "(", "x", ")", "if", "l", ">", "x", ".", "shape", "[", "2", "]", "-", "1", ":", "raise", "AttributeError", "(", "\"lag exceeds data length\"", ")", "## subtract mean from each trial", ...
Compute autocovariance matrix at lag l. This function calculates the autocovariance matrix of `x` at lag `l`. Parameters ---------- x : array, shape (n_trials, n_channels, n_samples) Signal data (2D or 3D for multiple trials) l : int Lag Returns ------- c : ndarray, sh...
[ "Compute", "autocovariance", "matrix", "at", "lag", "l", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/datatools.py#L178-L215
train
64,422
scot-dev/scot
scot/connectivity_statistics.py
jackknife_connectivity
def jackknife_connectivity(measures, data, var, nfft=512, leaveout=1, n_jobs=1, verbose=0): """Calculate jackknife estimates of connectivity. For each jackknife estimate a block of trials is left out. This is repeated until each trial was left out exactly once. The number of esti...
python
def jackknife_connectivity(measures, data, var, nfft=512, leaveout=1, n_jobs=1, verbose=0): """Calculate jackknife estimates of connectivity. For each jackknife estimate a block of trials is left out. This is repeated until each trial was left out exactly once. The number of esti...
[ "def", "jackknife_connectivity", "(", "measures", ",", "data", ",", "var", ",", "nfft", "=", "512", ",", "leaveout", "=", "1", ",", "n_jobs", "=", "1", ",", "verbose", "=", "0", ")", ":", "data", "=", "atleast_3d", "(", "data", ")", "t", ",", "m", ...
Calculate jackknife estimates of connectivity. For each jackknife estimate a block of trials is left out. This is repeated until each trial was left out exactly once. The number of estimates depends on the number of trials and the value of `leaveout`. It is calculated by repeats = `n_trials` // `leaveo...
[ "Calculate", "jackknife", "estimates", "of", "connectivity", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity_statistics.py#L67-L123
train
64,423
scot-dev/scot
scot/connectivity_statistics.py
bootstrap_connectivity
def bootstrap_connectivity(measures, data, var, nfft=512, repeats=100, num_samples=None, n_jobs=1, verbose=0, random_state=None): """Calculate bootstrap estimates of connectivity. To obtain a bootstrap estimate trials are sampled randomly with replacement ...
python
def bootstrap_connectivity(measures, data, var, nfft=512, repeats=100, num_samples=None, n_jobs=1, verbose=0, random_state=None): """Calculate bootstrap estimates of connectivity. To obtain a bootstrap estimate trials are sampled randomly with replacement ...
[ "def", "bootstrap_connectivity", "(", "measures", ",", "data", ",", "var", ",", "nfft", "=", "512", ",", "repeats", "=", "100", ",", "num_samples", "=", "None", ",", "n_jobs", "=", "1", ",", "verbose", "=", "0", ",", "random_state", "=", "None", ")", ...
Calculate bootstrap estimates of connectivity. To obtain a bootstrap estimate trials are sampled randomly with replacement from the data set. .. note:: Parameter `var` will be modified by the function. Treat as undefined after the function returns. Parameters ---------- measures : str or ...
[ "Calculate", "bootstrap", "estimates", "of", "connectivity", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity_statistics.py#L131-L188
train
64,424
scot-dev/scot
scot/connectivity_statistics.py
significance_fdr
def significance_fdr(p, alpha): """Calculate significance by controlling for the false discovery rate. This function determines which of the p-values in `p` can be considered significant. Correction for multiple comparisons is performed by controlling the false discovery rate (FDR). The FDR is the maxi...
python
def significance_fdr(p, alpha): """Calculate significance by controlling for the false discovery rate. This function determines which of the p-values in `p` can be considered significant. Correction for multiple comparisons is performed by controlling the false discovery rate (FDR). The FDR is the maxi...
[ "def", "significance_fdr", "(", "p", ",", "alpha", ")", ":", "i", "=", "np", ".", "argsort", "(", "p", ",", "axis", "=", "None", ")", "m", "=", "i", ".", "size", "-", "np", ".", "sum", "(", "np", ".", "isnan", "(", "p", ")", ")", "j", "=", ...
Calculate significance by controlling for the false discovery rate. This function determines which of the p-values in `p` can be considered significant. Correction for multiple comparisons is performed by controlling the false discovery rate (FDR). The FDR is the maximum fraction of p-values that are w...
[ "Calculate", "significance", "by", "controlling", "for", "the", "false", "discovery", "rate", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity_statistics.py#L252-L295
train
64,425
kolypto/py-good
good/schema/util.py
register_type_name
def register_type_name(t, name): """ Register a human-friendly name for the given type. This will be used in Invalid errors :param t: The type to register :type t: type :param name: Name for the type :type name: unicode """ assert isinstance(t, type) assert isinstance(name, unicode) ...
python
def register_type_name(t, name): """ Register a human-friendly name for the given type. This will be used in Invalid errors :param t: The type to register :type t: type :param name: Name for the type :type name: unicode """ assert isinstance(t, type) assert isinstance(name, unicode) ...
[ "def", "register_type_name", "(", "t", ",", "name", ")", ":", "assert", "isinstance", "(", "t", ",", "type", ")", "assert", "isinstance", "(", "name", ",", "unicode", ")", "__type_names", "[", "t", "]", "=", "name" ]
Register a human-friendly name for the given type. This will be used in Invalid errors :param t: The type to register :type t: type :param name: Name for the type :type name: unicode
[ "Register", "a", "human", "-", "friendly", "name", "for", "the", "given", "type", ".", "This", "will", "be", "used", "in", "Invalid", "errors" ]
192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4
https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/schema/util.py#L61-L71
train
64,426
kolypto/py-good
good/schema/util.py
get_type_name
def get_type_name(t): """ Get a human-friendly name for the given type. :type t: type|None :rtype: unicode """ # Lookup in the mapping try: return __type_names[t] except KeyError: # Specific types if issubclass(t, six.integer_types): return _(u'Integer nu...
python
def get_type_name(t): """ Get a human-friendly name for the given type. :type t: type|None :rtype: unicode """ # Lookup in the mapping try: return __type_names[t] except KeyError: # Specific types if issubclass(t, six.integer_types): return _(u'Integer nu...
[ "def", "get_type_name", "(", "t", ")", ":", "# Lookup in the mapping", "try", ":", "return", "__type_names", "[", "t", "]", "except", "KeyError", ":", "# Specific types", "if", "issubclass", "(", "t", ",", "six", ".", "integer_types", ")", ":", "return", "_"...
Get a human-friendly name for the given type. :type t: type|None :rtype: unicode
[ "Get", "a", "human", "-", "friendly", "name", "for", "the", "given", "type", "." ]
192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4
https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/schema/util.py#L84-L99
train
64,427
kolypto/py-good
good/schema/util.py
get_callable_name
def get_callable_name(c): """ Get a human-friendly name for the given callable. :param c: The callable to get the name for :type c: callable :rtype: unicode """ if hasattr(c, 'name'): return six.text_type(c.name) elif hasattr(c, '__name__'): return six.text_type(c.__name__) ...
python
def get_callable_name(c): """ Get a human-friendly name for the given callable. :param c: The callable to get the name for :type c: callable :rtype: unicode """ if hasattr(c, 'name'): return six.text_type(c.name) elif hasattr(c, '__name__'): return six.text_type(c.__name__) ...
[ "def", "get_callable_name", "(", "c", ")", ":", "if", "hasattr", "(", "c", ",", "'name'", ")", ":", "return", "six", ".", "text_type", "(", "c", ".", "name", ")", "elif", "hasattr", "(", "c", ",", "'__name__'", ")", ":", "return", "six", ".", "text...
Get a human-friendly name for the given callable. :param c: The callable to get the name for :type c: callable :rtype: unicode
[ "Get", "a", "human", "-", "friendly", "name", "for", "the", "given", "callable", "." ]
192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4
https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/schema/util.py#L102-L114
train
64,428
kolypto/py-good
good/schema/util.py
get_primitive_name
def get_primitive_name(schema): """ Get a human-friendly name for the given primitive. :param schema: Schema :type schema: * :rtype: unicode """ try: return { const.COMPILED_TYPE.LITERAL: six.text_type, const.COMPILED_TYPE.TYPE: get_type_name, const.C...
python
def get_primitive_name(schema): """ Get a human-friendly name for the given primitive. :param schema: Schema :type schema: * :rtype: unicode """ try: return { const.COMPILED_TYPE.LITERAL: six.text_type, const.COMPILED_TYPE.TYPE: get_type_name, const.C...
[ "def", "get_primitive_name", "(", "schema", ")", ":", "try", ":", "return", "{", "const", ".", "COMPILED_TYPE", ".", "LITERAL", ":", "six", ".", "text_type", ",", "const", ".", "COMPILED_TYPE", ".", "TYPE", ":", "get_type_name", ",", "const", ".", "COMPILE...
Get a human-friendly name for the given primitive. :param schema: Schema :type schema: * :rtype: unicode
[ "Get", "a", "human", "-", "friendly", "name", "for", "the", "given", "primitive", "." ]
192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4
https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/schema/util.py#L117-L134
train
64,429
kolypto/py-good
good/schema/util.py
primitive_type
def primitive_type(schema): """ Get schema type for the primitive argument. Note: it does treats markers & schemas as callables! :param schema: Value of a primitive type :type schema: * :return: const.COMPILED_TYPE.* :rtype: str|None """ schema_type = type(schema) # Literal if...
python
def primitive_type(schema): """ Get schema type for the primitive argument. Note: it does treats markers & schemas as callables! :param schema: Value of a primitive type :type schema: * :return: const.COMPILED_TYPE.* :rtype: str|None """ schema_type = type(schema) # Literal if...
[ "def", "primitive_type", "(", "schema", ")", ":", "schema_type", "=", "type", "(", "schema", ")", "# Literal", "if", "schema_type", "in", "const", ".", "literal_types", ":", "return", "const", ".", "COMPILED_TYPE", ".", "LITERAL", "# Enum", "elif", "Enum", "...
Get schema type for the primitive argument. Note: it does treats markers & schemas as callables! :param schema: Value of a primitive type :type schema: * :return: const.COMPILED_TYPE.* :rtype: str|None
[ "Get", "schema", "type", "for", "the", "primitive", "argument", "." ]
192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4
https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/schema/util.py#L179-L211
train
64,430
kolypto/py-good
good/schema/util.py
commajoin_as_strings
def commajoin_as_strings(iterable): """ Join the given iterable with ',' """ return _(u',').join((six.text_type(i) for i in iterable))
python
def commajoin_as_strings(iterable): """ Join the given iterable with ',' """ return _(u',').join((six.text_type(i) for i in iterable))
[ "def", "commajoin_as_strings", "(", "iterable", ")", ":", "return", "_", "(", "u','", ")", ".", "join", "(", "(", "six", ".", "text_type", "(", "i", ")", "for", "i", "in", "iterable", ")", ")" ]
Join the given iterable with ','
[ "Join", "the", "given", "iterable", "with" ]
192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4
https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/schema/util.py#L213-L215
train
64,431
scot-dev/scot
scot/plotting.py
prepare_topoplots
def prepare_topoplots(topo, values): """Prepare multiple topo maps for cached plotting. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_values`. Parameters ---------- topo : :class:`~eegtopo.topoplot.Topoplot` Scalp maps are created w...
python
def prepare_topoplots(topo, values): """Prepare multiple topo maps for cached plotting. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_values`. Parameters ---------- topo : :class:`~eegtopo.topoplot.Topoplot` Scalp maps are created w...
[ "def", "prepare_topoplots", "(", "topo", ",", "values", ")", ":", "values", "=", "np", ".", "atleast_2d", "(", "values", ")", "topomaps", "=", "[", "]", "for", "i", "in", "range", "(", "values", ".", "shape", "[", "0", "]", ")", ":", "topo", ".", ...
Prepare multiple topo maps for cached plotting. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_values`. Parameters ---------- topo : :class:`~eegtopo.topoplot.Topoplot` Scalp maps are created with this class values : array, shape = [...
[ "Prepare", "multiple", "topo", "maps", "for", "cached", "plotting", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/plotting.py#L35-L61
train
64,432
scot-dev/scot
scot/plotting.py
plot_topo
def plot_topo(axis, topo, topomap, crange=None, offset=(0,0), plot_locations=True, plot_head=True): """Draw a topoplot in given axis. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- axis : axis ...
python
def plot_topo(axis, topo, topomap, crange=None, offset=(0,0), plot_locations=True, plot_head=True): """Draw a topoplot in given axis. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- axis : axis ...
[ "def", "plot_topo", "(", "axis", ",", "topo", ",", "topomap", ",", "crange", "=", "None", ",", "offset", "=", "(", "0", ",", "0", ")", ",", "plot_locations", "=", "True", ",", "plot_head", "=", "True", ")", ":", "topo", ".", "set_map", "(", "topoma...
Draw a topoplot in given axis. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- axis : axis Axis to draw into. topo : :class:`~eegtopo.topoplot.Topoplot` This object draws the topo plot topomap :...
[ "Draw", "a", "topoplot", "in", "given", "axis", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/plotting.py#L64-L99
train
64,433
scot-dev/scot
scot/plotting.py
plot_sources
def plot_sources(topo, mixmaps, unmixmaps, global_scale=None, fig=None): """Plot all scalp projections of mixing- and unmixing-maps. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- topo : :class:`~eegtopo.topoplot....
python
def plot_sources(topo, mixmaps, unmixmaps, global_scale=None, fig=None): """Plot all scalp projections of mixing- and unmixing-maps. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- topo : :class:`~eegtopo.topoplot....
[ "def", "plot_sources", "(", "topo", ",", "mixmaps", ",", "unmixmaps", ",", "global_scale", "=", "None", ",", "fig", "=", "None", ")", ":", "urange", ",", "mrange", "=", "None", ",", "None", "m", "=", "len", "(", "mixmaps", ")", "if", "global_scale", ...
Plot all scalp projections of mixing- and unmixing-maps. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- topo : :class:`~eegtopo.topoplot.Topoplot` This object draws the topo plot mixmaps : array, shape = [...
[ "Plot", "all", "scalp", "projections", "of", "mixing", "-", "and", "unmixing", "-", "maps", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/plotting.py#L102-L167
train
64,434
scot-dev/scot
scot/plotting.py
plot_connectivity_topos
def plot_connectivity_topos(layout='diagonal', topo=None, topomaps=None, fig=None): """Place topo plots in a figure suitable for connectivity visualization. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- layout : ...
python
def plot_connectivity_topos(layout='diagonal', topo=None, topomaps=None, fig=None): """Place topo plots in a figure suitable for connectivity visualization. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- layout : ...
[ "def", "plot_connectivity_topos", "(", "layout", "=", "'diagonal'", ",", "topo", "=", "None", ",", "topomaps", "=", "None", ",", "fig", "=", "None", ")", ":", "m", "=", "len", "(", "topomaps", ")", "if", "fig", "is", "None", ":", "fig", "=", "new_fig...
Place topo plots in a figure suitable for connectivity visualization. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- layout : str 'diagonal' -> place topo plots on diagonal. otherwise -> place topo plo...
[ "Place", "topo", "plots", "in", "a", "figure", "suitable", "for", "connectivity", "visualization", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/plotting.py#L170-L214
train
64,435
scot-dev/scot
scot/plotting.py
plot_connectivity_significance
def plot_connectivity_significance(s, fs=2, freq_range=(-np.inf, np.inf), diagonal=0, border=False, fig=None): """Plot significance. Significance is drawn as a background image where dark vertical stripes indicate freuquencies where a evaluates to True. Parameters ---------- a : array, shape (...
python
def plot_connectivity_significance(s, fs=2, freq_range=(-np.inf, np.inf), diagonal=0, border=False, fig=None): """Plot significance. Significance is drawn as a background image where dark vertical stripes indicate freuquencies where a evaluates to True. Parameters ---------- a : array, shape (...
[ "def", "plot_connectivity_significance", "(", "s", ",", "fs", "=", "2", ",", "freq_range", "=", "(", "-", "np", ".", "inf", ",", "np", ".", "inf", ")", ",", "diagonal", "=", "0", ",", "border", "=", "False", ",", "fig", "=", "None", ")", ":", "a"...
Plot significance. Significance is drawn as a background image where dark vertical stripes indicate freuquencies where a evaluates to True. Parameters ---------- a : array, shape (n_channels, n_channels, n_fft), dtype bool Significance fs : float Sampling frequency freq_ran...
[ "Plot", "significance", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/plotting.py#L312-L387
train
64,436
scot-dev/scot
scot/plotting.py
plot_whiteness
def plot_whiteness(var, h, repeats=1000, axis=None): """ Draw distribution of the Portmanteu whiteness test. Parameters ---------- var : :class:`~scot.var.VARBase`-like object Vector autoregressive model (VAR) object whose residuals are tested for whiteness. h : int Maximum lag to i...
python
def plot_whiteness(var, h, repeats=1000, axis=None): """ Draw distribution of the Portmanteu whiteness test. Parameters ---------- var : :class:`~scot.var.VARBase`-like object Vector autoregressive model (VAR) object whose residuals are tested for whiteness. h : int Maximum lag to i...
[ "def", "plot_whiteness", "(", "var", ",", "h", ",", "repeats", "=", "1000", ",", "axis", "=", "None", ")", ":", "pr", ",", "q0", ",", "q", "=", "var", ".", "test_whiteness", "(", "h", ",", "repeats", ",", "True", ")", "if", "axis", "is", "None", ...
Draw distribution of the Portmanteu whiteness test. Parameters ---------- var : :class:`~scot.var.VARBase`-like object Vector autoregressive model (VAR) object whose residuals are tested for whiteness. h : int Maximum lag to include in the test. repeats : int, optional Numbe...
[ "Draw", "distribution", "of", "the", "Portmanteu", "whiteness", "test", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/plotting.py#L626-L664
train
64,437
scot-dev/scot
scot/xvschema.py
singletrial
def singletrial(num_trials, skipstep=1): """ Single-trial cross-validation schema Use one trial for training, all others for testing. Parameters ---------- num_trials : int Total number of trials skipstep : int only use every `skipstep` trial for training Returns -----...
python
def singletrial(num_trials, skipstep=1): """ Single-trial cross-validation schema Use one trial for training, all others for testing. Parameters ---------- num_trials : int Total number of trials skipstep : int only use every `skipstep` trial for training Returns -----...
[ "def", "singletrial", "(", "num_trials", ",", "skipstep", "=", "1", ")", ":", "for", "t", "in", "range", "(", "0", ",", "num_trials", ",", "skipstep", ")", ":", "trainset", "=", "[", "t", "]", "testset", "=", "[", "i", "for", "i", "in", "range", ...
Single-trial cross-validation schema Use one trial for training, all others for testing. Parameters ---------- num_trials : int Total number of trials skipstep : int only use every `skipstep` trial for training Returns ------- gen : generator object the generat...
[ "Single", "-", "trial", "cross", "-", "validation", "schema" ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/xvschema.py#L14-L36
train
64,438
scot-dev/scot
scot/xvschema.py
splitset
def splitset(num_trials, skipstep=None): """ Split-set cross validation Use half the trials for training, and the other half for testing. Then repeat the other way round. Parameters ---------- num_trials : int Total number of trials skipstep : int unused Returns --...
python
def splitset(num_trials, skipstep=None): """ Split-set cross validation Use half the trials for training, and the other half for testing. Then repeat the other way round. Parameters ---------- num_trials : int Total number of trials skipstep : int unused Returns --...
[ "def", "splitset", "(", "num_trials", ",", "skipstep", "=", "None", ")", ":", "split", "=", "num_trials", "//", "2", "a", "=", "list", "(", "range", "(", "0", ",", "split", ")", ")", "b", "=", "list", "(", "range", "(", "split", ",", "num_trials", ...
Split-set cross validation Use half the trials for training, and the other half for testing. Then repeat the other way round. Parameters ---------- num_trials : int Total number of trials skipstep : int unused Returns ------- gen : generator object the gene...
[ "Split", "-", "set", "cross", "validation" ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/xvschema.py#L64-L87
train
64,439
scot-dev/scot
scot/ooapi.py
Workspace.set_data
def set_data(self, data, cl=None, time_offset=0): """ Assign data to the workspace. This function assigns a new data set to the workspace. Doing so invalidates currently fitted VAR models, connectivity estimates, and activations. Parameters ---------- data : array-like,...
python
def set_data(self, data, cl=None, time_offset=0): """ Assign data to the workspace. This function assigns a new data set to the workspace. Doing so invalidates currently fitted VAR models, connectivity estimates, and activations. Parameters ---------- data : array-like,...
[ "def", "set_data", "(", "self", ",", "data", ",", "cl", "=", "None", ",", "time_offset", "=", "0", ")", ":", "self", ".", "data_", "=", "atleast_3d", "(", "data", ")", "self", ".", "cl_", "=", "np", ".", "asarray", "(", "cl", "if", "cl", "is", ...
Assign data to the workspace. This function assigns a new data set to the workspace. Doing so invalidates currently fitted VAR models, connectivity estimates, and activations. Parameters ---------- data : array-like, shape = [n_trials, n_channels, n_samples] or [n_channels, n_s...
[ "Assign", "data", "to", "the", "workspace", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L168-L200
train
64,440
scot-dev/scot
scot/ooapi.py
Workspace.set_used_labels
def set_used_labels(self, labels): """ Specify which trials to use in subsequent analysis steps. This function masks trials based on their class labels. Parameters ---------- labels : list of class labels Marks all trials that have a label that is in the `labels` li...
python
def set_used_labels(self, labels): """ Specify which trials to use in subsequent analysis steps. This function masks trials based on their class labels. Parameters ---------- labels : list of class labels Marks all trials that have a label that is in the `labels` li...
[ "def", "set_used_labels", "(", "self", ",", "labels", ")", ":", "mask", "=", "np", ".", "zeros", "(", "self", ".", "cl_", ".", "size", ",", "dtype", "=", "bool", ")", "for", "l", "in", "labels", ":", "mask", "=", "np", ".", "logical_or", "(", "ma...
Specify which trials to use in subsequent analysis steps. This function masks trials based on their class labels. Parameters ---------- labels : list of class labels Marks all trials that have a label that is in the `labels` list for further processing. Returns ...
[ "Specify", "which", "trials", "to", "use", "in", "subsequent", "analysis", "steps", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L202-L221
train
64,441
scot-dev/scot
scot/ooapi.py
Workspace.remove_sources
def remove_sources(self, sources): """ Remove sources from the decomposition. This function removes sources from the decomposition. Doing so invalidates currently fitted VAR models and connectivity estimates. Parameters ---------- sources : {slice, int, array of ints} ...
python
def remove_sources(self, sources): """ Remove sources from the decomposition. This function removes sources from the decomposition. Doing so invalidates currently fitted VAR models and connectivity estimates. Parameters ---------- sources : {slice, int, array of ints} ...
[ "def", "remove_sources", "(", "self", ",", "sources", ")", ":", "if", "self", ".", "unmixing_", "is", "None", "or", "self", ".", "mixing_", "is", "None", ":", "raise", "RuntimeError", "(", "\"No sources available (run do_mvarica first)\"", ")", "self", ".", "m...
Remove sources from the decomposition. This function removes sources from the decomposition. Doing so invalidates currently fitted VAR models and connectivity estimates. Parameters ---------- sources : {slice, int, array of ints} Indices of components to remove. ...
[ "Remove", "sources", "from", "the", "decomposition", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L341-L373
train
64,442
scot-dev/scot
scot/ooapi.py
Workspace.keep_sources
def keep_sources(self, keep): """Keep only the specified sources in the decomposition. """ if self.unmixing_ is None or self.mixing_ is None: raise RuntimeError("No sources available (run do_mvarica first)") n_sources = self.mixing_.shape[0] self.remove_sources(np.set...
python
def keep_sources(self, keep): """Keep only the specified sources in the decomposition. """ if self.unmixing_ is None or self.mixing_ is None: raise RuntimeError("No sources available (run do_mvarica first)") n_sources = self.mixing_.shape[0] self.remove_sources(np.set...
[ "def", "keep_sources", "(", "self", ",", "keep", ")", ":", "if", "self", ".", "unmixing_", "is", "None", "or", "self", ".", "mixing_", "is", "None", ":", "raise", "RuntimeError", "(", "\"No sources available (run do_mvarica first)\"", ")", "n_sources", "=", "s...
Keep only the specified sources in the decomposition.
[ "Keep", "only", "the", "specified", "sources", "in", "the", "decomposition", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L375-L382
train
64,443
scot-dev/scot
scot/ooapi.py
Workspace.fit_var
def fit_var(self): """ Fit a VAR model to the source activations. Returns ------- self : Workspace The Workspace object. Raises ------ RuntimeError If the :class:`Workspace` instance does not contain source activations. """ ...
python
def fit_var(self): """ Fit a VAR model to the source activations. Returns ------- self : Workspace The Workspace object. Raises ------ RuntimeError If the :class:`Workspace` instance does not contain source activations. """ ...
[ "def", "fit_var", "(", "self", ")", ":", "if", "self", ".", "activations_", "is", "None", ":", "raise", "RuntimeError", "(", "\"VAR fitting requires source activations (run do_mvarica first)\"", ")", "self", ".", "var_", ".", "fit", "(", "data", "=", "self", "."...
Fit a VAR model to the source activations. Returns ------- self : Workspace The Workspace object. Raises ------ RuntimeError If the :class:`Workspace` instance does not contain source activations.
[ "Fit", "a", "VAR", "model", "to", "the", "source", "activations", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L384-L401
train
64,444
scot-dev/scot
scot/ooapi.py
Workspace.get_connectivity
def get_connectivity(self, measure_name, plot=False): """ Calculate spectral connectivity measure. Parameters ---------- measure_name : str Name of the connectivity measure to calculate. See :class:`Connectivity` for supported measures. plot : {False, None, Figure ob...
python
def get_connectivity(self, measure_name, plot=False): """ Calculate spectral connectivity measure. Parameters ---------- measure_name : str Name of the connectivity measure to calculate. See :class:`Connectivity` for supported measures. plot : {False, None, Figure ob...
[ "def", "get_connectivity", "(", "self", ",", "measure_name", ",", "plot", "=", "False", ")", ":", "if", "self", ".", "connectivity_", "is", "None", ":", "raise", "RuntimeError", "(", "\"Connectivity requires a VAR model (run do_mvarica or fit_var first)\"", ")", "cm",...
Calculate spectral connectivity measure. Parameters ---------- measure_name : str Name of the connectivity measure to calculate. See :class:`Connectivity` for supported measures. plot : {False, None, Figure object}, optional Whether and where to plot the connecti...
[ "Calculate", "spectral", "connectivity", "measure", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L422-L470
train
64,445
scot-dev/scot
scot/ooapi.py
Workspace.get_surrogate_connectivity
def get_surrogate_connectivity(self, measure_name, repeats=100, plot=False, random_state=None): """ Calculate spectral connectivity measure under the assumption of no actual connectivity. Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity dis...
python
def get_surrogate_connectivity(self, measure_name, repeats=100, plot=False, random_state=None): """ Calculate spectral connectivity measure under the assumption of no actual connectivity. Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity dis...
[ "def", "get_surrogate_connectivity", "(", "self", ",", "measure_name", ",", "repeats", "=", "100", ",", "plot", "=", "False", ",", "random_state", "=", "None", ")", ":", "cs", "=", "surrogate_connectivity", "(", "measure_name", ",", "self", ".", "activations_"...
Calculate spectral connectivity measure under the assumption of no actual connectivity. Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity distribution if there was no causal structure in the data. Parameters ---------- measu...
[ "Calculate", "spectral", "connectivity", "measure", "under", "the", "assumption", "of", "no", "actual", "connectivity", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L472-L515
train
64,446
scot-dev/scot
scot/ooapi.py
Workspace.get_bootstrap_connectivity
def get_bootstrap_connectivity(self, measure_names, repeats=100, num_samples=None, plot=False, random_state=None): """ Calculate bootstrap estimates of spectral connectivity measures. Bootstrapping is performed on trial level. Parameters ---------- measure_names : {str, list of...
python
def get_bootstrap_connectivity(self, measure_names, repeats=100, num_samples=None, plot=False, random_state=None): """ Calculate bootstrap estimates of spectral connectivity measures. Bootstrapping is performed on trial level. Parameters ---------- measure_names : {str, list of...
[ "def", "get_bootstrap_connectivity", "(", "self", ",", "measure_names", ",", "repeats", "=", "100", ",", "num_samples", "=", "None", ",", "plot", "=", "False", ",", "random_state", "=", "None", ")", ":", "if", "num_samples", "is", "None", ":", "num_samples",...
Calculate bootstrap estimates of spectral connectivity measures. Bootstrapping is performed on trial level. Parameters ---------- measure_names : {str, list of str} Name(s) of the connectivity measure(s) to calculate. See :class:`Connectivity` for supported measures. ...
[ "Calculate", "bootstrap", "estimates", "of", "spectral", "connectivity", "measures", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L517-L571
train
64,447
scot-dev/scot
scot/ooapi.py
Workspace.plot_source_topos
def plot_source_topos(self, common_scale=None): """ Plot topography of the Source decomposition. Parameters ---------- common_scale : float, optional If set to None, each topoplot's color axis is scaled individually. Otherwise specifies the percentile (1-99) of v...
python
def plot_source_topos(self, common_scale=None): """ Plot topography of the Source decomposition. Parameters ---------- common_scale : float, optional If set to None, each topoplot's color axis is scaled individually. Otherwise specifies the percentile (1-99) of v...
[ "def", "plot_source_topos", "(", "self", ",", "common_scale", "=", "None", ")", ":", "if", "self", ".", "unmixing_", "is", "None", "and", "self", ".", "mixing_", "is", "None", ":", "raise", "RuntimeError", "(", "\"No sources available (run do_mvarica first)\"", ...
Plot topography of the Source decomposition. Parameters ---------- common_scale : float, optional If set to None, each topoplot's color axis is scaled individually. Otherwise specifies the percentile (1-99) of values in all plot. This value is taken as the maximum color ...
[ "Plot", "topography", "of", "the", "Source", "decomposition", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L765-L779
train
64,448
scot-dev/scot
scot/ooapi.py
Workspace.plot_connectivity_topos
def plot_connectivity_topos(self, fig=None): """ Plot scalp projections of the sources. This function only plots the topos. Use in combination with connectivity plotting. Parameters ---------- fig : {None, Figure object}, optional Where to plot the topos. f set to *...
python
def plot_connectivity_topos(self, fig=None): """ Plot scalp projections of the sources. This function only plots the topos. Use in combination with connectivity plotting. Parameters ---------- fig : {None, Figure object}, optional Where to plot the topos. f set to *...
[ "def", "plot_connectivity_topos", "(", "self", ",", "fig", "=", "None", ")", ":", "self", ".", "_prepare_plots", "(", "True", ",", "False", ")", "if", "self", ".", "plot_outside_topo", ":", "fig", "=", "self", ".", "plotting", ".", "plot_connectivity_topos",...
Plot scalp projections of the sources. This function only plots the topos. Use in combination with connectivity plotting. Parameters ---------- fig : {None, Figure object}, optional Where to plot the topos. f set to **None**, a new figure is created. Otherwise plot into the...
[ "Plot", "scalp", "projections", "of", "the", "sources", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L781-L802
train
64,449
scot-dev/scot
scot/ooapi.py
Workspace.plot_connectivity_surrogate
def plot_connectivity_surrogate(self, measure_name, repeats=100, fig=None): """ Plot spectral connectivity measure under the assumption of no actual connectivity. Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity distribution if there was no...
python
def plot_connectivity_surrogate(self, measure_name, repeats=100, fig=None): """ Plot spectral connectivity measure under the assumption of no actual connectivity. Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity distribution if there was no...
[ "def", "plot_connectivity_surrogate", "(", "self", ",", "measure_name", ",", "repeats", "=", "100", ",", "fig", "=", "None", ")", ":", "cb", "=", "self", ".", "get_surrogate_connectivity", "(", "measure_name", ",", "repeats", ")", "self", ".", "_prepare_plots"...
Plot spectral connectivity measure under the assumption of no actual connectivity. Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity distribution if there was no causal structure in the data. Parameters ---------- measure_na...
[ "Plot", "spectral", "connectivity", "measure", "under", "the", "assumption", "of", "no", "actual", "connectivity", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/ooapi.py#L804-L833
train
64,450
scot-dev/scot
scot/parallel.py
parallel_loop
def parallel_loop(func, n_jobs=1, verbose=1): """run loops in parallel, if joblib is available. Parameters ---------- func : function function to be executed in parallel n_jobs : int | None Number of jobs. If set to None, do not attempt to use joblib. verbose : int verbo...
python
def parallel_loop(func, n_jobs=1, verbose=1): """run loops in parallel, if joblib is available. Parameters ---------- func : function function to be executed in parallel n_jobs : int | None Number of jobs. If set to None, do not attempt to use joblib. verbose : int verbo...
[ "def", "parallel_loop", "(", "func", ",", "n_jobs", "=", "1", ",", "verbose", "=", "1", ")", ":", "if", "n_jobs", ":", "try", ":", "from", "joblib", "import", "Parallel", ",", "delayed", "except", "ImportError", ":", "try", ":", "from", "sklearn", ".",...
run loops in parallel, if joblib is available. Parameters ---------- func : function function to be executed in parallel n_jobs : int | None Number of jobs. If set to None, do not attempt to use joblib. verbose : int verbosity level Notes ----- Execution of the ...
[ "run", "loops", "in", "parallel", "if", "joblib", "is", "available", "." ]
48598b79d4400dad893b134cd2194715511facda
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/parallel.py#L8-L43
train
64,451
kolypto/py-good
good/voluptuous.py
_convert_errors
def _convert_errors(func): """ Decorator to convert throws errors to Voluptuous format.""" cast_Invalid = lambda e: Invalid( u"{message}, expected {expected}".format( message=e.message, expected=e.expected) if e.expected != u'-none-' else e.message, e.path, ...
python
def _convert_errors(func): """ Decorator to convert throws errors to Voluptuous format.""" cast_Invalid = lambda e: Invalid( u"{message}, expected {expected}".format( message=e.message, expected=e.expected) if e.expected != u'-none-' else e.message, e.path, ...
[ "def", "_convert_errors", "(", "func", ")", ":", "cast_Invalid", "=", "lambda", "e", ":", "Invalid", "(", "u\"{message}, expected {expected}\"", ".", "format", "(", "message", "=", "e", ".", "message", ",", "expected", "=", "e", ".", "expected", ")", "if", ...
Decorator to convert throws errors to Voluptuous format.
[ "Decorator", "to", "convert", "throws", "errors", "to", "Voluptuous", "format", "." ]
192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4
https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/voluptuous.py#L45-L66
train
64,452
kolypto/py-good
good/schema/markers.py
Marker.on_compiled
def on_compiled(self, name=None, key_schema=None, value_schema=None, as_mapping_key=None): """ When CompiledSchema compiles this marker, it sets informational values onto it. Note that arguments may be provided in two incomplete sets, e.g. (name, key_schema, None) and then (None, None, value_sc...
python
def on_compiled(self, name=None, key_schema=None, value_schema=None, as_mapping_key=None): """ When CompiledSchema compiles this marker, it sets informational values onto it. Note that arguments may be provided in two incomplete sets, e.g. (name, key_schema, None) and then (None, None, value_sc...
[ "def", "on_compiled", "(", "self", ",", "name", "=", "None", ",", "key_schema", "=", "None", ",", "value_schema", "=", "None", ",", "as_mapping_key", "=", "None", ")", ":", "if", "self", ".", "name", "is", "None", ":", "self", ".", "name", "=", "name...
When CompiledSchema compiles this marker, it sets informational values onto it. Note that arguments may be provided in two incomplete sets, e.g. (name, key_schema, None) and then (None, None, value_schema). Thus, all assignments must be handled individually. It is possible that a marke...
[ "When", "CompiledSchema", "compiles", "this", "marker", "it", "sets", "informational", "values", "onto", "it", "." ]
192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4
https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/schema/markers.py#L90-L119
train
64,453
openearth/bmi-python
bmi/runner.py
colorlogs
def colorlogs(format="short"): """Append a rainbow logging handler and a formatter to the root logger""" try: from rainbow_logging_handler import RainbowLoggingHandler import sys # setup `RainbowLoggingHandler` logger = logging.root # same as default if format == ...
python
def colorlogs(format="short"): """Append a rainbow logging handler and a formatter to the root logger""" try: from rainbow_logging_handler import RainbowLoggingHandler import sys # setup `RainbowLoggingHandler` logger = logging.root # same as default if format == ...
[ "def", "colorlogs", "(", "format", "=", "\"short\"", ")", ":", "try", ":", "from", "rainbow_logging_handler", "import", "RainbowLoggingHandler", "import", "sys", "# setup `RainbowLoggingHandler`", "logger", "=", "logging", ".", "root", "# same as default", "if", "form...
Append a rainbow logging handler and a formatter to the root logger
[ "Append", "a", "rainbow", "logging", "handler", "and", "a", "formatter", "to", "the", "root", "logger" ]
2f53f24d45515eb0711c2d28ddd6c1582045248f
https://github.com/openearth/bmi-python/blob/2f53f24d45515eb0711c2d28ddd6c1582045248f/bmi/runner.py#L30-L49
train
64,454
openearth/bmi-python
bmi/runner.py
main
def main(): """main bmi runner program""" arguments = docopt.docopt(__doc__, version=__version__) colorlogs() # Read input file file wrapper = BMIWrapper( engine=arguments['<engine>'], configfile=arguments['<config>'] or '' ) # add logger if required if not arguments[...
python
def main(): """main bmi runner program""" arguments = docopt.docopt(__doc__, version=__version__) colorlogs() # Read input file file wrapper = BMIWrapper( engine=arguments['<engine>'], configfile=arguments['<config>'] or '' ) # add logger if required if not arguments[...
[ "def", "main", "(", ")", ":", "arguments", "=", "docopt", ".", "docopt", "(", "__doc__", ",", "version", "=", "__version__", ")", "colorlogs", "(", ")", "# Read input file file", "wrapper", "=", "BMIWrapper", "(", "engine", "=", "arguments", "[", "'<engine>'...
main bmi runner program
[ "main", "bmi", "runner", "program" ]
2f53f24d45515eb0711c2d28ddd6c1582045248f
https://github.com/openearth/bmi-python/blob/2f53f24d45515eb0711c2d28ddd6c1582045248f/bmi/runner.py#L82-L126
train
64,455
insomnia-lab/libreant
conf/defaults.py
get_def_conf
def get_def_conf(): '''return default configurations as simple dict''' ret = dict() for k,v in defConf.items(): ret[k] = v[0] return ret
python
def get_def_conf(): '''return default configurations as simple dict''' ret = dict() for k,v in defConf.items(): ret[k] = v[0] return ret
[ "def", "get_def_conf", "(", ")", ":", "ret", "=", "dict", "(", ")", "for", "k", ",", "v", "in", "defConf", ".", "items", "(", ")", ":", "ret", "[", "k", "]", "=", "v", "[", "0", "]", "return", "ret" ]
return default configurations as simple dict
[ "return", "default", "configurations", "as", "simple", "dict" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/conf/defaults.py#L21-L26
train
64,456
iamjarret/pystockfish
pystockfish.py
Match.move
def move(self): """ Advance game by single move, if possible. @return: logical indicator if move was performed. """ if len(self.moves) == MAX_MOVES: return False elif len(self.moves) % 2: active_engine = self.black_engine active_engine...
python
def move(self): """ Advance game by single move, if possible. @return: logical indicator if move was performed. """ if len(self.moves) == MAX_MOVES: return False elif len(self.moves) % 2: active_engine = self.black_engine active_engine...
[ "def", "move", "(", "self", ")", ":", "if", "len", "(", "self", ".", "moves", ")", "==", "MAX_MOVES", ":", "return", "False", "elif", "len", "(", "self", ".", "moves", ")", "%", "2", ":", "active_engine", "=", "self", ".", "black_engine", "active_eng...
Advance game by single move, if possible. @return: logical indicator if move was performed.
[ "Advance", "game", "by", "single", "move", "if", "possible", "." ]
ae34a4b4d29c577c888b72691fcf0cb5a89b1792
https://github.com/iamjarret/pystockfish/blob/ae34a4b4d29c577c888b72691fcf0cb5a89b1792/pystockfish.py#L54-L90
train
64,457
iamjarret/pystockfish
pystockfish.py
Engine.bestmove
def bestmove(self): """ Get proposed best move for current position. @return: dictionary with 'move', 'ponder', 'info' containing best move's UCI notation, ponder value and info dictionary. """ self.go() last_info = "" while True: text = self....
python
def bestmove(self): """ Get proposed best move for current position. @return: dictionary with 'move', 'ponder', 'info' containing best move's UCI notation, ponder value and info dictionary. """ self.go() last_info = "" while True: text = self....
[ "def", "bestmove", "(", "self", ")", ":", "self", ".", "go", "(", ")", "last_info", "=", "\"\"", "while", "True", ":", "text", "=", "self", ".", "stdout", ".", "readline", "(", ")", ".", "strip", "(", ")", "split_text", "=", "text", ".", "split", ...
Get proposed best move for current position. @return: dictionary with 'move', 'ponder', 'info' containing best move's UCI notation, ponder value and info dictionary.
[ "Get", "proposed", "best", "move", "for", "current", "position", "." ]
ae34a4b4d29c577c888b72691fcf0cb5a89b1792
https://github.com/iamjarret/pystockfish/blob/ae34a4b4d29c577c888b72691fcf0cb5a89b1792/pystockfish.py#L213-L232
train
64,458
iamjarret/pystockfish
pystockfish.py
Engine._bestmove_get_info
def _bestmove_get_info(text): """ Parse stockfish evaluation output as dictionary. Examples of input: "info depth 2 seldepth 3 multipv 1 score cp -656 nodes 43 nps 43000 tbhits 0 \ time 1 pv g7g6 h3g3 g6f7" "info depth 10 seldepth 12 multipv 1 score mate 5 nodes 2378 n...
python
def _bestmove_get_info(text): """ Parse stockfish evaluation output as dictionary. Examples of input: "info depth 2 seldepth 3 multipv 1 score cp -656 nodes 43 nps 43000 tbhits 0 \ time 1 pv g7g6 h3g3 g6f7" "info depth 10 seldepth 12 multipv 1 score mate 5 nodes 2378 n...
[ "def", "_bestmove_get_info", "(", "text", ")", ":", "result_dict", "=", "Engine", ".", "_get_info_pv", "(", "text", ")", "result_dict", ".", "update", "(", "Engine", ".", "_get_info_score", "(", "text", ")", ")", "single_value_fields", "=", "[", "'depth'", "...
Parse stockfish evaluation output as dictionary. Examples of input: "info depth 2 seldepth 3 multipv 1 score cp -656 nodes 43 nps 43000 tbhits 0 \ time 1 pv g7g6 h3g3 g6f7" "info depth 10 seldepth 12 multipv 1 score mate 5 nodes 2378 nps 1189000 tbhits 0 \ time 2 pv h3g3 g6f7 ...
[ "Parse", "stockfish", "evaluation", "output", "as", "dictionary", "." ]
ae34a4b4d29c577c888b72691fcf0cb5a89b1792
https://github.com/iamjarret/pystockfish/blob/ae34a4b4d29c577c888b72691fcf0cb5a89b1792/pystockfish.py#L235-L254
train
64,459
iamjarret/pystockfish
pystockfish.py
Engine.isready
def isready(self): """ Used to synchronize the python engine object with the back-end engine. Sends 'isready' and waits for 'readyok.' """ self.put('isready') while True: text = self.stdout.readline().strip() if text == 'readyok': return t...
python
def isready(self): """ Used to synchronize the python engine object with the back-end engine. Sends 'isready' and waits for 'readyok.' """ self.put('isready') while True: text = self.stdout.readline().strip() if text == 'readyok': return t...
[ "def", "isready", "(", "self", ")", ":", "self", ".", "put", "(", "'isready'", ")", "while", "True", ":", "text", "=", "self", ".", "stdout", ".", "readline", "(", ")", ".", "strip", "(", ")", "if", "text", "==", "'readyok'", ":", "return", "text" ...
Used to synchronize the python engine object with the back-end engine. Sends 'isready' and waits for 'readyok.'
[ "Used", "to", "synchronize", "the", "python", "engine", "object", "with", "the", "back", "-", "end", "engine", ".", "Sends", "isready", "and", "waits", "for", "readyok", "." ]
ae34a4b4d29c577c888b72691fcf0cb5a89b1792
https://github.com/iamjarret/pystockfish/blob/ae34a4b4d29c577c888b72691fcf0cb5a89b1792/pystockfish.py#L289-L297
train
64,460
chaoss/grimoirelab-manuscripts
manuscripts2/metrics/github_prs.py
project_activity
def project_activity(index, start, end): """Compute the metrics for the project activity section of the enriched github pull requests index. Returns a dictionary containing a "metric" key. This key contains the metrics for this section. :param index: index object :param start: start date to ge...
python
def project_activity(index, start, end): """Compute the metrics for the project activity section of the enriched github pull requests index. Returns a dictionary containing a "metric" key. This key contains the metrics for this section. :param index: index object :param start: start date to ge...
[ "def", "project_activity", "(", "index", ",", "start", ",", "end", ")", ":", "results", "=", "{", "\"metrics\"", ":", "[", "SubmittedPRs", "(", "index", ",", "start", ",", "end", ")", ",", "ClosedPRs", "(", "index", ",", "start", ",", "end", ")", "]"...
Compute the metrics for the project activity section of the enriched github pull requests index. Returns a dictionary containing a "metric" key. This key contains the metrics for this section. :param index: index object :param start: start date to get the data from :param end: end date to get ...
[ "Compute", "the", "metrics", "for", "the", "project", "activity", "section", "of", "the", "enriched", "github", "pull", "requests", "index", "." ]
94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts2/metrics/github_prs.py#L234-L252
train
64,461
chaoss/grimoirelab-manuscripts
manuscripts2/metrics/github_prs.py
DaysToClosePRMedian.aggregations
def aggregations(self): """Get the single valued aggregations with respect to the previous time interval.""" prev_month_start = get_prev_month(self.end, self.query.interval_) self.query.since(prev_month_start) agg = super().aggregations() if agg is None: agg ...
python
def aggregations(self): """Get the single valued aggregations with respect to the previous time interval.""" prev_month_start = get_prev_month(self.end, self.query.interval_) self.query.since(prev_month_start) agg = super().aggregations() if agg is None: agg ...
[ "def", "aggregations", "(", "self", ")", ":", "prev_month_start", "=", "get_prev_month", "(", "self", ".", "end", ",", "self", ".", "query", ".", "interval_", ")", "self", ".", "query", ".", "since", "(", "prev_month_start", ")", "agg", "=", "super", "("...
Get the single valued aggregations with respect to the previous time interval.
[ "Get", "the", "single", "valued", "aggregations", "with", "respect", "to", "the", "previous", "time", "interval", "." ]
94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts2/metrics/github_prs.py#L110-L119
train
64,462
chaoss/grimoirelab-manuscripts
manuscripts2/metrics/github_prs.py
BMIPR.timeseries
def timeseries(self, dataframe=False): """Get BMIPR as a time series.""" closed_timeseries = self.closed.timeseries(dataframe=dataframe) opened_timeseries = self.opened.timeseries(dataframe=dataframe) return calculate_bmi(closed_timeseries, opened_timeseries)
python
def timeseries(self, dataframe=False): """Get BMIPR as a time series.""" closed_timeseries = self.closed.timeseries(dataframe=dataframe) opened_timeseries = self.opened.timeseries(dataframe=dataframe) return calculate_bmi(closed_timeseries, opened_timeseries)
[ "def", "timeseries", "(", "self", ",", "dataframe", "=", "False", ")", ":", "closed_timeseries", "=", "self", ".", "closed", ".", "timeseries", "(", "dataframe", "=", "dataframe", ")", "opened_timeseries", "=", "self", ".", "opened", ".", "timeseries", "(", ...
Get BMIPR as a time series.
[ "Get", "BMIPR", "as", "a", "time", "series", "." ]
94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts2/metrics/github_prs.py#L201-L206
train
64,463
chaoss/grimoirelab-manuscripts
manuscripts/metrics/metrics.py
Metrics.get_query
def get_query(self, evolutionary=False): """ Basic query to get the metric values :param evolutionary: if True the metric values time series is returned. If False the aggregated metric value. :return: the DSL query to be sent to Elasticsearch """ if not evolutionary: ...
python
def get_query(self, evolutionary=False): """ Basic query to get the metric values :param evolutionary: if True the metric values time series is returned. If False the aggregated metric value. :return: the DSL query to be sent to Elasticsearch """ if not evolutionary: ...
[ "def", "get_query", "(", "self", ",", "evolutionary", "=", "False", ")", ":", "if", "not", "evolutionary", ":", "interval", "=", "None", "offset", "=", "None", "else", ":", "interval", "=", "self", ".", "interval", "offset", "=", "self", ".", "offset", ...
Basic query to get the metric values :param evolutionary: if True the metric values time series is returned. If False the aggregated metric value. :return: the DSL query to be sent to Elasticsearch
[ "Basic", "query", "to", "get", "the", "metric", "values" ]
94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/metrics/metrics.py#L103-L130
train
64,464
chaoss/grimoirelab-manuscripts
manuscripts/metrics/metrics.py
Metrics.get_list
def get_list(self): """ Extract from a DSL aggregated response the values for each bucket :return: a list with the values in a DSL aggregated response """ field = self.FIELD_NAME query = ElasticQuery.get_agg(field=field, date_field=se...
python
def get_list(self): """ Extract from a DSL aggregated response the values for each bucket :return: a list with the values in a DSL aggregated response """ field = self.FIELD_NAME query = ElasticQuery.get_agg(field=field, date_field=se...
[ "def", "get_list", "(", "self", ")", ":", "field", "=", "self", ".", "FIELD_NAME", "query", "=", "ElasticQuery", ".", "get_agg", "(", "field", "=", "field", ",", "date_field", "=", "self", ".", "FIELD_DATE", ",", "start", "=", "self", ".", "start", ","...
Extract from a DSL aggregated response the values for each bucket :return: a list with the values in a DSL aggregated response
[ "Extract", "from", "a", "DSL", "aggregated", "response", "the", "values", "for", "each", "bucket" ]
94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/metrics/metrics.py#L132-L150
train
64,465
chaoss/grimoirelab-manuscripts
manuscripts/metrics/metrics.py
Metrics.get_metrics_data
def get_metrics_data(self, query): """ Get the metrics data from Elasticsearch given a DSL query :param query: query to be sent to Elasticsearch :return: a dict with the results of executing the query """ if self.es_url.startswith("http"): url = self.es_url ...
python
def get_metrics_data(self, query): """ Get the metrics data from Elasticsearch given a DSL query :param query: query to be sent to Elasticsearch :return: a dict with the results of executing the query """ if self.es_url.startswith("http"): url = self.es_url ...
[ "def", "get_metrics_data", "(", "self", ",", "query", ")", ":", "if", "self", ".", "es_url", ".", "startswith", "(", "\"http\"", ")", ":", "url", "=", "self", ".", "es_url", "else", ":", "url", "=", "'http://'", "+", "self", ".", "es_url", "es", "=",...
Get the metrics data from Elasticsearch given a DSL query :param query: query to be sent to Elasticsearch :return: a dict with the results of executing the query
[ "Get", "the", "metrics", "data", "from", "Elasticsearch", "given", "a", "DSL", "query" ]
94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/metrics/metrics.py#L152-L173
train
64,466
chaoss/grimoirelab-manuscripts
manuscripts/metrics/metrics.py
Metrics.get_ts
def get_ts(self): """ Returns a time series of a specific class A timeseries consists of a unixtime date, labels, some other fields and the data of the specific instantiated class metric per interval. This is built on a hash table. :return: a list with a time series wit...
python
def get_ts(self): """ Returns a time series of a specific class A timeseries consists of a unixtime date, labels, some other fields and the data of the specific instantiated class metric per interval. This is built on a hash table. :return: a list with a time series wit...
[ "def", "get_ts", "(", "self", ")", ":", "query", "=", "self", ".", "get_query", "(", "True", ")", "res", "=", "self", ".", "get_metrics_data", "(", "query", ")", "# Time to convert it to our grimoire timeseries format", "ts", "=", "{", "\"date\"", ":", "[", ...
Returns a time series of a specific class A timeseries consists of a unixtime date, labels, some other fields and the data of the specific instantiated class metric per interval. This is built on a hash table. :return: a list with a time series with the values of the metric
[ "Returns", "a", "time", "series", "of", "a", "specific", "class" ]
94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/metrics/metrics.py#L175-L210
train
64,467
chaoss/grimoirelab-manuscripts
manuscripts/metrics/metrics.py
Metrics.get_agg
def get_agg(self): """ Returns the aggregated value for the metric :return: the value of the metric """ """ Returns an aggregated value """ query = self.get_query(False) res = self.get_metrics_data(query) # We need to extract the data from the JSON res ...
python
def get_agg(self): """ Returns the aggregated value for the metric :return: the value of the metric """ """ Returns an aggregated value """ query = self.get_query(False) res = self.get_metrics_data(query) # We need to extract the data from the JSON res ...
[ "def", "get_agg", "(", "self", ")", ":", "\"\"\" Returns an aggregated value \"\"\"", "query", "=", "self", ".", "get_query", "(", "False", ")", "res", "=", "self", ".", "get_metrics_data", "(", "query", ")", "# We need to extract the data from the JSON res", "# If we...
Returns the aggregated value for the metric :return: the value of the metric
[ "Returns", "the", "aggregated", "value", "for", "the", "metric" ]
94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/metrics/metrics.py#L212-L237
train
64,468
chaoss/grimoirelab-manuscripts
manuscripts/metrics/metrics.py
Metrics.get_trend
def get_trend(self): """ Get the trend for the last two metric values using the interval defined in the metric :return: a tuple with the metric value for the last interval and the trend percentage between the last two intervals """ """ """ # TODO: We j...
python
def get_trend(self): """ Get the trend for the last two metric values using the interval defined in the metric :return: a tuple with the metric value for the last interval and the trend percentage between the last two intervals """ """ """ # TODO: We j...
[ "def", "get_trend", "(", "self", ")", ":", "\"\"\" \"\"\"", "# TODO: We just need the last two periods, not the full ts", "ts", "=", "self", ".", "get_ts", "(", ")", "last", "=", "ts", "[", "'value'", "]", "[", "len", "(", "ts", "[", "'value'", "]", ")", "-...
Get the trend for the last two metric values using the interval defined in the metric :return: a tuple with the metric value for the last interval and the trend percentage between the last two intervals
[ "Get", "the", "trend", "for", "the", "last", "two", "metric", "values", "using", "the", "interval", "defined", "in", "the", "metric" ]
94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/metrics/metrics.py#L239-L263
train
64,469
insomnia-lab/libreant
presets/presetManager.py
PresetManager._load_preset
def _load_preset(self, path): ''' load, validate and store a single preset file''' try: with open(path, 'r') as f: presetBody = json.load(f) except IOError as e: raise PresetException("IOError: " + e.strerror) except ValueError as e: r...
python
def _load_preset(self, path): ''' load, validate and store a single preset file''' try: with open(path, 'r') as f: presetBody = json.load(f) except IOError as e: raise PresetException("IOError: " + e.strerror) except ValueError as e: r...
[ "def", "_load_preset", "(", "self", ",", "path", ")", ":", "try", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "presetBody", "=", "json", ".", "load", "(", "f", ")", "except", "IOError", "as", "e", ":", "raise", "PresetExcepti...
load, validate and store a single preset file
[ "load", "validate", "and", "store", "a", "single", "preset", "file" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/presets/presetManager.py#L81-L103
train
64,470
insomnia-lab/libreant
presets/presetManager.py
Preset.validate
def validate(self, data): ''' Checks if `data` respects this preset specification It will check that every required property is present and for every property type it will make some specific control. ''' for prop in self.properties: if prop.id in data: ...
python
def validate(self, data): ''' Checks if `data` respects this preset specification It will check that every required property is present and for every property type it will make some specific control. ''' for prop in self.properties: if prop.id in data: ...
[ "def", "validate", "(", "self", ",", "data", ")", ":", "for", "prop", "in", "self", ".", "properties", ":", "if", "prop", ".", "id", "in", "data", ":", "if", "prop", ".", "type", "==", "'string'", ":", "if", "not", "isinstance", "(", "data", "[", ...
Checks if `data` respects this preset specification It will check that every required property is present and for every property type it will make some specific control.
[ "Checks", "if", "data", "respects", "this", "preset", "specification" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/presets/presetManager.py#L221-L240
train
64,471
insomnia-lab/libreant
webant/util.py
requestedFormat
def requestedFormat(request,acceptedFormat): """Return the response format requested by client Client could specify requested format using: (options are processed in this order) - `format` field in http request - `Accept` header in http request Example: ...
python
def requestedFormat(request,acceptedFormat): """Return the response format requested by client Client could specify requested format using: (options are processed in this order) - `format` field in http request - `Accept` header in http request Example: ...
[ "def", "requestedFormat", "(", "request", ",", "acceptedFormat", ")", ":", "if", "'format'", "in", "request", ".", "args", ":", "fieldFormat", "=", "request", ".", "args", ".", "get", "(", "'format'", ")", "if", "fieldFormat", "not", "in", "acceptedFormat", ...
Return the response format requested by client Client could specify requested format using: (options are processed in this order) - `format` field in http request - `Accept` header in http request Example: chooseFormat(request, ['text/html','application/json'...
[ "Return", "the", "response", "format", "requested", "by", "client" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/webant/util.py#L18-L40
train
64,472
insomnia-lab/libreant
webant/util.py
routes_collector
def routes_collector(gatherer): """Decorator utility to collect flask routes in a dictionary. This function together with :func:`add_routes` provides an easy way to split flask routes declaration in multiple modules. :param gatherer: dict in which will be collected routes The decorator provided b...
python
def routes_collector(gatherer): """Decorator utility to collect flask routes in a dictionary. This function together with :func:`add_routes` provides an easy way to split flask routes declaration in multiple modules. :param gatherer: dict in which will be collected routes The decorator provided b...
[ "def", "routes_collector", "(", "gatherer", ")", ":", "def", "hatFunc", "(", "rule", ",", "*", "*", "options", ")", ":", "def", "decorator", "(", "f", ")", ":", "rule_dict", "=", "{", "'rule'", ":", "rule", ",", "'view_func'", ":", "f", "}", "rule_di...
Decorator utility to collect flask routes in a dictionary. This function together with :func:`add_routes` provides an easy way to split flask routes declaration in multiple modules. :param gatherer: dict in which will be collected routes The decorator provided by this function should be used as the ...
[ "Decorator", "utility", "to", "collect", "flask", "routes", "in", "a", "dictionary", "." ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/webant/util.py#L53-L81
train
64,473
insomnia-lab/libreant
webant/util.py
add_routes
def add_routes(fapp, routes, prefix=""): """Batch routes registering Register routes to a blueprint/flask_app previously collected with :func:`routes_collector`. :param fapp: bluprint or flask_app to whom attach new routes. :param routes: dict of routes collected by :func:`routes_collector` :p...
python
def add_routes(fapp, routes, prefix=""): """Batch routes registering Register routes to a blueprint/flask_app previously collected with :func:`routes_collector`. :param fapp: bluprint or flask_app to whom attach new routes. :param routes: dict of routes collected by :func:`routes_collector` :p...
[ "def", "add_routes", "(", "fapp", ",", "routes", ",", "prefix", "=", "\"\"", ")", ":", "for", "r", "in", "routes", ":", "r", "[", "'rule'", "]", "=", "prefix", "+", "r", "[", "'rule'", "]", "fapp", ".", "add_url_rule", "(", "*", "*", "r", ")" ]
Batch routes registering Register routes to a blueprint/flask_app previously collected with :func:`routes_collector`. :param fapp: bluprint or flask_app to whom attach new routes. :param routes: dict of routes collected by :func:`routes_collector` :param prefix: url prefix under which register all...
[ "Batch", "routes", "registering" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/webant/util.py#L84-L96
train
64,474
insomnia-lab/libreant
webant/util.py
get_centered_pagination
def get_centered_pagination(current, total, visible=5): ''' Return the range of pages to render in a pagination menu. The current page is always kept in the middle except for the edge cases. Reeturns a dict { prev, first, current, last, next } :param current: the curre...
python
def get_centered_pagination(current, total, visible=5): ''' Return the range of pages to render in a pagination menu. The current page is always kept in the middle except for the edge cases. Reeturns a dict { prev, first, current, last, next } :param current: the curre...
[ "def", "get_centered_pagination", "(", "current", ",", "total", ",", "visible", "=", "5", ")", ":", "inc", "=", "visible", "/", "2", "first", "=", "current", "-", "inc", "last", "=", "current", "+", "inc", "if", "(", "total", "<=", "visible", ")", ":...
Return the range of pages to render in a pagination menu. The current page is always kept in the middle except for the edge cases. Reeturns a dict { prev, first, current, last, next } :param current: the current page :param total: total number of pages available ...
[ "Return", "the", "range", "of", "pages", "to", "render", "in", "a", "pagination", "menu", "." ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/webant/util.py#L99-L128
train
64,475
SiLab-Bonn/pylandau
examples/mpv_fwhm.py
fwhm
def fwhm(x, y, k=10): # http://stackoverflow.com/questions/10582795/finding-the-full-width-half-maximum-of-a-peak """ Determine full-with-half-maximum of a peaked set of points, x and y. Assumes that there is only one peak present in the datasset. The function uses a spline interpolation of order k. ...
python
def fwhm(x, y, k=10): # http://stackoverflow.com/questions/10582795/finding-the-full-width-half-maximum-of-a-peak """ Determine full-with-half-maximum of a peaked set of points, x and y. Assumes that there is only one peak present in the datasset. The function uses a spline interpolation of order k. ...
[ "def", "fwhm", "(", "x", ",", "y", ",", "k", "=", "10", ")", ":", "# http://stackoverflow.com/questions/10582795/finding-the-full-width-half-maximum-of-a-peak", "class", "MultiplePeaks", "(", "Exception", ")", ":", "pass", "class", "NoPeaksFound", "(", "Exception", ")...
Determine full-with-half-maximum of a peaked set of points, x and y. Assumes that there is only one peak present in the datasset. The function uses a spline interpolation of order k.
[ "Determine", "full", "-", "with", "-", "half", "-", "maximum", "of", "a", "peaked", "set", "of", "points", "x", "and", "y", "." ]
3095af4ce5ab29685f6c8cd3830f8035521be1c6
https://github.com/SiLab-Bonn/pylandau/blob/3095af4ce5ab29685f6c8cd3830f8035521be1c6/examples/mpv_fwhm.py#L8-L33
train
64,476
snowblink14/smatch
smatch.py
main
def main(arguments): """ Main function of smatch score calculation """ global verbose global veryVerbose global iteration_num global single_score global pr_flag global match_triple_dict # set the iteration number # total iteration number = restart number + 1 iteration_num...
python
def main(arguments): """ Main function of smatch score calculation """ global verbose global veryVerbose global iteration_num global single_score global pr_flag global match_triple_dict # set the iteration number # total iteration number = restart number + 1 iteration_num...
[ "def", "main", "(", "arguments", ")", ":", "global", "verbose", "global", "veryVerbose", "global", "iteration_num", "global", "single_score", "global", "pr_flag", "global", "match_triple_dict", "# set the iteration number", "# total iteration number = restart number + 1", "it...
Main function of smatch score calculation
[ "Main", "function", "of", "smatch", "score", "calculation" ]
ad7e6553a3d52e469b2eef69d7716c87a67eedac
https://github.com/snowblink14/smatch/blob/ad7e6553a3d52e469b2eef69d7716c87a67eedac/smatch.py#L820-L853
train
64,477
insomnia-lab/libreant
archivant/archivant.py
Archivant.normalize_volume
def normalize_volume(volume): '''convert volume metadata from es to archivant format This function makes side effect on input volume output example:: { 'id': 'AU0paPZOMZchuDv1iDv8', 'type': 'volume', 'metadata': {'_language': '...
python
def normalize_volume(volume): '''convert volume metadata from es to archivant format This function makes side effect on input volume output example:: { 'id': 'AU0paPZOMZchuDv1iDv8', 'type': 'volume', 'metadata': {'_language': '...
[ "def", "normalize_volume", "(", "volume", ")", ":", "res", "=", "dict", "(", ")", "res", "[", "'type'", "]", "=", "'volume'", "res", "[", "'id'", "]", "=", "volume", "[", "'_id'", "]", "if", "'_score'", "in", "volume", ":", "res", "[", "'score'", "...
convert volume metadata from es to archivant format This function makes side effect on input volume output example:: { 'id': 'AU0paPZOMZchuDv1iDv8', 'type': 'volume', 'metadata': {'_language': 'en', 'key1': ...
[ "convert", "volume", "metadata", "from", "es", "to", "archivant", "format" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L81-L125
train
64,478
insomnia-lab/libreant
archivant/archivant.py
Archivant.normalize_attachment
def normalize_attachment(attachment): ''' Convert attachment metadata from es to archivant format This function makes side effect on input attachment ''' res = dict() res['type'] = 'attachment' res['id'] = attachment['id'] del(attachment['id']) res['u...
python
def normalize_attachment(attachment): ''' Convert attachment metadata from es to archivant format This function makes side effect on input attachment ''' res = dict() res['type'] = 'attachment' res['id'] = attachment['id'] del(attachment['id']) res['u...
[ "def", "normalize_attachment", "(", "attachment", ")", ":", "res", "=", "dict", "(", ")", "res", "[", "'type'", "]", "=", "'attachment'", "res", "[", "'id'", "]", "=", "attachment", "[", "'id'", "]", "del", "(", "attachment", "[", "'id'", "]", ")", "...
Convert attachment metadata from es to archivant format This function makes side effect on input attachment
[ "Convert", "attachment", "metadata", "from", "es", "to", "archivant", "format" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L128-L140
train
64,479
insomnia-lab/libreant
archivant/archivant.py
Archivant.denormalize_volume
def denormalize_volume(volume): '''convert volume metadata from archivant to es format''' id = volume.get('id', None) res = dict() res.update(volume['metadata']) denorm_attachments = list() for a in volume['attachments']: denorm_attachments.append(Archivant.de...
python
def denormalize_volume(volume): '''convert volume metadata from archivant to es format''' id = volume.get('id', None) res = dict() res.update(volume['metadata']) denorm_attachments = list() for a in volume['attachments']: denorm_attachments.append(Archivant.de...
[ "def", "denormalize_volume", "(", "volume", ")", ":", "id", "=", "volume", ".", "get", "(", "'id'", ",", "None", ")", "res", "=", "dict", "(", ")", "res", ".", "update", "(", "volume", "[", "'metadata'", "]", ")", "denorm_attachments", "=", "list", "...
convert volume metadata from archivant to es format
[ "convert", "volume", "metadata", "from", "archivant", "to", "es", "format" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L143-L152
train
64,480
insomnia-lab/libreant
archivant/archivant.py
Archivant.denormalize_attachment
def denormalize_attachment(attachment): '''convert attachment metadata from archivant to es format''' res = dict() ext = ['id', 'url'] for k in ext: if k in attachment['metadata']: raise ValueError("metadata section could not contain special key '{}'".format(k...
python
def denormalize_attachment(attachment): '''convert attachment metadata from archivant to es format''' res = dict() ext = ['id', 'url'] for k in ext: if k in attachment['metadata']: raise ValueError("metadata section could not contain special key '{}'".format(k...
[ "def", "denormalize_attachment", "(", "attachment", ")", ":", "res", "=", "dict", "(", ")", "ext", "=", "[", "'id'", ",", "'url'", "]", "for", "k", "in", "ext", ":", "if", "k", "in", "attachment", "[", "'metadata'", "]", ":", "raise", "ValueError", "...
convert attachment metadata from archivant to es format
[ "convert", "attachment", "metadata", "from", "archivant", "to", "es", "format" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L155-L164
train
64,481
insomnia-lab/libreant
archivant/archivant.py
Archivant.iter_all_volumes
def iter_all_volumes(self): '''iterate over all stored volumes''' for raw_volume in self._db.iterate_all(): v = self.normalize_volume(raw_volume) del v['score'] yield v
python
def iter_all_volumes(self): '''iterate over all stored volumes''' for raw_volume in self._db.iterate_all(): v = self.normalize_volume(raw_volume) del v['score'] yield v
[ "def", "iter_all_volumes", "(", "self", ")", ":", "for", "raw_volume", "in", "self", ".", "_db", ".", "iterate_all", "(", ")", ":", "v", "=", "self", ".", "normalize_volume", "(", "raw_volume", ")", "del", "v", "[", "'score'", "]", "yield", "v" ]
iterate over all stored volumes
[ "iterate", "over", "all", "stored", "volumes" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L179-L184
train
64,482
insomnia-lab/libreant
archivant/archivant.py
Archivant.delete_attachments
def delete_attachments(self, volumeID, attachmentsID): ''' delete attachments from a volume ''' log.debug("deleting attachments from volume '{}': {}".format(volumeID, attachmentsID)) rawVolume = self._req_raw_volume(volumeID) insID = [a['id'] for a in rawVolume['_source']['_attachments']...
python
def delete_attachments(self, volumeID, attachmentsID): ''' delete attachments from a volume ''' log.debug("deleting attachments from volume '{}': {}".format(volumeID, attachmentsID)) rawVolume = self._req_raw_volume(volumeID) insID = [a['id'] for a in rawVolume['_source']['_attachments']...
[ "def", "delete_attachments", "(", "self", ",", "volumeID", ",", "attachmentsID", ")", ":", "log", ".", "debug", "(", "\"deleting attachments from volume '{}': {}\"", ".", "format", "(", "volumeID", ",", "attachmentsID", ")", ")", "rawVolume", "=", "self", ".", "...
delete attachments from a volume
[ "delete", "attachments", "from", "a", "volume" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L203-L214
train
64,483
insomnia-lab/libreant
archivant/archivant.py
Archivant.insert_attachments
def insert_attachments(self, volumeID, attachments): ''' add attachments to an already existing volume ''' log.debug("adding new attachments to volume '{}': {}".format(volumeID, attachments)) if not attachments: return rawVolume = self._req_raw_volume(volumeID) attsID...
python
def insert_attachments(self, volumeID, attachments): ''' add attachments to an already existing volume ''' log.debug("adding new attachments to volume '{}': {}".format(volumeID, attachments)) if not attachments: return rawVolume = self._req_raw_volume(volumeID) attsID...
[ "def", "insert_attachments", "(", "self", ",", "volumeID", ",", "attachments", ")", ":", "log", ".", "debug", "(", "\"adding new attachments to volume '{}': {}\"", ".", "format", "(", "volumeID", ",", "attachments", ")", ")", "if", "not", "attachments", ":", "re...
add attachments to an already existing volume
[ "add", "attachments", "to", "an", "already", "existing", "volume" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L223-L239
train
64,484
insomnia-lab/libreant
archivant/archivant.py
Archivant.insert_volume
def insert_volume(self, metadata, attachments=[]): '''Insert a new volume Returns the ID of the added volume `metadata` must be a dict containg metadata of the volume:: { "_language" : "it", # language of the metadata "key1" : "value1", # attribute ...
python
def insert_volume(self, metadata, attachments=[]): '''Insert a new volume Returns the ID of the added volume `metadata` must be a dict containg metadata of the volume:: { "_language" : "it", # language of the metadata "key1" : "value1", # attribute ...
[ "def", "insert_volume", "(", "self", ",", "metadata", ",", "attachments", "=", "[", "]", ")", ":", "log", ".", "debug", "(", "\"adding new volume:\\n\\tdata: {}\\n\\tfiles: {}\"", ".", "format", "(", "metadata", ",", "attachments", ")", ")", "requiredFields", "=...
Insert a new volume Returns the ID of the added volume `metadata` must be a dict containg metadata of the volume:: { "_language" : "it", # language of the metadata "key1" : "value1", # attribute "key2" : "value2", ... ...
[ "Insert", "a", "new", "volume" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L241-L292
train
64,485
insomnia-lab/libreant
archivant/archivant.py
Archivant._assemble_attachment
def _assemble_attachment(self, file, metadata): ''' store file and return a dict containing assembled metadata param `file` must be a path or a File Object param `metadata` must be a dict: { "name" : "nome_buffo.ext" # name of the file (extensi...
python
def _assemble_attachment(self, file, metadata): ''' store file and return a dict containing assembled metadata param `file` must be a path or a File Object param `metadata` must be a dict: { "name" : "nome_buffo.ext" # name of the file (extensi...
[ "def", "_assemble_attachment", "(", "self", ",", "file", ",", "metadata", ")", ":", "res", "=", "dict", "(", ")", "if", "isinstance", "(", "file", ",", "basestring", ")", "and", "os", ".", "path", ".", "isfile", "(", "file", ")", ":", "res", "[", "...
store file and return a dict containing assembled metadata param `file` must be a path or a File Object param `metadata` must be a dict: { "name" : "nome_buffo.ext" # name of the file (extension included) [optional if a path was given] ...
[ "store", "file", "and", "return", "a", "dict", "containing", "assembled", "metadata" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L294-L338
train
64,486
insomnia-lab/libreant
archivant/archivant.py
Archivant.update_volume
def update_volume(self, volumeID, metadata): '''update existing volume metadata the given metadata will substitute the old one ''' log.debug('updating volume metadata: {}'.format(volumeID)) rawVolume = self._req_raw_volume(volumeID) normalized = self.normalize_volume(r...
python
def update_volume(self, volumeID, metadata): '''update existing volume metadata the given metadata will substitute the old one ''' log.debug('updating volume metadata: {}'.format(volumeID)) rawVolume = self._req_raw_volume(volumeID) normalized = self.normalize_volume(r...
[ "def", "update_volume", "(", "self", ",", "volumeID", ",", "metadata", ")", ":", "log", ".", "debug", "(", "'updating volume metadata: {}'", ".", "format", "(", "volumeID", ")", ")", "rawVolume", "=", "self", ".", "_req_raw_volume", "(", "volumeID", ")", "no...
update existing volume metadata the given metadata will substitute the old one
[ "update", "existing", "volume", "metadata", "the", "given", "metadata", "will", "substitute", "the", "old", "one" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L340-L349
train
64,487
insomnia-lab/libreant
archivant/archivant.py
Archivant.update_attachment
def update_attachment(self, volumeID, attachmentID, metadata): '''update an existing attachment the given metadata dict will be merged with the old one. only the following fields could be updated: [name, mime, notes, download_count] ''' log.debug('updating metadata of at...
python
def update_attachment(self, volumeID, attachmentID, metadata): '''update an existing attachment the given metadata dict will be merged with the old one. only the following fields could be updated: [name, mime, notes, download_count] ''' log.debug('updating metadata of at...
[ "def", "update_attachment", "(", "self", ",", "volumeID", ",", "attachmentID", ",", "metadata", ")", ":", "log", ".", "debug", "(", "'updating metadata of attachment {} from volume {}'", ".", "format", "(", "attachmentID", ",", "volumeID", ")", ")", "modifiable_fiel...
update an existing attachment the given metadata dict will be merged with the old one. only the following fields could be updated: [name, mime, notes, download_count]
[ "update", "an", "existing", "attachment" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L351-L377
train
64,488
insomnia-lab/libreant
archivant/archivant.py
Archivant.dangling_files
def dangling_files(self): '''iterate over fsdb files no more attached to any volume''' for fid in self._fsdb: if not self._db.file_is_attached('fsdb:///' + fid): yield fid
python
def dangling_files(self): '''iterate over fsdb files no more attached to any volume''' for fid in self._fsdb: if not self._db.file_is_attached('fsdb:///' + fid): yield fid
[ "def", "dangling_files", "(", "self", ")", ":", "for", "fid", "in", "self", ".", "_fsdb", ":", "if", "not", "self", ".", "_db", ".", "file_is_attached", "(", "'fsdb:///'", "+", "fid", ")", ":", "yield", "fid" ]
iterate over fsdb files no more attached to any volume
[ "iterate", "over", "fsdb", "files", "no", "more", "attached", "to", "any", "volume" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L386-L390
train
64,489
pricingassistant/mongokat
mongokat/_bson/__init__.py
_get_string
def _get_string(data, position, obj_end, dummy): """Decode a BSON string to python unicode string.""" length = _UNPACK_INT(data[position:position + 4])[0] position += 4 if length < 1 or obj_end - position < length: raise InvalidBSON("invalid string length") end = position + length - 1 if...
python
def _get_string(data, position, obj_end, dummy): """Decode a BSON string to python unicode string.""" length = _UNPACK_INT(data[position:position + 4])[0] position += 4 if length < 1 or obj_end - position < length: raise InvalidBSON("invalid string length") end = position + length - 1 if...
[ "def", "_get_string", "(", "data", ",", "position", ",", "obj_end", ",", "dummy", ")", ":", "length", "=", "_UNPACK_INT", "(", "data", "[", "position", ":", "position", "+", "4", "]", ")", "[", "0", "]", "position", "+=", "4", "if", "length", "<", ...
Decode a BSON string to python unicode string.
[ "Decode", "a", "BSON", "string", "to", "python", "unicode", "string", "." ]
61eaf4bc1c4cc359c6f9592ec97b9a04d9561411
https://github.com/pricingassistant/mongokat/blob/61eaf4bc1c4cc359c6f9592ec97b9a04d9561411/mongokat/_bson/__init__.py#L115-L124
train
64,490
pricingassistant/mongokat
mongokat/_bson/__init__.py
_get_regex
def _get_regex(data, position, dummy0, dummy1): """Decode a BSON regex to bson.regex.Regex or a python pattern object.""" pattern, position = _get_c_string(data, position) bson_flags, position = _get_c_string(data, position) bson_re = Regex(pattern, bson_flags) return bson_re, position
python
def _get_regex(data, position, dummy0, dummy1): """Decode a BSON regex to bson.regex.Regex or a python pattern object.""" pattern, position = _get_c_string(data, position) bson_flags, position = _get_c_string(data, position) bson_re = Regex(pattern, bson_flags) return bson_re, position
[ "def", "_get_regex", "(", "data", ",", "position", ",", "dummy0", ",", "dummy1", ")", ":", "pattern", ",", "position", "=", "_get_c_string", "(", "data", ",", "position", ")", "bson_flags", ",", "position", "=", "_get_c_string", "(", "data", ",", "position...
Decode a BSON regex to bson.regex.Regex or a python pattern object.
[ "Decode", "a", "BSON", "regex", "to", "bson", ".", "regex", ".", "Regex", "or", "a", "python", "pattern", "object", "." ]
61eaf4bc1c4cc359c6f9592ec97b9a04d9561411
https://github.com/pricingassistant/mongokat/blob/61eaf4bc1c4cc359c6f9592ec97b9a04d9561411/mongokat/_bson/__init__.py#L240-L245
train
64,491
pricingassistant/mongokat
mongokat/_bson/__init__.py
_encode_mapping
def _encode_mapping(name, value, check_keys, opts): """Encode a mapping type.""" data = b"".join([_element_to_bson(key, val, check_keys, opts) for key, val in iteritems(value)]) return b"\x03" + name + _PACK_INT(len(data) + 5) + data + b"\x00"
python
def _encode_mapping(name, value, check_keys, opts): """Encode a mapping type.""" data = b"".join([_element_to_bson(key, val, check_keys, opts) for key, val in iteritems(value)]) return b"\x03" + name + _PACK_INT(len(data) + 5) + data + b"\x00"
[ "def", "_encode_mapping", "(", "name", ",", "value", ",", "check_keys", ",", "opts", ")", ":", "data", "=", "b\"\"", ".", "join", "(", "[", "_element_to_bson", "(", "key", ",", "val", ",", "check_keys", ",", "opts", ")", "for", "key", ",", "val", "in...
Encode a mapping type.
[ "Encode", "a", "mapping", "type", "." ]
61eaf4bc1c4cc359c6f9592ec97b9a04d9561411
https://github.com/pricingassistant/mongokat/blob/61eaf4bc1c4cc359c6f9592ec97b9a04d9561411/mongokat/_bson/__init__.py#L430-L434
train
64,492
pricingassistant/mongokat
mongokat/_bson/__init__.py
_encode_code
def _encode_code(name, value, dummy, opts): """Encode bson.code.Code.""" cstring = _make_c_string(value) cstrlen = len(cstring) if not value.scope: return b"\x0D" + name + _PACK_INT(cstrlen) + cstring scope = _dict_to_bson(value.scope, False, opts, False) full_length = _PACK_INT(8 + cstr...
python
def _encode_code(name, value, dummy, opts): """Encode bson.code.Code.""" cstring = _make_c_string(value) cstrlen = len(cstring) if not value.scope: return b"\x0D" + name + _PACK_INT(cstrlen) + cstring scope = _dict_to_bson(value.scope, False, opts, False) full_length = _PACK_INT(8 + cstr...
[ "def", "_encode_code", "(", "name", ",", "value", ",", "dummy", ",", "opts", ")", ":", "cstring", "=", "_make_c_string", "(", "value", ")", "cstrlen", "=", "len", "(", "cstring", ")", "if", "not", "value", ".", "scope", ":", "return", "b\"\\x0D\"", "+"...
Encode bson.code.Code.
[ "Encode", "bson", ".", "code", ".", "Code", "." ]
61eaf4bc1c4cc359c6f9592ec97b9a04d9561411
https://github.com/pricingassistant/mongokat/blob/61eaf4bc1c4cc359c6f9592ec97b9a04d9561411/mongokat/_bson/__init__.py#L551-L559
train
64,493
insomnia-lab/libreant
users/models.py
Capability.simToReg
def simToReg(self, sim): """Convert simplified domain expression to regular expression""" # remove initial slash if present res = re.sub('^/', '', sim) res = re.sub('/$', '', res) return '^/?' + re.sub('\*', '[^/]+', res) + '/?$'
python
def simToReg(self, sim): """Convert simplified domain expression to regular expression""" # remove initial slash if present res = re.sub('^/', '', sim) res = re.sub('/$', '', res) return '^/?' + re.sub('\*', '[^/]+', res) + '/?$'
[ "def", "simToReg", "(", "self", ",", "sim", ")", ":", "# remove initial slash if present", "res", "=", "re", ".", "sub", "(", "'^/'", ",", "''", ",", "sim", ")", "res", "=", "re", ".", "sub", "(", "'/$'", ",", "''", ",", "res", ")", "return", "'^/?...
Convert simplified domain expression to regular expression
[ "Convert", "simplified", "domain", "expression", "to", "regular", "expression" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/users/models.py#L61-L66
train
64,494
insomnia-lab/libreant
users/models.py
Capability.match
def match(self, dom, act): """ Check if the given `domain` and `act` are allowed by this capability """ return self.match_domain(dom) and self.match_action(act)
python
def match(self, dom, act): """ Check if the given `domain` and `act` are allowed by this capability """ return self.match_domain(dom) and self.match_action(act)
[ "def", "match", "(", "self", ",", "dom", ",", "act", ")", ":", "return", "self", ".", "match_domain", "(", "dom", ")", "and", "self", ".", "match_action", "(", "act", ")" ]
Check if the given `domain` and `act` are allowed by this capability
[ "Check", "if", "the", "given", "domain", "and", "act", "are", "allowed", "by", "this", "capability" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/users/models.py#L81-L86
train
64,495
insomnia-lab/libreant
users/models.py
Action.to_list
def to_list(self): '''convert an actions bitmask into a list of action strings''' res = [] for a in self.__class__.ACTIONS: aBit = self.__class__.action_bitmask(a) if ((self & aBit) == aBit): res.append(a) return res
python
def to_list(self): '''convert an actions bitmask into a list of action strings''' res = [] for a in self.__class__.ACTIONS: aBit = self.__class__.action_bitmask(a) if ((self & aBit) == aBit): res.append(a) return res
[ "def", "to_list", "(", "self", ")", ":", "res", "=", "[", "]", "for", "a", "in", "self", ".", "__class__", ".", "ACTIONS", ":", "aBit", "=", "self", ".", "__class__", ".", "action_bitmask", "(", "a", ")", "if", "(", "(", "self", "&", "aBit", ")",...
convert an actions bitmask into a list of action strings
[ "convert", "an", "actions", "bitmask", "into", "a", "list", "of", "action", "strings" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/users/models.py#L115-L122
train
64,496
insomnia-lab/libreant
users/models.py
Action.from_list
def from_list(cls, actions): '''convert list of actions into the corresponding bitmask''' bitmask = 0 for a in actions: bitmask |= cls.action_bitmask(a) return Action(bitmask)
python
def from_list(cls, actions): '''convert list of actions into the corresponding bitmask''' bitmask = 0 for a in actions: bitmask |= cls.action_bitmask(a) return Action(bitmask)
[ "def", "from_list", "(", "cls", ",", "actions", ")", ":", "bitmask", "=", "0", "for", "a", "in", "actions", ":", "bitmask", "|=", "cls", ".", "action_bitmask", "(", "a", ")", "return", "Action", "(", "bitmask", ")" ]
convert list of actions into the corresponding bitmask
[ "convert", "list", "of", "actions", "into", "the", "corresponding", "bitmask" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/users/models.py#L125-L130
train
64,497
chaoss/grimoirelab-manuscripts
manuscripts2/utils.py
str_val
def str_val(val): """ Format the value of a metric value to a string :param val: number to be formatted :return: a string with the formatted value """ str_val = val if val is None: str_val = "NA" elif type(val) == float: str_val = '%0.2f' % val else: str_val ...
python
def str_val(val): """ Format the value of a metric value to a string :param val: number to be formatted :return: a string with the formatted value """ str_val = val if val is None: str_val = "NA" elif type(val) == float: str_val = '%0.2f' % val else: str_val ...
[ "def", "str_val", "(", "val", ")", ":", "str_val", "=", "val", "if", "val", "is", "None", ":", "str_val", "=", "\"NA\"", "elif", "type", "(", "val", ")", "==", "float", ":", "str_val", "=", "'%0.2f'", "%", "val", "else", ":", "str_val", "=", "str",...
Format the value of a metric value to a string :param val: number to be formatted :return: a string with the formatted value
[ "Format", "the", "value", "of", "a", "metric", "value", "to", "a", "string" ]
94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts2/utils.py#L43-L57
train
64,498
insomnia-lab/libreant
cli/__init__.py
load_cfg
def load_cfg(path, envvar_prefix='LIBREANT_', debug=False): '''wrapper of config_utils.load_configs''' try: return load_configs(envvar_prefix, path=path) except Exception as e: if debug: raise else: die(str(e))
python
def load_cfg(path, envvar_prefix='LIBREANT_', debug=False): '''wrapper of config_utils.load_configs''' try: return load_configs(envvar_prefix, path=path) except Exception as e: if debug: raise else: die(str(e))
[ "def", "load_cfg", "(", "path", ",", "envvar_prefix", "=", "'LIBREANT_'", ",", "debug", "=", "False", ")", ":", "try", ":", "return", "load_configs", "(", "envvar_prefix", ",", "path", "=", "path", ")", "except", "Exception", "as", "e", ":", "if", "debug...
wrapper of config_utils.load_configs
[ "wrapper", "of", "config_utils", ".", "load_configs" ]
55d529435baf4c05a86b8341899e9f5e14e50245
https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/cli/__init__.py#L17-L25
train
64,499