repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
vnmabus/dcor
dcor/_dcor.py
_u_distance_correlation_sqr_naive
def _u_distance_correlation_sqr_naive(x, y, exponent=1): """Bias-corrected distance correlation estimator between two matrices.""" return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_u_distance_matrix, product=u_product, exponent=exponent).correlation_xy
python
def _u_distance_correlation_sqr_naive(x, y, exponent=1): """Bias-corrected distance correlation estimator between two matrices.""" return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_u_distance_matrix, product=u_product, exponent=exponent).correlation_xy
[ "def", "_u_distance_correlation_sqr_naive", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "return", "_distance_sqr_stats_naive_generic", "(", "x", ",", "y", ",", "matrix_centered", "=", "_u_distance_matrix", ",", "product", "=", "u_product", ",", "exp...
Bias-corrected distance correlation estimator between two matrices.
[ "Bias", "-", "corrected", "distance", "correlation", "estimator", "between", "two", "matrices", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L95-L101
train
vnmabus/dcor
dcor/_dcor.py
_can_use_fast_algorithm
def _can_use_fast_algorithm(x, y, exponent=1): """ Check if the fast algorithm for distance stats can be used. The fast algorithm has complexity :math:`O(NlogN)`, better than the complexity of the naive algorithm (:math:`O(N^2)`). The algorithm can only be used for random variables (not vectors) where the number of instances is greater than 3. Also, the exponent must be 1. """ return (_is_random_variable(x) and _is_random_variable(y) and x.shape[0] > 3 and y.shape[0] > 3 and exponent == 1)
python
def _can_use_fast_algorithm(x, y, exponent=1): """ Check if the fast algorithm for distance stats can be used. The fast algorithm has complexity :math:`O(NlogN)`, better than the complexity of the naive algorithm (:math:`O(N^2)`). The algorithm can only be used for random variables (not vectors) where the number of instances is greater than 3. Also, the exponent must be 1. """ return (_is_random_variable(x) and _is_random_variable(y) and x.shape[0] > 3 and y.shape[0] > 3 and exponent == 1)
[ "def", "_can_use_fast_algorithm", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "return", "(", "_is_random_variable", "(", "x", ")", "and", "_is_random_variable", "(", "y", ")", "and", "x", ".", "shape", "[", "0", "]", ">", "3", "and", "y"...
Check if the fast algorithm for distance stats can be used. The fast algorithm has complexity :math:`O(NlogN)`, better than the complexity of the naive algorithm (:math:`O(N^2)`). The algorithm can only be used for random variables (not vectors) where the number of instances is greater than 3. Also, the exponent must be 1.
[ "Check", "if", "the", "fast", "algorithm", "for", "distance", "stats", "can", "be", "used", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L115-L127
train
vnmabus/dcor
dcor/_dcor.py
_dyad_update
def _dyad_update(y, c): # pylint:disable=too-many-locals # This function has many locals so it can be compared # with the original algorithm. """ Inner function of the fast distance covariance. This function is compiled because otherwise it would become a bottleneck. """ n = y.shape[0] gamma = np.zeros(n, dtype=c.dtype) # Step 1: get the smallest l such that n <= 2^l l_max = int(math.ceil(np.log2(n))) # Step 2: assign s(l, k) = 0 s_len = 2 ** (l_max + 1) s = np.zeros(s_len, dtype=c.dtype) pos_sums = np.arange(l_max) pos_sums[:] = 2 ** (l_max - pos_sums) pos_sums = np.cumsum(pos_sums) # Step 3: iteration for i in range(1, n): # Step 3.a: update s(l, k) for l in range(l_max): k = int(math.ceil(y[i - 1] / 2 ** l)) pos = k - 1 if l > 0: pos += pos_sums[l - 1] s[pos] += c[i - 1] # Steps 3.b and 3.c for l in range(l_max): k = int(math.floor((y[i] - 1) / 2 ** l)) if k / 2 > math.floor(k / 2): pos = k - 1 if l > 0: pos += pos_sums[l - 1] gamma[i] = gamma[i] + s[pos] return gamma
python
def _dyad_update(y, c): # pylint:disable=too-many-locals # This function has many locals so it can be compared # with the original algorithm. """ Inner function of the fast distance covariance. This function is compiled because otherwise it would become a bottleneck. """ n = y.shape[0] gamma = np.zeros(n, dtype=c.dtype) # Step 1: get the smallest l such that n <= 2^l l_max = int(math.ceil(np.log2(n))) # Step 2: assign s(l, k) = 0 s_len = 2 ** (l_max + 1) s = np.zeros(s_len, dtype=c.dtype) pos_sums = np.arange(l_max) pos_sums[:] = 2 ** (l_max - pos_sums) pos_sums = np.cumsum(pos_sums) # Step 3: iteration for i in range(1, n): # Step 3.a: update s(l, k) for l in range(l_max): k = int(math.ceil(y[i - 1] / 2 ** l)) pos = k - 1 if l > 0: pos += pos_sums[l - 1] s[pos] += c[i - 1] # Steps 3.b and 3.c for l in range(l_max): k = int(math.floor((y[i] - 1) / 2 ** l)) if k / 2 > math.floor(k / 2): pos = k - 1 if l > 0: pos += pos_sums[l - 1] gamma[i] = gamma[i] + s[pos] return gamma
[ "def", "_dyad_update", "(", "y", ",", "c", ")", ":", "# pylint:disable=too-many-locals", "# This function has many locals so it can be compared", "# with the original algorithm.", "n", "=", "y", ".", "shape", "[", "0", "]", "gamma", "=", "np", ".", "zeros", "(", "n"...
Inner function of the fast distance covariance. This function is compiled because otherwise it would become a bottleneck.
[ "Inner", "function", "of", "the", "fast", "distance", "covariance", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L131-L178
train
vnmabus/dcor
dcor/_dcor.py
_distance_covariance_sqr_fast_generic
def _distance_covariance_sqr_fast_generic( x, y, unbiased=False): # pylint:disable=too-many-locals # This function has many locals so it can be compared # with the original algorithm. """Fast algorithm for the squared distance covariance.""" x = np.asarray(x) y = np.asarray(y) x = np.ravel(x) y = np.ravel(y) n = x.shape[0] assert n > 3 assert n == y.shape[0] temp = range(n) # Step 1 ix0 = np.argsort(x) vx = x[ix0] ix = np.zeros(n, dtype=int) ix[ix0] = temp iy0 = np.argsort(y) vy = y[iy0] iy = np.zeros(n, dtype=int) iy[iy0] = temp # Step 2 sx = np.cumsum(vx) sy = np.cumsum(vy) # Step 3 alpha_x = ix alpha_y = iy beta_x = sx[ix] - vx[ix] beta_y = sy[iy] - vy[iy] # Step 4 x_dot = np.sum(x) y_dot = np.sum(y) # Step 5 a_i_dot = x_dot + (2 * alpha_x - n) * x - 2 * beta_x b_i_dot = y_dot + (2 * alpha_y - n) * y - 2 * beta_y sum_ab = np.sum(a_i_dot * b_i_dot) # Step 6 a_dot_dot = 2 * np.sum(alpha_x * x) - 2 * np.sum(beta_x) b_dot_dot = 2 * np.sum(alpha_y * y) - 2 * np.sum(beta_y) # Step 7 gamma_1 = _partial_sum_2d(x, y, np.ones(n, dtype=x.dtype)) gamma_x = _partial_sum_2d(x, y, x) gamma_y = _partial_sum_2d(x, y, y) gamma_xy = _partial_sum_2d(x, y, x * y) # Step 8 aijbij = np.sum(x * y * gamma_1 + gamma_xy - x * gamma_y - y * gamma_x) if unbiased: d3 = (n - 3) d2 = (n - 2) d1 = (n - 1) else: d3 = d2 = d1 = n # Step 9 d_cov = (aijbij / n / d3 - 2 * sum_ab / n / d2 / d3 + a_dot_dot / n * b_dot_dot / d1 / d2 / d3) return d_cov
python
def _distance_covariance_sqr_fast_generic( x, y, unbiased=False): # pylint:disable=too-many-locals # This function has many locals so it can be compared # with the original algorithm. """Fast algorithm for the squared distance covariance.""" x = np.asarray(x) y = np.asarray(y) x = np.ravel(x) y = np.ravel(y) n = x.shape[0] assert n > 3 assert n == y.shape[0] temp = range(n) # Step 1 ix0 = np.argsort(x) vx = x[ix0] ix = np.zeros(n, dtype=int) ix[ix0] = temp iy0 = np.argsort(y) vy = y[iy0] iy = np.zeros(n, dtype=int) iy[iy0] = temp # Step 2 sx = np.cumsum(vx) sy = np.cumsum(vy) # Step 3 alpha_x = ix alpha_y = iy beta_x = sx[ix] - vx[ix] beta_y = sy[iy] - vy[iy] # Step 4 x_dot = np.sum(x) y_dot = np.sum(y) # Step 5 a_i_dot = x_dot + (2 * alpha_x - n) * x - 2 * beta_x b_i_dot = y_dot + (2 * alpha_y - n) * y - 2 * beta_y sum_ab = np.sum(a_i_dot * b_i_dot) # Step 6 a_dot_dot = 2 * np.sum(alpha_x * x) - 2 * np.sum(beta_x) b_dot_dot = 2 * np.sum(alpha_y * y) - 2 * np.sum(beta_y) # Step 7 gamma_1 = _partial_sum_2d(x, y, np.ones(n, dtype=x.dtype)) gamma_x = _partial_sum_2d(x, y, x) gamma_y = _partial_sum_2d(x, y, y) gamma_xy = _partial_sum_2d(x, y, x * y) # Step 8 aijbij = np.sum(x * y * gamma_1 + gamma_xy - x * gamma_y - y * gamma_x) if unbiased: d3 = (n - 3) d2 = (n - 2) d1 = (n - 1) else: d3 = d2 = d1 = n # Step 9 d_cov = (aijbij / n / d3 - 2 * sum_ab / n / d2 / d3 + a_dot_dot / n * b_dot_dot / d1 / d2 / d3) return d_cov
[ "def", "_distance_covariance_sqr_fast_generic", "(", "x", ",", "y", ",", "unbiased", "=", "False", ")", ":", "# pylint:disable=too-many-locals", "# This function has many locals so it can be compared", "# with the original algorithm.", "x", "=", "np", ".", "asarray", "(", "...
Fast algorithm for the squared distance covariance.
[ "Fast", "algorithm", "for", "the", "squared", "distance", "covariance", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L229-L303
train
vnmabus/dcor
dcor/_dcor.py
_distance_stats_sqr_fast_generic
def _distance_stats_sqr_fast_generic(x, y, dcov_function): """Compute the distance stats using the fast algorithm.""" covariance_xy_sqr = dcov_function(x, y) variance_x_sqr = dcov_function(x, x) variance_y_sqr = dcov_function(y, y) denominator_sqr_signed = variance_x_sqr * variance_y_sqr denominator_sqr = np.absolute(denominator_sqr_signed) denominator = _sqrt(denominator_sqr) # Comparisons using a tolerance can change results if the # covariance has a similar order of magnitude if denominator == 0.0: correlation_xy_sqr = denominator.dtype.type(0) else: correlation_xy_sqr = covariance_xy_sqr / denominator return Stats(covariance_xy=covariance_xy_sqr, correlation_xy=correlation_xy_sqr, variance_x=variance_x_sqr, variance_y=variance_y_sqr)
python
def _distance_stats_sqr_fast_generic(x, y, dcov_function): """Compute the distance stats using the fast algorithm.""" covariance_xy_sqr = dcov_function(x, y) variance_x_sqr = dcov_function(x, x) variance_y_sqr = dcov_function(y, y) denominator_sqr_signed = variance_x_sqr * variance_y_sqr denominator_sqr = np.absolute(denominator_sqr_signed) denominator = _sqrt(denominator_sqr) # Comparisons using a tolerance can change results if the # covariance has a similar order of magnitude if denominator == 0.0: correlation_xy_sqr = denominator.dtype.type(0) else: correlation_xy_sqr = covariance_xy_sqr / denominator return Stats(covariance_xy=covariance_xy_sqr, correlation_xy=correlation_xy_sqr, variance_x=variance_x_sqr, variance_y=variance_y_sqr)
[ "def", "_distance_stats_sqr_fast_generic", "(", "x", ",", "y", ",", "dcov_function", ")", ":", "covariance_xy_sqr", "=", "dcov_function", "(", "x", ",", "y", ")", "variance_x_sqr", "=", "dcov_function", "(", "x", ",", "x", ")", "variance_y_sqr", "=", "dcov_fun...
Compute the distance stats using the fast algorithm.
[ "Compute", "the", "distance", "stats", "using", "the", "fast", "algorithm", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L316-L335
train
vnmabus/dcor
dcor/_dcor.py
distance_covariance_sqr
def distance_covariance_sqr(x, y, **kwargs): """ distance_covariance_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Biased estimator of the squared distance covariance. See Also -------- distance_covariance u_distance_covariance_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_covariance_sqr(a, a) 52.0 >>> dcor.distance_covariance_sqr(a, b) 1.0 >>> dcor.distance_covariance_sqr(b, b) 0.25 >>> dcor.distance_covariance_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS 0.3705904... """ if _can_use_fast_algorithm(x, y, **kwargs): return _distance_covariance_sqr_fast(x, y) else: return _distance_covariance_sqr_naive(x, y, **kwargs)
python
def distance_covariance_sqr(x, y, **kwargs): """ distance_covariance_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Biased estimator of the squared distance covariance. See Also -------- distance_covariance u_distance_covariance_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_covariance_sqr(a, a) 52.0 >>> dcor.distance_covariance_sqr(a, b) 1.0 >>> dcor.distance_covariance_sqr(b, b) 0.25 >>> dcor.distance_covariance_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS 0.3705904... """ if _can_use_fast_algorithm(x, y, **kwargs): return _distance_covariance_sqr_fast(x, y) else: return _distance_covariance_sqr_naive(x, y, **kwargs)
[ "def", "distance_covariance_sqr", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "if", "_can_use_fast_algorithm", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "return", "_distance_covariance_sqr_fast", "(", "x", ",", "y", ")", "else", ...
distance_covariance_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Biased estimator of the squared distance covariance. See Also -------- distance_covariance u_distance_covariance_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_covariance_sqr(a, a) 52.0 >>> dcor.distance_covariance_sqr(a, b) 1.0 >>> dcor.distance_covariance_sqr(b, b) 0.25 >>> dcor.distance_covariance_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS 0.3705904...
[ "distance_covariance_sqr", "(", "x", "y", "*", "exponent", "=", "1", ")" ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L360-L417
train
vnmabus/dcor
dcor/_dcor.py
u_distance_covariance_sqr
def u_distance_covariance_sqr(x, y, **kwargs): """ u_distance_covariance_sqr(x, y, *, exponent=1) Computes the unbiased estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Value of the unbiased estimator of the squared distance covariance. See Also -------- distance_covariance distance_covariance_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.u_distance_covariance_sqr(a, a) # doctest: +ELLIPSIS 42.6666666... >>> dcor.u_distance_covariance_sqr(a, b) # doctest: +ELLIPSIS -2.6666666... >>> dcor.u_distance_covariance_sqr(b, b) # doctest: +ELLIPSIS 0.6666666... >>> dcor.u_distance_covariance_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS -0.2996598... """ if _can_use_fast_algorithm(x, y, **kwargs): return _u_distance_covariance_sqr_fast(x, y) else: return _u_distance_covariance_sqr_naive(x, y, **kwargs)
python
def u_distance_covariance_sqr(x, y, **kwargs): """ u_distance_covariance_sqr(x, y, *, exponent=1) Computes the unbiased estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Value of the unbiased estimator of the squared distance covariance. See Also -------- distance_covariance distance_covariance_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.u_distance_covariance_sqr(a, a) # doctest: +ELLIPSIS 42.6666666... >>> dcor.u_distance_covariance_sqr(a, b) # doctest: +ELLIPSIS -2.6666666... >>> dcor.u_distance_covariance_sqr(b, b) # doctest: +ELLIPSIS 0.6666666... >>> dcor.u_distance_covariance_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS -0.2996598... """ if _can_use_fast_algorithm(x, y, **kwargs): return _u_distance_covariance_sqr_fast(x, y) else: return _u_distance_covariance_sqr_naive(x, y, **kwargs)
[ "def", "u_distance_covariance_sqr", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "if", "_can_use_fast_algorithm", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "return", "_u_distance_covariance_sqr_fast", "(", "x", ",", "y", ")", "else...
u_distance_covariance_sqr(x, y, *, exponent=1) Computes the unbiased estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Value of the unbiased estimator of the squared distance covariance. See Also -------- distance_covariance distance_covariance_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.u_distance_covariance_sqr(a, a) # doctest: +ELLIPSIS 42.6666666... >>> dcor.u_distance_covariance_sqr(a, b) # doctest: +ELLIPSIS -2.6666666... >>> dcor.u_distance_covariance_sqr(b, b) # doctest: +ELLIPSIS 0.6666666... >>> dcor.u_distance_covariance_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS -0.2996598...
[ "u_distance_covariance_sqr", "(", "x", "y", "*", "exponent", "=", "1", ")" ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L420-L477
train
vnmabus/dcor
dcor/_dcor.py
distance_stats_sqr
def distance_stats_sqr(x, y, **kwargs): """ distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- Stats Squared distance covariance, squared distance correlation, squared distance variance of the first random vector and squared distance variance of the second random vector. See Also -------- distance_covariance_sqr distance_correlation_sqr Notes ----- It is less efficient to compute the statistics separately, rather than using this function, because some computations can be shared. The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_stats_sqr(a, a) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=52.0, correlation_xy=1.0, variance_x=52.0, variance_y=52.0) >>> dcor.distance_stats_sqr(a, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=1.0, correlation_xy=0.2773500..., variance_x=52.0, variance_y=0.25) >>> dcor.distance_stats_sqr(b, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.25, correlation_xy=1.0, variance_x=0.25, variance_y=0.25) >>> dcor.distance_stats_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.3705904..., correlation_xy=0.4493308..., variance_x=2.7209220..., variance_y=0.25) """ if _can_use_fast_algorithm(x, y, **kwargs): return _distance_stats_sqr_fast(x, y) else: return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_distance_matrix, product=mean_product, **kwargs)
python
def distance_stats_sqr(x, y, **kwargs): """ distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- Stats Squared distance covariance, squared distance correlation, squared distance variance of the first random vector and squared distance variance of the second random vector. See Also -------- distance_covariance_sqr distance_correlation_sqr Notes ----- It is less efficient to compute the statistics separately, rather than using this function, because some computations can be shared. The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_stats_sqr(a, a) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=52.0, correlation_xy=1.0, variance_x=52.0, variance_y=52.0) >>> dcor.distance_stats_sqr(a, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=1.0, correlation_xy=0.2773500..., variance_x=52.0, variance_y=0.25) >>> dcor.distance_stats_sqr(b, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.25, correlation_xy=1.0, variance_x=0.25, variance_y=0.25) >>> dcor.distance_stats_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.3705904..., correlation_xy=0.4493308..., variance_x=2.7209220..., variance_y=0.25) """ if _can_use_fast_algorithm(x, y, **kwargs): return _distance_stats_sqr_fast(x, y) else: return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_distance_matrix, product=mean_product, **kwargs)
[ "def", "distance_stats_sqr", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "if", "_can_use_fast_algorithm", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "return", "_distance_stats_sqr_fast", "(", "x", ",", "y", ")", "else", ":", "r...
distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- Stats Squared distance covariance, squared distance correlation, squared distance variance of the first random vector and squared distance variance of the second random vector. See Also -------- distance_covariance_sqr distance_correlation_sqr Notes ----- It is less efficient to compute the statistics separately, rather than using this function, because some computations can be shared. The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_stats_sqr(a, a) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=52.0, correlation_xy=1.0, variance_x=52.0, variance_y=52.0) >>> dcor.distance_stats_sqr(a, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=1.0, correlation_xy=0.2773500..., variance_x=52.0, variance_y=0.25) >>> dcor.distance_stats_sqr(b, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.25, correlation_xy=1.0, variance_x=0.25, variance_y=0.25) >>> dcor.distance_stats_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.3705904..., correlation_xy=0.4493308..., variance_x=2.7209220..., variance_y=0.25)
[ "distance_stats_sqr", "(", "x", "y", "*", "exponent", "=", "1", ")" ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L537-L609
train
vnmabus/dcor
dcor/_dcor.py
u_distance_stats_sqr
def u_distance_stats_sqr(x, y, **kwargs): """ u_distance_stats_sqr(x, y, *, exponent=1) Computes the unbiased estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- Stats Squared distance covariance, squared distance correlation, squared distance variance of the first random vector and squared distance variance of the second random vector. See Also -------- u_distance_covariance_sqr u_distance_correlation_sqr Notes ----- It is less efficient to compute the statistics separately, rather than using this function, because some computations can be shared. The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.u_distance_stats_sqr(a, a) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=42.6666666..., correlation_xy=1.0, variance_x=42.6666666..., variance_y=42.6666666...) >>> dcor.u_distance_stats_sqr(a, b) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=-2.6666666..., correlation_xy=-0.5, variance_x=42.6666666..., variance_y=0.6666666...) >>> dcor.u_distance_stats_sqr(b, b) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.6666666..., correlation_xy=1.0, variance_x=0.6666666..., variance_y=0.6666666...) >>> dcor.u_distance_stats_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=-0.2996598..., correlation_xy=-0.4050479..., variance_x=0.8209855..., variance_y=0.6666666...) """ if _can_use_fast_algorithm(x, y, **kwargs): return _u_distance_stats_sqr_fast(x, y) else: return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_u_distance_matrix, product=u_product, **kwargs)
python
def u_distance_stats_sqr(x, y, **kwargs): """ u_distance_stats_sqr(x, y, *, exponent=1) Computes the unbiased estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- Stats Squared distance covariance, squared distance correlation, squared distance variance of the first random vector and squared distance variance of the second random vector. See Also -------- u_distance_covariance_sqr u_distance_correlation_sqr Notes ----- It is less efficient to compute the statistics separately, rather than using this function, because some computations can be shared. The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.u_distance_stats_sqr(a, a) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=42.6666666..., correlation_xy=1.0, variance_x=42.6666666..., variance_y=42.6666666...) >>> dcor.u_distance_stats_sqr(a, b) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=-2.6666666..., correlation_xy=-0.5, variance_x=42.6666666..., variance_y=0.6666666...) >>> dcor.u_distance_stats_sqr(b, b) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.6666666..., correlation_xy=1.0, variance_x=0.6666666..., variance_y=0.6666666...) >>> dcor.u_distance_stats_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=-0.2996598..., correlation_xy=-0.4050479..., variance_x=0.8209855..., variance_y=0.6666666...) """ if _can_use_fast_algorithm(x, y, **kwargs): return _u_distance_stats_sqr_fast(x, y) else: return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_u_distance_matrix, product=u_product, **kwargs)
[ "def", "u_distance_stats_sqr", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "if", "_can_use_fast_algorithm", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "return", "_u_distance_stats_sqr_fast", "(", "x", ",", "y", ")", "else", ":", ...
u_distance_stats_sqr(x, y, *, exponent=1) Computes the unbiased estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- Stats Squared distance covariance, squared distance correlation, squared distance variance of the first random vector and squared distance variance of the second random vector. See Also -------- u_distance_covariance_sqr u_distance_correlation_sqr Notes ----- It is less efficient to compute the statistics separately, rather than using this function, because some computations can be shared. The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.u_distance_stats_sqr(a, a) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=42.6666666..., correlation_xy=1.0, variance_x=42.6666666..., variance_y=42.6666666...) >>> dcor.u_distance_stats_sqr(a, b) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=-2.6666666..., correlation_xy=-0.5, variance_x=42.6666666..., variance_y=0.6666666...) >>> dcor.u_distance_stats_sqr(b, b) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.6666666..., correlation_xy=1.0, variance_x=0.6666666..., variance_y=0.6666666...) >>> dcor.u_distance_stats_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=-0.2996598..., correlation_xy=-0.4050479..., variance_x=0.8209855..., variance_y=0.6666666...)
[ "u_distance_stats_sqr", "(", "x", "y", "*", "exponent", "=", "1", ")" ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L612-L687
train
vnmabus/dcor
dcor/_dcor.py
distance_stats
def distance_stats(x, y, **kwargs): """ distance_stats(x, y, *, exponent=1) Computes the usual (biased) estimators for the distance covariance and distance correlation between two random vectors, and the individual distance variances. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- Stats Distance covariance, distance correlation, distance variance of the first random vector and distance variance of the second random vector. See Also -------- distance_covariance distance_correlation Notes ----- It is less efficient to compute the statistics separately, rather than using this function, because some computations can be shared. The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_stats(a, a) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=7.2111025..., correlation_xy=1.0, variance_x=7.2111025..., variance_y=7.2111025...) >>> dcor.distance_stats(a, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=1.0, correlation_xy=0.5266403..., variance_x=7.2111025..., variance_y=0.5) >>> dcor.distance_stats(b, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.5, correlation_xy=1.0, variance_x=0.5, variance_y=0.5) >>> dcor.distance_stats(a, b, exponent=0.5) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.6087614..., correlation_xy=0.6703214..., variance_x=1.6495217..., variance_y=0.5) """ return Stats(*[_sqrt(s) for s in distance_stats_sqr(x, y, **kwargs)])
python
def distance_stats(x, y, **kwargs): """ distance_stats(x, y, *, exponent=1) Computes the usual (biased) estimators for the distance covariance and distance correlation between two random vectors, and the individual distance variances. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- Stats Distance covariance, distance correlation, distance variance of the first random vector and distance variance of the second random vector. See Also -------- distance_covariance distance_correlation Notes ----- It is less efficient to compute the statistics separately, rather than using this function, because some computations can be shared. The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_stats(a, a) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=7.2111025..., correlation_xy=1.0, variance_x=7.2111025..., variance_y=7.2111025...) >>> dcor.distance_stats(a, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=1.0, correlation_xy=0.5266403..., variance_x=7.2111025..., variance_y=0.5) >>> dcor.distance_stats(b, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.5, correlation_xy=1.0, variance_x=0.5, variance_y=0.5) >>> dcor.distance_stats(a, b, exponent=0.5) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.6087614..., correlation_xy=0.6703214..., variance_x=1.6495217..., variance_y=0.5) """ return Stats(*[_sqrt(s) for s in distance_stats_sqr(x, y, **kwargs)])
[ "def", "distance_stats", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "return", "Stats", "(", "*", "[", "_sqrt", "(", "s", ")", "for", "s", "in", "distance_stats_sqr", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", "]", ")" ]
distance_stats(x, y, *, exponent=1) Computes the usual (biased) estimators for the distance covariance and distance correlation between two random vectors, and the individual distance variances. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- Stats Distance covariance, distance correlation, distance variance of the first random vector and distance variance of the second random vector. See Also -------- distance_covariance distance_correlation Notes ----- It is less efficient to compute the statistics separately, rather than using this function, because some computations can be shared. The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_stats(a, a) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=7.2111025..., correlation_xy=1.0, variance_x=7.2111025..., variance_y=7.2111025...) >>> dcor.distance_stats(a, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=1.0, correlation_xy=0.5266403..., variance_x=7.2111025..., variance_y=0.5) >>> dcor.distance_stats(b, b) # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.5, correlation_xy=1.0, variance_x=0.5, variance_y=0.5) >>> dcor.distance_stats(a, b, exponent=0.5) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE Stats(covariance_xy=0.6087614..., correlation_xy=0.6703214..., variance_x=1.6495217..., variance_y=0.5)
[ "distance_stats", "(", "x", "y", "*", "exponent", "=", "1", ")" ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L690-L755
train
vnmabus/dcor
dcor/_dcor.py
distance_correlation_sqr
def distance_correlation_sqr(x, y, **kwargs): """ distance_correlation_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance correlation between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Value of the biased estimator of the squared distance correlation. See Also -------- distance_correlation u_distance_correlation_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_correlation_sqr(a, a) 1.0 >>> dcor.distance_correlation_sqr(a, b) # doctest: +ELLIPSIS 0.2773500... >>> dcor.distance_correlation_sqr(b, b) 1.0 >>> dcor.distance_correlation_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS 0.4493308... """ if _can_use_fast_algorithm(x, y, **kwargs): return _distance_correlation_sqr_fast(x, y) else: return _distance_correlation_sqr_naive(x, y, **kwargs)
python
def distance_correlation_sqr(x, y, **kwargs): """ distance_correlation_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance correlation between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Value of the biased estimator of the squared distance correlation. See Also -------- distance_correlation u_distance_correlation_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_correlation_sqr(a, a) 1.0 >>> dcor.distance_correlation_sqr(a, b) # doctest: +ELLIPSIS 0.2773500... >>> dcor.distance_correlation_sqr(b, b) 1.0 >>> dcor.distance_correlation_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS 0.4493308... """ if _can_use_fast_algorithm(x, y, **kwargs): return _distance_correlation_sqr_fast(x, y) else: return _distance_correlation_sqr_naive(x, y, **kwargs)
[ "def", "distance_correlation_sqr", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "if", "_can_use_fast_algorithm", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "return", "_distance_correlation_sqr_fast", "(", "x", ",", "y", ")", "else",...
distance_correlation_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance correlation between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Value of the biased estimator of the squared distance correlation. See Also -------- distance_correlation u_distance_correlation_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_correlation_sqr(a, a) 1.0 >>> dcor.distance_correlation_sqr(a, b) # doctest: +ELLIPSIS 0.2773500... >>> dcor.distance_correlation_sqr(b, b) 1.0 >>> dcor.distance_correlation_sqr(a, b, exponent=0.5) # doctest: +ELLIPSIS 0.4493308...
[ "distance_correlation_sqr", "(", "x", "y", "*", "exponent", "=", "1", ")" ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L758-L815
train
vnmabus/dcor
dcor/_dcor.py
u_distance_correlation_sqr
def u_distance_correlation_sqr(x, y, **kwargs): """ u_distance_correlation_sqr(x, y, *, exponent=1) Computes the bias-corrected estimator for the squared distance correlation between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Value of the bias-corrected estimator of the squared distance correlation. See Also -------- distance_correlation distance_correlation_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.u_distance_correlation_sqr(a, a) 1.0 >>> dcor.u_distance_correlation_sqr(a, b) -0.5 >>> dcor.u_distance_correlation_sqr(b, b) 1.0 >>> dcor.u_distance_correlation_sqr(a, b, exponent=0.5) ... # doctest: +ELLIPSIS -0.4050479... """ if _can_use_fast_algorithm(x, y, **kwargs): return _u_distance_correlation_sqr_fast(x, y) else: return _u_distance_correlation_sqr_naive(x, y, **kwargs)
python
def u_distance_correlation_sqr(x, y, **kwargs): """ u_distance_correlation_sqr(x, y, *, exponent=1) Computes the bias-corrected estimator for the squared distance correlation between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Value of the bias-corrected estimator of the squared distance correlation. See Also -------- distance_correlation distance_correlation_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.u_distance_correlation_sqr(a, a) 1.0 >>> dcor.u_distance_correlation_sqr(a, b) -0.5 >>> dcor.u_distance_correlation_sqr(b, b) 1.0 >>> dcor.u_distance_correlation_sqr(a, b, exponent=0.5) ... # doctest: +ELLIPSIS -0.4050479... """ if _can_use_fast_algorithm(x, y, **kwargs): return _u_distance_correlation_sqr_fast(x, y) else: return _u_distance_correlation_sqr_naive(x, y, **kwargs)
[ "def", "u_distance_correlation_sqr", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "if", "_can_use_fast_algorithm", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "return", "_u_distance_correlation_sqr_fast", "(", "x", ",", "y", ")", "el...
u_distance_correlation_sqr(x, y, *, exponent=1) Computes the bias-corrected estimator for the squared distance correlation between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. Returns ------- numpy scalar Value of the bias-corrected estimator of the squared distance correlation. See Also -------- distance_correlation distance_correlation_sqr Notes ----- The algorithm uses the fast distance covariance algorithm proposed in :cite:`b-fast_distance_correlation` when possible. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.u_distance_correlation_sqr(a, a) 1.0 >>> dcor.u_distance_correlation_sqr(a, b) -0.5 >>> dcor.u_distance_correlation_sqr(b, b) 1.0 >>> dcor.u_distance_correlation_sqr(a, b, exponent=0.5) ... # doctest: +ELLIPSIS -0.4050479...
[ "u_distance_correlation_sqr", "(", "x", "y", "*", "exponent", "=", "1", ")" ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L818-L877
train
vnmabus/dcor
dcor/_dcor.py
distance_correlation_af_inv_sqr
def distance_correlation_af_inv_sqr(x, y): """ Square of the affinely invariant distance correlation. Computes the estimator for the square of the affinely invariant distance correlation between two random vectors. .. warning:: The return value of this function is undefined when the covariance matrix of :math:`x` or :math:`y` is singular. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- numpy scalar Value of the estimator of the squared affinely invariant distance correlation. See Also -------- distance_correlation u_distance_correlation Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 3, 2, 5], ... [5, 7, 6, 8], ... [9, 10, 11, 12], ... [13, 15, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_correlation_af_inv_sqr(a, a) 1.0 >>> dcor.distance_correlation_af_inv_sqr(a, b) # doctest: +ELLIPSIS 0.5773502... >>> dcor.distance_correlation_af_inv_sqr(b, b) 1.0 """ x = _af_inv_scaled(x) y = _af_inv_scaled(y) correlation = distance_correlation_sqr(x, y) return 0 if np.isnan(correlation) else correlation
python
def distance_correlation_af_inv_sqr(x, y): """ Square of the affinely invariant distance correlation. Computes the estimator for the square of the affinely invariant distance correlation between two random vectors. .. warning:: The return value of this function is undefined when the covariance matrix of :math:`x` or :math:`y` is singular. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- numpy scalar Value of the estimator of the squared affinely invariant distance correlation. See Also -------- distance_correlation u_distance_correlation Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 3, 2, 5], ... [5, 7, 6, 8], ... [9, 10, 11, 12], ... [13, 15, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_correlation_af_inv_sqr(a, a) 1.0 >>> dcor.distance_correlation_af_inv_sqr(a, b) # doctest: +ELLIPSIS 0.5773502... >>> dcor.distance_correlation_af_inv_sqr(b, b) 1.0 """ x = _af_inv_scaled(x) y = _af_inv_scaled(y) correlation = distance_correlation_sqr(x, y) return 0 if np.isnan(correlation) else correlation
[ "def", "distance_correlation_af_inv_sqr", "(", "x", ",", "y", ")", ":", "x", "=", "_af_inv_scaled", "(", "x", ")", "y", "=", "_af_inv_scaled", "(", "y", ")", "correlation", "=", "distance_correlation_sqr", "(", "x", ",", "y", ")", "return", "0", "if", "n...
Square of the affinely invariant distance correlation. Computes the estimator for the square of the affinely invariant distance correlation between two random vectors. .. warning:: The return value of this function is undefined when the covariance matrix of :math:`x` or :math:`y` is singular. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- numpy scalar Value of the estimator of the squared affinely invariant distance correlation. See Also -------- distance_correlation u_distance_correlation Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 3, 2, 5], ... [5, 7, 6, 8], ... [9, 10, 11, 12], ... [13, 15, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> dcor.distance_correlation_af_inv_sqr(a, a) 1.0 >>> dcor.distance_correlation_af_inv_sqr(a, b) # doctest: +ELLIPSIS 0.5773502... >>> dcor.distance_correlation_af_inv_sqr(b, b) 1.0
[ "Square", "of", "the", "affinely", "invariant", "distance", "correlation", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L937-L988
train
vnmabus/dcor
dcor/_pairwise.py
pairwise
def pairwise(function, x, y=None, **kwargs): """ pairwise(function, x, y=None, *, pool=None, is_symmetric=None, **kwargs) Computes a dependency measure between each pair of elements. Parameters ---------- function: Dependency measure function. x: iterable of array_like First list of random vectors. The columns of each vector correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second list of random vectors. The columns of each vector correspond with the individual random variables while the rows are individual instances of the random vector. If None, the :math:`x` array is used. pool: object implementing multiprocessing.Pool interface Pool of processes/threads used to delegate computations. is_symmetric: bool or None If True, the dependency function is assumed to be symmetric. If False, it is assumed non-symmetric. If None (the default value), the attribute :code:`is_symmetric` of the function object is inspected to determine if the function is symmetric. If this attribute is absent, the function is assumed to not be symmetric. kwargs: dictionary Additional options necessary. Returns ------- numpy ndarray A :math:`n \times m` matrix where the :math:`(i, j)`-th entry is the dependency between :math:`x[i]` and :math:`y[j]`. Examples -------- >>> import numpy as np >>> import dcor >>> a = [np.array([[1, 1], ... [2, 4], ... [3, 8], ... [4, 16]]), ... np.array([[9, 10], ... [11, 12], ... [13, 14], ... [15, 16]]) ... ] >>> b = [np.array([[0, 1], ... [3, 1], ... [6, 2], ... [9, 3]]), ... np.array([[5, 1], ... [8, 1], ... [13, 1], ... [21, 1]]) ... ] >>> dcor.pairwise(dcor.distance_covariance, a) array([[4.61229635, 3.35991482], [3.35991482, 2.54950976]]) >>> dcor.pairwise(dcor.distance_correlation, a, b) array([[0.98182263, 0.99901855], [0.99989466, 0.98320103]]) A pool object can be used to improve performance for a large number of computations: >>> import multiprocessing >>> pool = multiprocessing.Pool() >>> dcor.pairwise(dcor.distance_correlation, a, b, pool=pool) array([[0.98182263, 0.99901855], [0.99989466, 0.98320103]]) It is possible to force to consider that the function is symmetric or not (useful only if :math:`y` is :code:`None`): >>> dcor.pairwise(dcor.distance_covariance, a, is_symmetric=True) array([[4.61229635, 3.35991482], [3.35991482, 2.54950976]]) >>> dcor.pairwise(dcor.distance_covariance, a, is_symmetric=False) array([[4.61229635, 3.35991482], [3.35991482, 2.54950976]]) """ return _pairwise_imp(function, x, y, **kwargs)
python
def pairwise(function, x, y=None, **kwargs): """ pairwise(function, x, y=None, *, pool=None, is_symmetric=None, **kwargs) Computes a dependency measure between each pair of elements. Parameters ---------- function: Dependency measure function. x: iterable of array_like First list of random vectors. The columns of each vector correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second list of random vectors. The columns of each vector correspond with the individual random variables while the rows are individual instances of the random vector. If None, the :math:`x` array is used. pool: object implementing multiprocessing.Pool interface Pool of processes/threads used to delegate computations. is_symmetric: bool or None If True, the dependency function is assumed to be symmetric. If False, it is assumed non-symmetric. If None (the default value), the attribute :code:`is_symmetric` of the function object is inspected to determine if the function is symmetric. If this attribute is absent, the function is assumed to not be symmetric. kwargs: dictionary Additional options necessary. Returns ------- numpy ndarray A :math:`n \times m` matrix where the :math:`(i, j)`-th entry is the dependency between :math:`x[i]` and :math:`y[j]`. Examples -------- >>> import numpy as np >>> import dcor >>> a = [np.array([[1, 1], ... [2, 4], ... [3, 8], ... [4, 16]]), ... np.array([[9, 10], ... [11, 12], ... [13, 14], ... [15, 16]]) ... ] >>> b = [np.array([[0, 1], ... [3, 1], ... [6, 2], ... [9, 3]]), ... np.array([[5, 1], ... [8, 1], ... [13, 1], ... [21, 1]]) ... ] >>> dcor.pairwise(dcor.distance_covariance, a) array([[4.61229635, 3.35991482], [3.35991482, 2.54950976]]) >>> dcor.pairwise(dcor.distance_correlation, a, b) array([[0.98182263, 0.99901855], [0.99989466, 0.98320103]]) A pool object can be used to improve performance for a large number of computations: >>> import multiprocessing >>> pool = multiprocessing.Pool() >>> dcor.pairwise(dcor.distance_correlation, a, b, pool=pool) array([[0.98182263, 0.99901855], [0.99989466, 0.98320103]]) It is possible to force to consider that the function is symmetric or not (useful only if :math:`y` is :code:`None`): >>> dcor.pairwise(dcor.distance_covariance, a, is_symmetric=True) array([[4.61229635, 3.35991482], [3.35991482, 2.54950976]]) >>> dcor.pairwise(dcor.distance_covariance, a, is_symmetric=False) array([[4.61229635, 3.35991482], [3.35991482, 2.54950976]]) """ return _pairwise_imp(function, x, y, **kwargs)
[ "def", "pairwise", "(", "function", ",", "x", ",", "y", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_pairwise_imp", "(", "function", ",", "x", ",", "y", ",", "*", "*", "kwargs", ")" ]
pairwise(function, x, y=None, *, pool=None, is_symmetric=None, **kwargs) Computes a dependency measure between each pair of elements. Parameters ---------- function: Dependency measure function. x: iterable of array_like First list of random vectors. The columns of each vector correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second list of random vectors. The columns of each vector correspond with the individual random variables while the rows are individual instances of the random vector. If None, the :math:`x` array is used. pool: object implementing multiprocessing.Pool interface Pool of processes/threads used to delegate computations. is_symmetric: bool or None If True, the dependency function is assumed to be symmetric. If False, it is assumed non-symmetric. If None (the default value), the attribute :code:`is_symmetric` of the function object is inspected to determine if the function is symmetric. If this attribute is absent, the function is assumed to not be symmetric. kwargs: dictionary Additional options necessary. Returns ------- numpy ndarray A :math:`n \times m` matrix where the :math:`(i, j)`-th entry is the dependency between :math:`x[i]` and :math:`y[j]`. Examples -------- >>> import numpy as np >>> import dcor >>> a = [np.array([[1, 1], ... [2, 4], ... [3, 8], ... [4, 16]]), ... np.array([[9, 10], ... [11, 12], ... [13, 14], ... [15, 16]]) ... ] >>> b = [np.array([[0, 1], ... [3, 1], ... [6, 2], ... [9, 3]]), ... np.array([[5, 1], ... [8, 1], ... [13, 1], ... [21, 1]]) ... ] >>> dcor.pairwise(dcor.distance_covariance, a) array([[4.61229635, 3.35991482], [3.35991482, 2.54950976]]) >>> dcor.pairwise(dcor.distance_correlation, a, b) array([[0.98182263, 0.99901855], [0.99989466, 0.98320103]]) A pool object can be used to improve performance for a large number of computations: >>> import multiprocessing >>> pool = multiprocessing.Pool() >>> dcor.pairwise(dcor.distance_correlation, a, b, pool=pool) array([[0.98182263, 0.99901855], [0.99989466, 0.98320103]]) It is possible to force to consider that the function is symmetric or not (useful only if :math:`y` is :code:`None`): >>> dcor.pairwise(dcor.distance_covariance, a, is_symmetric=True) array([[4.61229635, 3.35991482], [3.35991482, 2.54950976]]) >>> dcor.pairwise(dcor.distance_covariance, a, is_symmetric=False) array([[4.61229635, 3.35991482], [3.35991482, 2.54950976]])
[ "pairwise", "(", "function", "x", "y", "=", "None", "*", "pool", "=", "None", "is_symmetric", "=", "None", "**", "kwargs", ")" ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_pairwise.py#L10-L94
train
vnmabus/dcor
dcor/_pairwise.py
_pairwise_imp
def _pairwise_imp(function, x, y=None, pool=None, is_symmetric=None, **kwargs): """ Real implementation of :func:`pairwise`. This function is used to make several parameters keyword-only in Python 2. """ map_function = pool.map if pool else map if is_symmetric is None: is_symmetric = getattr(function, 'is_symmetric', False) pairwise_function = getattr(function, 'pairwise_function', None) if pairwise_function: return pairwise_function(x, y, pool=pool, is_symmetric=is_symmetric, **kwargs) if y is None and is_symmetric: partial = functools.partial(_map_aux_func_symmetric, x=x, function=function) dependencies = np.array(list(map_function(partial, enumerate(x)))) for i in range(len(x)): for j in range(i, len(x)): dependencies[j, i] = dependencies[i, j] return dependencies else: if y is None: y = x partial = functools.partial(_map_aux_func, y=y, function=function) return np.array(list(map_function(partial, x)))
python
def _pairwise_imp(function, x, y=None, pool=None, is_symmetric=None, **kwargs): """ Real implementation of :func:`pairwise`. This function is used to make several parameters keyword-only in Python 2. """ map_function = pool.map if pool else map if is_symmetric is None: is_symmetric = getattr(function, 'is_symmetric', False) pairwise_function = getattr(function, 'pairwise_function', None) if pairwise_function: return pairwise_function(x, y, pool=pool, is_symmetric=is_symmetric, **kwargs) if y is None and is_symmetric: partial = functools.partial(_map_aux_func_symmetric, x=x, function=function) dependencies = np.array(list(map_function(partial, enumerate(x)))) for i in range(len(x)): for j in range(i, len(x)): dependencies[j, i] = dependencies[i, j] return dependencies else: if y is None: y = x partial = functools.partial(_map_aux_func, y=y, function=function) return np.array(list(map_function(partial, x)))
[ "def", "_pairwise_imp", "(", "function", ",", "x", ",", "y", "=", "None", ",", "pool", "=", "None", ",", "is_symmetric", "=", "None", ",", "*", "*", "kwargs", ")", ":", "map_function", "=", "pool", ".", "map", "if", "pool", "else", "map", "if", "is...
Real implementation of :func:`pairwise`. This function is used to make several parameters keyword-only in Python 2.
[ "Real", "implementation", "of", ":", "func", ":", "pairwise", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_pairwise.py#L97-L134
train
vnmabus/dcor
dcor/_utils.py
_jit
def _jit(function): """ Compile a function using a jit compiler. The function is always compiled to check errors, but is only used outside tests, so that code coverage analysis can be performed in jitted functions. The tests set sys._called_from_test in conftest.py. """ import sys compiled = numba.jit(function) if hasattr(sys, '_called_from_test'): return function else: # pragma: no cover return compiled
python
def _jit(function): """ Compile a function using a jit compiler. The function is always compiled to check errors, but is only used outside tests, so that code coverage analysis can be performed in jitted functions. The tests set sys._called_from_test in conftest.py. """ import sys compiled = numba.jit(function) if hasattr(sys, '_called_from_test'): return function else: # pragma: no cover return compiled
[ "def", "_jit", "(", "function", ")", ":", "import", "sys", "compiled", "=", "numba", ".", "jit", "(", "function", ")", "if", "hasattr", "(", "sys", ",", "'_called_from_test'", ")", ":", "return", "function", "else", ":", "# pragma: no cover", "return", "co...
Compile a function using a jit compiler. The function is always compiled to check errors, but is only used outside tests, so that code coverage analysis can be performed in jitted functions. The tests set sys._called_from_test in conftest.py.
[ "Compile", "a", "function", "using", "a", "jit", "compiler", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_utils.py#L10-L27
train
vnmabus/dcor
dcor/_utils.py
_sqrt
def _sqrt(x): """ Return square root of an ndarray. This sqrt function for ndarrays tries to use the exponentiation operator if the objects stored do not supply a sqrt method. """ x = np.clip(x, a_min=0, a_max=None) try: return np.sqrt(x) except AttributeError: exponent = 0.5 try: exponent = np.take(x, 0).from_float(exponent) except AttributeError: pass return x ** exponent
python
def _sqrt(x): """ Return square root of an ndarray. This sqrt function for ndarrays tries to use the exponentiation operator if the objects stored do not supply a sqrt method. """ x = np.clip(x, a_min=0, a_max=None) try: return np.sqrt(x) except AttributeError: exponent = 0.5 try: exponent = np.take(x, 0).from_float(exponent) except AttributeError: pass return x ** exponent
[ "def", "_sqrt", "(", "x", ")", ":", "x", "=", "np", ".", "clip", "(", "x", ",", "a_min", "=", "0", ",", "a_max", "=", "None", ")", "try", ":", "return", "np", ".", "sqrt", "(", "x", ")", "except", "AttributeError", ":", "exponent", "=", "0.5", ...
Return square root of an ndarray. This sqrt function for ndarrays tries to use the exponentiation operator if the objects stored do not supply a sqrt method.
[ "Return", "square", "root", "of", "an", "ndarray", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_utils.py#L30-L50
train
vnmabus/dcor
dcor/_utils.py
_transform_to_2d
def _transform_to_2d(t): """Convert vectors to column matrices, to always have a 2d shape.""" t = np.asarray(t) dim = len(t.shape) assert dim <= 2 if dim < 2: t = np.atleast_2d(t).T return t
python
def _transform_to_2d(t): """Convert vectors to column matrices, to always have a 2d shape.""" t = np.asarray(t) dim = len(t.shape) assert dim <= 2 if dim < 2: t = np.atleast_2d(t).T return t
[ "def", "_transform_to_2d", "(", "t", ")", ":", "t", "=", "np", ".", "asarray", "(", "t", ")", "dim", "=", "len", "(", "t", ".", "shape", ")", "assert", "dim", "<=", "2", "if", "dim", "<", "2", ":", "t", "=", "np", ".", "atleast_2d", "(", "t",...
Convert vectors to column matrices, to always have a 2d shape.
[ "Convert", "vectors", "to", "column", "matrices", "to", "always", "have", "a", "2d", "shape", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_utils.py#L53-L63
train
vnmabus/dcor
dcor/_utils.py
_can_be_double
def _can_be_double(x): """ Return if the array can be safely converted to double. That happens when the dtype is a float with the same size of a double or narrower, or when is an integer that can be safely converted to double (if the roundtrip conversion works). """ return ((np.issubdtype(x.dtype, np.floating) and x.dtype.itemsize <= np.dtype(float).itemsize) or (np.issubdtype(x.dtype, np.signedinteger) and np.can_cast(x, float)))
python
def _can_be_double(x): """ Return if the array can be safely converted to double. That happens when the dtype is a float with the same size of a double or narrower, or when is an integer that can be safely converted to double (if the roundtrip conversion works). """ return ((np.issubdtype(x.dtype, np.floating) and x.dtype.itemsize <= np.dtype(float).itemsize) or (np.issubdtype(x.dtype, np.signedinteger) and np.can_cast(x, float)))
[ "def", "_can_be_double", "(", "x", ")", ":", "return", "(", "(", "np", ".", "issubdtype", "(", "x", ".", "dtype", ",", "np", ".", "floating", ")", "and", "x", ".", "dtype", ".", "itemsize", "<=", "np", ".", "dtype", "(", "float", ")", ".", "items...
Return if the array can be safely converted to double. That happens when the dtype is a float with the same size of a double or narrower, or when is an integer that can be safely converted to double (if the roundtrip conversion works).
[ "Return", "if", "the", "array", "can", "be", "safely", "converted", "to", "double", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_utils.py#L66-L78
train
vnmabus/dcor
dcor/distances.py
_cdist_naive
def _cdist_naive(x, y, exponent=1): """Pairwise distance, custom implementation.""" squared_norms = ((x[_np.newaxis, :, :] - y[:, _np.newaxis, :]) ** 2).sum(2) exponent = exponent / 2 try: exponent = squared_norms.take(0).from_float(exponent) except AttributeError: pass return squared_norms ** exponent
python
def _cdist_naive(x, y, exponent=1): """Pairwise distance, custom implementation.""" squared_norms = ((x[_np.newaxis, :, :] - y[:, _np.newaxis, :]) ** 2).sum(2) exponent = exponent / 2 try: exponent = squared_norms.take(0).from_float(exponent) except AttributeError: pass return squared_norms ** exponent
[ "def", "_cdist_naive", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "squared_norms", "=", "(", "(", "x", "[", "_np", ".", "newaxis", ",", ":", ",", ":", "]", "-", "y", "[", ":", ",", "_np", ".", "newaxis", ",", ":", "]", ")", "*...
Pairwise distance, custom implementation.
[ "Pairwise", "distance", "custom", "implementation", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/distances.py#L18-L28
train
vnmabus/dcor
dcor/distances.py
_pdist_scipy
def _pdist_scipy(x, exponent=1): """Pairwise distance between points in a set.""" metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.pdist(x, metric=metric) distances = _spatial.distance.squareform(distances) if exponent != 1: distances **= exponent / 2 return distances
python
def _pdist_scipy(x, exponent=1): """Pairwise distance between points in a set.""" metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.pdist(x, metric=metric) distances = _spatial.distance.squareform(distances) if exponent != 1: distances **= exponent / 2 return distances
[ "def", "_pdist_scipy", "(", "x", ",", "exponent", "=", "1", ")", ":", "metric", "=", "'euclidean'", "if", "exponent", "!=", "1", ":", "metric", "=", "'sqeuclidean'", "distances", "=", "_spatial", ".", "distance", ".", "pdist", "(", "x", ",", "metric", ...
Pairwise distance between points in a set.
[ "Pairwise", "distance", "between", "points", "in", "a", "set", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/distances.py#L31-L44
train
vnmabus/dcor
dcor/distances.py
_cdist_scipy
def _cdist_scipy(x, y, exponent=1): """Pairwise distance between the points in two sets.""" metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.cdist(x, y, metric=metric) if exponent != 1: distances **= exponent / 2 return distances
python
def _cdist_scipy(x, y, exponent=1): """Pairwise distance between the points in two sets.""" metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.cdist(x, y, metric=metric) if exponent != 1: distances **= exponent / 2 return distances
[ "def", "_cdist_scipy", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "metric", "=", "'euclidean'", "if", "exponent", "!=", "1", ":", "metric", "=", "'sqeuclidean'", "distances", "=", "_spatial", ".", "distance", ".", "cdist", "(", "x", ",", ...
Pairwise distance between the points in two sets.
[ "Pairwise", "distance", "between", "the", "points", "in", "two", "sets", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/distances.py#L47-L59
train
vnmabus/dcor
dcor/distances.py
_pdist
def _pdist(x, exponent=1): """ Pairwise distance between points in a set. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double. """ if _can_be_double(x): return _pdist_scipy(x, exponent) else: return _cdist_naive(x, x, exponent)
python
def _pdist(x, exponent=1): """ Pairwise distance between points in a set. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double. """ if _can_be_double(x): return _pdist_scipy(x, exponent) else: return _cdist_naive(x, x, exponent)
[ "def", "_pdist", "(", "x", ",", "exponent", "=", "1", ")", ":", "if", "_can_be_double", "(", "x", ")", ":", "return", "_pdist_scipy", "(", "x", ",", "exponent", ")", "else", ":", "return", "_cdist_naive", "(", "x", ",", "x", ",", "exponent", ")" ]
Pairwise distance between points in a set. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double.
[ "Pairwise", "distance", "between", "points", "in", "a", "set", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/distances.py#L62-L74
train
vnmabus/dcor
dcor/distances.py
_cdist
def _cdist(x, y, exponent=1): """ Pairwise distance between points in two sets. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double. """ if _can_be_double(x) and _can_be_double(y): return _cdist_scipy(x, y, exponent) else: return _cdist_naive(x, y, exponent)
python
def _cdist(x, y, exponent=1): """ Pairwise distance between points in two sets. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double. """ if _can_be_double(x) and _can_be_double(y): return _cdist_scipy(x, y, exponent) else: return _cdist_naive(x, y, exponent)
[ "def", "_cdist", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "if", "_can_be_double", "(", "x", ")", "and", "_can_be_double", "(", "y", ")", ":", "return", "_cdist_scipy", "(", "x", ",", "y", ",", "exponent", ")", "else", ":", "return",...
Pairwise distance between points in two sets. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double.
[ "Pairwise", "distance", "between", "points", "in", "two", "sets", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/distances.py#L77-L89
train
vnmabus/dcor
dcor/distances.py
pairwise_distances
def pairwise_distances(x, y=None, **kwargs): r""" pairwise_distances(x, y=None, *, exponent=1) Pairwise distance between points. Return the pairwise distance between points in two sets, or in the same set if only one set is passed. Parameters ---------- x: array_like An :math:`n \times m` array of :math:`n` observations in a :math:`m`-dimensional space. y: array_like An :math:`l \times m` array of :math:`l` observations in a :math:`m`-dimensional space. If None, the distances will be computed between the points in :math:`x`. exponent: float Exponent of the Euclidean distance. Returns ------- numpy ndarray A :math:`n \times l` matrix where the :math:`(i, j)`-th entry is the distance between :math:`x[i]` and :math:`y[j]`. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[16, 15, 14, 13], ... [12, 11, 10, 9], ... [8, 7, 6, 5], ... [4, 3, 2, 1]]) >>> dcor.distances.pairwise_distances(a) array([[ 0., 8., 16., 24.], [ 8., 0., 8., 16.], [16., 8., 0., 8.], [24., 16., 8., 0.]]) >>> dcor.distances.pairwise_distances(a, b) array([[24.41311123, 16.61324773, 9.16515139, 4.47213595], [16.61324773, 9.16515139, 4.47213595, 9.16515139], [ 9.16515139, 4.47213595, 9.16515139, 16.61324773], [ 4.47213595, 9.16515139, 16.61324773, 24.41311123]]) """ x = _transform_to_2d(x) if y is None or y is x: return _pdist(x, **kwargs) else: y = _transform_to_2d(y) return _cdist(x, y, **kwargs)
python
def pairwise_distances(x, y=None, **kwargs): r""" pairwise_distances(x, y=None, *, exponent=1) Pairwise distance between points. Return the pairwise distance between points in two sets, or in the same set if only one set is passed. Parameters ---------- x: array_like An :math:`n \times m` array of :math:`n` observations in a :math:`m`-dimensional space. y: array_like An :math:`l \times m` array of :math:`l` observations in a :math:`m`-dimensional space. If None, the distances will be computed between the points in :math:`x`. exponent: float Exponent of the Euclidean distance. Returns ------- numpy ndarray A :math:`n \times l` matrix where the :math:`(i, j)`-th entry is the distance between :math:`x[i]` and :math:`y[j]`. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[16, 15, 14, 13], ... [12, 11, 10, 9], ... [8, 7, 6, 5], ... [4, 3, 2, 1]]) >>> dcor.distances.pairwise_distances(a) array([[ 0., 8., 16., 24.], [ 8., 0., 8., 16.], [16., 8., 0., 8.], [24., 16., 8., 0.]]) >>> dcor.distances.pairwise_distances(a, b) array([[24.41311123, 16.61324773, 9.16515139, 4.47213595], [16.61324773, 9.16515139, 4.47213595, 9.16515139], [ 9.16515139, 4.47213595, 9.16515139, 16.61324773], [ 4.47213595, 9.16515139, 16.61324773, 24.41311123]]) """ x = _transform_to_2d(x) if y is None or y is x: return _pdist(x, **kwargs) else: y = _transform_to_2d(y) return _cdist(x, y, **kwargs)
[ "def", "pairwise_distances", "(", "x", ",", "y", "=", "None", ",", "*", "*", "kwargs", ")", ":", "x", "=", "_transform_to_2d", "(", "x", ")", "if", "y", "is", "None", "or", "y", "is", "x", ":", "return", "_pdist", "(", "x", ",", "*", "*", "kwar...
r""" pairwise_distances(x, y=None, *, exponent=1) Pairwise distance between points. Return the pairwise distance between points in two sets, or in the same set if only one set is passed. Parameters ---------- x: array_like An :math:`n \times m` array of :math:`n` observations in a :math:`m`-dimensional space. y: array_like An :math:`l \times m` array of :math:`l` observations in a :math:`m`-dimensional space. If None, the distances will be computed between the points in :math:`x`. exponent: float Exponent of the Euclidean distance. Returns ------- numpy ndarray A :math:`n \times l` matrix where the :math:`(i, j)`-th entry is the distance between :math:`x[i]` and :math:`y[j]`. Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[16, 15, 14, 13], ... [12, 11, 10, 9], ... [8, 7, 6, 5], ... [4, 3, 2, 1]]) >>> dcor.distances.pairwise_distances(a) array([[ 0., 8., 16., 24.], [ 8., 0., 8., 16.], [16., 8., 0., 8.], [24., 16., 8., 0.]]) >>> dcor.distances.pairwise_distances(a, b) array([[24.41311123, 16.61324773, 9.16515139, 4.47213595], [16.61324773, 9.16515139, 4.47213595, 9.16515139], [ 9.16515139, 4.47213595, 9.16515139, 16.61324773], [ 4.47213595, 9.16515139, 16.61324773, 24.41311123]])
[ "r", "pairwise_distances", "(", "x", "y", "=", "None", "*", "exponent", "=", "1", ")" ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/distances.py#L92-L149
train
kumar303/mohawk
mohawk/receiver.py
Receiver.respond
def respond(self, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, ext=None): """ Respond to the request. This generates the :attr:`mohawk.Receiver.response_header` attribute. :param content=EmptyValue: Byte string of response body that will be sent. :type content=EmptyValue: str :param content_type=EmptyValue: content-type header value for response. :type content_type=EmptyValue: str :param always_hash_content=True: When True, ``content`` and ``content_type`` must be provided. Read :ref:`skipping-content-checks` to learn more. :type always_hash_content=True: bool :param ext=None: An external `Hawk`_ string. If not None, this value will be signed so that the sender can trust it. :type ext=None: str .. _`Hawk`: https://github.com/hueniverse/hawk """ log.debug('generating response header') resource = Resource(url=self.resource.url, credentials=self.resource.credentials, ext=ext, app=self.parsed_header.get('app', None), dlg=self.parsed_header.get('dlg', None), method=self.resource.method, content=content, content_type=content_type, always_hash_content=always_hash_content, nonce=self.parsed_header['nonce'], timestamp=self.parsed_header['ts']) mac = calculate_mac('response', resource, resource.gen_content_hash()) self.response_header = self._make_header(resource, mac, additional_keys=['ext']) return self.response_header
python
def respond(self, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, ext=None): """ Respond to the request. This generates the :attr:`mohawk.Receiver.response_header` attribute. :param content=EmptyValue: Byte string of response body that will be sent. :type content=EmptyValue: str :param content_type=EmptyValue: content-type header value for response. :type content_type=EmptyValue: str :param always_hash_content=True: When True, ``content`` and ``content_type`` must be provided. Read :ref:`skipping-content-checks` to learn more. :type always_hash_content=True: bool :param ext=None: An external `Hawk`_ string. If not None, this value will be signed so that the sender can trust it. :type ext=None: str .. _`Hawk`: https://github.com/hueniverse/hawk """ log.debug('generating response header') resource = Resource(url=self.resource.url, credentials=self.resource.credentials, ext=ext, app=self.parsed_header.get('app', None), dlg=self.parsed_header.get('dlg', None), method=self.resource.method, content=content, content_type=content_type, always_hash_content=always_hash_content, nonce=self.parsed_header['nonce'], timestamp=self.parsed_header['ts']) mac = calculate_mac('response', resource, resource.gen_content_hash()) self.response_header = self._make_header(resource, mac, additional_keys=['ext']) return self.response_header
[ "def", "respond", "(", "self", ",", "content", "=", "EmptyValue", ",", "content_type", "=", "EmptyValue", ",", "always_hash_content", "=", "True", ",", "ext", "=", "None", ")", ":", "log", ".", "debug", "(", "'generating response header'", ")", "resource", "...
Respond to the request. This generates the :attr:`mohawk.Receiver.response_header` attribute. :param content=EmptyValue: Byte string of response body that will be sent. :type content=EmptyValue: str :param content_type=EmptyValue: content-type header value for response. :type content_type=EmptyValue: str :param always_hash_content=True: When True, ``content`` and ``content_type`` must be provided. Read :ref:`skipping-content-checks` to learn more. :type always_hash_content=True: bool :param ext=None: An external `Hawk`_ string. If not None, this value will be signed so that the sender can trust it. :type ext=None: str .. _`Hawk`: https://github.com/hueniverse/hawk
[ "Respond", "to", "the", "request", "." ]
037be67ccf50ae704705e67add44e02737a65d21
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/receiver.py#L123-L171
train
kumar303/mohawk
mohawk/util.py
calculate_payload_hash
def calculate_payload_hash(payload, algorithm, content_type): """Calculates a hash for a given payload.""" p_hash = hashlib.new(algorithm) parts = [] parts.append('hawk.' + str(HAWK_VER) + '.payload\n') parts.append(parse_content_type(content_type) + '\n') parts.append(payload or '') parts.append('\n') for i, p in enumerate(parts): # Make sure we are about to hash binary strings. if not isinstance(p, six.binary_type): p = p.encode('utf8') p_hash.update(p) parts[i] = p log.debug('calculating payload hash from:\n{parts}' .format(parts=pprint.pformat(parts))) return b64encode(p_hash.digest())
python
def calculate_payload_hash(payload, algorithm, content_type): """Calculates a hash for a given payload.""" p_hash = hashlib.new(algorithm) parts = [] parts.append('hawk.' + str(HAWK_VER) + '.payload\n') parts.append(parse_content_type(content_type) + '\n') parts.append(payload or '') parts.append('\n') for i, p in enumerate(parts): # Make sure we are about to hash binary strings. if not isinstance(p, six.binary_type): p = p.encode('utf8') p_hash.update(p) parts[i] = p log.debug('calculating payload hash from:\n{parts}' .format(parts=pprint.pformat(parts))) return b64encode(p_hash.digest())
[ "def", "calculate_payload_hash", "(", "payload", ",", "algorithm", ",", "content_type", ")", ":", "p_hash", "=", "hashlib", ".", "new", "(", "algorithm", ")", "parts", "=", "[", "]", "parts", ".", "append", "(", "'hawk.'", "+", "str", "(", "HAWK_VER", ")...
Calculates a hash for a given payload.
[ "Calculates", "a", "hash", "for", "a", "given", "payload", "." ]
037be67ccf50ae704705e67add44e02737a65d21
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/util.py#L49-L69
train
kumar303/mohawk
mohawk/util.py
calculate_mac
def calculate_mac(mac_type, resource, content_hash): """Calculates a message authorization code (MAC).""" normalized = normalize_string(mac_type, resource, content_hash) log.debug(u'normalized resource for mac calc: {norm}' .format(norm=normalized)) digestmod = getattr(hashlib, resource.credentials['algorithm']) # Make sure we are about to hash binary strings. if not isinstance(normalized, six.binary_type): normalized = normalized.encode('utf8') key = resource.credentials['key'] if not isinstance(key, six.binary_type): key = key.encode('ascii') result = hmac.new(key, normalized, digestmod) return b64encode(result.digest())
python
def calculate_mac(mac_type, resource, content_hash): """Calculates a message authorization code (MAC).""" normalized = normalize_string(mac_type, resource, content_hash) log.debug(u'normalized resource for mac calc: {norm}' .format(norm=normalized)) digestmod = getattr(hashlib, resource.credentials['algorithm']) # Make sure we are about to hash binary strings. if not isinstance(normalized, six.binary_type): normalized = normalized.encode('utf8') key = resource.credentials['key'] if not isinstance(key, six.binary_type): key = key.encode('ascii') result = hmac.new(key, normalized, digestmod) return b64encode(result.digest())
[ "def", "calculate_mac", "(", "mac_type", ",", "resource", ",", "content_hash", ")", ":", "normalized", "=", "normalize_string", "(", "mac_type", ",", "resource", ",", "content_hash", ")", "log", ".", "debug", "(", "u'normalized resource for mac calc: {norm}'", ".", ...
Calculates a message authorization code (MAC).
[ "Calculates", "a", "message", "authorization", "code", "(", "MAC", ")", "." ]
037be67ccf50ae704705e67add44e02737a65d21
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/util.py#L72-L88
train
kumar303/mohawk
mohawk/util.py
calculate_ts_mac
def calculate_ts_mac(ts, credentials): """Calculates a message authorization code (MAC) for a timestamp.""" normalized = ('hawk.{hawk_ver}.ts\n{ts}\n' .format(hawk_ver=HAWK_VER, ts=ts)) log.debug(u'normalized resource for ts mac calc: {norm}' .format(norm=normalized)) digestmod = getattr(hashlib, credentials['algorithm']) if not isinstance(normalized, six.binary_type): normalized = normalized.encode('utf8') key = credentials['key'] if not isinstance(key, six.binary_type): key = key.encode('ascii') result = hmac.new(key, normalized, digestmod) return b64encode(result.digest())
python
def calculate_ts_mac(ts, credentials): """Calculates a message authorization code (MAC) for a timestamp.""" normalized = ('hawk.{hawk_ver}.ts\n{ts}\n' .format(hawk_ver=HAWK_VER, ts=ts)) log.debug(u'normalized resource for ts mac calc: {norm}' .format(norm=normalized)) digestmod = getattr(hashlib, credentials['algorithm']) if not isinstance(normalized, six.binary_type): normalized = normalized.encode('utf8') key = credentials['key'] if not isinstance(key, six.binary_type): key = key.encode('ascii') result = hmac.new(key, normalized, digestmod) return b64encode(result.digest())
[ "def", "calculate_ts_mac", "(", "ts", ",", "credentials", ")", ":", "normalized", "=", "(", "'hawk.{hawk_ver}.ts\\n{ts}\\n'", ".", "format", "(", "hawk_ver", "=", "HAWK_VER", ",", "ts", "=", "ts", ")", ")", "log", ".", "debug", "(", "u'normalized resource for ...
Calculates a message authorization code (MAC) for a timestamp.
[ "Calculates", "a", "message", "authorization", "code", "(", "MAC", ")", "for", "a", "timestamp", "." ]
037be67ccf50ae704705e67add44e02737a65d21
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/util.py#L91-L106
train
kumar303/mohawk
mohawk/util.py
normalize_string
def normalize_string(mac_type, resource, content_hash): """Serializes mac_type and resource into a HAWK string.""" normalized = [ 'hawk.' + str(HAWK_VER) + '.' + mac_type, normalize_header_attr(resource.timestamp), normalize_header_attr(resource.nonce), normalize_header_attr(resource.method or ''), normalize_header_attr(resource.name or ''), normalize_header_attr(resource.host), normalize_header_attr(resource.port), normalize_header_attr(content_hash or '') ] # The blank lines are important. They follow what the Node Hawk lib does. normalized.append(normalize_header_attr(resource.ext or '')) if resource.app: normalized.append(normalize_header_attr(resource.app)) normalized.append(normalize_header_attr(resource.dlg or '')) # Add trailing new line. normalized.append('') normalized = '\n'.join(normalized) return normalized
python
def normalize_string(mac_type, resource, content_hash): """Serializes mac_type and resource into a HAWK string.""" normalized = [ 'hawk.' + str(HAWK_VER) + '.' + mac_type, normalize_header_attr(resource.timestamp), normalize_header_attr(resource.nonce), normalize_header_attr(resource.method or ''), normalize_header_attr(resource.name or ''), normalize_header_attr(resource.host), normalize_header_attr(resource.port), normalize_header_attr(content_hash or '') ] # The blank lines are important. They follow what the Node Hawk lib does. normalized.append(normalize_header_attr(resource.ext or '')) if resource.app: normalized.append(normalize_header_attr(resource.app)) normalized.append(normalize_header_attr(resource.dlg or '')) # Add trailing new line. normalized.append('') normalized = '\n'.join(normalized) return normalized
[ "def", "normalize_string", "(", "mac_type", ",", "resource", ",", "content_hash", ")", ":", "normalized", "=", "[", "'hawk.'", "+", "str", "(", "HAWK_VER", ")", "+", "'.'", "+", "mac_type", ",", "normalize_header_attr", "(", "resource", ".", "timestamp", ")"...
Serializes mac_type and resource into a HAWK string.
[ "Serializes", "mac_type", "and", "resource", "into", "a", "HAWK", "string", "." ]
037be67ccf50ae704705e67add44e02737a65d21
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/util.py#L109-L136
train
kumar303/mohawk
mohawk/util.py
parse_authorization_header
def parse_authorization_header(auth_header): """ Example Authorization header: 'Hawk id="dh37fgj492je", ts="1367076201", nonce="NPHgnG", ext="and welcome!", mac="CeWHy4d9kbLGhDlkyw2Nh3PJ7SDOdZDa267KH4ZaNMY="' """ if len(auth_header) > MAX_LENGTH: raise BadHeaderValue('Header exceeds maximum length of {max_length}'.format( max_length=MAX_LENGTH)) # Make sure we have a unicode object for consistency. if isinstance(auth_header, six.binary_type): auth_header = auth_header.decode('utf8') scheme, attributes_string = auth_header.split(' ', 1) if scheme.lower() != 'hawk': raise HawkFail("Unknown scheme '{scheme}' when parsing header" .format(scheme=scheme)) attributes = {} def replace_attribute(match): """Extract the next key="value"-pair in the header.""" key = match.group('key') value = match.group('value') if key not in allowable_header_keys: raise HawkFail("Unknown Hawk key '{key}' when parsing header" .format(key=key)) validate_header_attr(value, name=key) if key in attributes: raise BadHeaderValue('Duplicate key in header: {key}'.format(key=key)) attributes[key] = value # Iterate over all the key="value"-pairs in the header, replace them with # an empty string, and store the extracted attribute in the attributes # dict. Correctly formed headers will then leave nothing unparsed (''). unparsed_header = HAWK_HEADER_RE.sub(replace_attribute, attributes_string) if unparsed_header != '': raise BadHeaderValue("Couldn't parse Hawk header", unparsed_header) log.debug('parsed Hawk header: {header} into: \n{parsed}' .format(header=auth_header, parsed=pprint.pformat(attributes))) return attributes
python
def parse_authorization_header(auth_header): """ Example Authorization header: 'Hawk id="dh37fgj492je", ts="1367076201", nonce="NPHgnG", ext="and welcome!", mac="CeWHy4d9kbLGhDlkyw2Nh3PJ7SDOdZDa267KH4ZaNMY="' """ if len(auth_header) > MAX_LENGTH: raise BadHeaderValue('Header exceeds maximum length of {max_length}'.format( max_length=MAX_LENGTH)) # Make sure we have a unicode object for consistency. if isinstance(auth_header, six.binary_type): auth_header = auth_header.decode('utf8') scheme, attributes_string = auth_header.split(' ', 1) if scheme.lower() != 'hawk': raise HawkFail("Unknown scheme '{scheme}' when parsing header" .format(scheme=scheme)) attributes = {} def replace_attribute(match): """Extract the next key="value"-pair in the header.""" key = match.group('key') value = match.group('value') if key not in allowable_header_keys: raise HawkFail("Unknown Hawk key '{key}' when parsing header" .format(key=key)) validate_header_attr(value, name=key) if key in attributes: raise BadHeaderValue('Duplicate key in header: {key}'.format(key=key)) attributes[key] = value # Iterate over all the key="value"-pairs in the header, replace them with # an empty string, and store the extracted attribute in the attributes # dict. Correctly formed headers will then leave nothing unparsed (''). unparsed_header = HAWK_HEADER_RE.sub(replace_attribute, attributes_string) if unparsed_header != '': raise BadHeaderValue("Couldn't parse Hawk header", unparsed_header) log.debug('parsed Hawk header: {header} into: \n{parsed}' .format(header=auth_header, parsed=pprint.pformat(attributes))) return attributes
[ "def", "parse_authorization_header", "(", "auth_header", ")", ":", "if", "len", "(", "auth_header", ")", ">", "MAX_LENGTH", ":", "raise", "BadHeaderValue", "(", "'Header exceeds maximum length of {max_length}'", ".", "format", "(", "max_length", "=", "MAX_LENGTH", ")"...
Example Authorization header: 'Hawk id="dh37fgj492je", ts="1367076201", nonce="NPHgnG", ext="and welcome!", mac="CeWHy4d9kbLGhDlkyw2Nh3PJ7SDOdZDa267KH4ZaNMY="'
[ "Example", "Authorization", "header", ":" ]
037be67ccf50ae704705e67add44e02737a65d21
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/util.py#L147-L192
train
kumar303/mohawk
mohawk/bewit.py
get_bewit
def get_bewit(resource): """ Returns a bewit identifier for the resource as a string. :param resource: Resource to generate a bewit for :type resource: `mohawk.base.Resource` """ if resource.method != 'GET': raise ValueError('bewits can only be generated for GET requests') if resource.nonce != '': raise ValueError('bewits must use an empty nonce') mac = calculate_mac( 'bewit', resource, None, ) if isinstance(mac, six.binary_type): mac = mac.decode('ascii') if resource.ext is None: ext = '' else: validate_header_attr(resource.ext, name='ext') ext = resource.ext # b64encode works only with bytes in python3, but all of our parameters are # in unicode, so we need to encode them. The cleanest way to do this that # works in both python 2 and 3 is to use string formatting to get a # unicode string, and then explicitly encode it to bytes. inner_bewit = u"{id}\\{exp}\\{mac}\\{ext}".format( id=resource.credentials['id'], exp=resource.timestamp, mac=mac, ext=ext, ) inner_bewit_bytes = inner_bewit.encode('ascii') bewit_bytes = urlsafe_b64encode(inner_bewit_bytes) # Now decode the resulting bytes back to a unicode string return bewit_bytes.decode('ascii')
python
def get_bewit(resource): """ Returns a bewit identifier for the resource as a string. :param resource: Resource to generate a bewit for :type resource: `mohawk.base.Resource` """ if resource.method != 'GET': raise ValueError('bewits can only be generated for GET requests') if resource.nonce != '': raise ValueError('bewits must use an empty nonce') mac = calculate_mac( 'bewit', resource, None, ) if isinstance(mac, six.binary_type): mac = mac.decode('ascii') if resource.ext is None: ext = '' else: validate_header_attr(resource.ext, name='ext') ext = resource.ext # b64encode works only with bytes in python3, but all of our parameters are # in unicode, so we need to encode them. The cleanest way to do this that # works in both python 2 and 3 is to use string formatting to get a # unicode string, and then explicitly encode it to bytes. inner_bewit = u"{id}\\{exp}\\{mac}\\{ext}".format( id=resource.credentials['id'], exp=resource.timestamp, mac=mac, ext=ext, ) inner_bewit_bytes = inner_bewit.encode('ascii') bewit_bytes = urlsafe_b64encode(inner_bewit_bytes) # Now decode the resulting bytes back to a unicode string return bewit_bytes.decode('ascii')
[ "def", "get_bewit", "(", "resource", ")", ":", "if", "resource", ".", "method", "!=", "'GET'", ":", "raise", "ValueError", "(", "'bewits can only be generated for GET requests'", ")", "if", "resource", ".", "nonce", "!=", "''", ":", "raise", "ValueError", "(", ...
Returns a bewit identifier for the resource as a string. :param resource: Resource to generate a bewit for :type resource: `mohawk.base.Resource`
[ "Returns", "a", "bewit", "identifier", "for", "the", "resource", "as", "a", "string", "." ]
037be67ccf50ae704705e67add44e02737a65d21
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/bewit.py#L21-L61
train
kumar303/mohawk
mohawk/bewit.py
parse_bewit
def parse_bewit(bewit): """ Returns a `bewittuple` representing the parts of an encoded bewit string. This has the following named attributes: (id, expiration, mac, ext) :param bewit: A base64 encoded bewit string :type bewit: str """ decoded_bewit = b64decode(bewit).decode('ascii') bewit_parts = decoded_bewit.split("\\") if len(bewit_parts) != 4: raise InvalidBewit('Expected 4 parts to bewit: %s' % decoded_bewit) return bewittuple(*bewit_parts)
python
def parse_bewit(bewit): """ Returns a `bewittuple` representing the parts of an encoded bewit string. This has the following named attributes: (id, expiration, mac, ext) :param bewit: A base64 encoded bewit string :type bewit: str """ decoded_bewit = b64decode(bewit).decode('ascii') bewit_parts = decoded_bewit.split("\\") if len(bewit_parts) != 4: raise InvalidBewit('Expected 4 parts to bewit: %s' % decoded_bewit) return bewittuple(*bewit_parts)
[ "def", "parse_bewit", "(", "bewit", ")", ":", "decoded_bewit", "=", "b64decode", "(", "bewit", ")", ".", "decode", "(", "'ascii'", ")", "bewit_parts", "=", "decoded_bewit", ".", "split", "(", "\"\\\\\"", ")", "if", "len", "(", "bewit_parts", ")", "!=", "...
Returns a `bewittuple` representing the parts of an encoded bewit string. This has the following named attributes: (id, expiration, mac, ext) :param bewit: A base64 encoded bewit string :type bewit: str
[ "Returns", "a", "bewittuple", "representing", "the", "parts", "of", "an", "encoded", "bewit", "string", ".", "This", "has", "the", "following", "named", "attributes", ":", "(", "id", "expiration", "mac", "ext", ")" ]
037be67ccf50ae704705e67add44e02737a65d21
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/bewit.py#L67-L81
train
kumar303/mohawk
mohawk/bewit.py
strip_bewit
def strip_bewit(url): """ Strips the bewit parameter out of a url. Returns (encoded_bewit, stripped_url) Raises InvalidBewit if no bewit found. :param url: The url containing a bewit parameter :type url: str """ m = re.search('[?&]bewit=([^&]+)', url) if not m: raise InvalidBewit('no bewit data found') bewit = m.group(1) stripped_url = url[:m.start()] + url[m.end():] return bewit, stripped_url
python
def strip_bewit(url): """ Strips the bewit parameter out of a url. Returns (encoded_bewit, stripped_url) Raises InvalidBewit if no bewit found. :param url: The url containing a bewit parameter :type url: str """ m = re.search('[?&]bewit=([^&]+)', url) if not m: raise InvalidBewit('no bewit data found') bewit = m.group(1) stripped_url = url[:m.start()] + url[m.end():] return bewit, stripped_url
[ "def", "strip_bewit", "(", "url", ")", ":", "m", "=", "re", ".", "search", "(", "'[?&]bewit=([^&]+)'", ",", "url", ")", "if", "not", "m", ":", "raise", "InvalidBewit", "(", "'no bewit data found'", ")", "bewit", "=", "m", ".", "group", "(", "1", ")", ...
Strips the bewit parameter out of a url. Returns (encoded_bewit, stripped_url) Raises InvalidBewit if no bewit found. :param url: The url containing a bewit parameter :type url: str
[ "Strips", "the", "bewit", "parameter", "out", "of", "a", "url", "." ]
037be67ccf50ae704705e67add44e02737a65d21
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/bewit.py#L84-L101
train
kumar303/mohawk
mohawk/bewit.py
check_bewit
def check_bewit(url, credential_lookup, now=None): """ Validates the given bewit. Returns True if the resource has a valid bewit parameter attached, or raises a subclass of HawkFail otherwise. :param credential_lookup: Callable to look up the credentials dict by sender ID. The credentials dict must have the keys: ``id``, ``key``, and ``algorithm``. See :ref:`receiving-request` for an example. :type credential_lookup: callable :param now=None: Unix epoch time for the current time to determine if bewit has expired. If None, then the current time as given by utc_now() is used. :type now=None: integer """ raw_bewit, stripped_url = strip_bewit(url) bewit = parse_bewit(raw_bewit) try: credentials = credential_lookup(bewit.id) except LookupError: raise CredentialsLookupError('Could not find credentials for ID {0}' .format(bewit.id)) res = Resource(url=stripped_url, method='GET', credentials=credentials, timestamp=bewit.expiration, nonce='', ext=bewit.ext, ) mac = calculate_mac('bewit', res, None) mac = mac.decode('ascii') if not strings_match(mac, bewit.mac): raise MacMismatch('bewit with mac {bewit_mac} did not match expected mac {expected_mac}' .format(bewit_mac=bewit.mac, expected_mac=mac)) # Check that the timestamp isn't expired if now is None: # TODO: Add offset/skew now = utc_now() if int(bewit.expiration) < now: # TODO: Refactor TokenExpired to handle this better raise TokenExpired('bewit with UTC timestamp {ts} has expired; ' 'it was compared to {now}' .format(ts=bewit.expiration, now=now), localtime_in_seconds=now, www_authenticate='' ) return True
python
def check_bewit(url, credential_lookup, now=None): """ Validates the given bewit. Returns True if the resource has a valid bewit parameter attached, or raises a subclass of HawkFail otherwise. :param credential_lookup: Callable to look up the credentials dict by sender ID. The credentials dict must have the keys: ``id``, ``key``, and ``algorithm``. See :ref:`receiving-request` for an example. :type credential_lookup: callable :param now=None: Unix epoch time for the current time to determine if bewit has expired. If None, then the current time as given by utc_now() is used. :type now=None: integer """ raw_bewit, stripped_url = strip_bewit(url) bewit = parse_bewit(raw_bewit) try: credentials = credential_lookup(bewit.id) except LookupError: raise CredentialsLookupError('Could not find credentials for ID {0}' .format(bewit.id)) res = Resource(url=stripped_url, method='GET', credentials=credentials, timestamp=bewit.expiration, nonce='', ext=bewit.ext, ) mac = calculate_mac('bewit', res, None) mac = mac.decode('ascii') if not strings_match(mac, bewit.mac): raise MacMismatch('bewit with mac {bewit_mac} did not match expected mac {expected_mac}' .format(bewit_mac=bewit.mac, expected_mac=mac)) # Check that the timestamp isn't expired if now is None: # TODO: Add offset/skew now = utc_now() if int(bewit.expiration) < now: # TODO: Refactor TokenExpired to handle this better raise TokenExpired('bewit with UTC timestamp {ts} has expired; ' 'it was compared to {now}' .format(ts=bewit.expiration, now=now), localtime_in_seconds=now, www_authenticate='' ) return True
[ "def", "check_bewit", "(", "url", ",", "credential_lookup", ",", "now", "=", "None", ")", ":", "raw_bewit", ",", "stripped_url", "=", "strip_bewit", "(", "url", ")", "bewit", "=", "parse_bewit", "(", "raw_bewit", ")", "try", ":", "credentials", "=", "crede...
Validates the given bewit. Returns True if the resource has a valid bewit parameter attached, or raises a subclass of HawkFail otherwise. :param credential_lookup: Callable to look up the credentials dict by sender ID. The credentials dict must have the keys: ``id``, ``key``, and ``algorithm``. See :ref:`receiving-request` for an example. :type credential_lookup: callable :param now=None: Unix epoch time for the current time to determine if bewit has expired. If None, then the current time as given by utc_now() is used. :type now=None: integer
[ "Validates", "the", "given", "bewit", "." ]
037be67ccf50ae704705e67add44e02737a65d21
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/bewit.py#L104-L159
train
kumar303/mohawk
mohawk/sender.py
Sender.accept_response
def accept_response(self, response_header, content=EmptyValue, content_type=EmptyValue, accept_untrusted_content=False, localtime_offset_in_seconds=0, timestamp_skew_in_seconds=default_ts_skew_in_seconds, **auth_kw): """ Accept a response to this request. :param response_header: A `Hawk`_ ``Server-Authorization`` header such as one created by :class:`mohawk.Receiver`. :type response_header: str :param content=EmptyValue: Byte string of the response body received. :type content=EmptyValue: str :param content_type=EmptyValue: Content-Type header value of the response received. :type content_type=EmptyValue: str :param accept_untrusted_content=False: When True, allow responses that do not hash their content. Read :ref:`skipping-content-checks` to learn more. :type accept_untrusted_content=False: bool :param localtime_offset_in_seconds=0: Seconds to add to local time in case it's out of sync. :type localtime_offset_in_seconds=0: float :param timestamp_skew_in_seconds=60: Max seconds until a message expires. Upon expiry, :class:`mohawk.exc.TokenExpired` is raised. :type timestamp_skew_in_seconds=60: float .. _`Hawk`: https://github.com/hueniverse/hawk """ log.debug('accepting response {header}' .format(header=response_header)) parsed_header = parse_authorization_header(response_header) resource = Resource(ext=parsed_header.get('ext', None), content=content, content_type=content_type, # The following response attributes are # in reference to the original request, # not to the reponse header: timestamp=self.req_resource.timestamp, nonce=self.req_resource.nonce, url=self.req_resource.url, method=self.req_resource.method, app=self.req_resource.app, dlg=self.req_resource.dlg, credentials=self.credentials, seen_nonce=self.seen_nonce) self._authorize( 'response', parsed_header, resource, # Per Node lib, a responder macs the *sender's* timestamp. # It does not create its own timestamp. # I suppose a slow response could time out here. Maybe only check # mac failures, not timeouts? their_timestamp=resource.timestamp, timestamp_skew_in_seconds=timestamp_skew_in_seconds, localtime_offset_in_seconds=localtime_offset_in_seconds, accept_untrusted_content=accept_untrusted_content, **auth_kw)
python
def accept_response(self, response_header, content=EmptyValue, content_type=EmptyValue, accept_untrusted_content=False, localtime_offset_in_seconds=0, timestamp_skew_in_seconds=default_ts_skew_in_seconds, **auth_kw): """ Accept a response to this request. :param response_header: A `Hawk`_ ``Server-Authorization`` header such as one created by :class:`mohawk.Receiver`. :type response_header: str :param content=EmptyValue: Byte string of the response body received. :type content=EmptyValue: str :param content_type=EmptyValue: Content-Type header value of the response received. :type content_type=EmptyValue: str :param accept_untrusted_content=False: When True, allow responses that do not hash their content. Read :ref:`skipping-content-checks` to learn more. :type accept_untrusted_content=False: bool :param localtime_offset_in_seconds=0: Seconds to add to local time in case it's out of sync. :type localtime_offset_in_seconds=0: float :param timestamp_skew_in_seconds=60: Max seconds until a message expires. Upon expiry, :class:`mohawk.exc.TokenExpired` is raised. :type timestamp_skew_in_seconds=60: float .. _`Hawk`: https://github.com/hueniverse/hawk """ log.debug('accepting response {header}' .format(header=response_header)) parsed_header = parse_authorization_header(response_header) resource = Resource(ext=parsed_header.get('ext', None), content=content, content_type=content_type, # The following response attributes are # in reference to the original request, # not to the reponse header: timestamp=self.req_resource.timestamp, nonce=self.req_resource.nonce, url=self.req_resource.url, method=self.req_resource.method, app=self.req_resource.app, dlg=self.req_resource.dlg, credentials=self.credentials, seen_nonce=self.seen_nonce) self._authorize( 'response', parsed_header, resource, # Per Node lib, a responder macs the *sender's* timestamp. # It does not create its own timestamp. # I suppose a slow response could time out here. Maybe only check # mac failures, not timeouts? their_timestamp=resource.timestamp, timestamp_skew_in_seconds=timestamp_skew_in_seconds, localtime_offset_in_seconds=localtime_offset_in_seconds, accept_untrusted_content=accept_untrusted_content, **auth_kw)
[ "def", "accept_response", "(", "self", ",", "response_header", ",", "content", "=", "EmptyValue", ",", "content_type", "=", "EmptyValue", ",", "accept_untrusted_content", "=", "False", ",", "localtime_offset_in_seconds", "=", "0", ",", "timestamp_skew_in_seconds", "="...
Accept a response to this request. :param response_header: A `Hawk`_ ``Server-Authorization`` header such as one created by :class:`mohawk.Receiver`. :type response_header: str :param content=EmptyValue: Byte string of the response body received. :type content=EmptyValue: str :param content_type=EmptyValue: Content-Type header value of the response received. :type content_type=EmptyValue: str :param accept_untrusted_content=False: When True, allow responses that do not hash their content. Read :ref:`skipping-content-checks` to learn more. :type accept_untrusted_content=False: bool :param localtime_offset_in_seconds=0: Seconds to add to local time in case it's out of sync. :type localtime_offset_in_seconds=0: float :param timestamp_skew_in_seconds=60: Max seconds until a message expires. Upon expiry, :class:`mohawk.exc.TokenExpired` is raised. :type timestamp_skew_in_seconds=60: float .. _`Hawk`: https://github.com/hueniverse/hawk
[ "Accept", "a", "response", "to", "this", "request", "." ]
037be67ccf50ae704705e67add44e02737a65d21
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/sender.py#L106-L175
train
kajic/django-model-changes
django_model_changes/changes.py
ChangesMixin.current_state
def current_state(self): """ Returns a ``field -> value`` dict of the current state of the instance. """ field_names = set() [field_names.add(f.name) for f in self._meta.local_fields] [field_names.add(f.attname) for f in self._meta.local_fields] return dict([(field_name, getattr(self, field_name)) for field_name in field_names])
python
def current_state(self): """ Returns a ``field -> value`` dict of the current state of the instance. """ field_names = set() [field_names.add(f.name) for f in self._meta.local_fields] [field_names.add(f.attname) for f in self._meta.local_fields] return dict([(field_name, getattr(self, field_name)) for field_name in field_names])
[ "def", "current_state", "(", "self", ")", ":", "field_names", "=", "set", "(", ")", "[", "field_names", ".", "add", "(", "f", ".", "name", ")", "for", "f", "in", "self", ".", "_meta", ".", "local_fields", "]", "[", "field_names", ".", "add", "(", "...
Returns a ``field -> value`` dict of the current state of the instance.
[ "Returns", "a", "field", "-", ">", "value", "dict", "of", "the", "current", "state", "of", "the", "instance", "." ]
92124ebdf29cba930eb1ced00135823b961041d3
https://github.com/kajic/django-model-changes/blob/92124ebdf29cba930eb1ced00135823b961041d3/django_model_changes/changes.py#L98-L105
train
kajic/django-model-changes
django_model_changes/changes.py
ChangesMixin.was_persisted
def was_persisted(self): """ Returns true if the instance was persisted (saved) in its old state. Examples:: >>> user = User() >>> user.save() >>> user.was_persisted() False >>> user = User.objects.get(pk=1) >>> user.delete() >>> user.was_persisted() True """ pk_name = self._meta.pk.name return bool(self.old_state()[pk_name])
python
def was_persisted(self): """ Returns true if the instance was persisted (saved) in its old state. Examples:: >>> user = User() >>> user.save() >>> user.was_persisted() False >>> user = User.objects.get(pk=1) >>> user.delete() >>> user.was_persisted() True """ pk_name = self._meta.pk.name return bool(self.old_state()[pk_name])
[ "def", "was_persisted", "(", "self", ")", ":", "pk_name", "=", "self", ".", "_meta", ".", "pk", ".", "name", "return", "bool", "(", "self", ".", "old_state", "(", ")", "[", "pk_name", "]", ")" ]
Returns true if the instance was persisted (saved) in its old state. Examples:: >>> user = User() >>> user.save() >>> user.was_persisted() False >>> user = User.objects.get(pk=1) >>> user.delete() >>> user.was_persisted() True
[ "Returns", "true", "if", "the", "instance", "was", "persisted", "(", "saved", ")", "in", "its", "old", "state", "." ]
92124ebdf29cba930eb1ced00135823b961041d3
https://github.com/kajic/django-model-changes/blob/92124ebdf29cba930eb1ced00135823b961041d3/django_model_changes/changes.py#L149-L167
train
nilp0inter/cpe
cpe/cpe.py
CPE._trim
def _trim(cls, s): """ Remove trailing colons from the URI back to the first non-colon. :param string s: input URI string :returns: URI string with trailing colons removed :rtype: string TEST: trailing colons necessary >>> s = '1:2::::' >>> CPE._trim(s) '1:2' TEST: trailing colons not necessary >>> s = '1:2:3:4:5:6' >>> CPE._trim(s) '1:2:3:4:5:6' """ reverse = s[::-1] idx = 0 for i in range(0, len(reverse)): if reverse[i] == ":": idx += 1 else: break # Return the substring after all trailing colons, # reversed back to its original character order. new_s = reverse[idx: len(reverse)] return new_s[::-1]
python
def _trim(cls, s): """ Remove trailing colons from the URI back to the first non-colon. :param string s: input URI string :returns: URI string with trailing colons removed :rtype: string TEST: trailing colons necessary >>> s = '1:2::::' >>> CPE._trim(s) '1:2' TEST: trailing colons not necessary >>> s = '1:2:3:4:5:6' >>> CPE._trim(s) '1:2:3:4:5:6' """ reverse = s[::-1] idx = 0 for i in range(0, len(reverse)): if reverse[i] == ":": idx += 1 else: break # Return the substring after all trailing colons, # reversed back to its original character order. new_s = reverse[idx: len(reverse)] return new_s[::-1]
[ "def", "_trim", "(", "cls", ",", "s", ")", ":", "reverse", "=", "s", "[", ":", ":", "-", "1", "]", "idx", "=", "0", "for", "i", "in", "range", "(", "0", ",", "len", "(", "reverse", ")", ")", ":", "if", "reverse", "[", "i", "]", "==", "\":...
Remove trailing colons from the URI back to the first non-colon. :param string s: input URI string :returns: URI string with trailing colons removed :rtype: string TEST: trailing colons necessary >>> s = '1:2::::' >>> CPE._trim(s) '1:2' TEST: trailing colons not necessary >>> s = '1:2:3:4:5:6' >>> CPE._trim(s) '1:2:3:4:5:6'
[ "Remove", "trailing", "colons", "from", "the", "URI", "back", "to", "the", "first", "non", "-", "colon", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe.py#L115-L146
train
nilp0inter/cpe
cpe/cpe.py
CPE._create_cpe_parts
def _create_cpe_parts(self, system, components): """ Create the structure to store the input type of system associated with components of CPE Name (hardware, operating system and software). :param string system: type of system associated with CPE Name :param dict components: CPE Name components to store :returns: None :exception: KeyError - incorrect system """ if system not in CPEComponent.SYSTEM_VALUES: errmsg = "Key '{0}' is not exist".format(system) raise ValueError(errmsg) elements = [] elements.append(components) pk = CPE._system_and_parts[system] self[pk] = elements
python
def _create_cpe_parts(self, system, components): """ Create the structure to store the input type of system associated with components of CPE Name (hardware, operating system and software). :param string system: type of system associated with CPE Name :param dict components: CPE Name components to store :returns: None :exception: KeyError - incorrect system """ if system not in CPEComponent.SYSTEM_VALUES: errmsg = "Key '{0}' is not exist".format(system) raise ValueError(errmsg) elements = [] elements.append(components) pk = CPE._system_and_parts[system] self[pk] = elements
[ "def", "_create_cpe_parts", "(", "self", ",", "system", ",", "components", ")", ":", "if", "system", "not", "in", "CPEComponent", ".", "SYSTEM_VALUES", ":", "errmsg", "=", "\"Key '{0}' is not exist\"", ".", "format", "(", "system", ")", "raise", "ValueError", ...
Create the structure to store the input type of system associated with components of CPE Name (hardware, operating system and software). :param string system: type of system associated with CPE Name :param dict components: CPE Name components to store :returns: None :exception: KeyError - incorrect system
[ "Create", "the", "structure", "to", "store", "the", "input", "type", "of", "system", "associated", "with", "components", "of", "CPE", "Name", "(", "hardware", "operating", "system", "and", "software", ")", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe.py#L389-L408
train
nilp0inter/cpe
cpe/cpe.py
CPE._get_attribute_components
def _get_attribute_components(self, att): """ Returns the component list of input attribute. :param string att: Attribute name to get :returns: List of Component objects of the attribute in CPE Name :rtype: list :exception: ValueError - invalid attribute name """ lc = [] if not CPEComponent.is_valid_attribute(att): errmsg = "Invalid attribute name '{0}' is not exist".format(att) raise ValueError(errmsg) for pk in CPE.CPE_PART_KEYS: elements = self.get(pk) for elem in elements: lc.append(elem.get(att)) return lc
python
def _get_attribute_components(self, att): """ Returns the component list of input attribute. :param string att: Attribute name to get :returns: List of Component objects of the attribute in CPE Name :rtype: list :exception: ValueError - invalid attribute name """ lc = [] if not CPEComponent.is_valid_attribute(att): errmsg = "Invalid attribute name '{0}' is not exist".format(att) raise ValueError(errmsg) for pk in CPE.CPE_PART_KEYS: elements = self.get(pk) for elem in elements: lc.append(elem.get(att)) return lc
[ "def", "_get_attribute_components", "(", "self", ",", "att", ")", ":", "lc", "=", "[", "]", "if", "not", "CPEComponent", ".", "is_valid_attribute", "(", "att", ")", ":", "errmsg", "=", "\"Invalid attribute name '{0}' is not exist\"", ".", "format", "(", "att", ...
Returns the component list of input attribute. :param string att: Attribute name to get :returns: List of Component objects of the attribute in CPE Name :rtype: list :exception: ValueError - invalid attribute name
[ "Returns", "the", "component", "list", "of", "input", "attribute", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe.py#L410-L431
train
nilp0inter/cpe
cpe/cpe.py
CPE._pack_edition
def _pack_edition(self): """ Pack the values of the five arguments into the simple edition component. If all the values are blank, just return a blank. :returns: "edition", "sw_edition", "target_sw", "target_hw" and "other" attributes packed in a only value :rtype: string :exception: TypeError - incompatible version with pack operation """ COMP_KEYS = (CPEComponent.ATT_EDITION, CPEComponent.ATT_SW_EDITION, CPEComponent.ATT_TARGET_SW, CPEComponent.ATT_TARGET_HW, CPEComponent.ATT_OTHER) separator = CPEComponent2_3_URI_edpacked.SEPARATOR_COMP packed_ed = [] packed_ed.append(separator) for ck in COMP_KEYS: lc = self._get_attribute_components(ck) if len(lc) > 1: # Incompatible version 1.1, there are two or more elements # in CPE Name errmsg = "Incompatible version {0} with URI".format( self.VERSION) raise TypeError(errmsg) comp = lc[0] if (isinstance(comp, CPEComponentUndefined) or isinstance(comp, CPEComponentEmpty) or isinstance(comp, CPEComponentAnyValue)): value = "" elif (isinstance(comp, CPEComponentNotApplicable)): value = CPEComponent2_3_URI.VALUE_NA else: # Component has some value; transform this original value # in URI value value = comp.as_uri_2_3() # Save the value of edition attribute if ck == CPEComponent.ATT_EDITION: ed = value # Packed the value of component packed_ed.append(value) packed_ed.append(separator) # Del the last separator packed_ed_str = "".join(packed_ed[:-1]) only_ed = [] only_ed.append(separator) only_ed.append(ed) only_ed.append(separator) only_ed.append(separator) only_ed.append(separator) only_ed.append(separator) only_ed_str = "".join(only_ed) if (packed_ed_str == only_ed_str): # All the extended attributes are blank, # so don't do any packing, just return ed return ed else: # Otherwise, pack the five values into a simple string # prefixed and internally delimited with the tilde return packed_ed_str
python
def _pack_edition(self): """ Pack the values of the five arguments into the simple edition component. If all the values are blank, just return a blank. :returns: "edition", "sw_edition", "target_sw", "target_hw" and "other" attributes packed in a only value :rtype: string :exception: TypeError - incompatible version with pack operation """ COMP_KEYS = (CPEComponent.ATT_EDITION, CPEComponent.ATT_SW_EDITION, CPEComponent.ATT_TARGET_SW, CPEComponent.ATT_TARGET_HW, CPEComponent.ATT_OTHER) separator = CPEComponent2_3_URI_edpacked.SEPARATOR_COMP packed_ed = [] packed_ed.append(separator) for ck in COMP_KEYS: lc = self._get_attribute_components(ck) if len(lc) > 1: # Incompatible version 1.1, there are two or more elements # in CPE Name errmsg = "Incompatible version {0} with URI".format( self.VERSION) raise TypeError(errmsg) comp = lc[0] if (isinstance(comp, CPEComponentUndefined) or isinstance(comp, CPEComponentEmpty) or isinstance(comp, CPEComponentAnyValue)): value = "" elif (isinstance(comp, CPEComponentNotApplicable)): value = CPEComponent2_3_URI.VALUE_NA else: # Component has some value; transform this original value # in URI value value = comp.as_uri_2_3() # Save the value of edition attribute if ck == CPEComponent.ATT_EDITION: ed = value # Packed the value of component packed_ed.append(value) packed_ed.append(separator) # Del the last separator packed_ed_str = "".join(packed_ed[:-1]) only_ed = [] only_ed.append(separator) only_ed.append(ed) only_ed.append(separator) only_ed.append(separator) only_ed.append(separator) only_ed.append(separator) only_ed_str = "".join(only_ed) if (packed_ed_str == only_ed_str): # All the extended attributes are blank, # so don't do any packing, just return ed return ed else: # Otherwise, pack the five values into a simple string # prefixed and internally delimited with the tilde return packed_ed_str
[ "def", "_pack_edition", "(", "self", ")", ":", "COMP_KEYS", "=", "(", "CPEComponent", ".", "ATT_EDITION", ",", "CPEComponent", ".", "ATT_SW_EDITION", ",", "CPEComponent", ".", "ATT_TARGET_SW", ",", "CPEComponent", ".", "ATT_TARGET_HW", ",", "CPEComponent", ".", ...
Pack the values of the five arguments into the simple edition component. If all the values are blank, just return a blank. :returns: "edition", "sw_edition", "target_sw", "target_hw" and "other" attributes packed in a only value :rtype: string :exception: TypeError - incompatible version with pack operation
[ "Pack", "the", "values", "of", "the", "five", "arguments", "into", "the", "simple", "edition", "component", ".", "If", "all", "the", "values", "are", "blank", "just", "return", "a", "blank", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe.py#L433-L505
train
nilp0inter/cpe
cpe/cpe.py
CPE.as_uri_2_3
def as_uri_2_3(self): """ Returns the CPE Name as URI string of version 2.3. :returns: CPE Name as URI string of version 2.3 :rtype: string :exception: TypeError - incompatible version """ uri = [] uri.append("cpe:/") ordered_comp_parts = { 0: CPEComponent.ATT_PART, 1: CPEComponent.ATT_VENDOR, 2: CPEComponent.ATT_PRODUCT, 3: CPEComponent.ATT_VERSION, 4: CPEComponent.ATT_UPDATE, 5: CPEComponent.ATT_EDITION, 6: CPEComponent.ATT_LANGUAGE} # Indicates if the previous component must be set depending on the # value of current component set_prev_comp = False prev_comp_list = [] for i in range(0, len(ordered_comp_parts)): ck = ordered_comp_parts[i] lc = self._get_attribute_components(ck) if len(lc) > 1: # Incompatible version 1.1, there are two or more elements # in CPE Name errmsg = "Incompatible version {0} with URI".format( self.VERSION) raise TypeError(errmsg) if ck == CPEComponent.ATT_EDITION: # Call the pack() helper function to compute the proper # binding for the edition element v = self._pack_edition() if not v: set_prev_comp = True prev_comp_list.append(CPEComponent2_3_URI.VALUE_ANY) continue else: comp = lc[0] if (isinstance(comp, CPEComponentEmpty) or isinstance(comp, CPEComponentAnyValue)): # Logical value any v = CPEComponent2_3_URI.VALUE_ANY elif isinstance(comp, CPEComponentNotApplicable): # Logical value not applicable v = CPEComponent2_3_URI.VALUE_NA elif isinstance(comp, CPEComponentUndefined): set_prev_comp = True prev_comp_list.append(CPEComponent2_3_URI.VALUE_ANY) continue else: # Get the value of component encoded in URI v = comp.as_uri_2_3() # Append v to the URI and add a separator uri.append(v) uri.append(CPEComponent2_3_URI.SEPARATOR_COMP) if set_prev_comp: # Set the previous attribute as logical value any v = CPEComponent2_3_URI.VALUE_ANY pos_ini = max(len(uri) - len(prev_comp_list) - 1, 1) increment = 2 # Count of inserted values for p, val in enumerate(prev_comp_list): pos = pos_ini + (p * increment) uri.insert(pos, v) uri.insert(pos + 1, CPEComponent2_3_URI.SEPARATOR_COMP) set_prev_comp = False prev_comp_list = [] # Return the URI string, with trailing separator trimmed return CPE._trim("".join(uri[:-1]))
python
def as_uri_2_3(self): """ Returns the CPE Name as URI string of version 2.3. :returns: CPE Name as URI string of version 2.3 :rtype: string :exception: TypeError - incompatible version """ uri = [] uri.append("cpe:/") ordered_comp_parts = { 0: CPEComponent.ATT_PART, 1: CPEComponent.ATT_VENDOR, 2: CPEComponent.ATT_PRODUCT, 3: CPEComponent.ATT_VERSION, 4: CPEComponent.ATT_UPDATE, 5: CPEComponent.ATT_EDITION, 6: CPEComponent.ATT_LANGUAGE} # Indicates if the previous component must be set depending on the # value of current component set_prev_comp = False prev_comp_list = [] for i in range(0, len(ordered_comp_parts)): ck = ordered_comp_parts[i] lc = self._get_attribute_components(ck) if len(lc) > 1: # Incompatible version 1.1, there are two or more elements # in CPE Name errmsg = "Incompatible version {0} with URI".format( self.VERSION) raise TypeError(errmsg) if ck == CPEComponent.ATT_EDITION: # Call the pack() helper function to compute the proper # binding for the edition element v = self._pack_edition() if not v: set_prev_comp = True prev_comp_list.append(CPEComponent2_3_URI.VALUE_ANY) continue else: comp = lc[0] if (isinstance(comp, CPEComponentEmpty) or isinstance(comp, CPEComponentAnyValue)): # Logical value any v = CPEComponent2_3_URI.VALUE_ANY elif isinstance(comp, CPEComponentNotApplicable): # Logical value not applicable v = CPEComponent2_3_URI.VALUE_NA elif isinstance(comp, CPEComponentUndefined): set_prev_comp = True prev_comp_list.append(CPEComponent2_3_URI.VALUE_ANY) continue else: # Get the value of component encoded in URI v = comp.as_uri_2_3() # Append v to the URI and add a separator uri.append(v) uri.append(CPEComponent2_3_URI.SEPARATOR_COMP) if set_prev_comp: # Set the previous attribute as logical value any v = CPEComponent2_3_URI.VALUE_ANY pos_ini = max(len(uri) - len(prev_comp_list) - 1, 1) increment = 2 # Count of inserted values for p, val in enumerate(prev_comp_list): pos = pos_ini + (p * increment) uri.insert(pos, v) uri.insert(pos + 1, CPEComponent2_3_URI.SEPARATOR_COMP) set_prev_comp = False prev_comp_list = [] # Return the URI string, with trailing separator trimmed return CPE._trim("".join(uri[:-1]))
[ "def", "as_uri_2_3", "(", "self", ")", ":", "uri", "=", "[", "]", "uri", ".", "append", "(", "\"cpe:/\"", ")", "ordered_comp_parts", "=", "{", "0", ":", "CPEComponent", ".", "ATT_PART", ",", "1", ":", "CPEComponent", ".", "ATT_VENDOR", ",", "2", ":", ...
Returns the CPE Name as URI string of version 2.3. :returns: CPE Name as URI string of version 2.3 :rtype: string :exception: TypeError - incompatible version
[ "Returns", "the", "CPE", "Name", "as", "URI", "string", "of", "version", "2", ".", "3", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe.py#L517-L602
train
nilp0inter/cpe
cpe/cpe.py
CPE.as_wfn
def as_wfn(self): """ Returns the CPE Name as Well-Formed Name string of version 2.3. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version """ from .cpe2_3_wfn import CPE2_3_WFN wfn = [] wfn.append(CPE2_3_WFN.CPE_PREFIX) for i in range(0, len(CPEComponent.ordered_comp_parts)): ck = CPEComponent.ordered_comp_parts[i] lc = self._get_attribute_components(ck) if len(lc) > 1: # Incompatible version 1.1, there are two or more elements # in CPE Name errmsg = "Incompatible version {0} with WFN".format( self.VERSION) raise TypeError(errmsg) else: comp = lc[0] v = [] v.append(ck) v.append("=") if isinstance(comp, CPEComponentAnyValue): # Logical value any v.append(CPEComponent2_3_WFN.VALUE_ANY) elif isinstance(comp, CPEComponentNotApplicable): # Logical value not applicable v.append(CPEComponent2_3_WFN.VALUE_NA) elif (isinstance(comp, CPEComponentUndefined) or isinstance(comp, CPEComponentEmpty)): # Do not set the attribute continue else: # Get the simple value of WFN of component v.append('"') v.append(comp.as_wfn()) v.append('"') # Append v to the WFN and add a separator wfn.append("".join(v)) wfn.append(CPEComponent2_3_WFN.SEPARATOR_COMP) # Del the last separator wfn = wfn[:-1] # Return the WFN string wfn.append(CPE2_3_WFN.CPE_SUFFIX) return "".join(wfn)
python
def as_wfn(self): """ Returns the CPE Name as Well-Formed Name string of version 2.3. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version """ from .cpe2_3_wfn import CPE2_3_WFN wfn = [] wfn.append(CPE2_3_WFN.CPE_PREFIX) for i in range(0, len(CPEComponent.ordered_comp_parts)): ck = CPEComponent.ordered_comp_parts[i] lc = self._get_attribute_components(ck) if len(lc) > 1: # Incompatible version 1.1, there are two or more elements # in CPE Name errmsg = "Incompatible version {0} with WFN".format( self.VERSION) raise TypeError(errmsg) else: comp = lc[0] v = [] v.append(ck) v.append("=") if isinstance(comp, CPEComponentAnyValue): # Logical value any v.append(CPEComponent2_3_WFN.VALUE_ANY) elif isinstance(comp, CPEComponentNotApplicable): # Logical value not applicable v.append(CPEComponent2_3_WFN.VALUE_NA) elif (isinstance(comp, CPEComponentUndefined) or isinstance(comp, CPEComponentEmpty)): # Do not set the attribute continue else: # Get the simple value of WFN of component v.append('"') v.append(comp.as_wfn()) v.append('"') # Append v to the WFN and add a separator wfn.append("".join(v)) wfn.append(CPEComponent2_3_WFN.SEPARATOR_COMP) # Del the last separator wfn = wfn[:-1] # Return the WFN string wfn.append(CPE2_3_WFN.CPE_SUFFIX) return "".join(wfn)
[ "def", "as_wfn", "(", "self", ")", ":", "from", ".", "cpe2_3_wfn", "import", "CPE2_3_WFN", "wfn", "=", "[", "]", "wfn", ".", "append", "(", "CPE2_3_WFN", ".", "CPE_PREFIX", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "CPEComponent", "....
Returns the CPE Name as Well-Formed Name string of version 2.3. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version
[ "Returns", "the", "CPE", "Name", "as", "Well", "-", "Formed", "Name", "string", "of", "version", "2", ".", "3", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe.py#L604-L666
train
nilp0inter/cpe
cpe/cpe.py
CPE.as_fs
def as_fs(self): """ Returns the CPE Name as formatted string of version 2.3. :returns: CPE Name as formatted string :rtype: string :exception: TypeError - incompatible version """ fs = [] fs.append("cpe:2.3:") for i in range(0, len(CPEComponent.ordered_comp_parts)): ck = CPEComponent.ordered_comp_parts[i] lc = self._get_attribute_components(ck) if len(lc) > 1: # Incompatible version 1.1, there are two or more elements # in CPE Name errmsg = "Incompatible version {0} with formatted string".format( self.VERSION) raise TypeError(errmsg) else: comp = lc[0] if (isinstance(comp, CPEComponentUndefined) or isinstance(comp, CPEComponentEmpty) or isinstance(comp, CPEComponentAnyValue)): # Logical value any v = CPEComponent2_3_FS.VALUE_ANY elif isinstance(comp, CPEComponentNotApplicable): # Logical value not applicable v = CPEComponent2_3_FS.VALUE_NA else: # Get the value of component encoded in formatted string v = comp.as_fs() # Append v to the formatted string then add a separator. fs.append(v) fs.append(CPEComponent2_3_FS.SEPARATOR_COMP) # Return the formatted string return CPE._trim("".join(fs[:-1]))
python
def as_fs(self): """ Returns the CPE Name as formatted string of version 2.3. :returns: CPE Name as formatted string :rtype: string :exception: TypeError - incompatible version """ fs = [] fs.append("cpe:2.3:") for i in range(0, len(CPEComponent.ordered_comp_parts)): ck = CPEComponent.ordered_comp_parts[i] lc = self._get_attribute_components(ck) if len(lc) > 1: # Incompatible version 1.1, there are two or more elements # in CPE Name errmsg = "Incompatible version {0} with formatted string".format( self.VERSION) raise TypeError(errmsg) else: comp = lc[0] if (isinstance(comp, CPEComponentUndefined) or isinstance(comp, CPEComponentEmpty) or isinstance(comp, CPEComponentAnyValue)): # Logical value any v = CPEComponent2_3_FS.VALUE_ANY elif isinstance(comp, CPEComponentNotApplicable): # Logical value not applicable v = CPEComponent2_3_FS.VALUE_NA else: # Get the value of component encoded in formatted string v = comp.as_fs() # Append v to the formatted string then add a separator. fs.append(v) fs.append(CPEComponent2_3_FS.SEPARATOR_COMP) # Return the formatted string return CPE._trim("".join(fs[:-1]))
[ "def", "as_fs", "(", "self", ")", ":", "fs", "=", "[", "]", "fs", ".", "append", "(", "\"cpe:2.3:\"", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "CPEComponent", ".", "ordered_comp_parts", ")", ")", ":", "ck", "=", "CPEComponent", "....
Returns the CPE Name as formatted string of version 2.3. :returns: CPE Name as formatted string :rtype: string :exception: TypeError - incompatible version
[ "Returns", "the", "CPE", "Name", "as", "formatted", "string", "of", "version", "2", ".", "3", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe.py#L668-L714
train
nilp0inter/cpe
cpe/comp/cpecomp_simple.py
CPEComponentSimple._is_alphanum
def _is_alphanum(cls, c): """ Returns True if c is an uppercase letter, a lowercase letter, a digit or an underscore, otherwise False. :param string c: Character to check :returns: True if char is alphanumeric or an underscore, False otherwise :rtype: boolean TEST: a wrong character >>> c = "#" >>> CPEComponentSimple._is_alphanum(c) False """ alphanum_rxc = re.compile(CPEComponentSimple._ALPHANUM_PATTERN) return (alphanum_rxc.match(c) is not None)
python
def _is_alphanum(cls, c): """ Returns True if c is an uppercase letter, a lowercase letter, a digit or an underscore, otherwise False. :param string c: Character to check :returns: True if char is alphanumeric or an underscore, False otherwise :rtype: boolean TEST: a wrong character >>> c = "#" >>> CPEComponentSimple._is_alphanum(c) False """ alphanum_rxc = re.compile(CPEComponentSimple._ALPHANUM_PATTERN) return (alphanum_rxc.match(c) is not None)
[ "def", "_is_alphanum", "(", "cls", ",", "c", ")", ":", "alphanum_rxc", "=", "re", ".", "compile", "(", "CPEComponentSimple", ".", "_ALPHANUM_PATTERN", ")", "return", "(", "alphanum_rxc", ".", "match", "(", "c", ")", "is", "not", "None", ")" ]
Returns True if c is an uppercase letter, a lowercase letter, a digit or an underscore, otherwise False. :param string c: Character to check :returns: True if char is alphanumeric or an underscore, False otherwise :rtype: boolean TEST: a wrong character >>> c = "#" >>> CPEComponentSimple._is_alphanum(c) False
[ "Returns", "True", "if", "c", "is", "an", "uppercase", "letter", "a", "lowercase", "letter", "a", "digit", "or", "an", "underscore", "otherwise", "False", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp_simple.py#L98-L115
train
nilp0inter/cpe
cpe/comp/cpecomp_simple.py
CPEComponentSimple._pct_encode_uri
def _pct_encode_uri(cls, c): """ Return the appropriate percent-encoding of character c (URI string). Certain characters are returned without encoding. :param string c: Character to check :returns: Encoded character as URI :rtype: string TEST: >>> c = '.' >>> CPEComponentSimple._pct_encode_uri(c) '.' TEST: >>> c = '@' >>> CPEComponentSimple._pct_encode_uri(c) '%40' """ CPEComponentSimple.spechar_to_pce['-'] = c # bound without encoding CPEComponentSimple.spechar_to_pce['.'] = c # bound without encoding return CPEComponentSimple.spechar_to_pce[c]
python
def _pct_encode_uri(cls, c): """ Return the appropriate percent-encoding of character c (URI string). Certain characters are returned without encoding. :param string c: Character to check :returns: Encoded character as URI :rtype: string TEST: >>> c = '.' >>> CPEComponentSimple._pct_encode_uri(c) '.' TEST: >>> c = '@' >>> CPEComponentSimple._pct_encode_uri(c) '%40' """ CPEComponentSimple.spechar_to_pce['-'] = c # bound without encoding CPEComponentSimple.spechar_to_pce['.'] = c # bound without encoding return CPEComponentSimple.spechar_to_pce[c]
[ "def", "_pct_encode_uri", "(", "cls", ",", "c", ")", ":", "CPEComponentSimple", ".", "spechar_to_pce", "[", "'-'", "]", "=", "c", "# bound without encoding", "CPEComponentSimple", ".", "spechar_to_pce", "[", "'.'", "]", "=", "c", "# bound without encoding", "retur...
Return the appropriate percent-encoding of character c (URI string). Certain characters are returned without encoding. :param string c: Character to check :returns: Encoded character as URI :rtype: string TEST: >>> c = '.' >>> CPEComponentSimple._pct_encode_uri(c) '.' TEST: >>> c = '@' >>> CPEComponentSimple._pct_encode_uri(c) '%40'
[ "Return", "the", "appropriate", "percent", "-", "encoding", "of", "character", "c", "(", "URI", "string", ")", ".", "Certain", "characters", "are", "returned", "without", "encoding", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp_simple.py#L118-L143
train
nilp0inter/cpe
cpe/comp/cpecomp_simple.py
CPEComponentSimple._is_valid_language
def _is_valid_language(self): """ Return True if the value of component in attribute "language" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value.lower() lang_rxc = re.compile(CPEComponentSimple._LANGTAG_PATTERN) return lang_rxc.match(comp_str) is not None
python
def _is_valid_language(self): """ Return True if the value of component in attribute "language" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value.lower() lang_rxc = re.compile(CPEComponentSimple._LANGTAG_PATTERN) return lang_rxc.match(comp_str) is not None
[ "def", "_is_valid_language", "(", "self", ")", ":", "comp_str", "=", "self", ".", "_encoded_value", ".", "lower", "(", ")", "lang_rxc", "=", "re", ".", "compile", "(", "CPEComponentSimple", ".", "_LANGTAG_PATTERN", ")", "return", "lang_rxc", ".", "match", "(...
Return True if the value of component in attribute "language" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean
[ "Return", "True", "if", "the", "value", "of", "component", "in", "attribute", "language", "is", "valid", "and", "otherwise", "False", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp_simple.py#L184-L195
train
nilp0inter/cpe
cpe/comp/cpecomp_simple.py
CPEComponentSimple._is_valid_part
def _is_valid_part(self): """ Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value.lower() part_rxc = re.compile(CPEComponentSimple._PART_PATTERN) return part_rxc.match(comp_str) is not None
python
def _is_valid_part(self): """ Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value.lower() part_rxc = re.compile(CPEComponentSimple._PART_PATTERN) return part_rxc.match(comp_str) is not None
[ "def", "_is_valid_part", "(", "self", ")", ":", "comp_str", "=", "self", ".", "_encoded_value", ".", "lower", "(", ")", "part_rxc", "=", "re", ".", "compile", "(", "CPEComponentSimple", ".", "_PART_PATTERN", ")", "return", "part_rxc", ".", "match", "(", "c...
Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean
[ "Return", "True", "if", "the", "value", "of", "component", "in", "attribute", "part", "is", "valid", "and", "otherwise", "False", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp_simple.py#L197-L208
train
nilp0inter/cpe
cpe/comp/cpecomp_simple.py
CPEComponentSimple._parse
def _parse(self, comp_att): """ Check if the value of component is correct in the attribute "comp_att". :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component """ errmsg = "Invalid attribute '{0}'".format(comp_att) if not CPEComponent.is_valid_attribute(comp_att): raise ValueError(errmsg) comp_str = self._encoded_value errmsg = "Invalid value of attribute '{0}': {1}".format( comp_att, comp_str) # Check part (system type) value if comp_att == CPEComponentSimple.ATT_PART: if not self._is_valid_part(): raise ValueError(errmsg) # Check language value elif comp_att == CPEComponentSimple.ATT_LANGUAGE: if not self._is_valid_language(): raise ValueError(errmsg) # Check edition value elif comp_att == CPEComponentSimple.ATT_EDITION: if not self._is_valid_edition(): raise ValueError(errmsg) # Check other type of component value elif not self._is_valid_value(): raise ValueError(errmsg)
python
def _parse(self, comp_att): """ Check if the value of component is correct in the attribute "comp_att". :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component """ errmsg = "Invalid attribute '{0}'".format(comp_att) if not CPEComponent.is_valid_attribute(comp_att): raise ValueError(errmsg) comp_str = self._encoded_value errmsg = "Invalid value of attribute '{0}': {1}".format( comp_att, comp_str) # Check part (system type) value if comp_att == CPEComponentSimple.ATT_PART: if not self._is_valid_part(): raise ValueError(errmsg) # Check language value elif comp_att == CPEComponentSimple.ATT_LANGUAGE: if not self._is_valid_language(): raise ValueError(errmsg) # Check edition value elif comp_att == CPEComponentSimple.ATT_EDITION: if not self._is_valid_edition(): raise ValueError(errmsg) # Check other type of component value elif not self._is_valid_value(): raise ValueError(errmsg)
[ "def", "_parse", "(", "self", ",", "comp_att", ")", ":", "errmsg", "=", "\"Invalid attribute '{0}'\"", ".", "format", "(", "comp_att", ")", "if", "not", "CPEComponent", ".", "is_valid_attribute", "(", "comp_att", ")", ":", "raise", "ValueError", "(", "errmsg",...
Check if the value of component is correct in the attribute "comp_att". :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component
[ "Check", "if", "the", "value", "of", "component", "is", "correct", "in", "the", "attribute", "comp_att", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp_simple.py#L223-L259
train
nilp0inter/cpe
cpe/comp/cpecomp_simple.py
CPEComponentSimple.as_fs
def as_fs(self): """ Returns the value of component encoded as formatted string. Inspect each character in value of component. Certain nonalpha characters pass thru without escaping into the result, but most retain escaping. :returns: Formatted string associated with component :rtype: string """ s = self._standard_value result = [] idx = 0 while (idx < len(s)): c = s[idx] # get the idx'th character of s if c != "\\": # unquoted characters pass thru unharmed result.append(c) else: # Escaped characters are examined nextchr = s[idx + 1] if (nextchr == ".") or (nextchr == "-") or (nextchr == "_"): # the period, hyphen and underscore pass unharmed result.append(nextchr) idx += 1 else: # all others retain escaping result.append("\\") result.append(nextchr) idx += 2 continue idx += 1 return "".join(result)
python
def as_fs(self): """ Returns the value of component encoded as formatted string. Inspect each character in value of component. Certain nonalpha characters pass thru without escaping into the result, but most retain escaping. :returns: Formatted string associated with component :rtype: string """ s = self._standard_value result = [] idx = 0 while (idx < len(s)): c = s[idx] # get the idx'th character of s if c != "\\": # unquoted characters pass thru unharmed result.append(c) else: # Escaped characters are examined nextchr = s[idx + 1] if (nextchr == ".") or (nextchr == "-") or (nextchr == "_"): # the period, hyphen and underscore pass unharmed result.append(nextchr) idx += 1 else: # all others retain escaping result.append("\\") result.append(nextchr) idx += 2 continue idx += 1 return "".join(result)
[ "def", "as_fs", "(", "self", ")", ":", "s", "=", "self", ".", "_standard_value", "result", "=", "[", "]", "idx", "=", "0", "while", "(", "idx", "<", "len", "(", "s", ")", ")", ":", "c", "=", "s", "[", "idx", "]", "# get the idx'th character of s", ...
Returns the value of component encoded as formatted string. Inspect each character in value of component. Certain nonalpha characters pass thru without escaping into the result, but most retain escaping. :returns: Formatted string associated with component :rtype: string
[ "Returns", "the", "value", "of", "component", "encoded", "as", "formatted", "string", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp_simple.py#L261-L298
train
nilp0inter/cpe
cpe/comp/cpecomp_simple.py
CPEComponentSimple.as_uri_2_3
def as_uri_2_3(self): """ Returns the value of component encoded as URI string. Scans an input string s and applies the following transformations: - Pass alphanumeric characters thru untouched - Percent-encode quoted non-alphanumerics as needed - Unquoted special characters are mapped to their special forms. :returns: URI string associated with component :rtype: string """ s = self._standard_value result = [] idx = 0 while (idx < len(s)): thischar = s[idx] # get the idx'th character of s # alphanumerics (incl. underscore) pass untouched if (CPEComponentSimple._is_alphanum(thischar)): result.append(thischar) idx += 1 continue # escape character if (thischar == "\\"): idx += 1 nxtchar = s[idx] result.append(CPEComponentSimple._pct_encode_uri(nxtchar)) idx += 1 continue # Bind the unquoted '?' special character to "%01". if (thischar == "?"): result.append("%01") # Bind the unquoted '*' special character to "%02". if (thischar == "*"): result.append("%02") idx += 1 return "".join(result)
python
def as_uri_2_3(self): """ Returns the value of component encoded as URI string. Scans an input string s and applies the following transformations: - Pass alphanumeric characters thru untouched - Percent-encode quoted non-alphanumerics as needed - Unquoted special characters are mapped to their special forms. :returns: URI string associated with component :rtype: string """ s = self._standard_value result = [] idx = 0 while (idx < len(s)): thischar = s[idx] # get the idx'th character of s # alphanumerics (incl. underscore) pass untouched if (CPEComponentSimple._is_alphanum(thischar)): result.append(thischar) idx += 1 continue # escape character if (thischar == "\\"): idx += 1 nxtchar = s[idx] result.append(CPEComponentSimple._pct_encode_uri(nxtchar)) idx += 1 continue # Bind the unquoted '?' special character to "%01". if (thischar == "?"): result.append("%01") # Bind the unquoted '*' special character to "%02". if (thischar == "*"): result.append("%02") idx += 1 return "".join(result)
[ "def", "as_uri_2_3", "(", "self", ")", ":", "s", "=", "self", ".", "_standard_value", "result", "=", "[", "]", "idx", "=", "0", "while", "(", "idx", "<", "len", "(", "s", ")", ")", ":", "thischar", "=", "s", "[", "idx", "]", "# get the idx'th chara...
Returns the value of component encoded as URI string. Scans an input string s and applies the following transformations: - Pass alphanumeric characters thru untouched - Percent-encode quoted non-alphanumerics as needed - Unquoted special characters are mapped to their special forms. :returns: URI string associated with component :rtype: string
[ "Returns", "the", "value", "of", "component", "encoded", "as", "URI", "string", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp_simple.py#L300-L344
train
nilp0inter/cpe
cpe/comp/cpecomp_simple.py
CPEComponentSimple.set_value
def set_value(self, comp_str, comp_att): """ Set the value of component. By default, the component has a simple value. :param string comp_str: new value of component :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component """ old_value = self._encoded_value self._encoded_value = comp_str # Check the value of component try: self._parse(comp_att) except ValueError: # Restore old value of component self._encoded_value = old_value raise # Convert encoding value to standard value (WFN) self._decode()
python
def set_value(self, comp_str, comp_att): """ Set the value of component. By default, the component has a simple value. :param string comp_str: new value of component :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component """ old_value = self._encoded_value self._encoded_value = comp_str # Check the value of component try: self._parse(comp_att) except ValueError: # Restore old value of component self._encoded_value = old_value raise # Convert encoding value to standard value (WFN) self._decode()
[ "def", "set_value", "(", "self", ",", "comp_str", ",", "comp_att", ")", ":", "old_value", "=", "self", ".", "_encoded_value", "self", ".", "_encoded_value", "=", "comp_str", "# Check the value of component", "try", ":", "self", ".", "_parse", "(", "comp_att", ...
Set the value of component. By default, the component has a simple value. :param string comp_str: new value of component :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component
[ "Set", "the", "value", "of", "component", ".", "By", "default", "the", "component", "has", "a", "simple", "value", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp_simple.py#L367-L390
train
nilp0inter/cpe
cpe/comp/cpecomp2_3_fs.py
CPEComponent2_3_FS._decode
def _decode(self): """ Convert the characters of string s to standard value (WFN value). Inspect each character in value of component. Copy quoted characters, with their escaping, into the result. Look for unquoted non alphanumerics and if not "*" or "?", add escaping. :exception: ValueError - invalid character in value of component """ result = [] idx = 0 s = self._encoded_value embedded = False errmsg = [] errmsg.append("Invalid character '") while (idx < len(s)): c = s[idx] # get the idx'th character of s errmsg.append(c) errmsg.append("'") errmsg_str = "".join(errmsg) if (CPEComponentSimple._is_alphanum(c)): # Alphanumeric characters pass untouched result.append(c) idx += 1 embedded = True continue if c == "\\": # Anything quoted in the bound string stays quoted # in the unbound string. result.append(s[idx: idx + 2]) idx += 2 embedded = True continue if (c == CPEComponent2_3_FS.WILDCARD_MULTI): # An unquoted asterisk must appear at the beginning or # end of the string. if (idx == 0) or (idx == (len(s) - 1)): result.append(c) idx += 1 embedded = True continue else: raise ValueError(errmsg_str) if (c == CPEComponent2_3_FS.WILDCARD_ONE): # An unquoted question mark must appear at the beginning or # end of the string, or in a leading or trailing sequence: # - ? legal at beginning or end # - embedded is false, so must be preceded by ? # - embedded is true, so must be followed by ? if (((idx == 0) or (idx == (len(s) - 1))) or ((not embedded) and (s[idx - 1] == CPEComponent2_3_FS.WILDCARD_ONE)) or (embedded and (s[idx + 1] == CPEComponent2_3_FS.WILDCARD_ONE))): result.append(c) idx += 1 embedded = False continue else: raise ValueError(errmsg_str) # all other characters must be quoted result.append("\\") result.append(c) idx += 1 embedded = True self._standard_value = "".join(result)
python
def _decode(self): """ Convert the characters of string s to standard value (WFN value). Inspect each character in value of component. Copy quoted characters, with their escaping, into the result. Look for unquoted non alphanumerics and if not "*" or "?", add escaping. :exception: ValueError - invalid character in value of component """ result = [] idx = 0 s = self._encoded_value embedded = False errmsg = [] errmsg.append("Invalid character '") while (idx < len(s)): c = s[idx] # get the idx'th character of s errmsg.append(c) errmsg.append("'") errmsg_str = "".join(errmsg) if (CPEComponentSimple._is_alphanum(c)): # Alphanumeric characters pass untouched result.append(c) idx += 1 embedded = True continue if c == "\\": # Anything quoted in the bound string stays quoted # in the unbound string. result.append(s[idx: idx + 2]) idx += 2 embedded = True continue if (c == CPEComponent2_3_FS.WILDCARD_MULTI): # An unquoted asterisk must appear at the beginning or # end of the string. if (idx == 0) or (idx == (len(s) - 1)): result.append(c) idx += 1 embedded = True continue else: raise ValueError(errmsg_str) if (c == CPEComponent2_3_FS.WILDCARD_ONE): # An unquoted question mark must appear at the beginning or # end of the string, or in a leading or trailing sequence: # - ? legal at beginning or end # - embedded is false, so must be preceded by ? # - embedded is true, so must be followed by ? if (((idx == 0) or (idx == (len(s) - 1))) or ((not embedded) and (s[idx - 1] == CPEComponent2_3_FS.WILDCARD_ONE)) or (embedded and (s[idx + 1] == CPEComponent2_3_FS.WILDCARD_ONE))): result.append(c) idx += 1 embedded = False continue else: raise ValueError(errmsg_str) # all other characters must be quoted result.append("\\") result.append(c) idx += 1 embedded = True self._standard_value = "".join(result)
[ "def", "_decode", "(", "self", ")", ":", "result", "=", "[", "]", "idx", "=", "0", "s", "=", "self", ".", "_encoded_value", "embedded", "=", "False", "errmsg", "=", "[", "]", "errmsg", ".", "append", "(", "\"Invalid character '\"", ")", "while", "(", ...
Convert the characters of string s to standard value (WFN value). Inspect each character in value of component. Copy quoted characters, with their escaping, into the result. Look for unquoted non alphanumerics and if not "*" or "?", add escaping. :exception: ValueError - invalid character in value of component
[ "Convert", "the", "characters", "of", "string", "s", "to", "standard", "value", "(", "WFN", "value", ")", ".", "Inspect", "each", "character", "in", "value", "of", "component", ".", "Copy", "quoted", "characters", "with", "their", "escaping", "into", "the", ...
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp2_3_fs.py#L93-L165
train
nilp0inter/cpe
cpe/cpe1_1.py
CPE1_1._parse
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self.cpe_str.find(" ") != -1): errmsg = "Bad-formed CPE Name: it must not have whitespaces" raise ValueError(errmsg) # Partitioning of CPE Name in parts parts_match = CPE1_1._parts_rxc.match(self.cpe_str) # ################################ # Validation of CPE Name parts # # ################################ if (parts_match is None): errmsg = "Bad-formed CPE Name: not correct definition of CPE Name parts" raise ValueError(errmsg) CPE_PART_KEYS = (CPE.KEY_HW, CPE.KEY_OS, CPE.KEY_APP) for pk in CPE_PART_KEYS: # Get part content part = parts_match.group(pk) elements = [] if (part is not None): # Part of CPE Name defined # ############################### # Validation of part elements # # ############################### # semicolon (;) is used to separate the part elements for part_elem in part.split(CPE1_1.ELEMENT_SEPARATOR): j = 1 # #################################### # Validation of element components # # #################################### components = dict() # colon (:) is used to separate the element components for elem_comp in part_elem.split(CPEComponent1_1.SEPARATOR_COMP): comp_att = CPEComponent.ordered_comp_parts[j] if elem_comp == CPEComponent1_1.VALUE_EMPTY: comp = CPEComponentEmpty() else: try: comp = CPEComponent1_1(elem_comp, comp_att) except ValueError: errmsg = "Bad-formed CPE Name: not correct value: {0}".format( elem_comp) raise ValueError(errmsg) # Identification of component name components[comp_att] = comp j += 1 # Adds the components of version 2.3 of CPE not defined # in version 1.1 for idx in range(j, len(CPEComponent.ordered_comp_parts)): comp_att = CPEComponent.ordered_comp_parts[idx] components[comp_att] = CPEComponentUndefined() # Get the type of system associated with CPE Name and # store it in element as component if (pk == CPE.KEY_HW): components[CPEComponent.ATT_PART] = CPEComponent1_1( CPEComponent.VALUE_PART_HW, CPEComponent.ATT_PART) elif (pk == CPE.KEY_OS): components[CPEComponent.ATT_PART] = CPEComponent1_1( CPEComponent.VALUE_PART_OS, CPEComponent.ATT_PART) elif (pk == CPE.KEY_APP): components[CPEComponent.ATT_PART] = CPEComponent1_1( CPEComponent.VALUE_PART_APP, CPEComponent.ATT_PART) # Store the element identified elements.append(components) # Store the part identified self[pk] = elements self[CPE.KEY_UNDEFINED] = []
python
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self.cpe_str.find(" ") != -1): errmsg = "Bad-formed CPE Name: it must not have whitespaces" raise ValueError(errmsg) # Partitioning of CPE Name in parts parts_match = CPE1_1._parts_rxc.match(self.cpe_str) # ################################ # Validation of CPE Name parts # # ################################ if (parts_match is None): errmsg = "Bad-formed CPE Name: not correct definition of CPE Name parts" raise ValueError(errmsg) CPE_PART_KEYS = (CPE.KEY_HW, CPE.KEY_OS, CPE.KEY_APP) for pk in CPE_PART_KEYS: # Get part content part = parts_match.group(pk) elements = [] if (part is not None): # Part of CPE Name defined # ############################### # Validation of part elements # # ############################### # semicolon (;) is used to separate the part elements for part_elem in part.split(CPE1_1.ELEMENT_SEPARATOR): j = 1 # #################################### # Validation of element components # # #################################### components = dict() # colon (:) is used to separate the element components for elem_comp in part_elem.split(CPEComponent1_1.SEPARATOR_COMP): comp_att = CPEComponent.ordered_comp_parts[j] if elem_comp == CPEComponent1_1.VALUE_EMPTY: comp = CPEComponentEmpty() else: try: comp = CPEComponent1_1(elem_comp, comp_att) except ValueError: errmsg = "Bad-formed CPE Name: not correct value: {0}".format( elem_comp) raise ValueError(errmsg) # Identification of component name components[comp_att] = comp j += 1 # Adds the components of version 2.3 of CPE not defined # in version 1.1 for idx in range(j, len(CPEComponent.ordered_comp_parts)): comp_att = CPEComponent.ordered_comp_parts[idx] components[comp_att] = CPEComponentUndefined() # Get the type of system associated with CPE Name and # store it in element as component if (pk == CPE.KEY_HW): components[CPEComponent.ATT_PART] = CPEComponent1_1( CPEComponent.VALUE_PART_HW, CPEComponent.ATT_PART) elif (pk == CPE.KEY_OS): components[CPEComponent.ATT_PART] = CPEComponent1_1( CPEComponent.VALUE_PART_OS, CPEComponent.ATT_PART) elif (pk == CPE.KEY_APP): components[CPEComponent.ATT_PART] = CPEComponent1_1( CPEComponent.VALUE_PART_APP, CPEComponent.ATT_PART) # Store the element identified elements.append(components) # Store the part identified self[pk] = elements self[CPE.KEY_UNDEFINED] = []
[ "def", "_parse", "(", "self", ")", ":", "# CPE Name must not have whitespaces", "if", "(", "self", ".", "cpe_str", ".", "find", "(", "\" \"", ")", "!=", "-", "1", ")", ":", "errmsg", "=", "\"Bad-formed CPE Name: it must not have whitespaces\"", "raise", "ValueErro...
Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name
[ "Checks", "if", "the", "CPE", "Name", "is", "valid", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe1_1.py#L173-L264
train
nilp0inter/cpe
cpe/cpe1_1.py
CPE1_1.get_attribute_values
def get_attribute_values(self, att_name): """ Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - invalid attribute name """ lc = [] if not CPEComponent.is_valid_attribute(att_name): errmsg = "Invalid attribute name: {0}".format(att_name) raise ValueError(errmsg) for pk in CPE.CPE_PART_KEYS: elements = self.get(pk) for elem in elements: comp = elem.get(att_name) if (isinstance(comp, CPEComponentEmpty) or isinstance(comp, CPEComponentUndefined)): value = CPEComponent1_1.VALUE_EMPTY else: value = comp.get_value() lc.append(value) return lc
python
def get_attribute_values(self, att_name): """ Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - invalid attribute name """ lc = [] if not CPEComponent.is_valid_attribute(att_name): errmsg = "Invalid attribute name: {0}".format(att_name) raise ValueError(errmsg) for pk in CPE.CPE_PART_KEYS: elements = self.get(pk) for elem in elements: comp = elem.get(att_name) if (isinstance(comp, CPEComponentEmpty) or isinstance(comp, CPEComponentUndefined)): value = CPEComponent1_1.VALUE_EMPTY else: value = comp.get_value() lc.append(value) return lc
[ "def", "get_attribute_values", "(", "self", ",", "att_name", ")", ":", "lc", "=", "[", "]", "if", "not", "CPEComponent", ".", "is_valid_attribute", "(", "att_name", ")", ":", "errmsg", "=", "\"Invalid attribute name: {0}\"", ".", "format", "(", "att_name", ")"...
Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - invalid attribute name
[ "Returns", "the", "values", "of", "attribute", "att_name", "of", "CPE", "Name", ".", "By", "default", "a", "only", "element", "in", "each", "part", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe1_1.py#L318-L348
train
nilp0inter/cpe
cpe/comp/cpecomp2_3_uri_edpacked.py
CPEComponent2_3_URI_edpacked.set_value
def set_value(self, comp_str): """ Set the value of component. :param string comp_str: value of component :returns: None :exception: ValueError - incorrect value of component """ self._is_negated = False self._encoded_value = comp_str self._standard_value = super( CPEComponent2_3_URI_edpacked, self)._decode()
python
def set_value(self, comp_str): """ Set the value of component. :param string comp_str: value of component :returns: None :exception: ValueError - incorrect value of component """ self._is_negated = False self._encoded_value = comp_str self._standard_value = super( CPEComponent2_3_URI_edpacked, self)._decode()
[ "def", "set_value", "(", "self", ",", "comp_str", ")", ":", "self", ".", "_is_negated", "=", "False", "self", ".", "_encoded_value", "=", "comp_str", "self", ".", "_standard_value", "=", "super", "(", "CPEComponent2_3_URI_edpacked", ",", "self", ")", ".", "_...
Set the value of component. :param string comp_str: value of component :returns: None :exception: ValueError - incorrect value of component
[ "Set", "the", "value", "of", "component", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp2_3_uri_edpacked.py#L91-L103
train
nilp0inter/cpe
cpe/comp/cpecomp1_1.py
CPEComponent1_1._decode
def _decode(self): """ Convert the encoded value of component to standard value (WFN value). """ s = self._encoded_value elements = s.replace('~', '').split('!') dec_elements = [] for elem in elements: result = [] idx = 0 while (idx < len(elem)): # Get the idx'th character of s c = elem[idx] if (c in CPEComponent1_1.NON_STANDARD_VALUES): # Escape character result.append("\\") result.append(c) else: # Do nothing result.append(c) idx += 1 dec_elements.append("".join(result)) self._standard_value = dec_elements
python
def _decode(self): """ Convert the encoded value of component to standard value (WFN value). """ s = self._encoded_value elements = s.replace('~', '').split('!') dec_elements = [] for elem in elements: result = [] idx = 0 while (idx < len(elem)): # Get the idx'th character of s c = elem[idx] if (c in CPEComponent1_1.NON_STANDARD_VALUES): # Escape character result.append("\\") result.append(c) else: # Do nothing result.append(c) idx += 1 dec_elements.append("".join(result)) self._standard_value = dec_elements
[ "def", "_decode", "(", "self", ")", ":", "s", "=", "self", ".", "_encoded_value", "elements", "=", "s", ".", "replace", "(", "'~'", ",", "''", ")", ".", "split", "(", "'!'", ")", "dec_elements", "=", "[", "]", "for", "elem", "in", "elements", ":", ...
Convert the encoded value of component to standard value (WFN value).
[ "Convert", "the", "encoded", "value", "of", "component", "to", "standard", "value", "(", "WFN", "value", ")", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp1_1.py#L156-L183
train
nilp0inter/cpe
cpe/comp/cpecomp1_1.py
CPEComponent1_1._is_valid_value
def _is_valid_value(self): """ Return True if the value of component in generic attribute is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value value_pattern = [] value_pattern.append("^((") value_pattern.append("~[") value_pattern.append(CPEComponent1_1._STRING) value_pattern.append("]+") value_pattern.append(")|(") value_pattern.append("[") value_pattern.append(CPEComponent1_1._STRING) value_pattern.append("]+(![") value_pattern.append(CPEComponent1_1._STRING) value_pattern.append("]+)*") value_pattern.append("))$") value_rxc = re.compile("".join(value_pattern)) return value_rxc.match(comp_str) is not None
python
def _is_valid_value(self): """ Return True if the value of component in generic attribute is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value value_pattern = [] value_pattern.append("^((") value_pattern.append("~[") value_pattern.append(CPEComponent1_1._STRING) value_pattern.append("]+") value_pattern.append(")|(") value_pattern.append("[") value_pattern.append(CPEComponent1_1._STRING) value_pattern.append("]+(![") value_pattern.append(CPEComponent1_1._STRING) value_pattern.append("]+)*") value_pattern.append("))$") value_rxc = re.compile("".join(value_pattern)) return value_rxc.match(comp_str) is not None
[ "def", "_is_valid_value", "(", "self", ")", ":", "comp_str", "=", "self", ".", "_encoded_value", "value_pattern", "=", "[", "]", "value_pattern", ".", "append", "(", "\"^((\"", ")", "value_pattern", ".", "append", "(", "\"~[\"", ")", "value_pattern", ".", "a...
Return True if the value of component in generic attribute is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean
[ "Return", "True", "if", "the", "value", "of", "component", "in", "generic", "attribute", "is", "valid", "and", "otherwise", "False", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp1_1.py#L185-L210
train
nilp0inter/cpe
cpe/comp/cpecomp1_1.py
CPEComponent1_1.as_wfn
def as_wfn(self): r""" Returns the value of compoment encoded as Well-Formed Name (WFN) string. :returns: WFN string :rtype: string TEST: >>> val = 'xp!vista' >>> comp1 = CPEComponent1_1(val, CPEComponentSimple.ATT_VERSION) >>> comp1.as_wfn() 'xp\\!vista' """ result = [] for s in self._standard_value: result.append(s) result.append(CPEComponent1_1._ESCAPE_SEPARATOR) return "".join(result[0:-1])
python
def as_wfn(self): r""" Returns the value of compoment encoded as Well-Formed Name (WFN) string. :returns: WFN string :rtype: string TEST: >>> val = 'xp!vista' >>> comp1 = CPEComponent1_1(val, CPEComponentSimple.ATT_VERSION) >>> comp1.as_wfn() 'xp\\!vista' """ result = [] for s in self._standard_value: result.append(s) result.append(CPEComponent1_1._ESCAPE_SEPARATOR) return "".join(result[0:-1])
[ "def", "as_wfn", "(", "self", ")", ":", "result", "=", "[", "]", "for", "s", "in", "self", ".", "_standard_value", ":", "result", ".", "append", "(", "s", ")", "result", ".", "append", "(", "CPEComponent1_1", ".", "_ESCAPE_SEPARATOR", ")", "return", "\...
r""" Returns the value of compoment encoded as Well-Formed Name (WFN) string. :returns: WFN string :rtype: string TEST: >>> val = 'xp!vista' >>> comp1 = CPEComponent1_1(val, CPEComponentSimple.ATT_VERSION) >>> comp1.as_wfn() 'xp\\!vista'
[ "r", "Returns", "the", "value", "of", "compoment", "encoded", "as", "Well", "-", "Formed", "Name", "(", "WFN", ")", "string", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp1_1.py#L309-L331
train
nilp0inter/cpe
cpe/comp/cpecomp1_1.py
CPEComponent1_1.set_value
def set_value(self, comp_str, comp_att): """ Set the value of component. By default, the component has a simple value. :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component TEST: >>> val = 'xp!vista' >>> val2 = 'sp2' >>> att = CPEComponentSimple.ATT_VERSION >>> comp1 = CPEComponent1_1(val, att) >>> comp1.set_value(val2, att) >>> comp1.get_value() 'sp2' """ super(CPEComponent1_1, self).set_value(comp_str, comp_att) self._is_negated = comp_str.startswith('~')
python
def set_value(self, comp_str, comp_att): """ Set the value of component. By default, the component has a simple value. :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component TEST: >>> val = 'xp!vista' >>> val2 = 'sp2' >>> att = CPEComponentSimple.ATT_VERSION >>> comp1 = CPEComponent1_1(val, att) >>> comp1.set_value(val2, att) >>> comp1.get_value() 'sp2' """ super(CPEComponent1_1, self).set_value(comp_str, comp_att) self._is_negated = comp_str.startswith('~')
[ "def", "set_value", "(", "self", ",", "comp_str", ",", "comp_att", ")", ":", "super", "(", "CPEComponent1_1", ",", "self", ")", ".", "set_value", "(", "comp_str", ",", "comp_att", ")", "self", ".", "_is_negated", "=", "comp_str", ".", "startswith", "(", ...
Set the value of component. By default, the component has a simple value. :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component TEST: >>> val = 'xp!vista' >>> val2 = 'sp2' >>> att = CPEComponentSimple.ATT_VERSION >>> comp1 = CPEComponent1_1(val, att) >>> comp1.set_value(val2, att) >>> comp1.get_value() 'sp2'
[ "Set", "the", "value", "of", "component", ".", "By", "default", "the", "component", "has", "a", "simple", "value", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp1_1.py#L333-L354
train
nilp0inter/cpe
cpe/cpe2_3_uri.py
CPE2_3_URI._create_component
def _create_component(cls, att, value): """ Returns a component with value "value". :param string att: Attribute name :param string value: Attribute value :returns: Component object created :rtype: CPEComponent :exception: ValueError - invalid value of attribute """ if value == CPEComponent2_3_URI.VALUE_UNDEFINED: comp = CPEComponentUndefined() elif (value == CPEComponent2_3_URI.VALUE_ANY or value == CPEComponent2_3_URI.VALUE_EMPTY): comp = CPEComponentAnyValue() elif (value == CPEComponent2_3_URI.VALUE_NA): comp = CPEComponentNotApplicable() else: comp = CPEComponentNotApplicable() try: comp = CPEComponent2_3_URI(value, att) except ValueError: errmsg = "Invalid value of attribute '{0}': {1} ".format(att, value) raise ValueError(errmsg) return comp
python
def _create_component(cls, att, value): """ Returns a component with value "value". :param string att: Attribute name :param string value: Attribute value :returns: Component object created :rtype: CPEComponent :exception: ValueError - invalid value of attribute """ if value == CPEComponent2_3_URI.VALUE_UNDEFINED: comp = CPEComponentUndefined() elif (value == CPEComponent2_3_URI.VALUE_ANY or value == CPEComponent2_3_URI.VALUE_EMPTY): comp = CPEComponentAnyValue() elif (value == CPEComponent2_3_URI.VALUE_NA): comp = CPEComponentNotApplicable() else: comp = CPEComponentNotApplicable() try: comp = CPEComponent2_3_URI(value, att) except ValueError: errmsg = "Invalid value of attribute '{0}': {1} ".format(att, value) raise ValueError(errmsg) return comp
[ "def", "_create_component", "(", "cls", ",", "att", ",", "value", ")", ":", "if", "value", "==", "CPEComponent2_3_URI", ".", "VALUE_UNDEFINED", ":", "comp", "=", "CPEComponentUndefined", "(", ")", "elif", "(", "value", "==", "CPEComponent2_3_URI", ".", "VALUE_...
Returns a component with value "value". :param string att: Attribute name :param string value: Attribute value :returns: Component object created :rtype: CPEComponent :exception: ValueError - invalid value of attribute
[ "Returns", "a", "component", "with", "value", "value", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_3_uri.py#L104-L131
train
nilp0inter/cpe
cpe/cpe2_3_uri.py
CPE2_3_URI._unpack_edition
def _unpack_edition(cls, value): """ Unpack its elements and set the attributes in wfn accordingly. Parse out the five elements: ~ edition ~ software edition ~ target sw ~ target hw ~ other :param string value: Value of edition attribute :returns: Dictionary with parts of edition attribute :exception: ValueError - invalid value of edition attribute """ components = value.split(CPEComponent2_3_URI.SEPARATOR_PACKED_EDITION) d = dict() ed = components[1] sw_ed = components[2] t_sw = components[3] t_hw = components[4] oth = components[5] ck = CPEComponent.ATT_EDITION d[ck] = CPE2_3_URI._create_component(ck, ed) ck = CPEComponent.ATT_SW_EDITION d[ck] = CPE2_3_URI._create_component(ck, sw_ed) ck = CPEComponent.ATT_TARGET_SW d[ck] = CPE2_3_URI._create_component(ck, t_sw) ck = CPEComponent.ATT_TARGET_HW d[ck] = CPE2_3_URI._create_component(ck, t_hw) ck = CPEComponent.ATT_OTHER d[ck] = CPE2_3_URI._create_component(ck, oth) return d
python
def _unpack_edition(cls, value): """ Unpack its elements and set the attributes in wfn accordingly. Parse out the five elements: ~ edition ~ software edition ~ target sw ~ target hw ~ other :param string value: Value of edition attribute :returns: Dictionary with parts of edition attribute :exception: ValueError - invalid value of edition attribute """ components = value.split(CPEComponent2_3_URI.SEPARATOR_PACKED_EDITION) d = dict() ed = components[1] sw_ed = components[2] t_sw = components[3] t_hw = components[4] oth = components[5] ck = CPEComponent.ATT_EDITION d[ck] = CPE2_3_URI._create_component(ck, ed) ck = CPEComponent.ATT_SW_EDITION d[ck] = CPE2_3_URI._create_component(ck, sw_ed) ck = CPEComponent.ATT_TARGET_SW d[ck] = CPE2_3_URI._create_component(ck, t_sw) ck = CPEComponent.ATT_TARGET_HW d[ck] = CPE2_3_URI._create_component(ck, t_hw) ck = CPEComponent.ATT_OTHER d[ck] = CPE2_3_URI._create_component(ck, oth) return d
[ "def", "_unpack_edition", "(", "cls", ",", "value", ")", ":", "components", "=", "value", ".", "split", "(", "CPEComponent2_3_URI", ".", "SEPARATOR_PACKED_EDITION", ")", "d", "=", "dict", "(", ")", "ed", "=", "components", "[", "1", "]", "sw_ed", "=", "c...
Unpack its elements and set the attributes in wfn accordingly. Parse out the five elements: ~ edition ~ software edition ~ target sw ~ target hw ~ other :param string value: Value of edition attribute :returns: Dictionary with parts of edition attribute :exception: ValueError - invalid value of edition attribute
[ "Unpack", "its", "elements", "and", "set", "the", "attributes", "in", "wfn", "accordingly", ".", "Parse", "out", "the", "five", "elements", ":" ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_3_uri.py#L134-L166
train
nilp0inter/cpe
cpe/cpe2_3_uri.py
CPE2_3_URI._parse
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" raise ValueError(msg) # Partitioning of CPE Name parts_match = CPE2_3_URI._parts_rxc.match(self._str) # Validation of CPE Name parts if (parts_match is None): msg = "Bad-formed CPE Name: validation of parts failed" raise ValueError(msg) components = dict() edition_parts = dict() for ck in CPEComponent.CPE_COMP_KEYS: value = parts_match.group(ck) try: if (ck == CPEComponent.ATT_EDITION and value is not None): if value[0] == CPEComponent2_3_URI.SEPARATOR_PACKED_EDITION: # Unpack the edition part edition_parts = CPE2_3_URI._unpack_edition(value) else: comp = CPE2_3_URI._create_component(ck, value) else: comp = CPE2_3_URI._create_component(ck, value) except ValueError: errmsg = "Bad-formed CPE Name: not correct value '{0}'".format( value) raise ValueError(errmsg) else: components[ck] = comp components = dict(components, **edition_parts) # Adds the components of version 2.3 of CPE not defined in version 2.2 for ck2 in CPEComponent.CPE_COMP_KEYS_EXTENDED: if ck2 not in components.keys(): components[ck2] = CPEComponentUndefined() # Exchange the undefined values in middle attributes of CPE Name for # logical value ANY check_change = True # Start in the last attribute specififed in CPE Name for ck in CPEComponent.CPE_COMP_KEYS[::-1]: if ck in components: comp = components[ck] if check_change: check_change = ((ck != CPEComponent.ATT_EDITION) and (comp == CPEComponentUndefined()) or (ck == CPEComponent.ATT_EDITION and (len(edition_parts) == 0))) elif comp == CPEComponentUndefined(): comp = CPEComponentAnyValue() components[ck] = comp # Storage of CPE Name part_comp = components[CPEComponent.ATT_PART] if isinstance(part_comp, CPEComponentLogical): elements = [] elements.append(components) self[CPE.KEY_UNDEFINED] = elements else: # Create internal structure of CPE Name in parts: # one of them is filled with identified components, # the rest are empty system = parts_match.group(CPEComponent.ATT_PART) if system in CPEComponent.SYSTEM_VALUES: self._create_cpe_parts(system, components) else: self._create_cpe_parts(CPEComponent.VALUE_PART_UNDEFINED, components) # Fills the empty parts of internal structure of CPE Name for pk in CPE.CPE_PART_KEYS: if pk not in self.keys(): # Empty part self[pk] = []
python
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" raise ValueError(msg) # Partitioning of CPE Name parts_match = CPE2_3_URI._parts_rxc.match(self._str) # Validation of CPE Name parts if (parts_match is None): msg = "Bad-formed CPE Name: validation of parts failed" raise ValueError(msg) components = dict() edition_parts = dict() for ck in CPEComponent.CPE_COMP_KEYS: value = parts_match.group(ck) try: if (ck == CPEComponent.ATT_EDITION and value is not None): if value[0] == CPEComponent2_3_URI.SEPARATOR_PACKED_EDITION: # Unpack the edition part edition_parts = CPE2_3_URI._unpack_edition(value) else: comp = CPE2_3_URI._create_component(ck, value) else: comp = CPE2_3_URI._create_component(ck, value) except ValueError: errmsg = "Bad-formed CPE Name: not correct value '{0}'".format( value) raise ValueError(errmsg) else: components[ck] = comp components = dict(components, **edition_parts) # Adds the components of version 2.3 of CPE not defined in version 2.2 for ck2 in CPEComponent.CPE_COMP_KEYS_EXTENDED: if ck2 not in components.keys(): components[ck2] = CPEComponentUndefined() # Exchange the undefined values in middle attributes of CPE Name for # logical value ANY check_change = True # Start in the last attribute specififed in CPE Name for ck in CPEComponent.CPE_COMP_KEYS[::-1]: if ck in components: comp = components[ck] if check_change: check_change = ((ck != CPEComponent.ATT_EDITION) and (comp == CPEComponentUndefined()) or (ck == CPEComponent.ATT_EDITION and (len(edition_parts) == 0))) elif comp == CPEComponentUndefined(): comp = CPEComponentAnyValue() components[ck] = comp # Storage of CPE Name part_comp = components[CPEComponent.ATT_PART] if isinstance(part_comp, CPEComponentLogical): elements = [] elements.append(components) self[CPE.KEY_UNDEFINED] = elements else: # Create internal structure of CPE Name in parts: # one of them is filled with identified components, # the rest are empty system = parts_match.group(CPEComponent.ATT_PART) if system in CPEComponent.SYSTEM_VALUES: self._create_cpe_parts(system, components) else: self._create_cpe_parts(CPEComponent.VALUE_PART_UNDEFINED, components) # Fills the empty parts of internal structure of CPE Name for pk in CPE.CPE_PART_KEYS: if pk not in self.keys(): # Empty part self[pk] = []
[ "def", "_parse", "(", "self", ")", ":", "# CPE Name must not have whitespaces", "if", "(", "self", ".", "_str", ".", "find", "(", "\" \"", ")", "!=", "-", "1", ")", ":", "msg", "=", "\"Bad-formed CPE Name: it must not have whitespaces\"", "raise", "ValueError", ...
Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name
[ "Checks", "if", "the", "CPE", "Name", "is", "valid", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_3_uri.py#L254-L343
train
nilp0inter/cpe
cpe/cpe2_3_uri.py
CPE2_3_URI.as_wfn
def as_wfn(self): """ Returns the CPE Name as Well-Formed Name string of version 2.3. If edition component is not packed, only shows the first seven components, otherwise shows all. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version """ if self._str.find(CPEComponent2_3_URI.SEPARATOR_PACKED_EDITION) == -1: # Edition unpacked, only show the first seven components wfn = [] wfn.append(CPE2_3_WFN.CPE_PREFIX) for ck in CPEComponent.CPE_COMP_KEYS: lc = self._get_attribute_components(ck) if len(lc) > 1: # Incompatible version 1.1, there are two or more elements # in CPE Name errmsg = "Incompatible version {0} with WFN".format( self.VERSION) raise TypeError(errmsg) else: comp = lc[0] v = [] v.append(ck) v.append("=") if (isinstance(comp, CPEComponentUndefined) or isinstance(comp, CPEComponentEmpty)): # Do not set the attribute continue elif isinstance(comp, CPEComponentAnyValue): # Logical value any v.append(CPEComponent2_3_WFN.VALUE_ANY) elif isinstance(comp, CPEComponentNotApplicable): # Logical value not applicable v.append(CPEComponent2_3_WFN.VALUE_NA) else: # Get the value of WFN of component v.append('"') v.append(comp.as_wfn()) v.append('"') # Append v to the WFN and add a separator wfn.append("".join(v)) wfn.append(CPEComponent2_3_WFN.SEPARATOR_COMP) # Del the last separator wfn = wfn[:-1] # Return the WFN string wfn.append(CPE2_3_WFN.CPE_SUFFIX) return "".join(wfn) else: # Shows all components return super(CPE2_3_URI, self).as_wfn()
python
def as_wfn(self): """ Returns the CPE Name as Well-Formed Name string of version 2.3. If edition component is not packed, only shows the first seven components, otherwise shows all. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version """ if self._str.find(CPEComponent2_3_URI.SEPARATOR_PACKED_EDITION) == -1: # Edition unpacked, only show the first seven components wfn = [] wfn.append(CPE2_3_WFN.CPE_PREFIX) for ck in CPEComponent.CPE_COMP_KEYS: lc = self._get_attribute_components(ck) if len(lc) > 1: # Incompatible version 1.1, there are two or more elements # in CPE Name errmsg = "Incompatible version {0} with WFN".format( self.VERSION) raise TypeError(errmsg) else: comp = lc[0] v = [] v.append(ck) v.append("=") if (isinstance(comp, CPEComponentUndefined) or isinstance(comp, CPEComponentEmpty)): # Do not set the attribute continue elif isinstance(comp, CPEComponentAnyValue): # Logical value any v.append(CPEComponent2_3_WFN.VALUE_ANY) elif isinstance(comp, CPEComponentNotApplicable): # Logical value not applicable v.append(CPEComponent2_3_WFN.VALUE_NA) else: # Get the value of WFN of component v.append('"') v.append(comp.as_wfn()) v.append('"') # Append v to the WFN and add a separator wfn.append("".join(v)) wfn.append(CPEComponent2_3_WFN.SEPARATOR_COMP) # Del the last separator wfn = wfn[:-1] # Return the WFN string wfn.append(CPE2_3_WFN.CPE_SUFFIX) return "".join(wfn) else: # Shows all components return super(CPE2_3_URI, self).as_wfn()
[ "def", "as_wfn", "(", "self", ")", ":", "if", "self", ".", "_str", ".", "find", "(", "CPEComponent2_3_URI", ".", "SEPARATOR_PACKED_EDITION", ")", "==", "-", "1", ":", "# Edition unpacked, only show the first seven components", "wfn", "=", "[", "]", "wfn", ".", ...
Returns the CPE Name as Well-Formed Name string of version 2.3. If edition component is not packed, only shows the first seven components, otherwise shows all. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version
[ "Returns", "the", "CPE", "Name", "as", "Well", "-", "Formed", "Name", "string", "of", "version", "2", ".", "3", ".", "If", "edition", "component", "is", "not", "packed", "only", "shows", "the", "first", "seven", "components", "otherwise", "shows", "all", ...
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_3_uri.py#L345-L415
train
nilp0inter/cpe
cpe/comp/cpecomp2_3_uri.py
CPEComponent2_3_URI._decode
def _decode(self): """ Convert the characters of character in value of component to standard value (WFN value). This function scans the value of component and returns a copy with all percent-encoded characters decoded. :exception: ValueError - invalid character in value of component """ result = [] idx = 0 s = self._encoded_value embedded = False errmsg = [] errmsg.append("Invalid value: ") while (idx < len(s)): errmsg.append(s) errmsg_str = "".join(errmsg) # Get the idx'th character of s c = s[idx] # Deal with dot, hyphen and tilde: decode with quoting if ((c == '.') or (c == '-') or (c == '~')): result.append("\\") result.append(c) idx += 1 embedded = True # a non-%01 encountered continue if (c != '%'): result.append(c) idx += 1 embedded = True # a non-%01 encountered continue # we get here if we have a substring starting w/ '%' form = s[idx: idx + 3] # get the three-char sequence if form == CPEComponent2_3_URI.WILDCARD_ONE: # If %01 legal at beginning or end # embedded is false, so must be preceded by %01 # embedded is true, so must be followed by %01 if (((idx == 0) or (idx == (len(s)-3))) or ((not embedded) and (s[idx - 3:idx] == CPEComponent2_3_URI.WILDCARD_ONE)) or (embedded and (len(s) >= idx + 6) and (s[idx + 3:idx + 6] == CPEComponent2_3_URI.WILDCARD_ONE))): # A percent-encoded question mark is found # at the beginning or the end of the string, # or embedded in sequence as required. # Decode to unquoted form. result.append(CPEComponent2_3_WFN.WILDCARD_ONE) idx += 3 continue else: raise ValueError(errmsg_str) elif form == CPEComponent2_3_URI.WILDCARD_MULTI: if ((idx == 0) or (idx == (len(s) - 3))): # Percent-encoded asterisk is at the beginning # or the end of the string, as required. # Decode to unquoted form. result.append(CPEComponent2_3_WFN.WILDCARD_MULTI) else: raise ValueError(errmsg_str) elif form in CPEComponent2_3_URI.pce_char_to_decode.keys(): value = CPEComponent2_3_URI.pce_char_to_decode[form] result.append(value) else: errmsg.append("Invalid percent-encoded character: ") errmsg.append(s) raise ValueError("".join(errmsg)) idx += 3 embedded = True # a non-%01 encountered. self._standard_value = "".join(result)
python
def _decode(self): """ Convert the characters of character in value of component to standard value (WFN value). This function scans the value of component and returns a copy with all percent-encoded characters decoded. :exception: ValueError - invalid character in value of component """ result = [] idx = 0 s = self._encoded_value embedded = False errmsg = [] errmsg.append("Invalid value: ") while (idx < len(s)): errmsg.append(s) errmsg_str = "".join(errmsg) # Get the idx'th character of s c = s[idx] # Deal with dot, hyphen and tilde: decode with quoting if ((c == '.') or (c == '-') or (c == '~')): result.append("\\") result.append(c) idx += 1 embedded = True # a non-%01 encountered continue if (c != '%'): result.append(c) idx += 1 embedded = True # a non-%01 encountered continue # we get here if we have a substring starting w/ '%' form = s[idx: idx + 3] # get the three-char sequence if form == CPEComponent2_3_URI.WILDCARD_ONE: # If %01 legal at beginning or end # embedded is false, so must be preceded by %01 # embedded is true, so must be followed by %01 if (((idx == 0) or (idx == (len(s)-3))) or ((not embedded) and (s[idx - 3:idx] == CPEComponent2_3_URI.WILDCARD_ONE)) or (embedded and (len(s) >= idx + 6) and (s[idx + 3:idx + 6] == CPEComponent2_3_URI.WILDCARD_ONE))): # A percent-encoded question mark is found # at the beginning or the end of the string, # or embedded in sequence as required. # Decode to unquoted form. result.append(CPEComponent2_3_WFN.WILDCARD_ONE) idx += 3 continue else: raise ValueError(errmsg_str) elif form == CPEComponent2_3_URI.WILDCARD_MULTI: if ((idx == 0) or (idx == (len(s) - 3))): # Percent-encoded asterisk is at the beginning # or the end of the string, as required. # Decode to unquoted form. result.append(CPEComponent2_3_WFN.WILDCARD_MULTI) else: raise ValueError(errmsg_str) elif form in CPEComponent2_3_URI.pce_char_to_decode.keys(): value = CPEComponent2_3_URI.pce_char_to_decode[form] result.append(value) else: errmsg.append("Invalid percent-encoded character: ") errmsg.append(s) raise ValueError("".join(errmsg)) idx += 3 embedded = True # a non-%01 encountered. self._standard_value = "".join(result)
[ "def", "_decode", "(", "self", ")", ":", "result", "=", "[", "]", "idx", "=", "0", "s", "=", "self", ".", "_encoded_value", "embedded", "=", "False", "errmsg", "=", "[", "]", "errmsg", ".", "append", "(", "\"Invalid value: \"", ")", "while", "(", "id...
Convert the characters of character in value of component to standard value (WFN value). This function scans the value of component and returns a copy with all percent-encoded characters decoded. :exception: ValueError - invalid character in value of component
[ "Convert", "the", "characters", "of", "character", "in", "value", "of", "component", "to", "standard", "value", "(", "WFN", "value", ")", ".", "This", "function", "scans", "the", "value", "of", "component", "and", "returns", "a", "copy", "with", "all", "pe...
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp2_3_uri.py#L163-L244
train
nilp0inter/cpe
cpe/comp/cpecomp2_3_uri.py
CPEComponent2_3_URI._is_valid_edition
def _is_valid_edition(self): """ Return True if the input value of attribute "edition" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._standard_value[0] packed = [] packed.append("(") packed.append(CPEComponent2_3_URI.SEPARATOR_PACKED_EDITION) packed.append(CPEComponent2_3_URI._string) packed.append("){5}") value_pattern = [] value_pattern.append("^(") value_pattern.append(CPEComponent2_3_URI._string) value_pattern.append("|") value_pattern.append("".join(packed)) value_pattern.append(")$") value_rxc = re.compile("".join(value_pattern)) return value_rxc.match(comp_str) is not None
python
def _is_valid_edition(self): """ Return True if the input value of attribute "edition" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._standard_value[0] packed = [] packed.append("(") packed.append(CPEComponent2_3_URI.SEPARATOR_PACKED_EDITION) packed.append(CPEComponent2_3_URI._string) packed.append("){5}") value_pattern = [] value_pattern.append("^(") value_pattern.append(CPEComponent2_3_URI._string) value_pattern.append("|") value_pattern.append("".join(packed)) value_pattern.append(")$") value_rxc = re.compile("".join(value_pattern)) return value_rxc.match(comp_str) is not None
[ "def", "_is_valid_edition", "(", "self", ")", ":", "comp_str", "=", "self", ".", "_standard_value", "[", "0", "]", "packed", "=", "[", "]", "packed", ".", "append", "(", "\"(\"", ")", "packed", ".", "append", "(", "CPEComponent2_3_URI", ".", "SEPARATOR_PAC...
Return True if the input value of attribute "edition" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean
[ "Return", "True", "if", "the", "input", "value", "of", "attribute", "edition", "is", "valid", "and", "otherwise", "False", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp2_3_uri.py#L246-L271
train
nilp0inter/cpe
cpe/comp/cpecomp2_3.py
CPEComponent2_3._is_valid_language
def _is_valid_language(self): """ Return True if the value of component in attribute "language" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean CASE 1: Language part with/without region part CASE 2: Language part without region part CASE 3: Region part with language part CASE 4: Region part without language part """ def check_generic_language(self, value): """ Check possible values in language part when region part exists or not in language value. Possible values of language attribute: a=letter | *a | *aa | aa | aaa | ?a | ?aa | ?? | ??a | ??? """ lang_pattern = [] lang_pattern.append("^(\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("[a-z]{1,2}") lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("(([a-z][a-z]?)|(\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("(\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("|[a-z])?))") lang_pattern.append("|([a-z]{2,3}))$") lang_rxc = re.compile("".join(lang_pattern)) return lang_rxc.match(value) def check_language_without_region(self, value): """ Check possible values in language part when region part not exist in language value. Possible values of language attribute: a=letter | a? | aa? | a?? | a* | aa* | aaa* | *a* | *a? | ?a* | ?a? """ lang_pattern = [] lang_pattern.append("^([a-z]") lang_pattern.append("([a-z](\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("|") lang_pattern.append("([a-z]\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("))") lang_pattern.append("|") lang_pattern.append("\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("(\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append(")?") lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append(")|\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("[a-z](\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append(")") lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("[a-z](\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append(")") lang_pattern.append(")$") lang_rxc = re.compile("".join(lang_pattern)) return lang_rxc.match(value) def check_region_with_language(self, value): """ Check possible values in region part when language part exists. Possible values of language attribute: a=letter, 1=digit | * | a* | a? | aa | ?? | 1* | 1?? | 11* | 11? | 111 | ??? """ region_pattern = [] region_pattern.append("^(") region_pattern.append("(\\") region_pattern.append(self.WILDCARD_MULTI) region_pattern.append(")|((\\") region_pattern.append(self.WILDCARD_ONE) region_pattern.append("){2,3})|([a-z]([a-z]|\\") region_pattern.append(self.WILDCARD_MULTI) region_pattern.append("|\\") region_pattern.append(self.WILDCARD_ONE) region_pattern.append("))|([0-9](\\") region_pattern.append(self.WILDCARD_MULTI) region_pattern.append("|\\") region_pattern.append(self.WILDCARD_ONE) region_pattern.append("(\\") region_pattern.append(self.WILDCARD_ONE) region_pattern.append(")?|[0-9][0-9\\") region_pattern.append(self.WILDCARD_MULTI) region_pattern.append("\\") region_pattern.append(self.WILDCARD_ONE) region_pattern.append("])))$") region_rxc = re.compile("".join(region_pattern)) return region_rxc.match(region) def check_region_without_language(self, value): """ Check possible values in region part when language part not exist. Possible values of language attribute: 1=digit | *111 | *11 | *1 """ region_pattern = [] region_pattern.append("^(") region_pattern.append("(\\") region_pattern.append(self.WILDCARD_MULTI) region_pattern.append("[0-9])") region_pattern.append("([0-9]([0-9])?)?") region_pattern.append(")$") region_rxc = re.compile("".join(region_pattern)) return region_rxc.match(region) comp_str = self._encoded_value.lower() # Value with wildcards; separate language and region of value parts = comp_str.split(self.SEPARATOR_LANG) language = parts[0] region_exists = len(parts) == 2 # Check the language part if check_generic_language(self, language) is not None: # Valid language, check region part if region_exists: # Region part exists; check it region = parts[1] return (check_region_with_language(self, region) is not None) else: # Not region part return True elif check_language_without_region(self, language) is not None: # Language without region; region part should not exist return not region_exists else: # Language part not exist; check region part region = parts[0] return check_region_without_language(self, region) is not None
python
def _is_valid_language(self): """ Return True if the value of component in attribute "language" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean CASE 1: Language part with/without region part CASE 2: Language part without region part CASE 3: Region part with language part CASE 4: Region part without language part """ def check_generic_language(self, value): """ Check possible values in language part when region part exists or not in language value. Possible values of language attribute: a=letter | *a | *aa | aa | aaa | ?a | ?aa | ?? | ??a | ??? """ lang_pattern = [] lang_pattern.append("^(\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("[a-z]{1,2}") lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("(([a-z][a-z]?)|(\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("(\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("|[a-z])?))") lang_pattern.append("|([a-z]{2,3}))$") lang_rxc = re.compile("".join(lang_pattern)) return lang_rxc.match(value) def check_language_without_region(self, value): """ Check possible values in language part when region part not exist in language value. Possible values of language attribute: a=letter | a? | aa? | a?? | a* | aa* | aaa* | *a* | *a? | ?a* | ?a? """ lang_pattern = [] lang_pattern.append("^([a-z]") lang_pattern.append("([a-z](\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("|") lang_pattern.append("([a-z]\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("))") lang_pattern.append("|") lang_pattern.append("\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("(\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append(")?") lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append(")|\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append("[a-z](\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append(")") lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("[a-z](\\") lang_pattern.append(self.WILDCARD_MULTI) lang_pattern.append("|\\") lang_pattern.append(self.WILDCARD_ONE) lang_pattern.append(")") lang_pattern.append(")$") lang_rxc = re.compile("".join(lang_pattern)) return lang_rxc.match(value) def check_region_with_language(self, value): """ Check possible values in region part when language part exists. Possible values of language attribute: a=letter, 1=digit | * | a* | a? | aa | ?? | 1* | 1?? | 11* | 11? | 111 | ??? """ region_pattern = [] region_pattern.append("^(") region_pattern.append("(\\") region_pattern.append(self.WILDCARD_MULTI) region_pattern.append(")|((\\") region_pattern.append(self.WILDCARD_ONE) region_pattern.append("){2,3})|([a-z]([a-z]|\\") region_pattern.append(self.WILDCARD_MULTI) region_pattern.append("|\\") region_pattern.append(self.WILDCARD_ONE) region_pattern.append("))|([0-9](\\") region_pattern.append(self.WILDCARD_MULTI) region_pattern.append("|\\") region_pattern.append(self.WILDCARD_ONE) region_pattern.append("(\\") region_pattern.append(self.WILDCARD_ONE) region_pattern.append(")?|[0-9][0-9\\") region_pattern.append(self.WILDCARD_MULTI) region_pattern.append("\\") region_pattern.append(self.WILDCARD_ONE) region_pattern.append("])))$") region_rxc = re.compile("".join(region_pattern)) return region_rxc.match(region) def check_region_without_language(self, value): """ Check possible values in region part when language part not exist. Possible values of language attribute: 1=digit | *111 | *11 | *1 """ region_pattern = [] region_pattern.append("^(") region_pattern.append("(\\") region_pattern.append(self.WILDCARD_MULTI) region_pattern.append("[0-9])") region_pattern.append("([0-9]([0-9])?)?") region_pattern.append(")$") region_rxc = re.compile("".join(region_pattern)) return region_rxc.match(region) comp_str = self._encoded_value.lower() # Value with wildcards; separate language and region of value parts = comp_str.split(self.SEPARATOR_LANG) language = parts[0] region_exists = len(parts) == 2 # Check the language part if check_generic_language(self, language) is not None: # Valid language, check region part if region_exists: # Region part exists; check it region = parts[1] return (check_region_with_language(self, region) is not None) else: # Not region part return True elif check_language_without_region(self, language) is not None: # Language without region; region part should not exist return not region_exists else: # Language part not exist; check region part region = parts[0] return check_region_without_language(self, region) is not None
[ "def", "_is_valid_language", "(", "self", ")", ":", "def", "check_generic_language", "(", "self", ",", "value", ")", ":", "\"\"\"\n Check possible values in language part\n when region part exists or not in language value.\n\n Possible values of language ...
Return True if the value of component in attribute "language" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean CASE 1: Language part with/without region part CASE 2: Language part without region part CASE 3: Region part with language part CASE 4: Region part without language part
[ "Return", "True", "if", "the", "value", "of", "component", "in", "attribute", "language", "is", "valid", "and", "otherwise", "False", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp2_3.py#L58-L245
train
nilp0inter/cpe
cpe/comp/cpecomp2_3.py
CPEComponent2_3._is_valid_part
def _is_valid_part(self): """ Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value # Check if value of component do not have wildcard if ((comp_str.find(self.WILDCARD_ONE) == -1) and (comp_str.find(self.WILDCARD_MULTI) == -1)): return super(CPEComponent2_3, self)._is_valid_part() # Compilation of regular expression associated with value of part part_pattern = "^(\{0}|\{1})$".format(self.WILDCARD_ONE, self.WILDCARD_MULTI) part_rxc = re.compile(part_pattern) return part_rxc.match(comp_str) is not None
python
def _is_valid_part(self): """ Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value # Check if value of component do not have wildcard if ((comp_str.find(self.WILDCARD_ONE) == -1) and (comp_str.find(self.WILDCARD_MULTI) == -1)): return super(CPEComponent2_3, self)._is_valid_part() # Compilation of regular expression associated with value of part part_pattern = "^(\{0}|\{1})$".format(self.WILDCARD_ONE, self.WILDCARD_MULTI) part_rxc = re.compile(part_pattern) return part_rxc.match(comp_str) is not None
[ "def", "_is_valid_part", "(", "self", ")", ":", "comp_str", "=", "self", ".", "_encoded_value", "# Check if value of component do not have wildcard", "if", "(", "(", "comp_str", ".", "find", "(", "self", ".", "WILDCARD_ONE", ")", "==", "-", "1", ")", "and", "(...
Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean
[ "Return", "True", "if", "the", "value", "of", "component", "in", "attribute", "part", "is", "valid", "and", "otherwise", "False", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp2_3.py#L247-L269
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3._compare
def _compare(cls, source, target): """ Compares two values associated with a attribute of two WFNs, which may be logical values (ANY or NA) or string values. :param string source: First attribute value :param string target: Second attribute value :returns: The attribute comparison relation. :rtype: int This function is a support function for compare_WFNs. """ if (CPESet2_3._is_string(source)): source = source.lower() if (CPESet2_3._is_string(target)): target = target.lower() # In this specification, unquoted wildcard characters in the target # yield an undefined result if (CPESet2_3._is_string(target) and CPESet2_3._contains_wildcards(target)): return CPESet2_3.LOGICAL_VALUE_UNDEFINED # If source and target attribute values are equal, # then the result is EQUAL if (source == target): return CPESet2_3.LOGICAL_VALUE_EQUAL # If source attribute value is ANY, then the result is SUPERSET if (source == CPEComponent2_3_WFN.VALUE_ANY): return CPESet2_3.LOGICAL_VALUE_SUPERSET # If target attribute value is ANY, then the result is SUBSET if (target == CPEComponent2_3_WFN.VALUE_ANY): return CPESet2_3.LOGICAL_VALUE_SUBSET # If either source or target attribute value is NA # then the result is DISJOINT isSourceNA = source == CPEComponent2_3_WFN.VALUE_NA isTargetNA = target == CPEComponent2_3_WFN.VALUE_NA if (isSourceNA or isTargetNA): return CPESet2_3.LOGICAL_VALUE_DISJOINT # If we get to this point, we are comparing two strings return CPESet2_3._compare_strings(source, target)
python
def _compare(cls, source, target): """ Compares two values associated with a attribute of two WFNs, which may be logical values (ANY or NA) or string values. :param string source: First attribute value :param string target: Second attribute value :returns: The attribute comparison relation. :rtype: int This function is a support function for compare_WFNs. """ if (CPESet2_3._is_string(source)): source = source.lower() if (CPESet2_3._is_string(target)): target = target.lower() # In this specification, unquoted wildcard characters in the target # yield an undefined result if (CPESet2_3._is_string(target) and CPESet2_3._contains_wildcards(target)): return CPESet2_3.LOGICAL_VALUE_UNDEFINED # If source and target attribute values are equal, # then the result is EQUAL if (source == target): return CPESet2_3.LOGICAL_VALUE_EQUAL # If source attribute value is ANY, then the result is SUPERSET if (source == CPEComponent2_3_WFN.VALUE_ANY): return CPESet2_3.LOGICAL_VALUE_SUPERSET # If target attribute value is ANY, then the result is SUBSET if (target == CPEComponent2_3_WFN.VALUE_ANY): return CPESet2_3.LOGICAL_VALUE_SUBSET # If either source or target attribute value is NA # then the result is DISJOINT isSourceNA = source == CPEComponent2_3_WFN.VALUE_NA isTargetNA = target == CPEComponent2_3_WFN.VALUE_NA if (isSourceNA or isTargetNA): return CPESet2_3.LOGICAL_VALUE_DISJOINT # If we get to this point, we are comparing two strings return CPESet2_3._compare_strings(source, target)
[ "def", "_compare", "(", "cls", ",", "source", ",", "target", ")", ":", "if", "(", "CPESet2_3", ".", "_is_string", "(", "source", ")", ")", ":", "source", "=", "source", ".", "lower", "(", ")", "if", "(", "CPESet2_3", ".", "_is_string", "(", "target",...
Compares two values associated with a attribute of two WFNs, which may be logical values (ANY or NA) or string values. :param string source: First attribute value :param string target: Second attribute value :returns: The attribute comparison relation. :rtype: int This function is a support function for compare_WFNs.
[ "Compares", "two", "values", "associated", "with", "a", "attribute", "of", "two", "WFNs", "which", "may", "be", "logical", "values", "(", "ANY", "or", "NA", ")", "or", "string", "values", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L74-L121
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3._compare_strings
def _compare_strings(cls, source, target): """ Compares a source string to a target string, and addresses the condition in which the source string includes unquoted special characters. It performs a simple regular expression match, with the assumption that (as required) unquoted special characters appear only at the beginning and/or the end of the source string. It also properly differentiates between unquoted and quoted special characters. :param string source: First string value :param string target: Second string value :returns: The comparison relation among input strings. :rtype: int """ start = 0 end = len(source) begins = 0 ends = 0 # Reading of initial wildcard in source if source.startswith(CPEComponent2_3_WFN.WILDCARD_MULTI): # Source starts with "*" start = 1 begins = -1 else: while ((start < len(source)) and source.startswith(CPEComponent2_3_WFN.WILDCARD_ONE, start, start)): # Source starts with one or more "?" start += 1 begins += 1 # Reading of final wildcard in source if (source.endswith(CPEComponent2_3_WFN.WILDCARD_MULTI) and CPESet2_3._is_even_wildcards(source, end - 1)): # Source ends in "*" end -= 1 ends = -1 else: while ((end > 0) and source.endswith(CPEComponent2_3_WFN.WILDCARD_ONE, end - 1, end) and CPESet2_3._is_even_wildcards(source, end - 1)): # Source ends in "?" end -= 1 ends += 1 source = source[start: end] index = -1 leftover = len(target) while (leftover > 0): index = target.find(source, index + 1) if (index == -1): break escapes = target.count("\\", 0, index) if ((index > 0) and (begins != -1) and (begins < (index - escapes))): break escapes = target.count("\\", index + 1, len(target)) leftover = len(target) - index - escapes - len(source) if ((leftover > 0) and ((ends != -1) and (leftover > ends))): continue return CPESet2_3.LOGICAL_VALUE_SUPERSET return CPESet2_3.LOGICAL_VALUE_DISJOINT
python
def _compare_strings(cls, source, target): """ Compares a source string to a target string, and addresses the condition in which the source string includes unquoted special characters. It performs a simple regular expression match, with the assumption that (as required) unquoted special characters appear only at the beginning and/or the end of the source string. It also properly differentiates between unquoted and quoted special characters. :param string source: First string value :param string target: Second string value :returns: The comparison relation among input strings. :rtype: int """ start = 0 end = len(source) begins = 0 ends = 0 # Reading of initial wildcard in source if source.startswith(CPEComponent2_3_WFN.WILDCARD_MULTI): # Source starts with "*" start = 1 begins = -1 else: while ((start < len(source)) and source.startswith(CPEComponent2_3_WFN.WILDCARD_ONE, start, start)): # Source starts with one or more "?" start += 1 begins += 1 # Reading of final wildcard in source if (source.endswith(CPEComponent2_3_WFN.WILDCARD_MULTI) and CPESet2_3._is_even_wildcards(source, end - 1)): # Source ends in "*" end -= 1 ends = -1 else: while ((end > 0) and source.endswith(CPEComponent2_3_WFN.WILDCARD_ONE, end - 1, end) and CPESet2_3._is_even_wildcards(source, end - 1)): # Source ends in "?" end -= 1 ends += 1 source = source[start: end] index = -1 leftover = len(target) while (leftover > 0): index = target.find(source, index + 1) if (index == -1): break escapes = target.count("\\", 0, index) if ((index > 0) and (begins != -1) and (begins < (index - escapes))): break escapes = target.count("\\", index + 1, len(target)) leftover = len(target) - index - escapes - len(source) if ((leftover > 0) and ((ends != -1) and (leftover > ends))): continue return CPESet2_3.LOGICAL_VALUE_SUPERSET return CPESet2_3.LOGICAL_VALUE_DISJOINT
[ "def", "_compare_strings", "(", "cls", ",", "source", ",", "target", ")", ":", "start", "=", "0", "end", "=", "len", "(", "source", ")", "begins", "=", "0", "ends", "=", "0", "# Reading of initial wildcard in source", "if", "source", ".", "startswith", "("...
Compares a source string to a target string, and addresses the condition in which the source string includes unquoted special characters. It performs a simple regular expression match, with the assumption that (as required) unquoted special characters appear only at the beginning and/or the end of the source string. It also properly differentiates between unquoted and quoted special characters. :param string source: First string value :param string target: Second string value :returns: The comparison relation among input strings. :rtype: int
[ "Compares", "a", "source", "string", "to", "a", "target", "string", "and", "addresses", "the", "condition", "in", "which", "the", "source", "string", "includes", "unquoted", "special", "characters", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L124-L198
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3._contains_wildcards
def _contains_wildcards(cls, s): """ Return True if the string contains any unquoted special characters (question-mark or asterisk), otherwise False. Ex: _contains_wildcards("foo") => FALSE Ex: _contains_wildcards("foo\?") => FALSE Ex: _contains_wildcards("foo?") => TRUE Ex: _contains_wildcards("\*bar") => FALSE Ex: _contains_wildcards("*bar") => TRUE :param string s: string to check :returns: True if string contains any unquoted special characters, False otherwise. :rtype: boolean This function is a support function for _compare(). """ idx = s.find("*") if idx != -1: if idx == 0: return True else: if s[idx - 1] != "\\": return True idx = s.find("?") if idx != -1: if idx == 0: return True else: if s[idx - 1] != "\\": return True return False
python
def _contains_wildcards(cls, s): """ Return True if the string contains any unquoted special characters (question-mark or asterisk), otherwise False. Ex: _contains_wildcards("foo") => FALSE Ex: _contains_wildcards("foo\?") => FALSE Ex: _contains_wildcards("foo?") => TRUE Ex: _contains_wildcards("\*bar") => FALSE Ex: _contains_wildcards("*bar") => TRUE :param string s: string to check :returns: True if string contains any unquoted special characters, False otherwise. :rtype: boolean This function is a support function for _compare(). """ idx = s.find("*") if idx != -1: if idx == 0: return True else: if s[idx - 1] != "\\": return True idx = s.find("?") if idx != -1: if idx == 0: return True else: if s[idx - 1] != "\\": return True return False
[ "def", "_contains_wildcards", "(", "cls", ",", "s", ")", ":", "idx", "=", "s", ".", "find", "(", "\"*\"", ")", "if", "idx", "!=", "-", "1", ":", "if", "idx", "==", "0", ":", "return", "True", "else", ":", "if", "s", "[", "idx", "-", "1", "]",...
Return True if the string contains any unquoted special characters (question-mark or asterisk), otherwise False. Ex: _contains_wildcards("foo") => FALSE Ex: _contains_wildcards("foo\?") => FALSE Ex: _contains_wildcards("foo?") => TRUE Ex: _contains_wildcards("\*bar") => FALSE Ex: _contains_wildcards("*bar") => TRUE :param string s: string to check :returns: True if string contains any unquoted special characters, False otherwise. :rtype: boolean This function is a support function for _compare().
[ "Return", "True", "if", "the", "string", "contains", "any", "unquoted", "special", "characters", "(", "question", "-", "mark", "or", "asterisk", ")", "otherwise", "False", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L201-L235
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3._is_even_wildcards
def _is_even_wildcards(cls, str, idx): """ Returns True if an even number of escape (backslash) characters precede the character at index idx in string str. :param string str: string to check :returns: True if an even number of escape characters precede the character at index idx in string str, False otherwise. :rtype: boolean """ result = 0 while ((idx > 0) and (str[idx - 1] == "\\")): idx -= 1 result += 1 isEvenNumber = (result % 2) == 0 return isEvenNumber
python
def _is_even_wildcards(cls, str, idx): """ Returns True if an even number of escape (backslash) characters precede the character at index idx in string str. :param string str: string to check :returns: True if an even number of escape characters precede the character at index idx in string str, False otherwise. :rtype: boolean """ result = 0 while ((idx > 0) and (str[idx - 1] == "\\")): idx -= 1 result += 1 isEvenNumber = (result % 2) == 0 return isEvenNumber
[ "def", "_is_even_wildcards", "(", "cls", ",", "str", ",", "idx", ")", ":", "result", "=", "0", "while", "(", "(", "idx", ">", "0", ")", "and", "(", "str", "[", "idx", "-", "1", "]", "==", "\"\\\\\"", ")", ")", ":", "idx", "-=", "1", "result", ...
Returns True if an even number of escape (backslash) characters precede the character at index idx in string str. :param string str: string to check :returns: True if an even number of escape characters precede the character at index idx in string str, False otherwise. :rtype: boolean
[ "Returns", "True", "if", "an", "even", "number", "of", "escape", "(", "backslash", ")", "characters", "precede", "the", "character", "at", "index", "idx", "in", "string", "str", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L238-L255
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3._is_string
def _is_string(cls, arg): """ Return True if arg is a string value, and False if arg is a logical value (ANY or NA). :param string arg: string to check :returns: True if value is a string, False if it is a logical value. :rtype: boolean This function is a support function for _compare(). """ isAny = arg == CPEComponent2_3_WFN.VALUE_ANY isNa = arg == CPEComponent2_3_WFN.VALUE_NA return not (isAny or isNa)
python
def _is_string(cls, arg): """ Return True if arg is a string value, and False if arg is a logical value (ANY or NA). :param string arg: string to check :returns: True if value is a string, False if it is a logical value. :rtype: boolean This function is a support function for _compare(). """ isAny = arg == CPEComponent2_3_WFN.VALUE_ANY isNa = arg == CPEComponent2_3_WFN.VALUE_NA return not (isAny or isNa)
[ "def", "_is_string", "(", "cls", ",", "arg", ")", ":", "isAny", "=", "arg", "==", "CPEComponent2_3_WFN", ".", "VALUE_ANY", "isNa", "=", "arg", "==", "CPEComponent2_3_WFN", ".", "VALUE_NA", "return", "not", "(", "isAny", "or", "isNa", ")" ]
Return True if arg is a string value, and False if arg is a logical value (ANY or NA). :param string arg: string to check :returns: True if value is a string, False if it is a logical value. :rtype: boolean This function is a support function for _compare().
[ "Return", "True", "if", "arg", "is", "a", "string", "value", "and", "False", "if", "arg", "is", "a", "logical", "value", "(", "ANY", "or", "NA", ")", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L258-L273
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3.compare_wfns
def compare_wfns(cls, source, target): """ Compares two WFNs and returns a generator of pairwise attribute-value comparison results. It provides full access to the individual comparison results to enable use-case specific implementations of novel name-comparison algorithms. Compare each attribute of the Source WFN to the Target WFN: :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: generator of pairwise attribute comparison results :rtype: generator """ # Compare results using the get() function in WFN for att in CPEComponent.CPE_COMP_KEYS_EXTENDED: value_src = source.get_attribute_values(att)[0] if value_src.find('"') > -1: # Not a logical value: del double quotes value_src = value_src[1:-1] value_tar = target.get_attribute_values(att)[0] if value_tar.find('"') > -1: # Not a logical value: del double quotes value_tar = value_tar[1:-1] yield (att, CPESet2_3._compare(value_src, value_tar))
python
def compare_wfns(cls, source, target): """ Compares two WFNs and returns a generator of pairwise attribute-value comparison results. It provides full access to the individual comparison results to enable use-case specific implementations of novel name-comparison algorithms. Compare each attribute of the Source WFN to the Target WFN: :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: generator of pairwise attribute comparison results :rtype: generator """ # Compare results using the get() function in WFN for att in CPEComponent.CPE_COMP_KEYS_EXTENDED: value_src = source.get_attribute_values(att)[0] if value_src.find('"') > -1: # Not a logical value: del double quotes value_src = value_src[1:-1] value_tar = target.get_attribute_values(att)[0] if value_tar.find('"') > -1: # Not a logical value: del double quotes value_tar = value_tar[1:-1] yield (att, CPESet2_3._compare(value_src, value_tar))
[ "def", "compare_wfns", "(", "cls", ",", "source", ",", "target", ")", ":", "# Compare results using the get() function in WFN", "for", "att", "in", "CPEComponent", ".", "CPE_COMP_KEYS_EXTENDED", ":", "value_src", "=", "source", ".", "get_attribute_values", "(", "att",...
Compares two WFNs and returns a generator of pairwise attribute-value comparison results. It provides full access to the individual comparison results to enable use-case specific implementations of novel name-comparison algorithms. Compare each attribute of the Source WFN to the Target WFN: :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: generator of pairwise attribute comparison results :rtype: generator
[ "Compares", "two", "WFNs", "and", "returns", "a", "generator", "of", "pairwise", "attribute", "-", "value", "comparison", "results", ".", "It", "provides", "full", "access", "to", "the", "individual", "comparison", "results", "to", "enable", "use", "-", "case"...
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L276-L303
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3.cpe_disjoint
def cpe_disjoint(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is DISJOINT. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is DISJOINT, otherwise False. :rtype: boolean """ # If any pairwise comparison returned DISJOINT then # the overall name relationship is DISJOINT for att, result in CPESet2_3.compare_wfns(source, target): isDisjoint = result == CPESet2_3.LOGICAL_VALUE_DISJOINT if isDisjoint: return True return False
python
def cpe_disjoint(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is DISJOINT. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is DISJOINT, otherwise False. :rtype: boolean """ # If any pairwise comparison returned DISJOINT then # the overall name relationship is DISJOINT for att, result in CPESet2_3.compare_wfns(source, target): isDisjoint = result == CPESet2_3.LOGICAL_VALUE_DISJOINT if isDisjoint: return True return False
[ "def", "cpe_disjoint", "(", "cls", ",", "source", ",", "target", ")", ":", "# If any pairwise comparison returned DISJOINT then", "# the overall name relationship is DISJOINT", "for", "att", ",", "result", "in", "CPESet2_3", ".", "compare_wfns", "(", "source", ",", "ta...
Compares two WFNs and returns True if the set-theoretic relation between the names is DISJOINT. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is DISJOINT, otherwise False. :rtype: boolean
[ "Compares", "two", "WFNs", "and", "returns", "True", "if", "the", "set", "-", "theoretic", "relation", "between", "the", "names", "is", "DISJOINT", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L306-L324
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3.cpe_equal
def cpe_equal(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is EQUAL. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is EQUAL, otherwise False. :rtype: boolean """ # If any pairwise comparison returned EQUAL then # the overall name relationship is EQUAL for att, result in CPESet2_3.compare_wfns(source, target): isEqual = result == CPESet2_3.LOGICAL_VALUE_EQUAL if not isEqual: return False return True
python
def cpe_equal(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is EQUAL. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is EQUAL, otherwise False. :rtype: boolean """ # If any pairwise comparison returned EQUAL then # the overall name relationship is EQUAL for att, result in CPESet2_3.compare_wfns(source, target): isEqual = result == CPESet2_3.LOGICAL_VALUE_EQUAL if not isEqual: return False return True
[ "def", "cpe_equal", "(", "cls", ",", "source", ",", "target", ")", ":", "# If any pairwise comparison returned EQUAL then", "# the overall name relationship is EQUAL", "for", "att", ",", "result", "in", "CPESet2_3", ".", "compare_wfns", "(", "source", ",", "target", "...
Compares two WFNs and returns True if the set-theoretic relation between the names is EQUAL. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is EQUAL, otherwise False. :rtype: boolean
[ "Compares", "two", "WFNs", "and", "returns", "True", "if", "the", "set", "-", "theoretic", "relation", "between", "the", "names", "is", "EQUAL", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L327-L345
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3.cpe_subset
def cpe_subset(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is (non-proper) SUBSET. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is SUBSET, otherwise False. :rtype: boolean """ # If any pairwise comparison returned something other than SUBSET # or EQUAL, then SUBSET is False. for att, result in CPESet2_3.compare_wfns(source, target): isSubset = result == CPESet2_3.LOGICAL_VALUE_SUBSET isEqual = result == CPESet2_3.LOGICAL_VALUE_EQUAL if (not isSubset) and (not isEqual): return False return True
python
def cpe_subset(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is (non-proper) SUBSET. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is SUBSET, otherwise False. :rtype: boolean """ # If any pairwise comparison returned something other than SUBSET # or EQUAL, then SUBSET is False. for att, result in CPESet2_3.compare_wfns(source, target): isSubset = result == CPESet2_3.LOGICAL_VALUE_SUBSET isEqual = result == CPESet2_3.LOGICAL_VALUE_EQUAL if (not isSubset) and (not isEqual): return False return True
[ "def", "cpe_subset", "(", "cls", ",", "source", ",", "target", ")", ":", "# If any pairwise comparison returned something other than SUBSET", "# or EQUAL, then SUBSET is False.", "for", "att", ",", "result", "in", "CPESet2_3", ".", "compare_wfns", "(", "source", ",", "t...
Compares two WFNs and returns True if the set-theoretic relation between the names is (non-proper) SUBSET. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is SUBSET, otherwise False. :rtype: boolean
[ "Compares", "two", "WFNs", "and", "returns", "True", "if", "the", "set", "-", "theoretic", "relation", "between", "the", "names", "is", "(", "non", "-", "proper", ")", "SUBSET", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L348-L367
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3.cpe_superset
def cpe_superset(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is (non-proper) SUPERSET. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is SUPERSET, otherwise False. :rtype: boolean """ # If any pairwise comparison returned something other than SUPERSET # or EQUAL, then SUPERSET is False. for att, result in CPESet2_3.compare_wfns(source, target): isSuperset = result == CPESet2_3.LOGICAL_VALUE_SUPERSET isEqual = result == CPESet2_3.LOGICAL_VALUE_EQUAL if (not isSuperset) and (not isEqual): return False return True
python
def cpe_superset(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is (non-proper) SUPERSET. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is SUPERSET, otherwise False. :rtype: boolean """ # If any pairwise comparison returned something other than SUPERSET # or EQUAL, then SUPERSET is False. for att, result in CPESet2_3.compare_wfns(source, target): isSuperset = result == CPESet2_3.LOGICAL_VALUE_SUPERSET isEqual = result == CPESet2_3.LOGICAL_VALUE_EQUAL if (not isSuperset) and (not isEqual): return False return True
[ "def", "cpe_superset", "(", "cls", ",", "source", ",", "target", ")", ":", "# If any pairwise comparison returned something other than SUPERSET", "# or EQUAL, then SUPERSET is False.", "for", "att", ",", "result", "in", "CPESet2_3", ".", "compare_wfns", "(", "source", ","...
Compares two WFNs and returns True if the set-theoretic relation between the names is (non-proper) SUPERSET. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between source and target is SUPERSET, otherwise False. :rtype: boolean
[ "Compares", "two", "WFNs", "and", "returns", "True", "if", "the", "set", "-", "theoretic", "relation", "between", "the", "names", "is", "(", "non", "-", "proper", ")", "SUPERSET", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L370-L390
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3.append
def append(self, cpe): """ Adds a CPE element to the set if not already. Only WFN CPE Names are valid, so this function converts the input CPE object of version 2.3 to WFN style. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name """ if cpe.VERSION != CPE2_3.VERSION: errmsg = "CPE Name version {0} not valid, version 2.3 expected".format( cpe.VERSION) raise ValueError(errmsg) for k in self.K: if cpe._str == k._str: return None if isinstance(cpe, CPE2_3_WFN): self.K.append(cpe) else: # Convert the CPE Name to WFN wfn = CPE2_3_WFN(cpe.as_wfn()) self.K.append(wfn)
python
def append(self, cpe): """ Adds a CPE element to the set if not already. Only WFN CPE Names are valid, so this function converts the input CPE object of version 2.3 to WFN style. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name """ if cpe.VERSION != CPE2_3.VERSION: errmsg = "CPE Name version {0} not valid, version 2.3 expected".format( cpe.VERSION) raise ValueError(errmsg) for k in self.K: if cpe._str == k._str: return None if isinstance(cpe, CPE2_3_WFN): self.K.append(cpe) else: # Convert the CPE Name to WFN wfn = CPE2_3_WFN(cpe.as_wfn()) self.K.append(wfn)
[ "def", "append", "(", "self", ",", "cpe", ")", ":", "if", "cpe", ".", "VERSION", "!=", "CPE2_3", ".", "VERSION", ":", "errmsg", "=", "\"CPE Name version {0} not valid, version 2.3 expected\"", ".", "format", "(", "cpe", ".", "VERSION", ")", "raise", "ValueErro...
Adds a CPE element to the set if not already. Only WFN CPE Names are valid, so this function converts the input CPE object of version 2.3 to WFN style. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name
[ "Adds", "a", "CPE", "element", "to", "the", "set", "if", "not", "already", ".", "Only", "WFN", "CPE", "Names", "are", "valid", "so", "this", "function", "converts", "the", "input", "CPE", "object", "of", "version", "2", ".", "3", "to", "WFN", "style", ...
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L396-L421
train
nilp0inter/cpe
cpe/cpeset2_3.py
CPESet2_3.name_match
def name_match(self, wfn): """ Accepts a set of CPE Names K and a candidate CPE Name X. It returns 'True' if X matches any member of K, and 'False' otherwise. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :returns: True if X matches K, otherwise False. :rtype: boolean """ for N in self.K: if CPESet2_3.cpe_superset(wfn, N): return True return False
python
def name_match(self, wfn): """ Accepts a set of CPE Names K and a candidate CPE Name X. It returns 'True' if X matches any member of K, and 'False' otherwise. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :returns: True if X matches K, otherwise False. :rtype: boolean """ for N in self.K: if CPESet2_3.cpe_superset(wfn, N): return True return False
[ "def", "name_match", "(", "self", ",", "wfn", ")", ":", "for", "N", "in", "self", ".", "K", ":", "if", "CPESet2_3", ".", "cpe_superset", "(", "wfn", ",", "N", ")", ":", "return", "True", "return", "False" ]
Accepts a set of CPE Names K and a candidate CPE Name X. It returns 'True' if X matches any member of K, and 'False' otherwise. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :returns: True if X matches K, otherwise False. :rtype: boolean
[ "Accepts", "a", "set", "of", "CPE", "Names", "K", "and", "a", "candidate", "CPE", "Name", "X", ".", "It", "returns", "True", "if", "X", "matches", "any", "member", "of", "K", "and", "False", "otherwise", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L423-L437
train
nilp0inter/cpe
cpe/cpe2_3_wfn.py
CPE2_3_WFN._parse
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # Check prefix and initial bracket of WFN if self._str[0:5] != CPE2_3_WFN.CPE_PREFIX: errmsg = "Bad-formed CPE Name: WFN prefix not found" raise ValueError(errmsg) # Check final backet if self._str[-1:] != "]": errmsg = "Bad-formed CPE Name: final bracket of WFN not found" raise ValueError(errmsg) content = self._str[5:-1] if content != "": # Dictionary with pairs attribute-value components = dict() # Split WFN in components list_component = content.split(CPEComponent2_3_WFN.SEPARATOR_COMP) # Adds the defined components for e in list_component: # Whitespace not valid in component names and values if e.find(" ") != -1: msg = "Bad-formed CPE Name: WFN with too many whitespaces" raise ValueError(msg) # Split pair attribute-value pair = e.split(CPEComponent2_3_WFN.SEPARATOR_PAIR) att_name = pair[0] att_value = pair[1] # Check valid attribute name if att_name not in CPEComponent.CPE_COMP_KEYS_EXTENDED: msg = "Bad-formed CPE Name: invalid attribute name '{0}'".format( att_name) raise ValueError(msg) if att_name in components: # Duplicate attribute msg = "Bad-formed CPE Name: attribute '{0}' repeated".format( att_name) raise ValueError(msg) if not (att_value.startswith('"') and att_value.endswith('"')): # Logical value strUpper = att_value.upper() if strUpper == CPEComponent2_3_WFN.VALUE_ANY: comp = CPEComponentAnyValue() elif strUpper == CPEComponent2_3_WFN.VALUE_NA: comp = CPEComponentNotApplicable() else: msg = "Invalid logical value '{0}'".format(att_value) raise ValueError(msg) elif att_value.startswith('"') and att_value.endswith('"'): # String value comp = CPEComponent2_3_WFN(att_value, att_name) else: # Bad value msg = "Bad-formed CPE Name: invalid value '{0}'".format( att_value) raise ValueError(msg) components[att_name] = comp # Adds the undefined components for ck in CPEComponent.CPE_COMP_KEYS_EXTENDED: if ck not in components: components[ck] = CPEComponentUndefined() # ####################### # Storage of CPE Name # # ####################### part_comp = components[CPEComponent.ATT_PART] if isinstance(part_comp, CPEComponentLogical): elements = [] elements.append(components) self[CPE.KEY_UNDEFINED] = elements else: # Create internal structure of CPE Name in parts: # one of them is filled with identified components, # the rest are empty part_value = part_comp.get_value() # Del double quotes of value system = part_value[1:-1] if system in CPEComponent.SYSTEM_VALUES: self._create_cpe_parts(system, components) else: self._create_cpe_parts(CPEComponent.VALUE_PART_UNDEFINED, components) # Fills the empty parts of internal structure of CPE Name for pk in CPE.CPE_PART_KEYS: if pk not in self.keys(): self[pk] = []
python
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # Check prefix and initial bracket of WFN if self._str[0:5] != CPE2_3_WFN.CPE_PREFIX: errmsg = "Bad-formed CPE Name: WFN prefix not found" raise ValueError(errmsg) # Check final backet if self._str[-1:] != "]": errmsg = "Bad-formed CPE Name: final bracket of WFN not found" raise ValueError(errmsg) content = self._str[5:-1] if content != "": # Dictionary with pairs attribute-value components = dict() # Split WFN in components list_component = content.split(CPEComponent2_3_WFN.SEPARATOR_COMP) # Adds the defined components for e in list_component: # Whitespace not valid in component names and values if e.find(" ") != -1: msg = "Bad-formed CPE Name: WFN with too many whitespaces" raise ValueError(msg) # Split pair attribute-value pair = e.split(CPEComponent2_3_WFN.SEPARATOR_PAIR) att_name = pair[0] att_value = pair[1] # Check valid attribute name if att_name not in CPEComponent.CPE_COMP_KEYS_EXTENDED: msg = "Bad-formed CPE Name: invalid attribute name '{0}'".format( att_name) raise ValueError(msg) if att_name in components: # Duplicate attribute msg = "Bad-formed CPE Name: attribute '{0}' repeated".format( att_name) raise ValueError(msg) if not (att_value.startswith('"') and att_value.endswith('"')): # Logical value strUpper = att_value.upper() if strUpper == CPEComponent2_3_WFN.VALUE_ANY: comp = CPEComponentAnyValue() elif strUpper == CPEComponent2_3_WFN.VALUE_NA: comp = CPEComponentNotApplicable() else: msg = "Invalid logical value '{0}'".format(att_value) raise ValueError(msg) elif att_value.startswith('"') and att_value.endswith('"'): # String value comp = CPEComponent2_3_WFN(att_value, att_name) else: # Bad value msg = "Bad-formed CPE Name: invalid value '{0}'".format( att_value) raise ValueError(msg) components[att_name] = comp # Adds the undefined components for ck in CPEComponent.CPE_COMP_KEYS_EXTENDED: if ck not in components: components[ck] = CPEComponentUndefined() # ####################### # Storage of CPE Name # # ####################### part_comp = components[CPEComponent.ATT_PART] if isinstance(part_comp, CPEComponentLogical): elements = [] elements.append(components) self[CPE.KEY_UNDEFINED] = elements else: # Create internal structure of CPE Name in parts: # one of them is filled with identified components, # the rest are empty part_value = part_comp.get_value() # Del double quotes of value system = part_value[1:-1] if system in CPEComponent.SYSTEM_VALUES: self._create_cpe_parts(system, components) else: self._create_cpe_parts(CPEComponent.VALUE_PART_UNDEFINED, components) # Fills the empty parts of internal structure of CPE Name for pk in CPE.CPE_PART_KEYS: if pk not in self.keys(): self[pk] = []
[ "def", "_parse", "(", "self", ")", ":", "# Check prefix and initial bracket of WFN", "if", "self", ".", "_str", "[", "0", ":", "5", "]", "!=", "CPE2_3_WFN", ".", "CPE_PREFIX", ":", "errmsg", "=", "\"Bad-formed CPE Name: WFN prefix not found\"", "raise", "ValueError"...
Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name
[ "Checks", "if", "the", "CPE", "Name", "is", "valid", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_3_wfn.py#L110-L216
train
nilp0inter/cpe
cpe/cpelang2_2.py
CPELanguage2_2.language_match
def language_match(self, cpeset, cpel_dom=None): """ Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applicability Language, represented as the XML infoset for the platform element. :param CPESet cpeset: CPE set object to match with self expression. :param string cpel_dom: An expression in the CPE Applicability Language, represented as DOM tree. :returns: True if self expression can be satisfied by language matching against cpeset, False otherwise. :rtype: boolean """ # Root element tag TAG_ROOT = '#document' # A container for child platform definitions TAG_PLATSPEC = 'cpe:platform-specification' # Information about a platform definition TAG_PLATFORM = 'cpe:platform' TAG_LOGITEST = 'cpe:logical-test' TAG_CPE = 'cpe:fact-ref' # Tag attributes ATT_NAME = 'name' ATT_OP = 'operator' ATT_NEGATE = 'negate' # Attribute values ATT_OP_AND = 'AND' ATT_OP_OR = 'OR' ATT_NEGATE_TRUE = 'TRUE' if cpel_dom is None: cpel_dom = self.document # Identify the root element if cpel_dom.nodeName == TAG_ROOT or cpel_dom.nodeName == TAG_PLATSPEC: for node in cpel_dom.childNodes: if node.nodeName == TAG_PLATSPEC: return self.language_match(cpeset, node) if node.nodeName == TAG_PLATFORM: return self.language_match(cpeset, node) # Identify a platform element elif cpel_dom.nodeName == TAG_PLATFORM: for node in cpel_dom.childNodes: if node.nodeName == TAG_LOGITEST: return self.language_match(cpeset, node) # Identify a CPE element elif cpel_dom.nodeName == TAG_CPE: cpename = cpel_dom.getAttribute(ATT_NAME) c = CPE2_2(cpename) # Try to match a CPE name with CPE set return cpeset.name_match(c) # Identify a logical operator element elif cpel_dom.nodeName == TAG_LOGITEST: count = 0 len = 0 answer = False for node in cpel_dom.childNodes: if node.nodeName.find("#") == 0: continue len = len + 1 if self.language_match(cpeset, node): count = count + 1 operator = cpel_dom.getAttribute(ATT_OP).upper() if operator == ATT_OP_AND: if count == len: answer = True elif operator == ATT_OP_OR: if count > 0: answer = True operator_not = cpel_dom.getAttribute(ATT_NEGATE) if operator_not: if operator_not.upper() == ATT_NEGATE_TRUE: answer = not answer return answer else: return False
python
def language_match(self, cpeset, cpel_dom=None): """ Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applicability Language, represented as the XML infoset for the platform element. :param CPESet cpeset: CPE set object to match with self expression. :param string cpel_dom: An expression in the CPE Applicability Language, represented as DOM tree. :returns: True if self expression can be satisfied by language matching against cpeset, False otherwise. :rtype: boolean """ # Root element tag TAG_ROOT = '#document' # A container for child platform definitions TAG_PLATSPEC = 'cpe:platform-specification' # Information about a platform definition TAG_PLATFORM = 'cpe:platform' TAG_LOGITEST = 'cpe:logical-test' TAG_CPE = 'cpe:fact-ref' # Tag attributes ATT_NAME = 'name' ATT_OP = 'operator' ATT_NEGATE = 'negate' # Attribute values ATT_OP_AND = 'AND' ATT_OP_OR = 'OR' ATT_NEGATE_TRUE = 'TRUE' if cpel_dom is None: cpel_dom = self.document # Identify the root element if cpel_dom.nodeName == TAG_ROOT or cpel_dom.nodeName == TAG_PLATSPEC: for node in cpel_dom.childNodes: if node.nodeName == TAG_PLATSPEC: return self.language_match(cpeset, node) if node.nodeName == TAG_PLATFORM: return self.language_match(cpeset, node) # Identify a platform element elif cpel_dom.nodeName == TAG_PLATFORM: for node in cpel_dom.childNodes: if node.nodeName == TAG_LOGITEST: return self.language_match(cpeset, node) # Identify a CPE element elif cpel_dom.nodeName == TAG_CPE: cpename = cpel_dom.getAttribute(ATT_NAME) c = CPE2_2(cpename) # Try to match a CPE name with CPE set return cpeset.name_match(c) # Identify a logical operator element elif cpel_dom.nodeName == TAG_LOGITEST: count = 0 len = 0 answer = False for node in cpel_dom.childNodes: if node.nodeName.find("#") == 0: continue len = len + 1 if self.language_match(cpeset, node): count = count + 1 operator = cpel_dom.getAttribute(ATT_OP).upper() if operator == ATT_OP_AND: if count == len: answer = True elif operator == ATT_OP_OR: if count > 0: answer = True operator_not = cpel_dom.getAttribute(ATT_NEGATE) if operator_not: if operator_not.upper() == ATT_NEGATE_TRUE: answer = not answer return answer else: return False
[ "def", "language_match", "(", "self", ",", "cpeset", ",", "cpel_dom", "=", "None", ")", ":", "# Root element tag", "TAG_ROOT", "=", "'#document'", "# A container for child platform definitions", "TAG_PLATSPEC", "=", "'cpe:platform-specification'", "# Information about a platf...
Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applicability Language, represented as the XML infoset for the platform element. :param CPESet cpeset: CPE set object to match with self expression. :param string cpel_dom: An expression in the CPE Applicability Language, represented as DOM tree. :returns: True if self expression can be satisfied by language matching against cpeset, False otherwise. :rtype: boolean
[ "Accepts", "a", "set", "of", "known", "CPE", "Names", "and", "an", "expression", "in", "the", "CPE", "language", "and", "delivers", "the", "answer", "True", "if", "the", "expression", "matches", "with", "the", "set", ".", "Otherwise", "it", "returns", "Fal...
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpelang2_2.py#L59-L149
train
nilp0inter/cpe
cpe/cpeset2_2.py
CPESet2_2.append
def append(self, cpe): """ Adds a CPE Name to the set if not already. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset2_2 import CPESet2_2 >>> from .cpe2_2 import CPE2_2 >>> uri1 = 'cpe:/h:hp' >>> c1 = CPE2_2(uri1) >>> s = CPESet2_2() >>> s.append(c1) """ if cpe.VERSION != CPE.VERSION_2_2: errmsg = "CPE Name version {0} not valid, version 2.2 expected".format( cpe.VERSION) raise ValueError(errmsg) for k in self.K: if cpe.cpe_str == k.cpe_str: return None self.K.append(cpe)
python
def append(self, cpe): """ Adds a CPE Name to the set if not already. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset2_2 import CPESet2_2 >>> from .cpe2_2 import CPE2_2 >>> uri1 = 'cpe:/h:hp' >>> c1 = CPE2_2(uri1) >>> s = CPESet2_2() >>> s.append(c1) """ if cpe.VERSION != CPE.VERSION_2_2: errmsg = "CPE Name version {0} not valid, version 2.2 expected".format( cpe.VERSION) raise ValueError(errmsg) for k in self.K: if cpe.cpe_str == k.cpe_str: return None self.K.append(cpe)
[ "def", "append", "(", "self", ",", "cpe", ")", ":", "if", "cpe", ".", "VERSION", "!=", "CPE", ".", "VERSION_2_2", ":", "errmsg", "=", "\"CPE Name version {0} not valid, version 2.2 expected\"", ".", "format", "(", "cpe", ".", "VERSION", ")", "raise", "ValueErr...
Adds a CPE Name to the set if not already. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset2_2 import CPESet2_2 >>> from .cpe2_2 import CPE2_2 >>> uri1 = 'cpe:/h:hp' >>> c1 = CPE2_2(uri1) >>> s = CPESet2_2() >>> s.append(c1)
[ "Adds", "a", "CPE", "Name", "to", "the", "set", "if", "not", "already", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_2.py#L58-L86
train
nilp0inter/cpe
cpe/comp/cpecomp2_3_wfn.py
CPEComponent2_3_WFN.set_value
def set_value(self, comp_str, comp_att): """ Set the value of component. :param string comp_str: value of component :param string comp_att: attribute associated with comp_str :returns: None :exception: ValueError - incorrect value of component """ # Del double quotes of value str = comp_str[1:-1] self._standard_value = str # Parse the value super(CPEComponent2_3_WFN, self).set_value(str, comp_att)
python
def set_value(self, comp_str, comp_att): """ Set the value of component. :param string comp_str: value of component :param string comp_att: attribute associated with comp_str :returns: None :exception: ValueError - incorrect value of component """ # Del double quotes of value str = comp_str[1:-1] self._standard_value = str # Parse the value super(CPEComponent2_3_WFN, self).set_value(str, comp_att)
[ "def", "set_value", "(", "self", ",", "comp_str", ",", "comp_att", ")", ":", "# Del double quotes of value", "str", "=", "comp_str", "[", "1", ":", "-", "1", "]", "self", ".", "_standard_value", "=", "str", "# Parse the value", "super", "(", "CPEComponent2_3_W...
Set the value of component. :param string comp_str: value of component :param string comp_att: attribute associated with comp_str :returns: None :exception: ValueError - incorrect value of component
[ "Set", "the", "value", "of", "component", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp2_3_wfn.py#L132-L147
train
nilp0inter/cpe
cpe/cpeset1_1.py
CPESet1_1.append
def append(self, cpe): """ Adds a CPE Name to the set if not already. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset1_1 import CPESet1_1 >>> from .cpe1_1 import CPE1_1 >>> uri1 = 'cpe://microsoft:windows:xp!vista' >>> c1 = CPE1_1(uri1) >>> s = CPESet1_1() >>> s.append(c1) """ if cpe.VERSION != CPE.VERSION_1_1: msg = "CPE Name version {0} not valid, version 1.1 expected".format( cpe.VERSION) raise ValueError(msg) for k in self.K: if cpe.cpe_str == k.cpe_str: return None self.K.append(cpe)
python
def append(self, cpe): """ Adds a CPE Name to the set if not already. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset1_1 import CPESet1_1 >>> from .cpe1_1 import CPE1_1 >>> uri1 = 'cpe://microsoft:windows:xp!vista' >>> c1 = CPE1_1(uri1) >>> s = CPESet1_1() >>> s.append(c1) """ if cpe.VERSION != CPE.VERSION_1_1: msg = "CPE Name version {0} not valid, version 1.1 expected".format( cpe.VERSION) raise ValueError(msg) for k in self.K: if cpe.cpe_str == k.cpe_str: return None self.K.append(cpe)
[ "def", "append", "(", "self", ",", "cpe", ")", ":", "if", "cpe", ".", "VERSION", "!=", "CPE", ".", "VERSION_1_1", ":", "msg", "=", "\"CPE Name version {0} not valid, version 1.1 expected\"", ".", "format", "(", "cpe", ".", "VERSION", ")", "raise", "ValueError"...
Adds a CPE Name to the set if not already. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset1_1 import CPESet1_1 >>> from .cpe1_1 import CPE1_1 >>> uri1 = 'cpe://microsoft:windows:xp!vista' >>> c1 = CPE1_1(uri1) >>> s = CPESet1_1() >>> s.append(c1)
[ "Adds", "a", "CPE", "Name", "to", "the", "set", "if", "not", "already", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset1_1.py#L56-L83
train
nilp0inter/cpe
cpe/cpeset1_1.py
CPESet1_1.name_match
def name_match(self, cpe): """ Accepts a set of known instances of CPE Names and a candidate CPE Name, and returns 'True' if the candidate can be shown to be an instance based on the content of the known instances. Otherwise, it returns 'False'. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :returns: True if X matches K, otherwise False. :rtype: boolean TEST: matching with identical CPE in set >>> from .cpe1_1 import CPE1_1 >>> from .cpeset1_1 import CPESet1_1 >>> uri1 = 'cpe://microsoft:windows:xp!vista' >>> uri2 = 'cpe:/cisco::3825;cisco:2:44/cisco:ios:12.3:enterprise' >>> c1 = CPE1_1(uri1) >>> c2 = CPE1_1(uri2) >>> s = CPESet1_1() >>> s.append(c1) >>> s.append(c2) >>> s.name_match(c2) True """ # An empty set not matching with any CPE if len(self) == 0: return False # If input CPE Name string is in set of CPE Name strings # not do searching more because there is a matching for k in self.K: if (k.cpe_str == cpe.cpe_str): return True # There are not a CPE Name string in set equal to # input CPE Name string match = False for p in CPE.CPE_PART_KEYS: elems_cpe = cpe.get(p) for ec in elems_cpe: # Search of element of part of input CPE # Each element ec of input cpe[p] is compared with # each element ek of k[p] in set K for k in self.K: elems_k = k.get(p) for ek in elems_k: # Matching # Each component in element ec is compared with # each component in element ek for ck in CPEComponent.CPE_COMP_KEYS: comp_cpe = ec.get(ck) comp_k = ek.get(ck) match = comp_k in comp_cpe if not match: # Search compoment in another element ek[p] break # Component analyzed if match: # Element matched break if match: break # Next element in part in "cpe" if not match: # cpe part not match with parts in set return False # Next part in input CPE Name # All parts in input CPE Name matched return True
python
def name_match(self, cpe): """ Accepts a set of known instances of CPE Names and a candidate CPE Name, and returns 'True' if the candidate can be shown to be an instance based on the content of the known instances. Otherwise, it returns 'False'. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :returns: True if X matches K, otherwise False. :rtype: boolean TEST: matching with identical CPE in set >>> from .cpe1_1 import CPE1_1 >>> from .cpeset1_1 import CPESet1_1 >>> uri1 = 'cpe://microsoft:windows:xp!vista' >>> uri2 = 'cpe:/cisco::3825;cisco:2:44/cisco:ios:12.3:enterprise' >>> c1 = CPE1_1(uri1) >>> c2 = CPE1_1(uri2) >>> s = CPESet1_1() >>> s.append(c1) >>> s.append(c2) >>> s.name_match(c2) True """ # An empty set not matching with any CPE if len(self) == 0: return False # If input CPE Name string is in set of CPE Name strings # not do searching more because there is a matching for k in self.K: if (k.cpe_str == cpe.cpe_str): return True # There are not a CPE Name string in set equal to # input CPE Name string match = False for p in CPE.CPE_PART_KEYS: elems_cpe = cpe.get(p) for ec in elems_cpe: # Search of element of part of input CPE # Each element ec of input cpe[p] is compared with # each element ek of k[p] in set K for k in self.K: elems_k = k.get(p) for ek in elems_k: # Matching # Each component in element ec is compared with # each component in element ek for ck in CPEComponent.CPE_COMP_KEYS: comp_cpe = ec.get(ck) comp_k = ek.get(ck) match = comp_k in comp_cpe if not match: # Search compoment in another element ek[p] break # Component analyzed if match: # Element matched break if match: break # Next element in part in "cpe" if not match: # cpe part not match with parts in set return False # Next part in input CPE Name # All parts in input CPE Name matched return True
[ "def", "name_match", "(", "self", ",", "cpe", ")", ":", "# An empty set not matching with any CPE", "if", "len", "(", "self", ")", "==", "0", ":", "return", "False", "# If input CPE Name string is in set of CPE Name strings", "# not do searching more because there is a matchi...
Accepts a set of known instances of CPE Names and a candidate CPE Name, and returns 'True' if the candidate can be shown to be an instance based on the content of the known instances. Otherwise, it returns 'False'. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :returns: True if X matches K, otherwise False. :rtype: boolean TEST: matching with identical CPE in set >>> from .cpe1_1 import CPE1_1 >>> from .cpeset1_1 import CPESet1_1 >>> uri1 = 'cpe://microsoft:windows:xp!vista' >>> uri2 = 'cpe:/cisco::3825;cisco:2:44/cisco:ios:12.3:enterprise' >>> c1 = CPE1_1(uri1) >>> c2 = CPE1_1(uri2) >>> s = CPESet1_1() >>> s.append(c1) >>> s.append(c2) >>> s.name_match(c2) True
[ "Accepts", "a", "set", "of", "known", "instances", "of", "CPE", "Names", "and", "a", "candidate", "CPE", "Name", "and", "returns", "True", "if", "the", "candidate", "can", "be", "shown", "to", "be", "an", "instance", "based", "on", "the", "content", "of"...
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset1_1.py#L85-L169
train
nilp0inter/cpe
cpe/cpe2_3_fs.py
CPE2_3_FS._parse
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" raise ValueError(msg) # Partitioning of CPE Name parts_match = CPE2_3_FS._parts_rxc.match(self._str) # Validation of CPE Name parts if (parts_match is None): msg = "Bad-formed CPE Name: validation of parts failed" raise ValueError(msg) components = dict() parts_match_dict = parts_match.groupdict() for ck in CPEComponent.CPE_COMP_KEYS_EXTENDED: if ck in parts_match_dict: value = parts_match.group(ck) if (value == CPEComponent2_3_FS.VALUE_ANY): comp = CPEComponentAnyValue() elif (value == CPEComponent2_3_FS.VALUE_NA): comp = CPEComponentNotApplicable() else: try: comp = CPEComponent2_3_FS(value, ck) except ValueError: errmsg = "Bad-formed CPE Name: not correct value: {0}".format( value) raise ValueError(errmsg) else: errmsg = "Component {0} should be specified".format(ck) raise ValueError(ck) components[ck] = comp # ####################### # Storage of CPE Name # # ####################### part_comp = components[CPEComponent.ATT_PART] if isinstance(part_comp, CPEComponentLogical): elements = [] elements.append(components) self[CPE.KEY_UNDEFINED] = elements else: # Create internal structure of CPE Name in parts: # one of them is filled with identified components, # the rest are empty system = parts_match.group(CPEComponent.ATT_PART) if system in CPEComponent.SYSTEM_VALUES: self._create_cpe_parts(system, components) else: self._create_cpe_parts(CPEComponent.VALUE_PART_UNDEFINED, components) # Fills the empty parts of internal structure of CPE Name for pk in CPE.CPE_PART_KEYS: if pk not in self.keys(): # Empty part self[pk] = []
python
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" raise ValueError(msg) # Partitioning of CPE Name parts_match = CPE2_3_FS._parts_rxc.match(self._str) # Validation of CPE Name parts if (parts_match is None): msg = "Bad-formed CPE Name: validation of parts failed" raise ValueError(msg) components = dict() parts_match_dict = parts_match.groupdict() for ck in CPEComponent.CPE_COMP_KEYS_EXTENDED: if ck in parts_match_dict: value = parts_match.group(ck) if (value == CPEComponent2_3_FS.VALUE_ANY): comp = CPEComponentAnyValue() elif (value == CPEComponent2_3_FS.VALUE_NA): comp = CPEComponentNotApplicable() else: try: comp = CPEComponent2_3_FS(value, ck) except ValueError: errmsg = "Bad-formed CPE Name: not correct value: {0}".format( value) raise ValueError(errmsg) else: errmsg = "Component {0} should be specified".format(ck) raise ValueError(ck) components[ck] = comp # ####################### # Storage of CPE Name # # ####################### part_comp = components[CPEComponent.ATT_PART] if isinstance(part_comp, CPEComponentLogical): elements = [] elements.append(components) self[CPE.KEY_UNDEFINED] = elements else: # Create internal structure of CPE Name in parts: # one of them is filled with identified components, # the rest are empty system = parts_match.group(CPEComponent.ATT_PART) if system in CPEComponent.SYSTEM_VALUES: self._create_cpe_parts(system, components) else: self._create_cpe_parts(CPEComponent.VALUE_PART_UNDEFINED, components) # Fills the empty parts of internal structure of CPE Name for pk in CPE.CPE_PART_KEYS: if pk not in self.keys(): # Empty part self[pk] = []
[ "def", "_parse", "(", "self", ")", ":", "# CPE Name must not have whitespaces", "if", "(", "self", ".", "_str", ".", "find", "(", "\" \"", ")", "!=", "-", "1", ")", ":", "msg", "=", "\"Bad-formed CPE Name: it must not have whitespaces\"", "raise", "ValueError", ...
Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name
[ "Checks", "if", "the", "CPE", "Name", "is", "valid", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_3_fs.py#L130-L199
train
nilp0inter/cpe
cpe/cpe2_3_fs.py
CPE2_3_FS.get_attribute_values
def get_attribute_values(self, att_name): """ Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - invalid attribute name """ lc = [] if not CPEComponent.is_valid_attribute(att_name): errmsg = "Invalid attribute name: {0}".format(att_name) raise ValueError(errmsg) for pk in CPE.CPE_PART_KEYS: elements = self.get(pk) for elem in elements: comp = elem.get(att_name) if isinstance(comp, CPEComponentAnyValue): value = CPEComponent2_3_FS.VALUE_ANY elif isinstance(comp, CPEComponentNotApplicable): value = CPEComponent2_3_FS.VALUE_NA else: value = comp.get_value() lc.append(value) return lc
python
def get_attribute_values(self, att_name): """ Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - invalid attribute name """ lc = [] if not CPEComponent.is_valid_attribute(att_name): errmsg = "Invalid attribute name: {0}".format(att_name) raise ValueError(errmsg) for pk in CPE.CPE_PART_KEYS: elements = self.get(pk) for elem in elements: comp = elem.get(att_name) if isinstance(comp, CPEComponentAnyValue): value = CPEComponent2_3_FS.VALUE_ANY elif isinstance(comp, CPEComponentNotApplicable): value = CPEComponent2_3_FS.VALUE_NA else: value = comp.get_value() lc.append(value) return lc
[ "def", "get_attribute_values", "(", "self", ",", "att_name", ")", ":", "lc", "=", "[", "]", "if", "not", "CPEComponent", ".", "is_valid_attribute", "(", "att_name", ")", ":", "errmsg", "=", "\"Invalid attribute name: {0}\"", ".", "format", "(", "att_name", ")"...
Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - invalid attribute name
[ "Returns", "the", "values", "of", "attribute", "att_name", "of", "CPE", "Name", ".", "By", "default", "a", "only", "element", "in", "each", "part", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_3_fs.py#L201-L233
train
nilp0inter/cpe
cpe/cpe2_2.py
CPE2_2._parse
def _parse(self): """ Checks if CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" raise ValueError(msg) # Partitioning of CPE Name parts_match = CPE2_2._parts_rxc.match(self._str) # Validation of CPE Name parts if (parts_match is None): msg = "Bad-formed CPE Name: validation of parts failed" raise ValueError(msg) components = dict() parts_match_dict = parts_match.groupdict() for ck in CPEComponent.CPE_COMP_KEYS: if ck in parts_match_dict: value = parts_match.group(ck) if (value == CPEComponent2_2.VALUE_UNDEFINED): comp = CPEComponentUndefined() elif (value == CPEComponent2_2.VALUE_EMPTY): comp = CPEComponentEmpty() else: try: comp = CPEComponent2_2(value, ck) except ValueError: errmsg = "Bad-formed CPE Name: not correct value: {0}".format( value) raise ValueError(errmsg) else: # Component not exist in this version of CPE comp = CPEComponentUndefined() components[ck] = comp # Adds the components of version 2.3 of CPE not defined in version 2.2 for ck2 in CPEComponent.CPE_COMP_KEYS_EXTENDED: if ck2 not in components.keys(): components[ck2] = CPEComponentUndefined() # ####################### # Storage of CPE Name # # ####################### # If part component is undefined, store it in the part without name if components[CPEComponent.ATT_PART] == CPEComponentUndefined(): system = CPEComponent.VALUE_PART_UNDEFINED else: system = parts_match.group(CPEComponent.ATT_PART) self._create_cpe_parts(system, components) # Adds the undefined parts for sys in CPEComponent.SYSTEM_VALUES: if sys != system: pk = CPE._system_and_parts[sys] self[pk] = []
python
def _parse(self): """ Checks if CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" raise ValueError(msg) # Partitioning of CPE Name parts_match = CPE2_2._parts_rxc.match(self._str) # Validation of CPE Name parts if (parts_match is None): msg = "Bad-formed CPE Name: validation of parts failed" raise ValueError(msg) components = dict() parts_match_dict = parts_match.groupdict() for ck in CPEComponent.CPE_COMP_KEYS: if ck in parts_match_dict: value = parts_match.group(ck) if (value == CPEComponent2_2.VALUE_UNDEFINED): comp = CPEComponentUndefined() elif (value == CPEComponent2_2.VALUE_EMPTY): comp = CPEComponentEmpty() else: try: comp = CPEComponent2_2(value, ck) except ValueError: errmsg = "Bad-formed CPE Name: not correct value: {0}".format( value) raise ValueError(errmsg) else: # Component not exist in this version of CPE comp = CPEComponentUndefined() components[ck] = comp # Adds the components of version 2.3 of CPE not defined in version 2.2 for ck2 in CPEComponent.CPE_COMP_KEYS_EXTENDED: if ck2 not in components.keys(): components[ck2] = CPEComponentUndefined() # ####################### # Storage of CPE Name # # ####################### # If part component is undefined, store it in the part without name if components[CPEComponent.ATT_PART] == CPEComponentUndefined(): system = CPEComponent.VALUE_PART_UNDEFINED else: system = parts_match.group(CPEComponent.ATT_PART) self._create_cpe_parts(system, components) # Adds the undefined parts for sys in CPEComponent.SYSTEM_VALUES: if sys != system: pk = CPE._system_and_parts[sys] self[pk] = []
[ "def", "_parse", "(", "self", ")", ":", "# CPE Name must not have whitespaces", "if", "(", "self", ".", "_str", ".", "find", "(", "\" \"", ")", "!=", "-", "1", ")", ":", "msg", "=", "\"Bad-formed CPE Name: it must not have whitespaces\"", "raise", "ValueError", ...
Checks if CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name
[ "Checks", "if", "CPE", "Name", "is", "valid", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_2.py#L127-L193
train
nilp0inter/cpe
cpe/cpe2_2.py
CPE2_2.as_wfn
def as_wfn(self): """ Returns the CPE Name as WFN string of version 2.3. Only shows the first seven components. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version """ wfn = [] wfn.append(CPE2_3_WFN.CPE_PREFIX) for ck in CPEComponent.CPE_COMP_KEYS: lc = self._get_attribute_components(ck) comp = lc[0] if (isinstance(comp, CPEComponentUndefined) or isinstance(comp, CPEComponentEmpty)): # Do not set the attribute continue else: v = [] v.append(ck) v.append("=") # Get the value of WFN of component v.append('"') v.append(comp.as_wfn()) v.append('"') # Append v to the WFN and add a separator wfn.append("".join(v)) wfn.append(CPEComponent2_3_WFN.SEPARATOR_COMP) # Del the last separator wfn = wfn[:-1] # Return the WFN string wfn.append(CPE2_3_WFN.CPE_SUFFIX) return "".join(wfn)
python
def as_wfn(self): """ Returns the CPE Name as WFN string of version 2.3. Only shows the first seven components. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version """ wfn = [] wfn.append(CPE2_3_WFN.CPE_PREFIX) for ck in CPEComponent.CPE_COMP_KEYS: lc = self._get_attribute_components(ck) comp = lc[0] if (isinstance(comp, CPEComponentUndefined) or isinstance(comp, CPEComponentEmpty)): # Do not set the attribute continue else: v = [] v.append(ck) v.append("=") # Get the value of WFN of component v.append('"') v.append(comp.as_wfn()) v.append('"') # Append v to the WFN and add a separator wfn.append("".join(v)) wfn.append(CPEComponent2_3_WFN.SEPARATOR_COMP) # Del the last separator wfn = wfn[:-1] # Return the WFN string wfn.append(CPE2_3_WFN.CPE_SUFFIX) return "".join(wfn)
[ "def", "as_wfn", "(", "self", ")", ":", "wfn", "=", "[", "]", "wfn", ".", "append", "(", "CPE2_3_WFN", ".", "CPE_PREFIX", ")", "for", "ck", "in", "CPEComponent", ".", "CPE_COMP_KEYS", ":", "lc", "=", "self", ".", "_get_attribute_components", "(", "ck", ...
Returns the CPE Name as WFN string of version 2.3. Only shows the first seven components. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version
[ "Returns", "the", "CPE", "Name", "as", "WFN", "string", "of", "version", "2", ".", "3", ".", "Only", "shows", "the", "first", "seven", "components", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_2.py#L195-L238
train
nilp0inter/cpe
cpe/cpelang2_3.py
CPELanguage2_3._fact_ref_eval
def _fact_ref_eval(cls, cpeset, wfn): """ Returns True if wfn is a non-proper superset (True superset or equal to) any of the names in cpeset, otherwise False. :param CPESet cpeset: list of CPE bound Names. :param CPE2_3_WFN wfn: WFN CPE Name. :returns: True if wfn is a non-proper superset any of the names in cpeset, otherwise False :rtype: boolean """ for n in cpeset: # Need to convert each n from bound form to WFN if (CPESet2_3.cpe_superset(wfn, n)): return True return False
python
def _fact_ref_eval(cls, cpeset, wfn): """ Returns True if wfn is a non-proper superset (True superset or equal to) any of the names in cpeset, otherwise False. :param CPESet cpeset: list of CPE bound Names. :param CPE2_3_WFN wfn: WFN CPE Name. :returns: True if wfn is a non-proper superset any of the names in cpeset, otherwise False :rtype: boolean """ for n in cpeset: # Need to convert each n from bound form to WFN if (CPESet2_3.cpe_superset(wfn, n)): return True return False
[ "def", "_fact_ref_eval", "(", "cls", ",", "cpeset", ",", "wfn", ")", ":", "for", "n", "in", "cpeset", ":", "# Need to convert each n from bound form to WFN", "if", "(", "CPESet2_3", ".", "cpe_superset", "(", "wfn", ",", "n", ")", ")", ":", "return", "True", ...
Returns True if wfn is a non-proper superset (True superset or equal to) any of the names in cpeset, otherwise False. :param CPESet cpeset: list of CPE bound Names. :param CPE2_3_WFN wfn: WFN CPE Name. :returns: True if wfn is a non-proper superset any of the names in cpeset, otherwise False :rtype: boolean
[ "Returns", "True", "if", "wfn", "is", "a", "non", "-", "proper", "superset", "(", "True", "superset", "or", "equal", "to", ")", "any", "of", "the", "names", "in", "cpeset", "otherwise", "False", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpelang2_3.py#L62-L78
train
nilp0inter/cpe
cpe/cpelang2_3.py
CPELanguage2_3._check_fact_ref_eval
def _check_fact_ref_eval(cls, cpel_dom): """ Returns the result (True, False, Error) of performing the specified check, unless the check isn’t supported, in which case it returns False. Error is a catch-all for all results other than True and False. :param string cpel_dom: XML infoset for the check_fact_ref element. :returns: result of performing the specified check :rtype: boolean or error """ CHECK_SYSTEM = "check-system" CHECK_LOCATION = "check-location" CHECK_ID = "check-id" checksystemID = cpel_dom.getAttribute(CHECK_SYSTEM) if (checksystemID == "http://oval.mitre.org/XMLSchema/ovaldefinitions-5"): # Perform an OVAL check. # First attribute is the URI of an OVAL definitions file. # Second attribute is an OVAL definition ID. return CPELanguage2_3._ovalcheck(cpel_dom.getAttribute(CHECK_LOCATION), cpel_dom.getAttribute(CHECK_ID)) if (checksystemID == "http://scap.nist.gov/schema/ocil/2"): # Perform an OCIL check. # First attribute is the URI of an OCIL questionnaire file. # Second attribute is OCIL questionnaire ID. return CPELanguage2_3._ocilcheck(cpel_dom.getAttribute(CHECK_LOCATION), cpel_dom.getAttribute(CHECK_ID)) # Can add additional check systems here, with each returning a # True, False, or Error value return False
python
def _check_fact_ref_eval(cls, cpel_dom): """ Returns the result (True, False, Error) of performing the specified check, unless the check isn’t supported, in which case it returns False. Error is a catch-all for all results other than True and False. :param string cpel_dom: XML infoset for the check_fact_ref element. :returns: result of performing the specified check :rtype: boolean or error """ CHECK_SYSTEM = "check-system" CHECK_LOCATION = "check-location" CHECK_ID = "check-id" checksystemID = cpel_dom.getAttribute(CHECK_SYSTEM) if (checksystemID == "http://oval.mitre.org/XMLSchema/ovaldefinitions-5"): # Perform an OVAL check. # First attribute is the URI of an OVAL definitions file. # Second attribute is an OVAL definition ID. return CPELanguage2_3._ovalcheck(cpel_dom.getAttribute(CHECK_LOCATION), cpel_dom.getAttribute(CHECK_ID)) if (checksystemID == "http://scap.nist.gov/schema/ocil/2"): # Perform an OCIL check. # First attribute is the URI of an OCIL questionnaire file. # Second attribute is OCIL questionnaire ID. return CPELanguage2_3._ocilcheck(cpel_dom.getAttribute(CHECK_LOCATION), cpel_dom.getAttribute(CHECK_ID)) # Can add additional check systems here, with each returning a # True, False, or Error value return False
[ "def", "_check_fact_ref_eval", "(", "cls", ",", "cpel_dom", ")", ":", "CHECK_SYSTEM", "=", "\"check-system\"", "CHECK_LOCATION", "=", "\"check-location\"", "CHECK_ID", "=", "\"check-id\"", "checksystemID", "=", "cpel_dom", ".", "getAttribute", "(", "CHECK_SYSTEM", ")"...
Returns the result (True, False, Error) of performing the specified check, unless the check isn’t supported, in which case it returns False. Error is a catch-all for all results other than True and False. :param string cpel_dom: XML infoset for the check_fact_ref element. :returns: result of performing the specified check :rtype: boolean or error
[ "Returns", "the", "result", "(", "True", "False", "Error", ")", "of", "performing", "the", "specified", "check", "unless", "the", "check", "isn’t", "supported", "in", "which", "case", "it", "returns", "False", ".", "Error", "is", "a", "catch", "-", "all", ...
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpelang2_3.py#L81-L114
train
nilp0inter/cpe
cpe/cpelang2_3.py
CPELanguage2_3._unbind
def _unbind(cls, boundname): """ Unbinds a bound form to a WFN. :param string boundname: CPE name :returns: WFN object associated with boundname. :rtype: CPE2_3_WFN """ try: fs = CPE2_3_FS(boundname) except: # CPE name is not formatted string try: uri = CPE2_3_URI(boundname) except: # CPE name is not URI but WFN return CPE2_3_WFN(boundname) else: return CPE2_3_WFN(uri.as_wfn()) else: return CPE2_3_WFN(fs.as_wfn())
python
def _unbind(cls, boundname): """ Unbinds a bound form to a WFN. :param string boundname: CPE name :returns: WFN object associated with boundname. :rtype: CPE2_3_WFN """ try: fs = CPE2_3_FS(boundname) except: # CPE name is not formatted string try: uri = CPE2_3_URI(boundname) except: # CPE name is not URI but WFN return CPE2_3_WFN(boundname) else: return CPE2_3_WFN(uri.as_wfn()) else: return CPE2_3_WFN(fs.as_wfn())
[ "def", "_unbind", "(", "cls", ",", "boundname", ")", ":", "try", ":", "fs", "=", "CPE2_3_FS", "(", "boundname", ")", "except", ":", "# CPE name is not formatted string", "try", ":", "uri", "=", "CPE2_3_URI", "(", "boundname", ")", "except", ":", "# CPE name ...
Unbinds a bound form to a WFN. :param string boundname: CPE name :returns: WFN object associated with boundname. :rtype: CPE2_3_WFN
[ "Unbinds", "a", "bound", "form", "to", "a", "WFN", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpelang2_3.py#L145-L166
train
nilp0inter/cpe
cpe/cpelang2_3.py
CPELanguage2_3.language_match
def language_match(self, cpeset, cpel_dom=None): """ Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applicability Language, represented as the XML infoset for the platform element. :param CPESet cpeset: CPE set object to match with self expression. :param string cpel_dom: An expression in the CPE Applicability Language, represented as DOM tree. :returns: True if self expression can be satisfied by language matching against cpeset, False otherwise. :rtype: boolean """ # Root element tag TAG_ROOT = '#document' # A container for child platform definitions TAG_PLATSPEC = 'cpe:platform-specification' # Information about a platform definition TAG_PLATFORM = 'cpe:platform' TAG_LOGITEST = 'cpe:logical-test' TAG_CPE = 'cpe:fact-ref' TAG_CHECK_CPE = 'check-fact-ref' # Tag attributes ATT_NAME = 'name' ATT_OP = 'operator' ATT_NEGATE = 'negate' # Attribute values ATT_OP_AND = 'AND' ATT_OP_OR = 'OR' ATT_NEGATE_TRUE = 'TRUE' # Constant associated with an error in language matching ERROR = 2 if cpel_dom is None: cpel_dom = self.document # Identify the root element if cpel_dom.nodeName == TAG_ROOT or cpel_dom.nodeName == TAG_PLATSPEC: for node in cpel_dom.childNodes: if node.nodeName == TAG_PLATSPEC: return self.language_match(cpeset, node) if node.nodeName == TAG_PLATFORM: return self.language_match(cpeset, node) # Identify a platform element elif cpel_dom.nodeName == TAG_PLATFORM: # Parse through E's elements and ignore all but logical-test for node in cpel_dom.childNodes: if node.nodeName == TAG_LOGITEST: # Call the function again, but with logical-test # as the root element return self.language_match(cpeset, node) # Identify a CPE element elif cpel_dom.nodeName == TAG_CPE: # fact-ref's name attribute is a bound name, # so we unbind it to a WFN before passing it cpename = cpel_dom.getAttribute(ATT_NAME) wfn = CPELanguage2_3._unbind(cpename) return CPELanguage2_3._fact_ref_eval(cpeset, wfn) # Identify a check of CPE names (OVAL, OCIL...) elif cpel_dom.nodeName == TAG_CHECK_CPE: return CPELanguage2_3._check_fact_ref_Eval(cpel_dom) # Identify a logical operator element elif cpel_dom.nodeName == TAG_LOGITEST: count = 0 len = 0 answer = False for node in cpel_dom.childNodes: if node.nodeName.find("#") == 0: continue len = len + 1 result = self.language_match(cpeset, node) if result: count = count + 1 elif result == ERROR: answer = ERROR operator = cpel_dom.getAttribute(ATT_OP).upper() if operator == ATT_OP_AND: if count == len: answer = True elif operator == ATT_OP_OR: if count > 0: answer = True operator_not = cpel_dom.getAttribute(ATT_NEGATE) if operator_not: if ((operator_not.upper() == ATT_NEGATE_TRUE) and (answer != ERROR)): answer = not answer return answer else: return False
python
def language_match(self, cpeset, cpel_dom=None): """ Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applicability Language, represented as the XML infoset for the platform element. :param CPESet cpeset: CPE set object to match with self expression. :param string cpel_dom: An expression in the CPE Applicability Language, represented as DOM tree. :returns: True if self expression can be satisfied by language matching against cpeset, False otherwise. :rtype: boolean """ # Root element tag TAG_ROOT = '#document' # A container for child platform definitions TAG_PLATSPEC = 'cpe:platform-specification' # Information about a platform definition TAG_PLATFORM = 'cpe:platform' TAG_LOGITEST = 'cpe:logical-test' TAG_CPE = 'cpe:fact-ref' TAG_CHECK_CPE = 'check-fact-ref' # Tag attributes ATT_NAME = 'name' ATT_OP = 'operator' ATT_NEGATE = 'negate' # Attribute values ATT_OP_AND = 'AND' ATT_OP_OR = 'OR' ATT_NEGATE_TRUE = 'TRUE' # Constant associated with an error in language matching ERROR = 2 if cpel_dom is None: cpel_dom = self.document # Identify the root element if cpel_dom.nodeName == TAG_ROOT or cpel_dom.nodeName == TAG_PLATSPEC: for node in cpel_dom.childNodes: if node.nodeName == TAG_PLATSPEC: return self.language_match(cpeset, node) if node.nodeName == TAG_PLATFORM: return self.language_match(cpeset, node) # Identify a platform element elif cpel_dom.nodeName == TAG_PLATFORM: # Parse through E's elements and ignore all but logical-test for node in cpel_dom.childNodes: if node.nodeName == TAG_LOGITEST: # Call the function again, but with logical-test # as the root element return self.language_match(cpeset, node) # Identify a CPE element elif cpel_dom.nodeName == TAG_CPE: # fact-ref's name attribute is a bound name, # so we unbind it to a WFN before passing it cpename = cpel_dom.getAttribute(ATT_NAME) wfn = CPELanguage2_3._unbind(cpename) return CPELanguage2_3._fact_ref_eval(cpeset, wfn) # Identify a check of CPE names (OVAL, OCIL...) elif cpel_dom.nodeName == TAG_CHECK_CPE: return CPELanguage2_3._check_fact_ref_Eval(cpel_dom) # Identify a logical operator element elif cpel_dom.nodeName == TAG_LOGITEST: count = 0 len = 0 answer = False for node in cpel_dom.childNodes: if node.nodeName.find("#") == 0: continue len = len + 1 result = self.language_match(cpeset, node) if result: count = count + 1 elif result == ERROR: answer = ERROR operator = cpel_dom.getAttribute(ATT_OP).upper() if operator == ATT_OP_AND: if count == len: answer = True elif operator == ATT_OP_OR: if count > 0: answer = True operator_not = cpel_dom.getAttribute(ATT_NEGATE) if operator_not: if ((operator_not.upper() == ATT_NEGATE_TRUE) and (answer != ERROR)): answer = not answer return answer else: return False
[ "def", "language_match", "(", "self", ",", "cpeset", ",", "cpel_dom", "=", "None", ")", ":", "# Root element tag", "TAG_ROOT", "=", "'#document'", "# A container for child platform definitions", "TAG_PLATSPEC", "=", "'cpe:platform-specification'", "# Information about a platf...
Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applicability Language, represented as the XML infoset for the platform element. :param CPESet cpeset: CPE set object to match with self expression. :param string cpel_dom: An expression in the CPE Applicability Language, represented as DOM tree. :returns: True if self expression can be satisfied by language matching against cpeset, False otherwise. :rtype: boolean
[ "Accepts", "a", "set", "of", "known", "CPE", "Names", "and", "an", "expression", "in", "the", "CPE", "language", "and", "delivers", "the", "answer", "True", "if", "the", "expression", "matches", "with", "the", "set", ".", "Otherwise", "it", "returns", "Fal...
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpelang2_3.py#L172-L277
train
nilp0inter/cpe
cpe/cpeset.py
CPESet.name_match
def name_match(self, cpe): """ Accepts a set of known instances of CPE Names and a candidate CPE Name, and returns 'True' if the candidate can be shown to be an instance based on the content of the known instances. Otherwise, it returns 'False'. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :returns: True if X matches K, otherwise False. :rtype: boolean """ # An empty set not matching with any CPE if len(self) == 0: return False # If input CPE Name string is in set of CPE Name strings # not do searching more because there is a matching for k in self.K: if (k.cpe_str == cpe.cpe_str): return True # If "cpe" is an empty CPE Name any system matches if len(cpe) == 0: return True # There are not a CPE Name string in set equal to # input CPE Name string match = False for p in CPE.CPE_PART_KEYS: elems_cpe = cpe.get(p) for ec in elems_cpe: # Search of element of part of input CPE # Each element ec of input cpe[p] is compared with # each element ek of k[p] in set K for k in self.K: if (len(k) >= len(cpe)): elems_k = k.get(p) for ek in elems_k: # Matching # Each component in element ec is compared with # each component in element ek for c in range(0, len(cpe)): key = CPEComponent.ordered_comp_parts[c] comp_cpe = ec.get(key) comp_k = ek.get(key) match = comp_k in comp_cpe if not match: # Search compoment in another element ek[p] break # Component analyzed if match: # Element matched break if match: break # Next element in part in "cpe" if not match: # cpe part not match with parts in set return False # Next part in input CPE Name # All parts in input CPE Name matched return True
python
def name_match(self, cpe): """ Accepts a set of known instances of CPE Names and a candidate CPE Name, and returns 'True' if the candidate can be shown to be an instance based on the content of the known instances. Otherwise, it returns 'False'. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :returns: True if X matches K, otherwise False. :rtype: boolean """ # An empty set not matching with any CPE if len(self) == 0: return False # If input CPE Name string is in set of CPE Name strings # not do searching more because there is a matching for k in self.K: if (k.cpe_str == cpe.cpe_str): return True # If "cpe" is an empty CPE Name any system matches if len(cpe) == 0: return True # There are not a CPE Name string in set equal to # input CPE Name string match = False for p in CPE.CPE_PART_KEYS: elems_cpe = cpe.get(p) for ec in elems_cpe: # Search of element of part of input CPE # Each element ec of input cpe[p] is compared with # each element ek of k[p] in set K for k in self.K: if (len(k) >= len(cpe)): elems_k = k.get(p) for ek in elems_k: # Matching # Each component in element ec is compared with # each component in element ek for c in range(0, len(cpe)): key = CPEComponent.ordered_comp_parts[c] comp_cpe = ec.get(key) comp_k = ek.get(key) match = comp_k in comp_cpe if not match: # Search compoment in another element ek[p] break # Component analyzed if match: # Element matched break if match: break # Next element in part in "cpe" if not match: # cpe part not match with parts in set return False # Next part in input CPE Name # All parts in input CPE Name matched return True
[ "def", "name_match", "(", "self", ",", "cpe", ")", ":", "# An empty set not matching with any CPE", "if", "len", "(", "self", ")", "==", "0", ":", "return", "False", "# If input CPE Name string is in set of CPE Name strings", "# not do searching more because there is a matchi...
Accepts a set of known instances of CPE Names and a candidate CPE Name, and returns 'True' if the candidate can be shown to be an instance based on the content of the known instances. Otherwise, it returns 'False'. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :returns: True if X matches K, otherwise False. :rtype: boolean
[ "Accepts", "a", "set", "of", "known", "instances", "of", "CPE", "Names", "and", "a", "candidate", "CPE", "Name", "and", "returns", "True", "if", "the", "candidate", "can", "be", "shown", "to", "be", "an", "instance", "based", "on", "the", "content", "of"...
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset.py#L121-L195
train
nilp0inter/cpe
cpe/comp/cpecomp2_2.py
CPEComponent2_2._decode
def _decode(self): """ Convert the encoded value of component to standard value (WFN value). """ result = [] idx = 0 s = self._encoded_value while (idx < len(s)): # Get the idx'th character of s c = s[idx] if (c in CPEComponent2_2.NON_STANDARD_VALUES): # Escape character result.append("\\") result.append(c) else: # Do nothing result.append(c) idx += 1 self._standard_value = "".join(result)
python
def _decode(self): """ Convert the encoded value of component to standard value (WFN value). """ result = [] idx = 0 s = self._encoded_value while (idx < len(s)): # Get the idx'th character of s c = s[idx] if (c in CPEComponent2_2.NON_STANDARD_VALUES): # Escape character result.append("\\") result.append(c) else: # Do nothing result.append(c) idx += 1 self._standard_value = "".join(result)
[ "def", "_decode", "(", "self", ")", ":", "result", "=", "[", "]", "idx", "=", "0", "s", "=", "self", ".", "_encoded_value", "while", "(", "idx", "<", "len", "(", "s", ")", ")", ":", "# Get the idx'th character of s", "c", "=", "s", "[", "idx", "]",...
Convert the encoded value of component to standard value (WFN value).
[ "Convert", "the", "encoded", "value", "of", "component", "to", "standard", "value", "(", "WFN", "value", ")", "." ]
670d947472a7652af5149324977b50f9a7af9bcf
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp2_2.py#L90-L113
train
pysal/giddy
giddy/components.py
is_component
def is_component(w, ids): """Check if the set of ids form a single connected component Parameters ---------- w : spatial weights boject ids : list identifiers of units that are tested to be a single connected component Returns ------- True : if the list of ids represents a single connected component False : if the list of ids forms more than a single connected component """ components = 0 marks = dict([(node, 0) for node in ids]) q = [] for node in ids: if marks[node] == 0: components += 1 q.append(node) if components > 1: return False while q: node = q.pop() marks[node] = components others = [neighbor for neighbor in w.neighbors[node] if neighbor in ids] for other in others: if marks[other] == 0 and other not in q: q.append(other) return True
python
def is_component(w, ids): """Check if the set of ids form a single connected component Parameters ---------- w : spatial weights boject ids : list identifiers of units that are tested to be a single connected component Returns ------- True : if the list of ids represents a single connected component False : if the list of ids forms more than a single connected component """ components = 0 marks = dict([(node, 0) for node in ids]) q = [] for node in ids: if marks[node] == 0: components += 1 q.append(node) if components > 1: return False while q: node = q.pop() marks[node] = components others = [neighbor for neighbor in w.neighbors[node] if neighbor in ids] for other in others: if marks[other] == 0 and other not in q: q.append(other) return True
[ "def", "is_component", "(", "w", ",", "ids", ")", ":", "components", "=", "0", "marks", "=", "dict", "(", "[", "(", "node", ",", "0", ")", "for", "node", "in", "ids", "]", ")", "q", "=", "[", "]", "for", "node", "in", "ids", ":", "if", "marks...
Check if the set of ids form a single connected component Parameters ---------- w : spatial weights boject ids : list identifiers of units that are tested to be a single connected component Returns ------- True : if the list of ids represents a single connected component False : if the list of ids forms more than a single connected component
[ "Check", "if", "the", "set", "of", "ids", "form", "a", "single", "connected", "component" ]
13fae6c18933614be78e91a6b5060693bea33a04
https://github.com/pysal/giddy/blob/13fae6c18933614be78e91a6b5060693bea33a04/giddy/components.py#L11-L50
train
pysal/giddy
giddy/components.py
check_contiguity
def check_contiguity(w, neighbors, leaver): """Check if contiguity is maintained if leaver is removed from neighbors Parameters ---------- w : spatial weights object simple contiguity based weights neighbors : list nodes that are to be checked if they form a single \ connected component leaver : id a member of neighbors to check for removal Returns ------- True : if removing leaver from neighbors does not break contiguity of remaining set in neighbors False : if removing leaver from neighbors breaks contiguity Example ------- Setup imports and a 25x25 spatial weights matrix on a 5x5 square region. >>> import libpysal as lps >>> w = lps.weights.lat2W(5, 5) Test removing various areas from a subset of the region's areas. In the first case the subset is defined as observations 0, 1, 2, 3 and 4. The test shows that observations 0, 1, 2 and 3 remain connected even if observation 4 is removed. >>> check_contiguity(w,[0,1,2,3,4],4) True >>> check_contiguity(w,[0,1,2,3,4],3) False >>> check_contiguity(w,[0,1,2,3,4],0) True >>> check_contiguity(w,[0,1,2,3,4],1) False >>> """ ids = neighbors[:] ids.remove(leaver) return is_component(w, ids)
python
def check_contiguity(w, neighbors, leaver): """Check if contiguity is maintained if leaver is removed from neighbors Parameters ---------- w : spatial weights object simple contiguity based weights neighbors : list nodes that are to be checked if they form a single \ connected component leaver : id a member of neighbors to check for removal Returns ------- True : if removing leaver from neighbors does not break contiguity of remaining set in neighbors False : if removing leaver from neighbors breaks contiguity Example ------- Setup imports and a 25x25 spatial weights matrix on a 5x5 square region. >>> import libpysal as lps >>> w = lps.weights.lat2W(5, 5) Test removing various areas from a subset of the region's areas. In the first case the subset is defined as observations 0, 1, 2, 3 and 4. The test shows that observations 0, 1, 2 and 3 remain connected even if observation 4 is removed. >>> check_contiguity(w,[0,1,2,3,4],4) True >>> check_contiguity(w,[0,1,2,3,4],3) False >>> check_contiguity(w,[0,1,2,3,4],0) True >>> check_contiguity(w,[0,1,2,3,4],1) False >>> """ ids = neighbors[:] ids.remove(leaver) return is_component(w, ids)
[ "def", "check_contiguity", "(", "w", ",", "neighbors", ",", "leaver", ")", ":", "ids", "=", "neighbors", "[", ":", "]", "ids", ".", "remove", "(", "leaver", ")", "return", "is_component", "(", "w", ",", "ids", ")" ]
Check if contiguity is maintained if leaver is removed from neighbors Parameters ---------- w : spatial weights object simple contiguity based weights neighbors : list nodes that are to be checked if they form a single \ connected component leaver : id a member of neighbors to check for removal Returns ------- True : if removing leaver from neighbors does not break contiguity of remaining set in neighbors False : if removing leaver from neighbors breaks contiguity Example ------- Setup imports and a 25x25 spatial weights matrix on a 5x5 square region. >>> import libpysal as lps >>> w = lps.weights.lat2W(5, 5) Test removing various areas from a subset of the region's areas. In the first case the subset is defined as observations 0, 1, 2, 3 and 4. The test shows that observations 0, 1, 2 and 3 remain connected even if observation 4 is removed. >>> check_contiguity(w,[0,1,2,3,4],4) True >>> check_contiguity(w,[0,1,2,3,4],3) False >>> check_contiguity(w,[0,1,2,3,4],0) True >>> check_contiguity(w,[0,1,2,3,4],1) False >>>
[ "Check", "if", "contiguity", "is", "maintained", "if", "leaver", "is", "removed", "from", "neighbors" ]
13fae6c18933614be78e91a6b5060693bea33a04
https://github.com/pysal/giddy/blob/13fae6c18933614be78e91a6b5060693bea33a04/giddy/components.py#L53-L103
train
pyinvoke/invocations
invocations/console.py
confirm
def confirm(question, assume_yes=True): """ Ask user a yes/no question and return their response as a boolean. ``question`` should be a simple, grammatically complete question such as "Do you wish to continue?", and will have a string similar to ``" [Y/n] "`` appended automatically. This function will *not* append a question mark for you. By default, when the user presses Enter without typing anything, "yes" is assumed. This can be changed by specifying ``affirmative=False``. .. note:: If the user does not supplies input that is (case-insensitively) equal to "y", "yes", "n" or "no", they will be re-prompted until they do. :param str question: The question part of the prompt. :param bool assume_yes: Whether to assume the affirmative answer by default. Default value: ``True``. :returns: A `bool`. """ # Set up suffix if assume_yes: suffix = "Y/n" else: suffix = "y/N" # Loop till we get something we like # TODO: maybe don't do this? It can be annoying. Turn into 'q'-for-quit? while True: # TODO: ensure that this is Ctrl-C friendly, ISTR issues with # raw_input/input on some Python versions blocking KeyboardInterrupt. response = input("{0} [{1}] ".format(question, suffix)) response = response.lower().strip() # Normalize # Default if not response: return assume_yes # Yes if response in ["y", "yes"]: return True # No if response in ["n", "no"]: return False # Didn't get empty, yes or no, so complain and loop err = "I didn't understand you. Please specify '(y)es' or '(n)o'." print(err, file=sys.stderr)
python
def confirm(question, assume_yes=True): """ Ask user a yes/no question and return their response as a boolean. ``question`` should be a simple, grammatically complete question such as "Do you wish to continue?", and will have a string similar to ``" [Y/n] "`` appended automatically. This function will *not* append a question mark for you. By default, when the user presses Enter without typing anything, "yes" is assumed. This can be changed by specifying ``affirmative=False``. .. note:: If the user does not supplies input that is (case-insensitively) equal to "y", "yes", "n" or "no", they will be re-prompted until they do. :param str question: The question part of the prompt. :param bool assume_yes: Whether to assume the affirmative answer by default. Default value: ``True``. :returns: A `bool`. """ # Set up suffix if assume_yes: suffix = "Y/n" else: suffix = "y/N" # Loop till we get something we like # TODO: maybe don't do this? It can be annoying. Turn into 'q'-for-quit? while True: # TODO: ensure that this is Ctrl-C friendly, ISTR issues with # raw_input/input on some Python versions blocking KeyboardInterrupt. response = input("{0} [{1}] ".format(question, suffix)) response = response.lower().strip() # Normalize # Default if not response: return assume_yes # Yes if response in ["y", "yes"]: return True # No if response in ["n", "no"]: return False # Didn't get empty, yes or no, so complain and loop err = "I didn't understand you. Please specify '(y)es' or '(n)o'." print(err, file=sys.stderr)
[ "def", "confirm", "(", "question", ",", "assume_yes", "=", "True", ")", ":", "# Set up suffix", "if", "assume_yes", ":", "suffix", "=", "\"Y/n\"", "else", ":", "suffix", "=", "\"y/N\"", "# Loop till we get something we like", "# TODO: maybe don't do this? It can be anno...
Ask user a yes/no question and return their response as a boolean. ``question`` should be a simple, grammatically complete question such as "Do you wish to continue?", and will have a string similar to ``" [Y/n] "`` appended automatically. This function will *not* append a question mark for you. By default, when the user presses Enter without typing anything, "yes" is assumed. This can be changed by specifying ``affirmative=False``. .. note:: If the user does not supplies input that is (case-insensitively) equal to "y", "yes", "n" or "no", they will be re-prompted until they do. :param str question: The question part of the prompt. :param bool assume_yes: Whether to assume the affirmative answer by default. Default value: ``True``. :returns: A `bool`.
[ "Ask", "user", "a", "yes", "/", "no", "question", "and", "return", "their", "response", "as", "a", "boolean", "." ]
bbf1b319bd1536817d5301ceb9eeb2f31830e5dc
https://github.com/pyinvoke/invocations/blob/bbf1b319bd1536817d5301ceb9eeb2f31830e5dc/invocations/console.py#L13-L59
train