repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
brbsix/pip-utils | pip_utils/outdated.py | ListCommand.run_outdated | def run_outdated(cls, options):
"""Print outdated user packages."""
latest_versions = sorted(
cls.find_packages_latest_versions(cls.options),
key=lambda p: p[0].project_name.lower())
for dist, latest_version, typ in latest_versions:
if latest_version > dist.parsed_version:
if options.all:
pass
elif options.pinned:
if cls.can_be_updated(dist, latest_version):
continue
elif not options.pinned:
if not cls.can_be_updated(dist, latest_version):
continue
elif options.update:
print(dist.project_name if options.brief else
'Updating %s to Latest: %s [%s]' %
(cls.output_package(dist), latest_version, typ))
main(['install', '--upgrade'] + ([
'--user'
] if ENABLE_USER_SITE else []) + [dist.key])
continue
print(dist.project_name if options.brief else
'%s - Latest: %s [%s]' %
(cls.output_package(dist), latest_version, typ)) | python | def run_outdated(cls, options):
"""Print outdated user packages."""
latest_versions = sorted(
cls.find_packages_latest_versions(cls.options),
key=lambda p: p[0].project_name.lower())
for dist, latest_version, typ in latest_versions:
if latest_version > dist.parsed_version:
if options.all:
pass
elif options.pinned:
if cls.can_be_updated(dist, latest_version):
continue
elif not options.pinned:
if not cls.can_be_updated(dist, latest_version):
continue
elif options.update:
print(dist.project_name if options.brief else
'Updating %s to Latest: %s [%s]' %
(cls.output_package(dist), latest_version, typ))
main(['install', '--upgrade'] + ([
'--user'
] if ENABLE_USER_SITE else []) + [dist.key])
continue
print(dist.project_name if options.brief else
'%s - Latest: %s [%s]' %
(cls.output_package(dist), latest_version, typ)) | [
"def",
"run_outdated",
"(",
"cls",
",",
"options",
")",
":",
"latest_versions",
"=",
"sorted",
"(",
"cls",
".",
"find_packages_latest_versions",
"(",
"cls",
".",
"options",
")",
",",
"key",
"=",
"lambda",
"p",
":",
"p",
"[",
"0",
"]",
".",
"project_name"... | Print outdated user packages. | [
"Print",
"outdated",
"user",
"packages",
"."
] | train | https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/outdated.py#L218-L245 |
MaxHalford/starboost | starboost/boosting.py | softmax | def softmax(x):
"""Can be replaced once scipy 1.3 is released, although numeric stability should be checked."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum(axis=1)[:, None] | python | def softmax(x):
"""Can be replaced once scipy 1.3 is released, although numeric stability should be checked."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum(axis=1)[:, None] | [
"def",
"softmax",
"(",
"x",
")",
":",
"e_x",
"=",
"np",
".",
"exp",
"(",
"x",
"-",
"np",
".",
"max",
"(",
"x",
")",
")",
"return",
"e_x",
"/",
"e_x",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"[",
":",
",",
"None",
"]"
] | Can be replaced once scipy 1.3 is released, although numeric stability should be checked. | [
"Can",
"be",
"replaced",
"once",
"scipy",
"1",
".",
"3",
"is",
"released",
"although",
"numeric",
"stability",
"should",
"be",
"checked",
"."
] | train | https://github.com/MaxHalford/starboost/blob/59d96dcc983404cbc326878facd8171fd2655ce1/starboost/boosting.py#L275-L278 |
MaxHalford/starboost | starboost/boosting.py | BaseBoosting.fit | def fit(self, X, y, eval_set=None):
"""Fit a gradient boosting procedure to a dataset.
Args:
X (array-like or sparse matrix of shape (n_samples, n_features)): The training input
samples. Sparse matrices are accepted only if they are supported by the weak model.
y (array-like of shape (n_samples,)): The training target values (strings or integers
in classification, real numbers in regression).
eval_set (tuple of length 2, optional, default=None): The evaluation set is a tuple
``(X_val, y_val)``. It has to respect the same conventions as ``X`` and ``y``.
Returns:
self
"""
# Verify the input parameters
base_estimator = self.base_estimator
base_estimator_is_tree = self.base_estimator_is_tree
if base_estimator is None:
base_estimator = tree.DecisionTreeRegressor(max_depth=1, random_state=self.random_state)
base_estimator_is_tree = True
if not isinstance(base_estimator, base.RegressorMixin):
raise ValueError('base_estimator must be a RegressorMixin')
loss = self.loss or self._default_loss
self.init_estimator_ = base.clone(self.init_estimator or loss.default_init_estimator)
eval_metric = self.eval_metric or loss
line_searcher = self.line_searcher
if line_searcher is None and base_estimator_is_tree:
line_searcher = loss.tree_line_searcher
self._rng = utils.check_random_state(self.random_state)
# At this point we assume the input data has been checked
if y.ndim == 1:
y = y.reshape(-1, 1)
# Instantiate some training variables
self.estimators_ = []
self.line_searchers_ = []
self.columns_ = []
self.eval_scores_ = [] if eval_set else None
# Use init_estimator for the first fit
self.init_estimator_.fit(X, y)
y_pred = self.init_estimator_.predict(X)
# We keep training weak learners until we reach n_estimators or early stopping occurs
for _ in range(self.n_estimators):
# If row_sampling is lower than 1 then we're doing stochastic gradient descent
rows = None
if self.row_sampling < 1:
n_rows = int(X.shape[0] * self.row_sampling)
rows = self._rng.choice(X.shape[0], n_rows, replace=False)
# If col_sampling is lower than 1 then we only use a subset of the features
cols = None
if self.col_sampling < 1:
n_cols = int(X.shape[1] * self.col_sampling)
cols = self._rng.choice(X.shape[1], n_cols, replace=False)
# Subset X
X_fit = X
if rows is not None:
X_fit = X_fit[rows, :]
if cols is not None:
X_fit = X_fit[:, cols]
# Compute the gradients of the loss for the current prediction
gradients = loss.gradient(y, self._transform_y_pred(y_pred))
# We will train one weak model per column in y
estimators = []
line_searchers = []
for i, gradient in enumerate(gradients.T):
# Fit a weak learner to the negative gradient of the loss function
estimator = base.clone(base_estimator)
estimator = estimator.fit(X_fit, -gradient if rows is None else -gradient[rows])
estimators.append(estimator)
# Estimate the descent direction using the weak learner
direction = estimator.predict(X if cols is None else X[:, cols])
# Apply line search if a line searcher has been provided
if line_searcher:
ls = copy.copy(line_searcher)
ls = ls.fit(y[:, i], y_pred[:, i], gradient, direction)
line_searchers.append(ls)
direction = ls.update(direction)
# Move the predictions along the estimated descent direction
y_pred[:, i] += self.learning_rate * direction
# Store the estimator and the step
self.estimators_.append(estimators)
if line_searchers:
self.line_searchers_.append(line_searchers)
self.columns_.append(cols)
# We're now at the end of a round so we can evaluate the model on the validation set
if not eval_set:
continue
X_val, y_val = eval_set
self.eval_scores_.append(eval_metric(y_val, self.predict(X_val)))
# Check for early stopping
if self.early_stopping_rounds and len(self.eval_scores_) > self.early_stopping_rounds:
if self.eval_scores_[-1] > self.eval_scores_[-(self.early_stopping_rounds + 1)]:
break
return self | python | def fit(self, X, y, eval_set=None):
"""Fit a gradient boosting procedure to a dataset.
Args:
X (array-like or sparse matrix of shape (n_samples, n_features)): The training input
samples. Sparse matrices are accepted only if they are supported by the weak model.
y (array-like of shape (n_samples,)): The training target values (strings or integers
in classification, real numbers in regression).
eval_set (tuple of length 2, optional, default=None): The evaluation set is a tuple
``(X_val, y_val)``. It has to respect the same conventions as ``X`` and ``y``.
Returns:
self
"""
# Verify the input parameters
base_estimator = self.base_estimator
base_estimator_is_tree = self.base_estimator_is_tree
if base_estimator is None:
base_estimator = tree.DecisionTreeRegressor(max_depth=1, random_state=self.random_state)
base_estimator_is_tree = True
if not isinstance(base_estimator, base.RegressorMixin):
raise ValueError('base_estimator must be a RegressorMixin')
loss = self.loss or self._default_loss
self.init_estimator_ = base.clone(self.init_estimator or loss.default_init_estimator)
eval_metric = self.eval_metric or loss
line_searcher = self.line_searcher
if line_searcher is None and base_estimator_is_tree:
line_searcher = loss.tree_line_searcher
self._rng = utils.check_random_state(self.random_state)
# At this point we assume the input data has been checked
if y.ndim == 1:
y = y.reshape(-1, 1)
# Instantiate some training variables
self.estimators_ = []
self.line_searchers_ = []
self.columns_ = []
self.eval_scores_ = [] if eval_set else None
# Use init_estimator for the first fit
self.init_estimator_.fit(X, y)
y_pred = self.init_estimator_.predict(X)
# We keep training weak learners until we reach n_estimators or early stopping occurs
for _ in range(self.n_estimators):
# If row_sampling is lower than 1 then we're doing stochastic gradient descent
rows = None
if self.row_sampling < 1:
n_rows = int(X.shape[0] * self.row_sampling)
rows = self._rng.choice(X.shape[0], n_rows, replace=False)
# If col_sampling is lower than 1 then we only use a subset of the features
cols = None
if self.col_sampling < 1:
n_cols = int(X.shape[1] * self.col_sampling)
cols = self._rng.choice(X.shape[1], n_cols, replace=False)
# Subset X
X_fit = X
if rows is not None:
X_fit = X_fit[rows, :]
if cols is not None:
X_fit = X_fit[:, cols]
# Compute the gradients of the loss for the current prediction
gradients = loss.gradient(y, self._transform_y_pred(y_pred))
# We will train one weak model per column in y
estimators = []
line_searchers = []
for i, gradient in enumerate(gradients.T):
# Fit a weak learner to the negative gradient of the loss function
estimator = base.clone(base_estimator)
estimator = estimator.fit(X_fit, -gradient if rows is None else -gradient[rows])
estimators.append(estimator)
# Estimate the descent direction using the weak learner
direction = estimator.predict(X if cols is None else X[:, cols])
# Apply line search if a line searcher has been provided
if line_searcher:
ls = copy.copy(line_searcher)
ls = ls.fit(y[:, i], y_pred[:, i], gradient, direction)
line_searchers.append(ls)
direction = ls.update(direction)
# Move the predictions along the estimated descent direction
y_pred[:, i] += self.learning_rate * direction
# Store the estimator and the step
self.estimators_.append(estimators)
if line_searchers:
self.line_searchers_.append(line_searchers)
self.columns_.append(cols)
# We're now at the end of a round so we can evaluate the model on the validation set
if not eval_set:
continue
X_val, y_val = eval_set
self.eval_scores_.append(eval_metric(y_val, self.predict(X_val)))
# Check for early stopping
if self.early_stopping_rounds and len(self.eval_scores_) > self.early_stopping_rounds:
if self.eval_scores_[-1] > self.eval_scores_[-(self.early_stopping_rounds + 1)]:
break
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"eval_set",
"=",
"None",
")",
":",
"# Verify the input parameters",
"base_estimator",
"=",
"self",
".",
"base_estimator",
"base_estimator_is_tree",
"=",
"self",
".",
"base_estimator_is_tree",
"if",
"base_estimato... | Fit a gradient boosting procedure to a dataset.
Args:
X (array-like or sparse matrix of shape (n_samples, n_features)): The training input
samples. Sparse matrices are accepted only if they are supported by the weak model.
y (array-like of shape (n_samples,)): The training target values (strings or integers
in classification, real numbers in regression).
eval_set (tuple of length 2, optional, default=None): The evaluation set is a tuple
``(X_val, y_val)``. It has to respect the same conventions as ``X`` and ``y``.
Returns:
self | [
"Fit",
"a",
"gradient",
"boosting",
"procedure",
"to",
"a",
"dataset",
"."
] | train | https://github.com/MaxHalford/starboost/blob/59d96dcc983404cbc326878facd8171fd2655ce1/starboost/boosting.py#L49-L164 |
MaxHalford/starboost | starboost/boosting.py | BaseBoosting.iter_predict | def iter_predict(self, X, include_init=False):
"""Returns the predictions for ``X`` at every stage of the boosting procedure.
Args:
X (array-like or sparse matrix of shape (n_samples, n_features): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
include_init (bool, default=False): If ``True`` then the prediction from
``init_estimator`` will also be returned.
Returns:
iterator of arrays of shape (n_samples,) containing the predicted values at each stage
"""
utils.validation.check_is_fitted(self, 'init_estimator_')
X = utils.check_array(X, accept_sparse=['csr', 'csc'], dtype=None, force_all_finite=False)
y_pred = self.init_estimator_.predict(X)
# The user decides if the initial prediction should be included or not
if include_init:
yield y_pred
for estimators, line_searchers, cols in itertools.zip_longest(self.estimators_,
self.line_searchers_,
self.columns_):
for i, (estimator, line_searcher) in enumerate(itertools.zip_longest(estimators,
line_searchers or [])):
# If we used column sampling then we have to make sure the columns of X are arranged
# in the correct order
if cols is None:
direction = estimator.predict(X)
else:
direction = estimator.predict(X[:, cols])
if line_searcher:
direction = line_searcher.update(direction)
y_pred[:, i] += self.learning_rate * direction
yield y_pred | python | def iter_predict(self, X, include_init=False):
"""Returns the predictions for ``X`` at every stage of the boosting procedure.
Args:
X (array-like or sparse matrix of shape (n_samples, n_features): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
include_init (bool, default=False): If ``True`` then the prediction from
``init_estimator`` will also be returned.
Returns:
iterator of arrays of shape (n_samples,) containing the predicted values at each stage
"""
utils.validation.check_is_fitted(self, 'init_estimator_')
X = utils.check_array(X, accept_sparse=['csr', 'csc'], dtype=None, force_all_finite=False)
y_pred = self.init_estimator_.predict(X)
# The user decides if the initial prediction should be included or not
if include_init:
yield y_pred
for estimators, line_searchers, cols in itertools.zip_longest(self.estimators_,
self.line_searchers_,
self.columns_):
for i, (estimator, line_searcher) in enumerate(itertools.zip_longest(estimators,
line_searchers or [])):
# If we used column sampling then we have to make sure the columns of X are arranged
# in the correct order
if cols is None:
direction = estimator.predict(X)
else:
direction = estimator.predict(X[:, cols])
if line_searcher:
direction = line_searcher.update(direction)
y_pred[:, i] += self.learning_rate * direction
yield y_pred | [
"def",
"iter_predict",
"(",
"self",
",",
"X",
",",
"include_init",
"=",
"False",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'init_estimator_'",
")",
"X",
"=",
"utils",
".",
"check_array",
"(",
"X",
",",
"accept_sparse"... | Returns the predictions for ``X`` at every stage of the boosting procedure.
Args:
X (array-like or sparse matrix of shape (n_samples, n_features): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
include_init (bool, default=False): If ``True`` then the prediction from
``init_estimator`` will also be returned.
Returns:
iterator of arrays of shape (n_samples,) containing the predicted values at each stage | [
"Returns",
"the",
"predictions",
"for",
"X",
"at",
"every",
"stage",
"of",
"the",
"boosting",
"procedure",
"."
] | train | https://github.com/MaxHalford/starboost/blob/59d96dcc983404cbc326878facd8171fd2655ce1/starboost/boosting.py#L166-L205 |
MaxHalford/starboost | starboost/boosting.py | BaseBoosting.predict | def predict(self, X):
"""Returns the predictions for ``X``.
Under the hood this method simply goes through the outputs of ``iter_predict`` and returns
the final one.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
Returns:
array of shape (n_samples,) containing the predicted values.
"""
return collections.deque(self.iter_predict(X), maxlen=1).pop() | python | def predict(self, X):
"""Returns the predictions for ``X``.
Under the hood this method simply goes through the outputs of ``iter_predict`` and returns
the final one.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
Returns:
array of shape (n_samples,) containing the predicted values.
"""
return collections.deque(self.iter_predict(X), maxlen=1).pop() | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"return",
"collections",
".",
"deque",
"(",
"self",
".",
"iter_predict",
"(",
"X",
")",
",",
"maxlen",
"=",
"1",
")",
".",
"pop",
"(",
")"
] | Returns the predictions for ``X``.
Under the hood this method simply goes through the outputs of ``iter_predict`` and returns
the final one.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
Returns:
array of shape (n_samples,) containing the predicted values. | [
"Returns",
"the",
"predictions",
"for",
"X",
"."
] | train | https://github.com/MaxHalford/starboost/blob/59d96dcc983404cbc326878facd8171fd2655ce1/starboost/boosting.py#L207-L220 |
MaxHalford/starboost | starboost/boosting.py | BoostingClassifier.iter_predict_proba | def iter_predict_proba(self, X, include_init=False):
"""Returns the predicted probabilities for ``X`` at every stage of the boosting procedure.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
include_init (bool, default=False): If ``True`` then the prediction from
``init_estimator`` will also be returned.
Returns:
iterator of arrays of shape (n_samples, n_classes) containing the predicted
probabilities at each stage
"""
utils.validation.check_is_fitted(self, 'init_estimator_')
X = utils.check_array(X, accept_sparse=['csr', 'csc'], dtype=None, force_all_finite=False)
probas = np.empty(shape=(len(X), len(self.classes_)), dtype=np.float64)
for y_pred in super().iter_predict(X, include_init=include_init):
if len(self.classes_) == 2:
probas[:, 1] = sigmoid(y_pred[:, 0])
probas[:, 0] = 1. - probas[:, 1]
else:
probas[:] = softmax(y_pred)
yield probas | python | def iter_predict_proba(self, X, include_init=False):
"""Returns the predicted probabilities for ``X`` at every stage of the boosting procedure.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
include_init (bool, default=False): If ``True`` then the prediction from
``init_estimator`` will also be returned.
Returns:
iterator of arrays of shape (n_samples, n_classes) containing the predicted
probabilities at each stage
"""
utils.validation.check_is_fitted(self, 'init_estimator_')
X = utils.check_array(X, accept_sparse=['csr', 'csc'], dtype=None, force_all_finite=False)
probas = np.empty(shape=(len(X), len(self.classes_)), dtype=np.float64)
for y_pred in super().iter_predict(X, include_init=include_init):
if len(self.classes_) == 2:
probas[:, 1] = sigmoid(y_pred[:, 0])
probas[:, 0] = 1. - probas[:, 1]
else:
probas[:] = softmax(y_pred)
yield probas | [
"def",
"iter_predict_proba",
"(",
"self",
",",
"X",
",",
"include_init",
"=",
"False",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'init_estimator_'",
")",
"X",
"=",
"utils",
".",
"check_array",
"(",
"X",
",",
"accept_s... | Returns the predicted probabilities for ``X`` at every stage of the boosting procedure.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
include_init (bool, default=False): If ``True`` then the prediction from
``init_estimator`` will also be returned.
Returns:
iterator of arrays of shape (n_samples, n_classes) containing the predicted
probabilities at each stage | [
"Returns",
"the",
"predicted",
"probabilities",
"for",
"X",
"at",
"every",
"stage",
"of",
"the",
"boosting",
"procedure",
"."
] | train | https://github.com/MaxHalford/starboost/blob/59d96dcc983404cbc326878facd8171fd2655ce1/starboost/boosting.py#L343-L367 |
MaxHalford/starboost | starboost/boosting.py | BoostingClassifier.iter_predict | def iter_predict(self, X, include_init=False):
"""Returns the predicted classes for ``X`` at every stage of the boosting procedure.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
include_init (bool, default=False): If ``True`` then the prediction from
``init_estimator`` will also be returned.
Returns:
iterator of arrays of shape (n_samples, n_classes) containing the predicted classes at
each stage.
"""
for probas in self.iter_predict_proba(X, include_init=include_init):
yield self.encoder_.inverse_transform(np.argmax(probas, axis=1)) | python | def iter_predict(self, X, include_init=False):
"""Returns the predicted classes for ``X`` at every stage of the boosting procedure.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
include_init (bool, default=False): If ``True`` then the prediction from
``init_estimator`` will also be returned.
Returns:
iterator of arrays of shape (n_samples, n_classes) containing the predicted classes at
each stage.
"""
for probas in self.iter_predict_proba(X, include_init=include_init):
yield self.encoder_.inverse_transform(np.argmax(probas, axis=1)) | [
"def",
"iter_predict",
"(",
"self",
",",
"X",
",",
"include_init",
"=",
"False",
")",
":",
"for",
"probas",
"in",
"self",
".",
"iter_predict_proba",
"(",
"X",
",",
"include_init",
"=",
"include_init",
")",
":",
"yield",
"self",
".",
"encoder_",
".",
"inv... | Returns the predicted classes for ``X`` at every stage of the boosting procedure.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
include_init (bool, default=False): If ``True`` then the prediction from
``init_estimator`` will also be returned.
Returns:
iterator of arrays of shape (n_samples, n_classes) containing the predicted classes at
each stage. | [
"Returns",
"the",
"predicted",
"classes",
"for",
"X",
"at",
"every",
"stage",
"of",
"the",
"boosting",
"procedure",
"."
] | train | https://github.com/MaxHalford/starboost/blob/59d96dcc983404cbc326878facd8171fd2655ce1/starboost/boosting.py#L369-L383 |
MaxHalford/starboost | starboost/boosting.py | BoostingClassifier.predict_proba | def predict_proba(self, X):
"""Returns the predicted probabilities for ``X``.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
Returns:
array of shape (n_samples, n_classes) containing the predicted probabilities.
"""
return collections.deque(self.iter_predict_proba(X), maxlen=1).pop() | python | def predict_proba(self, X):
"""Returns the predicted probabilities for ``X``.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
Returns:
array of shape (n_samples, n_classes) containing the predicted probabilities.
"""
return collections.deque(self.iter_predict_proba(X), maxlen=1).pop() | [
"def",
"predict_proba",
"(",
"self",
",",
"X",
")",
":",
"return",
"collections",
".",
"deque",
"(",
"self",
".",
"iter_predict_proba",
"(",
"X",
")",
",",
"maxlen",
"=",
"1",
")",
".",
"pop",
"(",
")"
] | Returns the predicted probabilities for ``X``.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
Returns:
array of shape (n_samples, n_classes) containing the predicted probabilities. | [
"Returns",
"the",
"predicted",
"probabilities",
"for",
"X",
"."
] | train | https://github.com/MaxHalford/starboost/blob/59d96dcc983404cbc326878facd8171fd2655ce1/starboost/boosting.py#L385-L395 |
tomduck/pandoc-xnos | pandocxnos/pandocattributes.py | PandocAttributes.parse_pandoc | def parse_pandoc(self, attrs):
"""Read pandoc attributes."""
id = attrs[0]
classes = attrs[1]
kvs = OrderedDict(attrs[2])
return id, classes, kvs | python | def parse_pandoc(self, attrs):
"""Read pandoc attributes."""
id = attrs[0]
classes = attrs[1]
kvs = OrderedDict(attrs[2])
return id, classes, kvs | [
"def",
"parse_pandoc",
"(",
"self",
",",
"attrs",
")",
":",
"id",
"=",
"attrs",
"[",
"0",
"]",
"classes",
"=",
"attrs",
"[",
"1",
"]",
"kvs",
"=",
"OrderedDict",
"(",
"attrs",
"[",
"2",
"]",
")",
"return",
"id",
",",
"classes",
",",
"kvs"
] | Read pandoc attributes. | [
"Read",
"pandoc",
"attributes",
"."
] | train | https://github.com/tomduck/pandoc-xnos/blob/df8e162d257a548cea7eebf597efb2c21a1a4ba3/pandocxnos/pandocattributes.py#L88-L94 |
tomduck/pandoc-xnos | pandocxnos/pandocattributes.py | PandocAttributes.parse_markdown | def parse_markdown(self, attr_string):
"""Read markdown attributes."""
attr_string = attr_string.strip('{}')
splitter = re.compile(self.split_regex(separator=self.spnl))
attrs = splitter.split(attr_string)[1::2]
# match single word attributes e.g. ```python
if len(attrs) == 1 \
and not attr_string.startswith(('#', '.')) \
and '=' not in attr_string:
return '', [attr_string], OrderedDict()
try:
id = [a[1:] for a in attrs if a.startswith('#')][0]
except IndexError:
id = ''
classes = [a[1:] for a in attrs if a.startswith('.')]
special = ['unnumbered' for a in attrs if a == '-']
classes.extend(special)
kvs = OrderedDict(a.split('=', 1) for a in attrs if '=' in a)
return id, classes, kvs | python | def parse_markdown(self, attr_string):
"""Read markdown attributes."""
attr_string = attr_string.strip('{}')
splitter = re.compile(self.split_regex(separator=self.spnl))
attrs = splitter.split(attr_string)[1::2]
# match single word attributes e.g. ```python
if len(attrs) == 1 \
and not attr_string.startswith(('#', '.')) \
and '=' not in attr_string:
return '', [attr_string], OrderedDict()
try:
id = [a[1:] for a in attrs if a.startswith('#')][0]
except IndexError:
id = ''
classes = [a[1:] for a in attrs if a.startswith('.')]
special = ['unnumbered' for a in attrs if a == '-']
classes.extend(special)
kvs = OrderedDict(a.split('=', 1) for a in attrs if '=' in a)
return id, classes, kvs | [
"def",
"parse_markdown",
"(",
"self",
",",
"attr_string",
")",
":",
"attr_string",
"=",
"attr_string",
".",
"strip",
"(",
"'{}'",
")",
"splitter",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"split_regex",
"(",
"separator",
"=",
"self",
".",
"spnl",
")"... | Read markdown attributes. | [
"Read",
"markdown",
"attributes",
"."
] | train | https://github.com/tomduck/pandoc-xnos/blob/df8e162d257a548cea7eebf597efb2c21a1a4ba3/pandocxnos/pandocattributes.py#L97-L120 |
tomduck/pandoc-xnos | pandocxnos/pandocattributes.py | PandocAttributes.parse_html | def parse_html(self, attr_string):
"""Read a html string to attributes."""
splitter = re.compile(self.split_regex(separator=self.spnl))
attrs = splitter.split(attr_string)[1::2]
idre = re.compile(r'''id=["']?([\w ]*)['"]?''')
clsre = re.compile(r'''class=["']?([\w ]*)['"]?''')
id_matches = [idre.search(a) for a in attrs]
cls_matches = [clsre.search(a) for a in attrs]
try:
id = [m.groups()[0] for m in id_matches if m][0]
except IndexError:
id = ''
classes = [m.groups()[0] for m in cls_matches if m][0].split()
special = ['unnumbered' for a in attrs if '-' in a]
classes.extend(special)
kvs = [a.split('=', 1) for a in attrs if '=' in a]
kvs = OrderedDict((k, v) for k, v in kvs if k not in ('id', 'class'))
return id, classes, kvs | python | def parse_html(self, attr_string):
"""Read a html string to attributes."""
splitter = re.compile(self.split_regex(separator=self.spnl))
attrs = splitter.split(attr_string)[1::2]
idre = re.compile(r'''id=["']?([\w ]*)['"]?''')
clsre = re.compile(r'''class=["']?([\w ]*)['"]?''')
id_matches = [idre.search(a) for a in attrs]
cls_matches = [clsre.search(a) for a in attrs]
try:
id = [m.groups()[0] for m in id_matches if m][0]
except IndexError:
id = ''
classes = [m.groups()[0] for m in cls_matches if m][0].split()
special = ['unnumbered' for a in attrs if '-' in a]
classes.extend(special)
kvs = [a.split('=', 1) for a in attrs if '=' in a]
kvs = OrderedDict((k, v) for k, v in kvs if k not in ('id', 'class'))
return id, classes, kvs | [
"def",
"parse_html",
"(",
"self",
",",
"attr_string",
")",
":",
"splitter",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"split_regex",
"(",
"separator",
"=",
"self",
".",
"spnl",
")",
")",
"attrs",
"=",
"splitter",
".",
"split",
"(",
"attr_string",
")... | Read a html string to attributes. | [
"Read",
"a",
"html",
"string",
"to",
"attributes",
"."
] | train | https://github.com/tomduck/pandoc-xnos/blob/df8e162d257a548cea7eebf597efb2c21a1a4ba3/pandocxnos/pandocattributes.py#L122-L146 |
tomduck/pandoc-xnos | pandocxnos/pandocattributes.py | PandocAttributes.parse_dict | def parse_dict(self, attrs):
"""Read a dict to attributes."""
attrs = attrs or {}
ident = attrs.get("id", "")
classes = attrs.get("classes", [])
kvs = OrderedDict((k, v) for k, v in attrs.items()
if k not in ("classes", "id"))
return ident, classes, kvs | python | def parse_dict(self, attrs):
"""Read a dict to attributes."""
attrs = attrs or {}
ident = attrs.get("id", "")
classes = attrs.get("classes", [])
kvs = OrderedDict((k, v) for k, v in attrs.items()
if k not in ("classes", "id"))
return ident, classes, kvs | [
"def",
"parse_dict",
"(",
"self",
",",
"attrs",
")",
":",
"attrs",
"=",
"attrs",
"or",
"{",
"}",
"ident",
"=",
"attrs",
".",
"get",
"(",
"\"id\"",
",",
"\"\"",
")",
"classes",
"=",
"attrs",
".",
"get",
"(",
"\"classes\"",
",",
"[",
"]",
")",
"kvs... | Read a dict to attributes. | [
"Read",
"a",
"dict",
"to",
"attributes",
"."
] | train | https://github.com/tomduck/pandoc-xnos/blob/df8e162d257a548cea7eebf597efb2c21a1a4ba3/pandocxnos/pandocattributes.py#L149-L157 |
tomduck/pandoc-xnos | pandocxnos/pandocattributes.py | PandocAttributes.to_markdown | def to_markdown(self, format='{id} {classes} {kvs}', surround=True):
"""Returns attributes formatted as markdown with optional
format argument to determine order of attribute contents.
"""
id = '#' + self.id if self.id else ''
classes = ' '.join('.' + cls for cls in self.classes)
kvs = ' '.join('{}={}'.format(k, v) for k, v in self.kvs.items())
attrs = format.format(id=id, classes=classes, kvs=kvs).strip()
if surround:
return '{' + attrs + '}'
elif not surround:
return attrs | python | def to_markdown(self, format='{id} {classes} {kvs}', surround=True):
"""Returns attributes formatted as markdown with optional
format argument to determine order of attribute contents.
"""
id = '#' + self.id if self.id else ''
classes = ' '.join('.' + cls for cls in self.classes)
kvs = ' '.join('{}={}'.format(k, v) for k, v in self.kvs.items())
attrs = format.format(id=id, classes=classes, kvs=kvs).strip()
if surround:
return '{' + attrs + '}'
elif not surround:
return attrs | [
"def",
"to_markdown",
"(",
"self",
",",
"format",
"=",
"'{id} {classes} {kvs}'",
",",
"surround",
"=",
"True",
")",
":",
"id",
"=",
"'#'",
"+",
"self",
".",
"id",
"if",
"self",
".",
"id",
"else",
"''",
"classes",
"=",
"' '",
".",
"join",
"(",
"'.'",
... | Returns attributes formatted as markdown with optional
format argument to determine order of attribute contents. | [
"Returns",
"attributes",
"formatted",
"as",
"markdown",
"with",
"optional",
"format",
"argument",
"to",
"determine",
"order",
"of",
"attribute",
"contents",
"."
] | train | https://github.com/tomduck/pandoc-xnos/blob/df8e162d257a548cea7eebf597efb2c21a1a4ba3/pandocxnos/pandocattributes.py#L159-L172 |
tomduck/pandoc-xnos | pandocxnos/pandocattributes.py | PandocAttributes.to_html | def to_html(self):
"""Returns attributes formatted as html."""
id, classes, kvs = self.id, self.classes, self.kvs
id_str = 'id="{}"'.format(id) if id else ''
class_str = 'class="{}"'.format(' '.join(classes)) if classes else ''
key_str = ' '.join('{}={}'.format(k, v) for k, v in kvs.items())
return ' '.join((id_str, class_str, key_str)).strip() | python | def to_html(self):
"""Returns attributes formatted as html."""
id, classes, kvs = self.id, self.classes, self.kvs
id_str = 'id="{}"'.format(id) if id else ''
class_str = 'class="{}"'.format(' '.join(classes)) if classes else ''
key_str = ' '.join('{}={}'.format(k, v) for k, v in kvs.items())
return ' '.join((id_str, class_str, key_str)).strip() | [
"def",
"to_html",
"(",
"self",
")",
":",
"id",
",",
"classes",
",",
"kvs",
"=",
"self",
".",
"id",
",",
"self",
".",
"classes",
",",
"self",
".",
"kvs",
"id_str",
"=",
"'id=\"{}\"'",
".",
"format",
"(",
"id",
")",
"if",
"id",
"else",
"''",
"class... | Returns attributes formatted as html. | [
"Returns",
"attributes",
"formatted",
"as",
"html",
"."
] | train | https://github.com/tomduck/pandoc-xnos/blob/df8e162d257a548cea7eebf597efb2c21a1a4ba3/pandocxnos/pandocattributes.py#L174-L180 |
tomduck/pandoc-xnos | pandocxnos/pandocattributes.py | PandocAttributes.to_dict | def to_dict(self):
"""Returns attributes formatted as a dictionary."""
d = {'id': self.id, 'classes': self.classes}
d.update(self.kvs)
return d | python | def to_dict(self):
"""Returns attributes formatted as a dictionary."""
d = {'id': self.id, 'classes': self.classes}
d.update(self.kvs)
return d | [
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'classes'",
":",
"self",
".",
"classes",
"}",
"d",
".",
"update",
"(",
"self",
".",
"kvs",
")",
"return",
"d"
] | Returns attributes formatted as a dictionary. | [
"Returns",
"attributes",
"formatted",
"as",
"a",
"dictionary",
"."
] | train | https://github.com/tomduck/pandoc-xnos/blob/df8e162d257a548cea7eebf597efb2c21a1a4ba3/pandocxnos/pandocattributes.py#L182-L186 |
carver/web3utils.py | web3utils/monitors.py | TransactionMonitor.watch_pending_transactions | def watch_pending_transactions(self, callback):
'''
Callback will receive one argument: the transaction object just observed
This is equivalent to `eth.filter('pending')`
'''
self.pending_tx_watchers.append(callback)
if len(self.pending_tx_watchers) == 1:
eth.filter('pending').watch(self._new_pending_tx) | python | def watch_pending_transactions(self, callback):
'''
Callback will receive one argument: the transaction object just observed
This is equivalent to `eth.filter('pending')`
'''
self.pending_tx_watchers.append(callback)
if len(self.pending_tx_watchers) == 1:
eth.filter('pending').watch(self._new_pending_tx) | [
"def",
"watch_pending_transactions",
"(",
"self",
",",
"callback",
")",
":",
"self",
".",
"pending_tx_watchers",
".",
"append",
"(",
"callback",
")",
"if",
"len",
"(",
"self",
".",
"pending_tx_watchers",
")",
"==",
"1",
":",
"eth",
".",
"filter",
"(",
"'pe... | Callback will receive one argument: the transaction object just observed
This is equivalent to `eth.filter('pending')` | [
"Callback",
"will",
"receive",
"one",
"argument",
":",
"the",
"transaction",
"object",
"just",
"observed"
] | train | https://github.com/carver/web3utils.py/blob/81aa6b55f64dc857c604d5d071a37e0de6cd63ab/web3utils/monitors.py#L51-L59 |
carver/web3utils.py | web3utils/monitors.py | TransactionMonitor._start_watching_blocks | def _start_watching_blocks(self):
'''
Internal: call immediately after registering a block watcher
If the new watcher is the first, then start watching web3 remotely
'''
if sum(map(len, (self.solid_watchers, self.block_watchers))) == 1:
eth.filter('latest').watch(self._new_block) | python | def _start_watching_blocks(self):
'''
Internal: call immediately after registering a block watcher
If the new watcher is the first, then start watching web3 remotely
'''
if sum(map(len, (self.solid_watchers, self.block_watchers))) == 1:
eth.filter('latest').watch(self._new_block) | [
"def",
"_start_watching_blocks",
"(",
"self",
")",
":",
"if",
"sum",
"(",
"map",
"(",
"len",
",",
"(",
"self",
".",
"solid_watchers",
",",
"self",
".",
"block_watchers",
")",
")",
")",
"==",
"1",
":",
"eth",
".",
"filter",
"(",
"'latest'",
")",
".",
... | Internal: call immediately after registering a block watcher
If the new watcher is the first, then start watching web3 remotely | [
"Internal",
":",
"call",
"immediately",
"after",
"registering",
"a",
"block",
"watcher",
"If",
"the",
"new",
"watcher",
"is",
"the",
"first",
"then",
"start",
"watching",
"web3",
"remotely"
] | train | https://github.com/carver/web3utils.py/blob/81aa6b55f64dc857c604d5d071a37e0de6cd63ab/web3utils/monitors.py#L61-L67 |
Contraz/pyrocket | rocket/rocket.py | Rocket.from_files | def from_files(controller, track_path, log_level=logging.ERROR):
"""Create rocket instance using project file connector"""
rocket = Rocket(controller, track_path=track_path, log_level=log_level)
rocket.connector = FilesConnector(track_path,
controller=controller,
tracks=rocket.tracks)
return rocket | python | def from_files(controller, track_path, log_level=logging.ERROR):
"""Create rocket instance using project file connector"""
rocket = Rocket(controller, track_path=track_path, log_level=log_level)
rocket.connector = FilesConnector(track_path,
controller=controller,
tracks=rocket.tracks)
return rocket | [
"def",
"from_files",
"(",
"controller",
",",
"track_path",
",",
"log_level",
"=",
"logging",
".",
"ERROR",
")",
":",
"rocket",
"=",
"Rocket",
"(",
"controller",
",",
"track_path",
"=",
"track_path",
",",
"log_level",
"=",
"log_level",
")",
"rocket",
".",
"... | Create rocket instance using project file connector | [
"Create",
"rocket",
"instance",
"using",
"project",
"file",
"connector"
] | train | https://github.com/Contraz/pyrocket/blob/97f4153c79030497b97fbaf43b1aa6dc1a6c7f7b/rocket/rocket.py#L28-L34 |
Contraz/pyrocket | rocket/rocket.py | Rocket.from_project_file | def from_project_file(controller, project_file, track_path=None, log_level=logging.ERROR):
"""Create rocket instance using project file connector"""
rocket = Rocket(controller, track_path=track_path, log_level=log_level)
rocket.connector = ProjectFileConnector(project_file,
controller=controller,
tracks=rocket.tracks)
return rocket | python | def from_project_file(controller, project_file, track_path=None, log_level=logging.ERROR):
"""Create rocket instance using project file connector"""
rocket = Rocket(controller, track_path=track_path, log_level=log_level)
rocket.connector = ProjectFileConnector(project_file,
controller=controller,
tracks=rocket.tracks)
return rocket | [
"def",
"from_project_file",
"(",
"controller",
",",
"project_file",
",",
"track_path",
"=",
"None",
",",
"log_level",
"=",
"logging",
".",
"ERROR",
")",
":",
"rocket",
"=",
"Rocket",
"(",
"controller",
",",
"track_path",
"=",
"track_path",
",",
"log_level",
... | Create rocket instance using project file connector | [
"Create",
"rocket",
"instance",
"using",
"project",
"file",
"connector"
] | train | https://github.com/Contraz/pyrocket/blob/97f4153c79030497b97fbaf43b1aa6dc1a6c7f7b/rocket/rocket.py#L37-L43 |
Contraz/pyrocket | rocket/rocket.py | Rocket.from_socket | def from_socket(controller, host=None, port=None, track_path=None, log_level=logging.ERROR):
"""Create rocket instance using socket connector"""
rocket = Rocket(controller, track_path=track_path, log_level=log_level)
rocket.connector = SocketConnector(controller=controller,
tracks=rocket.tracks,
host=host,
port=port)
return rocket | python | def from_socket(controller, host=None, port=None, track_path=None, log_level=logging.ERROR):
"""Create rocket instance using socket connector"""
rocket = Rocket(controller, track_path=track_path, log_level=log_level)
rocket.connector = SocketConnector(controller=controller,
tracks=rocket.tracks,
host=host,
port=port)
return rocket | [
"def",
"from_socket",
"(",
"controller",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"track_path",
"=",
"None",
",",
"log_level",
"=",
"logging",
".",
"ERROR",
")",
":",
"rocket",
"=",
"Rocket",
"(",
"controller",
",",
"track_path",
"=",
"... | Create rocket instance using socket connector | [
"Create",
"rocket",
"instance",
"using",
"socket",
"connector"
] | train | https://github.com/Contraz/pyrocket/blob/97f4153c79030497b97fbaf43b1aa6dc1a6c7f7b/rocket/rocket.py#L46-L53 |
Contraz/pyrocket | rocket/rocket.py | Rocket.value | def value(self, name):
"""get value of a track at the current time"""
return self.tracks.get(name).row_value(self.controller.row) | python | def value(self, name):
"""get value of a track at the current time"""
return self.tracks.get(name).row_value(self.controller.row) | [
"def",
"value",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"tracks",
".",
"get",
"(",
"name",
")",
".",
"row_value",
"(",
"self",
".",
"controller",
".",
"row",
")"
] | get value of a track at the current time | [
"get",
"value",
"of",
"a",
"track",
"at",
"the",
"current",
"time"
] | train | https://github.com/Contraz/pyrocket/blob/97f4153c79030497b97fbaf43b1aa6dc1a6c7f7b/rocket/rocket.py#L74-L76 |
noxdafox/vminspect | vminspect/comparator.py | compare_filesystems | def compare_filesystems(fs0, fs1, concurrent=False):
"""Compares the two given filesystems.
fs0 and fs1 are two mounted GuestFS instances
containing the two disks to be compared.
If the concurrent flag is True,
two processes will be used speeding up the comparison on multiple CPUs.
Returns a dictionary containing files created, removed and modified.
{'created_files': [<files in fs1 and not in fs0>],
'deleted_files': [<files in fs0 and not in fs1>],
'modified_files': [<files in both fs0 and fs1 but different>]}
"""
if concurrent:
future0 = concurrent_hash_filesystem(fs0)
future1 = concurrent_hash_filesystem(fs1)
files0 = future0.result()
files1 = future1.result()
else:
files0 = hash_filesystem(fs0)
files1 = hash_filesystem(fs1)
return file_comparison(files0, files1) | python | def compare_filesystems(fs0, fs1, concurrent=False):
"""Compares the two given filesystems.
fs0 and fs1 are two mounted GuestFS instances
containing the two disks to be compared.
If the concurrent flag is True,
two processes will be used speeding up the comparison on multiple CPUs.
Returns a dictionary containing files created, removed and modified.
{'created_files': [<files in fs1 and not in fs0>],
'deleted_files': [<files in fs0 and not in fs1>],
'modified_files': [<files in both fs0 and fs1 but different>]}
"""
if concurrent:
future0 = concurrent_hash_filesystem(fs0)
future1 = concurrent_hash_filesystem(fs1)
files0 = future0.result()
files1 = future1.result()
else:
files0 = hash_filesystem(fs0)
files1 = hash_filesystem(fs1)
return file_comparison(files0, files1) | [
"def",
"compare_filesystems",
"(",
"fs0",
",",
"fs1",
",",
"concurrent",
"=",
"False",
")",
":",
"if",
"concurrent",
":",
"future0",
"=",
"concurrent_hash_filesystem",
"(",
"fs0",
")",
"future1",
"=",
"concurrent_hash_filesystem",
"(",
"fs1",
")",
"files0",
"=... | Compares the two given filesystems.
fs0 and fs1 are two mounted GuestFS instances
containing the two disks to be compared.
If the concurrent flag is True,
two processes will be used speeding up the comparison on multiple CPUs.
Returns a dictionary containing files created, removed and modified.
{'created_files': [<files in fs1 and not in fs0>],
'deleted_files': [<files in fs0 and not in fs1>],
'modified_files': [<files in both fs0 and fs1 but different>]} | [
"Compares",
"the",
"two",
"given",
"filesystems",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L175-L201 |
noxdafox/vminspect | vminspect/comparator.py | file_comparison | def file_comparison(files0, files1):
"""Compares two dictionaries of files returning their difference.
{'created_files': [<files in files1 and not in files0>],
'deleted_files': [<files in files0 and not in files1>],
'modified_files': [<files in both files0 and files1 but different>]}
"""
comparison = {'created_files': [],
'deleted_files': [],
'modified_files': []}
for path, sha1 in files1.items():
if path in files0:
if sha1 != files0[path]:
comparison['modified_files'].append(
{'path': path,
'original_sha1': files0[path],
'sha1': sha1})
else:
comparison['created_files'].append({'path': path,
'sha1': sha1})
for path, sha1 in files0.items():
if path not in files1:
comparison['deleted_files'].append({'path': path,
'original_sha1': files0[path]})
return comparison | python | def file_comparison(files0, files1):
"""Compares two dictionaries of files returning their difference.
{'created_files': [<files in files1 and not in files0>],
'deleted_files': [<files in files0 and not in files1>],
'modified_files': [<files in both files0 and files1 but different>]}
"""
comparison = {'created_files': [],
'deleted_files': [],
'modified_files': []}
for path, sha1 in files1.items():
if path in files0:
if sha1 != files0[path]:
comparison['modified_files'].append(
{'path': path,
'original_sha1': files0[path],
'sha1': sha1})
else:
comparison['created_files'].append({'path': path,
'sha1': sha1})
for path, sha1 in files0.items():
if path not in files1:
comparison['deleted_files'].append({'path': path,
'original_sha1': files0[path]})
return comparison | [
"def",
"file_comparison",
"(",
"files0",
",",
"files1",
")",
":",
"comparison",
"=",
"{",
"'created_files'",
":",
"[",
"]",
",",
"'deleted_files'",
":",
"[",
"]",
",",
"'modified_files'",
":",
"[",
"]",
"}",
"for",
"path",
",",
"sha1",
"in",
"files1",
... | Compares two dictionaries of files returning their difference.
{'created_files': [<files in files1 and not in files0>],
'deleted_files': [<files in files0 and not in files1>],
'modified_files': [<files in both files0 and files1 but different>]} | [
"Compares",
"two",
"dictionaries",
"of",
"files",
"returning",
"their",
"difference",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L204-L231 |
noxdafox/vminspect | vminspect/comparator.py | extract_files | def extract_files(filesystem, files, path):
"""Extracts requested files.
files must be a list of files in the format
{"C:\\Windows\\System32\\NTUSER.DAT": "sha1_hash"} for windows
{"/home/user/text.txt": "sha1_hash"} for other FS.
files will be extracted into path which must exist beforehand.
Returns two dictionaries:
{"sha1": "/local/path/sha1"} files successfully extracted
{"sha1": "C:\\..\\text.txt"} files which could not be extracted windows
{"sha1": "/../text.txt"} files which could not be extracted linux
"""
extracted_files = {}
failed_extractions = {}
for file_to_extract in files:
source = file_to_extract['path']
destination = Path(path, file_to_extract['sha1'])
if not destination.exists():
destination = str(destination)
try:
filesystem.download(source, destination)
extracted_files[file_to_extract['sha1']] = destination
except RuntimeError:
failed_extractions[file_to_extract['sha1']] = source
else:
extracted_files[file_to_extract['sha1']] = destination
return extracted_files, failed_extractions | python | def extract_files(filesystem, files, path):
"""Extracts requested files.
files must be a list of files in the format
{"C:\\Windows\\System32\\NTUSER.DAT": "sha1_hash"} for windows
{"/home/user/text.txt": "sha1_hash"} for other FS.
files will be extracted into path which must exist beforehand.
Returns two dictionaries:
{"sha1": "/local/path/sha1"} files successfully extracted
{"sha1": "C:\\..\\text.txt"} files which could not be extracted windows
{"sha1": "/../text.txt"} files which could not be extracted linux
"""
extracted_files = {}
failed_extractions = {}
for file_to_extract in files:
source = file_to_extract['path']
destination = Path(path, file_to_extract['sha1'])
if not destination.exists():
destination = str(destination)
try:
filesystem.download(source, destination)
extracted_files[file_to_extract['sha1']] = destination
except RuntimeError:
failed_extractions[file_to_extract['sha1']] = source
else:
extracted_files[file_to_extract['sha1']] = destination
return extracted_files, failed_extractions | [
"def",
"extract_files",
"(",
"filesystem",
",",
"files",
",",
"path",
")",
":",
"extracted_files",
"=",
"{",
"}",
"failed_extractions",
"=",
"{",
"}",
"for",
"file_to_extract",
"in",
"files",
":",
"source",
"=",
"file_to_extract",
"[",
"'path'",
"]",
"destin... | Extracts requested files.
files must be a list of files in the format
{"C:\\Windows\\System32\\NTUSER.DAT": "sha1_hash"} for windows
{"/home/user/text.txt": "sha1_hash"} for other FS.
files will be extracted into path which must exist beforehand.
Returns two dictionaries:
{"sha1": "/local/path/sha1"} files successfully extracted
{"sha1": "C:\\..\\text.txt"} files which could not be extracted windows
{"sha1": "/../text.txt"} files which could not be extracted linux | [
"Extracts",
"requested",
"files",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L234-L269 |
noxdafox/vminspect | vminspect/comparator.py | compare_registries | def compare_registries(fs0, fs1, concurrent=False):
"""Compares the Windows Registry contained within the two File Systems.
If the concurrent flag is True,
two processes will be used speeding up the comparison on multiple CPUs.
Returns a dictionary.
{'created_keys': {'\\Reg\\Key': (('Key', 'Type', 'Value'), ...)}
'deleted_keys': ['\\Reg\\Key', ...],
'created_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'), ...)},
'deleted_values': {'\\Reg\\Key': (('Key', 'Type', 'OldValue'), ...)},
'modified_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'), ...)}}
"""
hives = compare_hives(fs0, fs1)
if concurrent:
future0 = concurrent_parse_registries(fs0, hives)
future1 = concurrent_parse_registries(fs1, hives)
registry0 = future0.result()
registry1 = future1.result()
else:
registry0 = parse_registries(fs0, hives)
registry1 = parse_registries(fs1, hives)
return registry_comparison(registry0, registry1) | python | def compare_registries(fs0, fs1, concurrent=False):
"""Compares the Windows Registry contained within the two File Systems.
If the concurrent flag is True,
two processes will be used speeding up the comparison on multiple CPUs.
Returns a dictionary.
{'created_keys': {'\\Reg\\Key': (('Key', 'Type', 'Value'), ...)}
'deleted_keys': ['\\Reg\\Key', ...],
'created_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'), ...)},
'deleted_values': {'\\Reg\\Key': (('Key', 'Type', 'OldValue'), ...)},
'modified_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'), ...)}}
"""
hives = compare_hives(fs0, fs1)
if concurrent:
future0 = concurrent_parse_registries(fs0, hives)
future1 = concurrent_parse_registries(fs1, hives)
registry0 = future0.result()
registry1 = future1.result()
else:
registry0 = parse_registries(fs0, hives)
registry1 = parse_registries(fs1, hives)
return registry_comparison(registry0, registry1) | [
"def",
"compare_registries",
"(",
"fs0",
",",
"fs1",
",",
"concurrent",
"=",
"False",
")",
":",
"hives",
"=",
"compare_hives",
"(",
"fs0",
",",
"fs1",
")",
"if",
"concurrent",
":",
"future0",
"=",
"concurrent_parse_registries",
"(",
"fs0",
",",
"hives",
")... | Compares the Windows Registry contained within the two File Systems.
If the concurrent flag is True,
two processes will be used speeding up the comparison on multiple CPUs.
Returns a dictionary.
{'created_keys': {'\\Reg\\Key': (('Key', 'Type', 'Value'), ...)}
'deleted_keys': ['\\Reg\\Key', ...],
'created_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'), ...)},
'deleted_values': {'\\Reg\\Key': (('Key', 'Type', 'OldValue'), ...)},
'modified_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'), ...)}} | [
"Compares",
"the",
"Windows",
"Registry",
"contained",
"within",
"the",
"two",
"File",
"Systems",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L272-L299 |
noxdafox/vminspect | vminspect/comparator.py | registry_comparison | def registry_comparison(registry0, registry1):
"""Compares two dictionaries of registry keys returning their difference."""
comparison = {'created_keys': {},
'deleted_keys': [],
'created_values': {},
'deleted_values': {},
'modified_values': {}}
for key, info in registry1.items():
if key in registry0:
if info[1] != registry0[key][1]:
created, deleted, modified = compare_values(
registry0[key][1], info[1])
if created:
comparison['created_values'][key] = (info[0], created)
if deleted:
comparison['deleted_values'][key] = (info[0], deleted)
if modified:
comparison['modified_values'][key] = (info[0], modified)
else:
comparison['created_keys'][key] = info
for key in registry0.keys():
if key not in registry1:
comparison['deleted_keys'].append(key)
return comparison | python | def registry_comparison(registry0, registry1):
"""Compares two dictionaries of registry keys returning their difference."""
comparison = {'created_keys': {},
'deleted_keys': [],
'created_values': {},
'deleted_values': {},
'modified_values': {}}
for key, info in registry1.items():
if key in registry0:
if info[1] != registry0[key][1]:
created, deleted, modified = compare_values(
registry0[key][1], info[1])
if created:
comparison['created_values'][key] = (info[0], created)
if deleted:
comparison['deleted_values'][key] = (info[0], deleted)
if modified:
comparison['modified_values'][key] = (info[0], modified)
else:
comparison['created_keys'][key] = info
for key in registry0.keys():
if key not in registry1:
comparison['deleted_keys'].append(key)
return comparison | [
"def",
"registry_comparison",
"(",
"registry0",
",",
"registry1",
")",
":",
"comparison",
"=",
"{",
"'created_keys'",
":",
"{",
"}",
",",
"'deleted_keys'",
":",
"[",
"]",
",",
"'created_values'",
":",
"{",
"}",
",",
"'deleted_values'",
":",
"{",
"}",
",",
... | Compares two dictionaries of registry keys returning their difference. | [
"Compares",
"two",
"dictionaries",
"of",
"registry",
"keys",
"returning",
"their",
"difference",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L302-L329 |
noxdafox/vminspect | vminspect/comparator.py | compare_values | def compare_values(values0, values1):
"""Compares all the values of a single registry key."""
values0 = {v[0]: v[1:] for v in values0}
values1 = {v[0]: v[1:] for v in values1}
created = [(k, v[0], v[1]) for k, v in values1.items() if k not in values0]
deleted = [(k, v[0], v[1]) for k, v in values0.items() if k not in values1]
modified = [(k, v[0], v[1]) for k, v in values0.items()
if v != values1.get(k, None)]
return created, deleted, modified | python | def compare_values(values0, values1):
"""Compares all the values of a single registry key."""
values0 = {v[0]: v[1:] for v in values0}
values1 = {v[0]: v[1:] for v in values1}
created = [(k, v[0], v[1]) for k, v in values1.items() if k not in values0]
deleted = [(k, v[0], v[1]) for k, v in values0.items() if k not in values1]
modified = [(k, v[0], v[1]) for k, v in values0.items()
if v != values1.get(k, None)]
return created, deleted, modified | [
"def",
"compare_values",
"(",
"values0",
",",
"values1",
")",
":",
"values0",
"=",
"{",
"v",
"[",
"0",
"]",
":",
"v",
"[",
"1",
":",
"]",
"for",
"v",
"in",
"values0",
"}",
"values1",
"=",
"{",
"v",
"[",
"0",
"]",
":",
"v",
"[",
"1",
":",
"]... | Compares all the values of a single registry key. | [
"Compares",
"all",
"the",
"values",
"of",
"a",
"single",
"registry",
"key",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L332-L342 |
noxdafox/vminspect | vminspect/comparator.py | compare_hives | def compare_hives(fs0, fs1):
"""Compares all the windows registry hive files
returning those which differ.
"""
registries = []
for path in chain(registries_path(fs0.fsroot), user_registries(fs0, fs1)):
if fs0.checksum(path) != fs1.checksum(path):
registries.append(path)
return registries | python | def compare_hives(fs0, fs1):
"""Compares all the windows registry hive files
returning those which differ.
"""
registries = []
for path in chain(registries_path(fs0.fsroot), user_registries(fs0, fs1)):
if fs0.checksum(path) != fs1.checksum(path):
registries.append(path)
return registries | [
"def",
"compare_hives",
"(",
"fs0",
",",
"fs1",
")",
":",
"registries",
"=",
"[",
"]",
"for",
"path",
"in",
"chain",
"(",
"registries_path",
"(",
"fs0",
".",
"fsroot",
")",
",",
"user_registries",
"(",
"fs0",
",",
"fs1",
")",
")",
":",
"if",
"fs0",
... | Compares all the windows registry hive files
returning those which differ. | [
"Compares",
"all",
"the",
"windows",
"registry",
"hive",
"files",
"returning",
"those",
"which",
"differ",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L345-L356 |
noxdafox/vminspect | vminspect/comparator.py | user_registries | def user_registries(fs0, fs1):
"""Returns the list of user registries present on both FileSystems."""
for user in fs0.ls('{}Users'.format(fs0.fsroot)):
for path in user_registries_path(fs0.fsroot, user):
if fs1.exists(path):
yield path | python | def user_registries(fs0, fs1):
"""Returns the list of user registries present on both FileSystems."""
for user in fs0.ls('{}Users'.format(fs0.fsroot)):
for path in user_registries_path(fs0.fsroot, user):
if fs1.exists(path):
yield path | [
"def",
"user_registries",
"(",
"fs0",
",",
"fs1",
")",
":",
"for",
"user",
"in",
"fs0",
".",
"ls",
"(",
"'{}Users'",
".",
"format",
"(",
"fs0",
".",
"fsroot",
")",
")",
":",
"for",
"path",
"in",
"user_registries_path",
"(",
"fs0",
".",
"fsroot",
",",... | Returns the list of user registries present on both FileSystems. | [
"Returns",
"the",
"list",
"of",
"user",
"registries",
"present",
"on",
"both",
"FileSystems",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L359-L364 |
noxdafox/vminspect | vminspect/comparator.py | files_type | def files_type(fs0, fs1, files):
"""Inspects the file type of the given files."""
for file_meta in files['deleted_files']:
file_meta['type'] = fs0.file(file_meta['path'])
for file_meta in files['created_files'] + files['modified_files']:
file_meta['type'] = fs1.file(file_meta['path'])
return files | python | def files_type(fs0, fs1, files):
"""Inspects the file type of the given files."""
for file_meta in files['deleted_files']:
file_meta['type'] = fs0.file(file_meta['path'])
for file_meta in files['created_files'] + files['modified_files']:
file_meta['type'] = fs1.file(file_meta['path'])
return files | [
"def",
"files_type",
"(",
"fs0",
",",
"fs1",
",",
"files",
")",
":",
"for",
"file_meta",
"in",
"files",
"[",
"'deleted_files'",
"]",
":",
"file_meta",
"[",
"'type'",
"]",
"=",
"fs0",
".",
"file",
"(",
"file_meta",
"[",
"'path'",
"]",
")",
"for",
"fil... | Inspects the file type of the given files. | [
"Inspects",
"the",
"file",
"type",
"of",
"the",
"given",
"files",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L367-L374 |
noxdafox/vminspect | vminspect/comparator.py | files_size | def files_size(fs0, fs1, files):
"""Gets the file size of the given files."""
for file_meta in files['deleted_files']:
file_meta['size'] = fs0.stat(file_meta['path'])['size']
for file_meta in files['created_files'] + files['modified_files']:
file_meta['size'] = fs1.stat(file_meta['path'])['size']
return files | python | def files_size(fs0, fs1, files):
"""Gets the file size of the given files."""
for file_meta in files['deleted_files']:
file_meta['size'] = fs0.stat(file_meta['path'])['size']
for file_meta in files['created_files'] + files['modified_files']:
file_meta['size'] = fs1.stat(file_meta['path'])['size']
return files | [
"def",
"files_size",
"(",
"fs0",
",",
"fs1",
",",
"files",
")",
":",
"for",
"file_meta",
"in",
"files",
"[",
"'deleted_files'",
"]",
":",
"file_meta",
"[",
"'size'",
"]",
"=",
"fs0",
".",
"stat",
"(",
"file_meta",
"[",
"'path'",
"]",
")",
"[",
"'size... | Gets the file size of the given files. | [
"Gets",
"the",
"file",
"size",
"of",
"the",
"given",
"files",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L377-L384 |
noxdafox/vminspect | vminspect/comparator.py | parse_registries | def parse_registries(filesystem, registries):
"""Returns a dictionary with the content of the given registry hives.
{"\\Registry\\Key\\", (("ValueKey", "ValueType", ValueValue))}
"""
results = {}
for path in registries:
with NamedTemporaryFile(buffering=0) as tempfile:
filesystem.download(path, tempfile.name)
registry = RegistryHive(tempfile.name)
registry.rootkey = registry_root(path)
results.update({k.path: (k.timestamp, k.values)
for k in registry.keys()})
return results | python | def parse_registries(filesystem, registries):
"""Returns a dictionary with the content of the given registry hives.
{"\\Registry\\Key\\", (("ValueKey", "ValueType", ValueValue))}
"""
results = {}
for path in registries:
with NamedTemporaryFile(buffering=0) as tempfile:
filesystem.download(path, tempfile.name)
registry = RegistryHive(tempfile.name)
registry.rootkey = registry_root(path)
results.update({k.path: (k.timestamp, k.values)
for k in registry.keys()})
return results | [
"def",
"parse_registries",
"(",
"filesystem",
",",
"registries",
")",
":",
"results",
"=",
"{",
"}",
"for",
"path",
"in",
"registries",
":",
"with",
"NamedTemporaryFile",
"(",
"buffering",
"=",
"0",
")",
"as",
"tempfile",
":",
"filesystem",
".",
"download",
... | Returns a dictionary with the content of the given registry hives.
{"\\Registry\\Key\\", (("ValueKey", "ValueType", ValueValue))} | [
"Returns",
"a",
"dictionary",
"with",
"the",
"content",
"of",
"the",
"given",
"registry",
"hives",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L392-L410 |
noxdafox/vminspect | vminspect/comparator.py | makedirs | def makedirs(path):
"""Creates the directory tree if non existing."""
path = Path(path)
if not path.exists():
path.mkdir(parents=True) | python | def makedirs(path):
"""Creates the directory tree if non existing."""
path = Path(path)
if not path.exists():
path.mkdir(parents=True) | [
"def",
"makedirs",
"(",
"path",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"if",
"not",
"path",
".",
"exists",
"(",
")",
":",
"path",
".",
"mkdir",
"(",
"parents",
"=",
"True",
")"
] | Creates the directory tree if non existing. | [
"Creates",
"the",
"directory",
"tree",
"if",
"non",
"existing",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L418-L423 |
noxdafox/vminspect | vminspect/comparator.py | DiskComparator.compare | def compare(self, concurrent=False, identify=False, size=False):
"""Compares the two disks according to flags.
Generates the following report:
::
{'created_files': [{'path': '/file/in/disk1/not/in/disk0',
'sha1': 'sha1_of_the_file'}],
'deleted_files': [{'path': '/file/in/disk0/not/in/disk1',
'original_sha1': 'sha1_of_the_file'}],
'modified_files': [{'path': '/file/both/disks/but/different',
'sha1': 'sha1_of_the_file_on_disk0',
'original_sha1': 'sha1_of_the_file_on_disk0'}]}
If concurrent is set to True, the logic will use multiple CPUs to
speed up the process.
The identify and size keywords will add respectively the type
and the size of the files to the results.
"""
self.logger.debug("Comparing FS contents.")
results = compare_filesystems(self.filesystems[0], self.filesystems[1],
concurrent=concurrent)
if identify:
self.logger.debug("Gatering file types.")
results = files_type(self.filesystems[0], self.filesystems[1],
results)
if size:
self.logger.debug("Gatering file sizes.")
results = files_size(self.filesystems[0], self.filesystems[1],
results)
return results | python | def compare(self, concurrent=False, identify=False, size=False):
"""Compares the two disks according to flags.
Generates the following report:
::
{'created_files': [{'path': '/file/in/disk1/not/in/disk0',
'sha1': 'sha1_of_the_file'}],
'deleted_files': [{'path': '/file/in/disk0/not/in/disk1',
'original_sha1': 'sha1_of_the_file'}],
'modified_files': [{'path': '/file/both/disks/but/different',
'sha1': 'sha1_of_the_file_on_disk0',
'original_sha1': 'sha1_of_the_file_on_disk0'}]}
If concurrent is set to True, the logic will use multiple CPUs to
speed up the process.
The identify and size keywords will add respectively the type
and the size of the files to the results.
"""
self.logger.debug("Comparing FS contents.")
results = compare_filesystems(self.filesystems[0], self.filesystems[1],
concurrent=concurrent)
if identify:
self.logger.debug("Gatering file types.")
results = files_type(self.filesystems[0], self.filesystems[1],
results)
if size:
self.logger.debug("Gatering file sizes.")
results = files_size(self.filesystems[0], self.filesystems[1],
results)
return results | [
"def",
"compare",
"(",
"self",
",",
"concurrent",
"=",
"False",
",",
"identify",
"=",
"False",
",",
"size",
"=",
"False",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Comparing FS contents.\"",
")",
"results",
"=",
"compare_filesystems",
"(",
"se... | Compares the two disks according to flags.
Generates the following report:
::
{'created_files': [{'path': '/file/in/disk1/not/in/disk0',
'sha1': 'sha1_of_the_file'}],
'deleted_files': [{'path': '/file/in/disk0/not/in/disk1',
'original_sha1': 'sha1_of_the_file'}],
'modified_files': [{'path': '/file/both/disks/but/different',
'sha1': 'sha1_of_the_file_on_disk0',
'original_sha1': 'sha1_of_the_file_on_disk0'}]}
If concurrent is set to True, the logic will use multiple CPUs to
speed up the process.
The identify and size keywords will add respectively the type
and the size of the files to the results. | [
"Compares",
"the",
"two",
"disks",
"according",
"to",
"flags",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L67-L103 |
noxdafox/vminspect | vminspect/comparator.py | DiskComparator.extract | def extract(self, disk, files, path='.'):
"""Extracts the given files from the given disk.
Disk must be an integer (1 or 2) indicating from which of the two disks
to extract.
Files must be a list of dictionaries containing
the keys 'path' and 'sha1'.
Files will be extracted in path and will be named with their sha1.
Returns a dictionary.
{'extracted_files': [<sha1>, <sha1>],
'extraction_errors': [<sha1>, <sha1>]}
"""
self.logger.debug("Extracting files.")
extracted_files, failed = self._extract_files(disk, files, path)
return {'extracted_files': [f for f in extracted_files.keys()],
'extraction_errors': [f for f in failed.keys()]} | python | def extract(self, disk, files, path='.'):
"""Extracts the given files from the given disk.
Disk must be an integer (1 or 2) indicating from which of the two disks
to extract.
Files must be a list of dictionaries containing
the keys 'path' and 'sha1'.
Files will be extracted in path and will be named with their sha1.
Returns a dictionary.
{'extracted_files': [<sha1>, <sha1>],
'extraction_errors': [<sha1>, <sha1>]}
"""
self.logger.debug("Extracting files.")
extracted_files, failed = self._extract_files(disk, files, path)
return {'extracted_files': [f for f in extracted_files.keys()],
'extraction_errors': [f for f in failed.keys()]} | [
"def",
"extract",
"(",
"self",
",",
"disk",
",",
"files",
",",
"path",
"=",
"'.'",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Extracting files.\"",
")",
"extracted_files",
",",
"failed",
"=",
"self",
".",
"_extract_files",
"(",
"disk",
",",
... | Extracts the given files from the given disk.
Disk must be an integer (1 or 2) indicating from which of the two disks
to extract.
Files must be a list of dictionaries containing
the keys 'path' and 'sha1'.
Files will be extracted in path and will be named with their sha1.
Returns a dictionary.
{'extracted_files': [<sha1>, <sha1>],
'extraction_errors': [<sha1>, <sha1>]} | [
"Extracts",
"the",
"given",
"files",
"from",
"the",
"given",
"disk",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L105-L126 |
noxdafox/vminspect | vminspect/comparator.py | DiskComparator.compare_registry | def compare_registry(self, concurrent=False):
"""Compares the Windows Registry contained within the two File Systems.
It parses all the registry hive files contained within the disks
and generates the following report.
{'created_keys': {'\\Reg\\Key': (('Key', 'Type', 'Value'))}
'deleted_keys': ['\\Reg\\Key', ...],
'created_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'))},
'deleted_values': {'\\Reg\\Key': (('Key', 'Type', 'OldValue'))},
'modified_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'))}}
Only registry hives which are contained in both disks are compared.
If the second disk contains a new registry hive,
its content can be listed using winreg.RegistryHive.registry() method.
If the concurrent flag is True,
two processes will be used speeding up the comparison on multiple CPUs.
"""
self.logger.debug("Comparing Windows registries.")
self._assert_windows()
return compare_registries(self.filesystems[0], self.filesystems[1],
concurrent=concurrent) | python | def compare_registry(self, concurrent=False):
"""Compares the Windows Registry contained within the two File Systems.
It parses all the registry hive files contained within the disks
and generates the following report.
{'created_keys': {'\\Reg\\Key': (('Key', 'Type', 'Value'))}
'deleted_keys': ['\\Reg\\Key', ...],
'created_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'))},
'deleted_values': {'\\Reg\\Key': (('Key', 'Type', 'OldValue'))},
'modified_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'))}}
Only registry hives which are contained in both disks are compared.
If the second disk contains a new registry hive,
its content can be listed using winreg.RegistryHive.registry() method.
If the concurrent flag is True,
two processes will be used speeding up the comparison on multiple CPUs.
"""
self.logger.debug("Comparing Windows registries.")
self._assert_windows()
return compare_registries(self.filesystems[0], self.filesystems[1],
concurrent=concurrent) | [
"def",
"compare_registry",
"(",
"self",
",",
"concurrent",
"=",
"False",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Comparing Windows registries.\"",
")",
"self",
".",
"_assert_windows",
"(",
")",
"return",
"compare_registries",
"(",
"self",
".",
"... | Compares the Windows Registry contained within the two File Systems.
It parses all the registry hive files contained within the disks
and generates the following report.
{'created_keys': {'\\Reg\\Key': (('Key', 'Type', 'Value'))}
'deleted_keys': ['\\Reg\\Key', ...],
'created_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'))},
'deleted_values': {'\\Reg\\Key': (('Key', 'Type', 'OldValue'))},
'modified_values': {'\\Reg\\Key': (('Key', 'Type', 'NewValue'))}}
Only registry hives which are contained in both disks are compared.
If the second disk contains a new registry hive,
its content can be listed using winreg.RegistryHive.registry() method.
If the concurrent flag is True,
two processes will be used speeding up the comparison on multiple CPUs. | [
"Compares",
"the",
"Windows",
"Registry",
"contained",
"within",
"the",
"two",
"File",
"Systems",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L128-L153 |
erinn/comodo_api | comodo_api/comodo_api.py | ComodoTLSService._create_error | def _create_error(self, status_code):
"""
Construct an error message in jsend format.
:param int status_code: The status code to translate into an error message
:return: A dictionary in jsend format with the error and the code
:rtype: dict
"""
return jsend.error(message=ComodoCA.status_code[status_code], code=status_code) | python | def _create_error(self, status_code):
"""
Construct an error message in jsend format.
:param int status_code: The status code to translate into an error message
:return: A dictionary in jsend format with the error and the code
:rtype: dict
"""
return jsend.error(message=ComodoCA.status_code[status_code], code=status_code) | [
"def",
"_create_error",
"(",
"self",
",",
"status_code",
")",
":",
"return",
"jsend",
".",
"error",
"(",
"message",
"=",
"ComodoCA",
".",
"status_code",
"[",
"status_code",
"]",
",",
"code",
"=",
"status_code",
")"
] | Construct an error message in jsend format.
:param int status_code: The status code to translate into an error message
:return: A dictionary in jsend format with the error and the code
:rtype: dict | [
"Construct",
"an",
"error",
"message",
"in",
"jsend",
"format",
"."
] | train | https://github.com/erinn/comodo_api/blob/ddc2f0b487cab27cf6af1ad6a2deee17da11a1dd/comodo_api/comodo_api.py#L122-L131 |
erinn/comodo_api | comodo_api/comodo_api.py | ComodoTLSService.get_cert_types | def get_cert_types(self):
"""
Collect the certificate types that are available to the customer.
:return: A list of dictionaries of certificate types
:rtype: list
"""
result = self.client.service.getCustomerCertTypes(authData=self.auth)
if result.statusCode == 0:
return jsend.success({'cert_types': result.types})
else:
return self._create_error(result.statusCode) | python | def get_cert_types(self):
"""
Collect the certificate types that are available to the customer.
:return: A list of dictionaries of certificate types
:rtype: list
"""
result = self.client.service.getCustomerCertTypes(authData=self.auth)
if result.statusCode == 0:
return jsend.success({'cert_types': result.types})
else:
return self._create_error(result.statusCode) | [
"def",
"get_cert_types",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"client",
".",
"service",
".",
"getCustomerCertTypes",
"(",
"authData",
"=",
"self",
".",
"auth",
")",
"if",
"result",
".",
"statusCode",
"==",
"0",
":",
"return",
"jsend",
".",
... | Collect the certificate types that are available to the customer.
:return: A list of dictionaries of certificate types
:rtype: list | [
"Collect",
"the",
"certificate",
"types",
"that",
"are",
"available",
"to",
"the",
"customer",
"."
] | train | https://github.com/erinn/comodo_api/blob/ddc2f0b487cab27cf6af1ad6a2deee17da11a1dd/comodo_api/comodo_api.py#L133-L145 |
erinn/comodo_api | comodo_api/comodo_api.py | ComodoTLSService.collect | def collect(self, cert_id, format_type):
"""
Poll for certificate availability after submission.
:param int cert_id: The certificate ID
:param str format_type: The format type to use (example: 'X509 PEM Certificate only')
:return: The certificate_id or the certificate depending on whether the certificate is ready (check status code)
:rtype: dict
"""
result = self.client.service.collect(authData=self.auth, id=cert_id,
formatType=ComodoCA.format_type[format_type])
# The certificate is ready for collection
if result.statusCode == 2:
return jsend.success({'certificate': result.SSL.certificate, 'certificate_status': 'issued',
'certificate_id': cert_id})
# The certificate is not ready for collection yet
elif result.statusCode == 0:
return jsend.fail({'certificate_id': cert_id, 'certificate': '', 'certificate_status': 'pending'})
# Some error occurred
else:
return self._create_error(result.statusCode) | python | def collect(self, cert_id, format_type):
"""
Poll for certificate availability after submission.
:param int cert_id: The certificate ID
:param str format_type: The format type to use (example: 'X509 PEM Certificate only')
:return: The certificate_id or the certificate depending on whether the certificate is ready (check status code)
:rtype: dict
"""
result = self.client.service.collect(authData=self.auth, id=cert_id,
formatType=ComodoCA.format_type[format_type])
# The certificate is ready for collection
if result.statusCode == 2:
return jsend.success({'certificate': result.SSL.certificate, 'certificate_status': 'issued',
'certificate_id': cert_id})
# The certificate is not ready for collection yet
elif result.statusCode == 0:
return jsend.fail({'certificate_id': cert_id, 'certificate': '', 'certificate_status': 'pending'})
# Some error occurred
else:
return self._create_error(result.statusCode) | [
"def",
"collect",
"(",
"self",
",",
"cert_id",
",",
"format_type",
")",
":",
"result",
"=",
"self",
".",
"client",
".",
"service",
".",
"collect",
"(",
"authData",
"=",
"self",
".",
"auth",
",",
"id",
"=",
"cert_id",
",",
"formatType",
"=",
"ComodoCA",... | Poll for certificate availability after submission.
:param int cert_id: The certificate ID
:param str format_type: The format type to use (example: 'X509 PEM Certificate only')
:return: The certificate_id or the certificate depending on whether the certificate is ready (check status code)
:rtype: dict | [
"Poll",
"for",
"certificate",
"availability",
"after",
"submission",
"."
] | train | https://github.com/erinn/comodo_api/blob/ddc2f0b487cab27cf6af1ad6a2deee17da11a1dd/comodo_api/comodo_api.py#L147-L169 |
erinn/comodo_api | comodo_api/comodo_api.py | ComodoTLSService.revoke | def revoke(self, cert_id, reason=''):
"""
Revoke a certificate.
:param int cert_id: The certificate ID
:param str reason: Reason for revocation (up to 256 characters), can be blank: ''
:return: The result of the operation, 'Successful' on success
:rtype: dict
"""
result = self.client.service.revoke(authData=self.auth, id=cert_id, reason=reason)
if result == 0:
return jsend.success()
else:
return self._create_error(result) | python | def revoke(self, cert_id, reason=''):
"""
Revoke a certificate.
:param int cert_id: The certificate ID
:param str reason: Reason for revocation (up to 256 characters), can be blank: ''
:return: The result of the operation, 'Successful' on success
:rtype: dict
"""
result = self.client.service.revoke(authData=self.auth, id=cert_id, reason=reason)
if result == 0:
return jsend.success()
else:
return self._create_error(result) | [
"def",
"revoke",
"(",
"self",
",",
"cert_id",
",",
"reason",
"=",
"''",
")",
":",
"result",
"=",
"self",
".",
"client",
".",
"service",
".",
"revoke",
"(",
"authData",
"=",
"self",
".",
"auth",
",",
"id",
"=",
"cert_id",
",",
"reason",
"=",
"reason... | Revoke a certificate.
:param int cert_id: The certificate ID
:param str reason: Reason for revocation (up to 256 characters), can be blank: ''
:return: The result of the operation, 'Successful' on success
:rtype: dict | [
"Revoke",
"a",
"certificate",
"."
] | train | https://github.com/erinn/comodo_api/blob/ddc2f0b487cab27cf6af1ad6a2deee17da11a1dd/comodo_api/comodo_api.py#L171-L185 |
erinn/comodo_api | comodo_api/comodo_api.py | ComodoTLSService.submit | def submit(self, cert_type_name, csr, revoke_password, term, subject_alt_names='',
server_type='OTHER'):
"""
Submit a certificate request to Comodo.
:param string cert_type_name: The full cert type name (Example: 'PlatinumSSL Certificate') the supported
certificate types for your account can be obtained with the
get_cert_types() method.
:param string csr: The Certificate Signing Request (CSR)
:param string revoke_password: A password for certificate revocation
:param int term: The length, in years, for the certificate to be issued
:param string subject_alt_names: Subject Alternative Names separated by a ",".
:param string server_type: The type of server for the TLS certificate e.g 'Apache/ModSSL' full list available in
ComodoCA.server_type (Default: OTHER)
:return: The certificate_id and the normal status messages for errors.
:rtype: dict
"""
cert_types = self.get_cert_types()
# If collection of cert types fails we simply pass the error back.
if cert_types['status'] == 'error':
return cert_types
# We do this because we need to pass the entire cert type definition back to Comodo
# not just the name.
for cert_type in cert_types['data']['cert_types']:
if cert_type.name == cert_type_name:
cert_type_def = cert_type
result = self.client.service.enroll(authData=self.auth, orgId=self.org_id, secretKey=self.secret_key,
csr=csr, phrase=revoke_password, subjAltNames=subject_alt_names,
certType=cert_type_def, numberServers=1,
serverType=ComodoCA.formats[server_type], term=term, comments='')
# Anything greater than 0 is the certificate ID
if result > 0:
return jsend.success({'certificate_id': result})
# Anything else is an error
else:
return self._create_error(result) | python | def submit(self, cert_type_name, csr, revoke_password, term, subject_alt_names='',
server_type='OTHER'):
"""
Submit a certificate request to Comodo.
:param string cert_type_name: The full cert type name (Example: 'PlatinumSSL Certificate') the supported
certificate types for your account can be obtained with the
get_cert_types() method.
:param string csr: The Certificate Signing Request (CSR)
:param string revoke_password: A password for certificate revocation
:param int term: The length, in years, for the certificate to be issued
:param string subject_alt_names: Subject Alternative Names separated by a ",".
:param string server_type: The type of server for the TLS certificate e.g 'Apache/ModSSL' full list available in
ComodoCA.server_type (Default: OTHER)
:return: The certificate_id and the normal status messages for errors.
:rtype: dict
"""
cert_types = self.get_cert_types()
# If collection of cert types fails we simply pass the error back.
if cert_types['status'] == 'error':
return cert_types
# We do this because we need to pass the entire cert type definition back to Comodo
# not just the name.
for cert_type in cert_types['data']['cert_types']:
if cert_type.name == cert_type_name:
cert_type_def = cert_type
result = self.client.service.enroll(authData=self.auth, orgId=self.org_id, secretKey=self.secret_key,
csr=csr, phrase=revoke_password, subjAltNames=subject_alt_names,
certType=cert_type_def, numberServers=1,
serverType=ComodoCA.formats[server_type], term=term, comments='')
# Anything greater than 0 is the certificate ID
if result > 0:
return jsend.success({'certificate_id': result})
# Anything else is an error
else:
return self._create_error(result) | [
"def",
"submit",
"(",
"self",
",",
"cert_type_name",
",",
"csr",
",",
"revoke_password",
",",
"term",
",",
"subject_alt_names",
"=",
"''",
",",
"server_type",
"=",
"'OTHER'",
")",
":",
"cert_types",
"=",
"self",
".",
"get_cert_types",
"(",
")",
"# If collect... | Submit a certificate request to Comodo.
:param string cert_type_name: The full cert type name (Example: 'PlatinumSSL Certificate') the supported
certificate types for your account can be obtained with the
get_cert_types() method.
:param string csr: The Certificate Signing Request (CSR)
:param string revoke_password: A password for certificate revocation
:param int term: The length, in years, for the certificate to be issued
:param string subject_alt_names: Subject Alternative Names separated by a ",".
:param string server_type: The type of server for the TLS certificate e.g 'Apache/ModSSL' full list available in
ComodoCA.server_type (Default: OTHER)
:return: The certificate_id and the normal status messages for errors.
:rtype: dict | [
"Submit",
"a",
"certificate",
"request",
"to",
"Comodo",
"."
] | train | https://github.com/erinn/comodo_api/blob/ddc2f0b487cab27cf6af1ad6a2deee17da11a1dd/comodo_api/comodo_api.py#L187-L226 |
kirbs-/svm | svm/spark.py | Spark.build_from_source | def build_from_source(version, **kwargs):
"""
Builds specified Spark version from source.
:param version:
:param kwargs:
:return: (Integer) Status code of build/mvn command.
"""
mvn = os.path.join(Spark.svm_version_path(version), 'build', 'mvn')
Spark.chmod_add_excute(mvn)
p = subprocess.Popen([mvn, '-DskipTests', 'clean', 'package'], cwd=Spark.svm_version_path(version))
p.wait()
return p.returncode | python | def build_from_source(version, **kwargs):
"""
Builds specified Spark version from source.
:param version:
:param kwargs:
:return: (Integer) Status code of build/mvn command.
"""
mvn = os.path.join(Spark.svm_version_path(version), 'build', 'mvn')
Spark.chmod_add_excute(mvn)
p = subprocess.Popen([mvn, '-DskipTests', 'clean', 'package'], cwd=Spark.svm_version_path(version))
p.wait()
return p.returncode | [
"def",
"build_from_source",
"(",
"version",
",",
"*",
"*",
"kwargs",
")",
":",
"mvn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"Spark",
".",
"svm_version_path",
"(",
"version",
")",
",",
"'build'",
",",
"'mvn'",
")",
"Spark",
".",
"chmod_add_excute",
... | Builds specified Spark version from source.
:param version:
:param kwargs:
:return: (Integer) Status code of build/mvn command. | [
"Builds",
"specified",
"Spark",
"version",
"from",
"source",
".",
":",
"param",
"version",
":",
":",
"param",
"kwargs",
":",
":",
"return",
":",
"(",
"Integer",
")",
"Status",
"code",
"of",
"build",
"/",
"mvn",
"command",
"."
] | train | https://github.com/kirbs-/svm/blob/ce92a26a81013e2c0f7f4553b0a0b296d361c787/svm/spark.py#L161-L172 |
kirbs-/svm | svm/spark.py | Spark.chmod_add_excute | def chmod_add_excute(filename):
"""
Adds execute permission to file.
:param filename:
:return:
"""
st = os.stat(filename)
os.chmod(filename, st.st_mode | stat.S_IEXEC) | python | def chmod_add_excute(filename):
"""
Adds execute permission to file.
:param filename:
:return:
"""
st = os.stat(filename)
os.chmod(filename, st.st_mode | stat.S_IEXEC) | [
"def",
"chmod_add_excute",
"(",
"filename",
")",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"filename",
")",
"os",
".",
"chmod",
"(",
"filename",
",",
"st",
".",
"st_mode",
"|",
"stat",
".",
"S_IEXEC",
")"
] | Adds execute permission to file.
:param filename:
:return: | [
"Adds",
"execute",
"permission",
"to",
"file",
".",
":",
"param",
"filename",
":",
":",
"return",
":"
] | train | https://github.com/kirbs-/svm/blob/ce92a26a81013e2c0f7f4553b0a0b296d361c787/svm/spark.py#L175-L182 |
kirbs-/svm | svm/spark.py | Spark.download_source | def download_source(version):
"""
Download Spark version. Uses same name as release tag without the leading 'v'.
:param version: Version number to download.
:return: None
"""
local_filename = 'v{}.zip'.format(Spark.svm_version_path(version))
Spark.download(Spark.spark_versions()['v{}'.format(version)], local_filename) | python | def download_source(version):
"""
Download Spark version. Uses same name as release tag without the leading 'v'.
:param version: Version number to download.
:return: None
"""
local_filename = 'v{}.zip'.format(Spark.svm_version_path(version))
Spark.download(Spark.spark_versions()['v{}'.format(version)], local_filename) | [
"def",
"download_source",
"(",
"version",
")",
":",
"local_filename",
"=",
"'v{}.zip'",
".",
"format",
"(",
"Spark",
".",
"svm_version_path",
"(",
"version",
")",
")",
"Spark",
".",
"download",
"(",
"Spark",
".",
"spark_versions",
"(",
")",
"[",
"'v{}'",
"... | Download Spark version. Uses same name as release tag without the leading 'v'.
:param version: Version number to download.
:return: None | [
"Download",
"Spark",
"version",
".",
"Uses",
"same",
"name",
"as",
"release",
"tag",
"without",
"the",
"leading",
"v",
".",
":",
"param",
"version",
":",
"Version",
"number",
"to",
"download",
".",
":",
"return",
":",
"None"
] | train | https://github.com/kirbs-/svm/blob/ce92a26a81013e2c0f7f4553b0a0b296d361c787/svm/spark.py#L185-L192 |
kirbs-/svm | svm/spark.py | Spark.svm_version_path | def svm_version_path(version):
"""
Path to specified spark version. Accepts semantic version numbering.
:param version: Spark version as String
:return: String.
"""
return os.path.join(Spark.HOME_DIR, Spark.SVM_DIR, 'v{}'.format(version)) | python | def svm_version_path(version):
"""
Path to specified spark version. Accepts semantic version numbering.
:param version: Spark version as String
:return: String.
"""
return os.path.join(Spark.HOME_DIR, Spark.SVM_DIR, 'v{}'.format(version)) | [
"def",
"svm_version_path",
"(",
"version",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"Spark",
".",
"HOME_DIR",
",",
"Spark",
".",
"SVM_DIR",
",",
"'v{}'",
".",
"format",
"(",
"version",
")",
")"
] | Path to specified spark version. Accepts semantic version numbering.
:param version: Spark version as String
:return: String. | [
"Path",
"to",
"specified",
"spark",
"version",
".",
"Accepts",
"semantic",
"version",
"numbering",
".",
":",
"param",
"version",
":",
"Spark",
"version",
"as",
"String",
":",
"return",
":",
"String",
"."
] | train | https://github.com/kirbs-/svm/blob/ce92a26a81013e2c0f7f4553b0a0b296d361c787/svm/spark.py#L195-L201 |
kirbs-/svm | svm/spark.py | Spark.unzip | def unzip(filename):
"""
Unzips specified file into ~/.svm
:param filename:
:return:
"""
with zipfile.ZipFile(filename, "r") as zip_ref:
zip_ref.extractall(Spark.svm_path())
return True | python | def unzip(filename):
"""
Unzips specified file into ~/.svm
:param filename:
:return:
"""
with zipfile.ZipFile(filename, "r") as zip_ref:
zip_ref.extractall(Spark.svm_path())
return True | [
"def",
"unzip",
"(",
"filename",
")",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"zip_ref",
":",
"zip_ref",
".",
"extractall",
"(",
"Spark",
".",
"svm_path",
"(",
")",
")",
"return",
"True"
] | Unzips specified file into ~/.svm
:param filename:
:return: | [
"Unzips",
"specified",
"file",
"into",
"~",
"/",
".",
"svm",
":",
"param",
"filename",
":",
":",
"return",
":"
] | train | https://github.com/kirbs-/svm/blob/ce92a26a81013e2c0f7f4553b0a0b296d361c787/svm/spark.py#L212-L220 |
kirbs-/svm | svm/spark.py | Spark.rename_unzipped_folder | def rename_unzipped_folder(version):
"""
Renames unzipped spark version folder to the release tag.
:param version: version from release tag.
:return:
"""
for filename in os.listdir(Spark.svm_path()):
if fnmatch.fnmatch(filename, 'apache-spark-*'):
return os.rename(os.path.join(Spark.svm_path(), filename), Spark.svm_version_path(version))
raise SparkInstallationError("Unable to find unzipped Spark folder in {}".format(Spark.svm_path())) | python | def rename_unzipped_folder(version):
"""
Renames unzipped spark version folder to the release tag.
:param version: version from release tag.
:return:
"""
for filename in os.listdir(Spark.svm_path()):
if fnmatch.fnmatch(filename, 'apache-spark-*'):
return os.rename(os.path.join(Spark.svm_path(), filename), Spark.svm_version_path(version))
raise SparkInstallationError("Unable to find unzipped Spark folder in {}".format(Spark.svm_path())) | [
"def",
"rename_unzipped_folder",
"(",
"version",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"Spark",
".",
"svm_path",
"(",
")",
")",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"filename",
",",
"'apache-spark-*'",
")",
":",
"return",
"o... | Renames unzipped spark version folder to the release tag.
:param version: version from release tag.
:return: | [
"Renames",
"unzipped",
"spark",
"version",
"folder",
"to",
"the",
"release",
"tag",
".",
":",
"param",
"version",
":",
"version",
"from",
"release",
"tag",
".",
":",
"return",
":"
] | train | https://github.com/kirbs-/svm/blob/ce92a26a81013e2c0f7f4553b0a0b296d361c787/svm/spark.py#L223-L234 |
jasonbot/arcrest | arcrest/gptypes.py | GPMultiValue.fromType | def fromType(datatype):
"""Use this method to create a MultiValue type from a specific GP Value
type.
>>> gpmultistr = arcrest.GPMultiValue.fromType(arcrest.GPString)
>>> gpvalue = gpmultistr(["a", "b", "c"])
"""
if issubclass(datatype, GPBaseType):
return GPBaseType._get_type_by_name("GPMultiValue:%s" %
datatype.__name__)
else:
return GPBaseType._get_type_by_name("GPMultiValue:%s" %
str(datatype)) | python | def fromType(datatype):
"""Use this method to create a MultiValue type from a specific GP Value
type.
>>> gpmultistr = arcrest.GPMultiValue.fromType(arcrest.GPString)
>>> gpvalue = gpmultistr(["a", "b", "c"])
"""
if issubclass(datatype, GPBaseType):
return GPBaseType._get_type_by_name("GPMultiValue:%s" %
datatype.__name__)
else:
return GPBaseType._get_type_by_name("GPMultiValue:%s" %
str(datatype)) | [
"def",
"fromType",
"(",
"datatype",
")",
":",
"if",
"issubclass",
"(",
"datatype",
",",
"GPBaseType",
")",
":",
"return",
"GPBaseType",
".",
"_get_type_by_name",
"(",
"\"GPMultiValue:%s\"",
"%",
"datatype",
".",
"__name__",
")",
"else",
":",
"return",
"GPBaseT... | Use this method to create a MultiValue type from a specific GP Value
type.
>>> gpmultistr = arcrest.GPMultiValue.fromType(arcrest.GPString)
>>> gpvalue = gpmultistr(["a", "b", "c"]) | [
"Use",
"this",
"method",
"to",
"create",
"a",
"MultiValue",
"type",
"from",
"a",
"specific",
"GP",
"Value",
"type",
".",
">>>",
"gpmultistr",
"=",
"arcrest",
".",
"GPMultiValue",
".",
"fromType",
"(",
"arcrest",
".",
"GPString",
")",
">>>",
"gpvalue",
"=",... | train | https://github.com/jasonbot/arcrest/blob/b1ba71fd59bb6349415e7879d753d307dbc0da26/arcrest/gptypes.py#L35-L47 |
MaxHalford/starboost | starboost/losses.py | L1Loss.gradient | def gradient(self, y_true, y_pred):
"""Returns the gradient of the L1 loss with respect to each prediction.
Example:
>>> import starboost as sb
>>> y_true = [0, 0, 1]
>>> y_pred = [0.3, 0, 0.8]
>>> sb.losses.L1Loss().gradient(y_true, y_pred)
array([ 1., 0., -1.])
"""
return np.sign(np.subtract(y_pred, y_true)) | python | def gradient(self, y_true, y_pred):
"""Returns the gradient of the L1 loss with respect to each prediction.
Example:
>>> import starboost as sb
>>> y_true = [0, 0, 1]
>>> y_pred = [0.3, 0, 0.8]
>>> sb.losses.L1Loss().gradient(y_true, y_pred)
array([ 1., 0., -1.])
"""
return np.sign(np.subtract(y_pred, y_true)) | [
"def",
"gradient",
"(",
"self",
",",
"y_true",
",",
"y_pred",
")",
":",
"return",
"np",
".",
"sign",
"(",
"np",
".",
"subtract",
"(",
"y_pred",
",",
"y_true",
")",
")"
] | Returns the gradient of the L1 loss with respect to each prediction.
Example:
>>> import starboost as sb
>>> y_true = [0, 0, 1]
>>> y_pred = [0.3, 0, 0.8]
>>> sb.losses.L1Loss().gradient(y_true, y_pred)
array([ 1., 0., -1.]) | [
"Returns",
"the",
"gradient",
"of",
"the",
"L1",
"loss",
"with",
"respect",
"to",
"each",
"prediction",
"."
] | train | https://github.com/MaxHalford/starboost/blob/59d96dcc983404cbc326878facd8171fd2655ce1/starboost/losses.py#L111-L121 |
brbsix/pip-utils | pip_utils/parents.py | get_parents | def get_parents():
"""Return sorted list of names of packages without dependants."""
distributions = get_installed_distributions(user_only=ENABLE_USER_SITE)
remaining = {d.project_name.lower() for d in distributions}
requirements = {r.project_name.lower() for d in distributions for
r in d.requires()}
return get_realnames(remaining - requirements) | python | def get_parents():
"""Return sorted list of names of packages without dependants."""
distributions = get_installed_distributions(user_only=ENABLE_USER_SITE)
remaining = {d.project_name.lower() for d in distributions}
requirements = {r.project_name.lower() for d in distributions for
r in d.requires()}
return get_realnames(remaining - requirements) | [
"def",
"get_parents",
"(",
")",
":",
"distributions",
"=",
"get_installed_distributions",
"(",
"user_only",
"=",
"ENABLE_USER_SITE",
")",
"remaining",
"=",
"{",
"d",
".",
"project_name",
".",
"lower",
"(",
")",
"for",
"d",
"in",
"distributions",
"}",
"requirem... | Return sorted list of names of packages without dependants. | [
"Return",
"sorted",
"list",
"of",
"names",
"of",
"packages",
"without",
"dependants",
"."
] | train | https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/parents.py#L28-L35 |
brbsix/pip-utils | pip_utils/parents.py | get_realnames | def get_realnames(packages):
"""
Return list of unique case-correct package names.
Packages are listed in a case-insensitive sorted order.
"""
return sorted({get_distribution(p).project_name for p in packages},
key=lambda n: n.lower()) | python | def get_realnames(packages):
"""
Return list of unique case-correct package names.
Packages are listed in a case-insensitive sorted order.
"""
return sorted({get_distribution(p).project_name for p in packages},
key=lambda n: n.lower()) | [
"def",
"get_realnames",
"(",
"packages",
")",
":",
"return",
"sorted",
"(",
"{",
"get_distribution",
"(",
"p",
")",
".",
"project_name",
"for",
"p",
"in",
"packages",
"}",
",",
"key",
"=",
"lambda",
"n",
":",
"n",
".",
"lower",
"(",
")",
")"
] | Return list of unique case-correct package names.
Packages are listed in a case-insensitive sorted order. | [
"Return",
"list",
"of",
"unique",
"case",
"-",
"correct",
"package",
"names",
"."
] | train | https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/parents.py#L38-L45 |
sashka/flask-googleauth | flask_googleauth.py | OpenIdMixin.authenticate_redirect | def authenticate_redirect(self, callback_uri=None,
ask_for=["name", "email", "language", "username"]):
"""
Performs a redirect to the authentication URL for this service.
After authentication, the service will redirect back to the given
callback URI.
We request the given attributes for the authenticated user by
default (name, email, language, and username). If you don't need
all those attributes for your app, you can request fewer with
the |ask_for| keyword argument.
"""
callback_uri = callback_uri or request.url
args = self._openid_args(callback_uri, ax_attrs=ask_for)
return redirect(self._OPENID_ENDPOINT +
("&" if "?" in self._OPENID_ENDPOINT else "?") +
urllib.urlencode(args)) | python | def authenticate_redirect(self, callback_uri=None,
ask_for=["name", "email", "language", "username"]):
"""
Performs a redirect to the authentication URL for this service.
After authentication, the service will redirect back to the given
callback URI.
We request the given attributes for the authenticated user by
default (name, email, language, and username). If you don't need
all those attributes for your app, you can request fewer with
the |ask_for| keyword argument.
"""
callback_uri = callback_uri or request.url
args = self._openid_args(callback_uri, ax_attrs=ask_for)
return redirect(self._OPENID_ENDPOINT +
("&" if "?" in self._OPENID_ENDPOINT else "?") +
urllib.urlencode(args)) | [
"def",
"authenticate_redirect",
"(",
"self",
",",
"callback_uri",
"=",
"None",
",",
"ask_for",
"=",
"[",
"\"name\"",
",",
"\"email\"",
",",
"\"language\"",
",",
"\"username\"",
"]",
")",
":",
"callback_uri",
"=",
"callback_uri",
"or",
"request",
".",
"url",
... | Performs a redirect to the authentication URL for this service.
After authentication, the service will redirect back to the given
callback URI.
We request the given attributes for the authenticated user by
default (name, email, language, and username). If you don't need
all those attributes for your app, you can request fewer with
the |ask_for| keyword argument. | [
"Performs",
"a",
"redirect",
"to",
"the",
"authentication",
"URL",
"for",
"this",
"service",
"."
] | train | https://github.com/sashka/flask-googleauth/blob/4e481d645f1bb22124a6d79c7881746004cf4369/flask_googleauth.py#L67-L84 |
sashka/flask-googleauth | flask_googleauth.py | OpenIdMixin.get_authenticated_user | def get_authenticated_user(self, callback):
"""Fetches the authenticated user data upon redirect.
This method should be called by the handler that receives the
redirect from the authenticate_redirect() or authorize_redirect()
methods.
"""
# Verify the OpenID response via direct request to the OP
args = dict((k, v) for k, v in request.args.items())
args["openid.mode"] = u"check_authentication"
r = requests.post(self._OPENID_ENDPOINT, data=args)
return self._on_authentication_verified(callback, r) | python | def get_authenticated_user(self, callback):
"""Fetches the authenticated user data upon redirect.
This method should be called by the handler that receives the
redirect from the authenticate_redirect() or authorize_redirect()
methods.
"""
# Verify the OpenID response via direct request to the OP
args = dict((k, v) for k, v in request.args.items())
args["openid.mode"] = u"check_authentication"
r = requests.post(self._OPENID_ENDPOINT, data=args)
return self._on_authentication_verified(callback, r) | [
"def",
"get_authenticated_user",
"(",
"self",
",",
"callback",
")",
":",
"# Verify the OpenID response via direct request to the OP",
"args",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"request",
".",
"args",
".",
"items",
"(",
")... | Fetches the authenticated user data upon redirect.
This method should be called by the handler that receives the
redirect from the authenticate_redirect() or authorize_redirect()
methods. | [
"Fetches",
"the",
"authenticated",
"user",
"data",
"upon",
"redirect",
"."
] | train | https://github.com/sashka/flask-googleauth/blob/4e481d645f1bb22124a6d79c7881746004cf4369/flask_googleauth.py#L86-L98 |
sashka/flask-googleauth | flask_googleauth.py | GoogleAuth._on_auth | def _on_auth(self, user):
"""
This is called when login with OpenID succeeded and it's not
necessary to figure out if this is the users's first login or not.
"""
app = current_app._get_current_object()
if not user:
# Google auth failed.
login_error.send(app, user=None)
abort(403)
session["openid"] = user
login.send(app, user=user)
return redirect(request.args.get("next", None) or request.referrer or "/") | python | def _on_auth(self, user):
"""
This is called when login with OpenID succeeded and it's not
necessary to figure out if this is the users's first login or not.
"""
app = current_app._get_current_object()
if not user:
# Google auth failed.
login_error.send(app, user=None)
abort(403)
session["openid"] = user
login.send(app, user=user)
return redirect(request.args.get("next", None) or request.referrer or "/") | [
"def",
"_on_auth",
"(",
"self",
",",
"user",
")",
":",
"app",
"=",
"current_app",
".",
"_get_current_object",
"(",
")",
"if",
"not",
"user",
":",
"# Google auth failed.",
"login_error",
".",
"send",
"(",
"app",
",",
"user",
"=",
"None",
")",
"abort",
"("... | This is called when login with OpenID succeeded and it's not
necessary to figure out if this is the users's first login or not. | [
"This",
"is",
"called",
"when",
"login",
"with",
"OpenID",
"succeeded",
"and",
"it",
"s",
"not",
"necessary",
"to",
"figure",
"out",
"if",
"this",
"is",
"the",
"users",
"s",
"first",
"login",
"or",
"not",
"."
] | train | https://github.com/sashka/flask-googleauth/blob/4e481d645f1bb22124a6d79c7881746004cf4369/flask_googleauth.py#L269-L281 |
sashka/flask-googleauth | flask_googleauth.py | GoogleAuth.required | def required(self, fn):
"""Request decorator. Forces authentication."""
@functools.wraps(fn)
def decorated(*args, **kwargs):
if (not self._check_auth()
# Don't try to force authentication if the request is part
# of the authentication process - otherwise we end up in a
# loop.
and request.blueprint != self.blueprint.name):
return redirect(url_for("%s.login" % self.blueprint.name,
next=request.url))
return fn(*args, **kwargs)
return decorated | python | def required(self, fn):
"""Request decorator. Forces authentication."""
@functools.wraps(fn)
def decorated(*args, **kwargs):
if (not self._check_auth()
# Don't try to force authentication if the request is part
# of the authentication process - otherwise we end up in a
# loop.
and request.blueprint != self.blueprint.name):
return redirect(url_for("%s.login" % self.blueprint.name,
next=request.url))
return fn(*args, **kwargs)
return decorated | [
"def",
"required",
"(",
"self",
",",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"not",
"self",
".",
"_check_auth",
"(",
")",
"# Don't try to fo... | Request decorator. Forces authentication. | [
"Request",
"decorator",
".",
"Forces",
"authentication",
"."
] | train | https://github.com/sashka/flask-googleauth/blob/4e481d645f1bb22124a6d79c7881746004cf4369/flask_googleauth.py#L292-L304 |
noxdafox/vminspect | vminspect/usnjrnl.py | parse_journal_file | def parse_journal_file(journal_file):
"""Iterates over the journal's file taking care of paddings."""
counter = count()
for block in read_next_block(journal_file):
block = remove_nullchars(block)
while len(block) > MIN_RECORD_SIZE:
header = RECORD_HEADER.unpack_from(block)
size = header[0]
try:
yield parse_record(header, block[:size])
next(counter)
except RuntimeError:
yield CorruptedUsnRecord(next(counter))
finally:
block = remove_nullchars(block[size:])
journal_file.seek(- len(block), 1) | python | def parse_journal_file(journal_file):
"""Iterates over the journal's file taking care of paddings."""
counter = count()
for block in read_next_block(journal_file):
block = remove_nullchars(block)
while len(block) > MIN_RECORD_SIZE:
header = RECORD_HEADER.unpack_from(block)
size = header[0]
try:
yield parse_record(header, block[:size])
next(counter)
except RuntimeError:
yield CorruptedUsnRecord(next(counter))
finally:
block = remove_nullchars(block[size:])
journal_file.seek(- len(block), 1) | [
"def",
"parse_journal_file",
"(",
"journal_file",
")",
":",
"counter",
"=",
"count",
"(",
")",
"for",
"block",
"in",
"read_next_block",
"(",
"journal_file",
")",
":",
"block",
"=",
"remove_nullchars",
"(",
"block",
")",
"while",
"len",
"(",
"block",
")",
"... | Iterates over the journal's file taking care of paddings. | [
"Iterates",
"over",
"the",
"journal",
"s",
"file",
"taking",
"care",
"of",
"paddings",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/usnjrnl.py#L51-L71 |
noxdafox/vminspect | vminspect/usnjrnl.py | parse_record | def parse_record(header, record):
"""Parses a record according to its version."""
major_version = header[1]
try:
return RECORD_PARSER[major_version](header, record)
except (KeyError, struct.error) as error:
raise RuntimeError("Corrupted USN Record") from error | python | def parse_record(header, record):
"""Parses a record according to its version."""
major_version = header[1]
try:
return RECORD_PARSER[major_version](header, record)
except (KeyError, struct.error) as error:
raise RuntimeError("Corrupted USN Record") from error | [
"def",
"parse_record",
"(",
"header",
",",
"record",
")",
":",
"major_version",
"=",
"header",
"[",
"1",
"]",
"try",
":",
"return",
"RECORD_PARSER",
"[",
"major_version",
"]",
"(",
"header",
",",
"record",
")",
"except",
"(",
"KeyError",
",",
"struct",
"... | Parses a record according to its version. | [
"Parses",
"a",
"record",
"according",
"to",
"its",
"version",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/usnjrnl.py#L74-L81 |
noxdafox/vminspect | vminspect/usnjrnl.py | usn_v2_record | def usn_v2_record(header, record):
"""Extracts USN V2 record information."""
length, major_version, minor_version = header
fields = V2_RECORD.unpack_from(record, RECORD_HEADER.size)
return UsnRecord(length,
float('{}.{}'.format(major_version, minor_version)),
fields[0] | fields[1] << 16, # 6 bytes little endian mft
fields[2], # 2 bytes little endian mft sequence
fields[3] | fields[4] << 16, # 6 bytes little endian mft
fields[5], # 2 bytes little endian mft sequence
fields[6],
(datetime(1601, 1, 1) +
timedelta(microseconds=(fields[7] / 10))).isoformat(' '),
unpack_flags(fields[8], REASONS),
unpack_flags(fields[9], SOURCEINFO),
fields[10],
unpack_flags(fields[11], ATTRIBUTES),
str(struct.unpack_from('{}s'.format(fields[12]).encode(),
record, fields[13])[0], 'utf16')) | python | def usn_v2_record(header, record):
"""Extracts USN V2 record information."""
length, major_version, minor_version = header
fields = V2_RECORD.unpack_from(record, RECORD_HEADER.size)
return UsnRecord(length,
float('{}.{}'.format(major_version, minor_version)),
fields[0] | fields[1] << 16, # 6 bytes little endian mft
fields[2], # 2 bytes little endian mft sequence
fields[3] | fields[4] << 16, # 6 bytes little endian mft
fields[5], # 2 bytes little endian mft sequence
fields[6],
(datetime(1601, 1, 1) +
timedelta(microseconds=(fields[7] / 10))).isoformat(' '),
unpack_flags(fields[8], REASONS),
unpack_flags(fields[9], SOURCEINFO),
fields[10],
unpack_flags(fields[11], ATTRIBUTES),
str(struct.unpack_from('{}s'.format(fields[12]).encode(),
record, fields[13])[0], 'utf16')) | [
"def",
"usn_v2_record",
"(",
"header",
",",
"record",
")",
":",
"length",
",",
"major_version",
",",
"minor_version",
"=",
"header",
"fields",
"=",
"V2_RECORD",
".",
"unpack_from",
"(",
"record",
",",
"RECORD_HEADER",
".",
"size",
")",
"return",
"UsnRecord",
... | Extracts USN V2 record information. | [
"Extracts",
"USN",
"V2",
"record",
"information",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/usnjrnl.py#L84-L103 |
noxdafox/vminspect | vminspect/usnjrnl.py | usn_v4_record | def usn_v4_record(header, record):
"""Extracts USN V4 record information."""
length, major_version, minor_version = header
fields = V4_RECORD.unpack_from(record, RECORD_HEADER.size)
raise NotImplementedError('Not implemented') | python | def usn_v4_record(header, record):
"""Extracts USN V4 record information."""
length, major_version, minor_version = header
fields = V4_RECORD.unpack_from(record, RECORD_HEADER.size)
raise NotImplementedError('Not implemented') | [
"def",
"usn_v4_record",
"(",
"header",
",",
"record",
")",
":",
"length",
",",
"major_version",
",",
"minor_version",
"=",
"header",
"fields",
"=",
"V4_RECORD",
".",
"unpack_from",
"(",
"record",
",",
"RECORD_HEADER",
".",
"size",
")",
"raise",
"NotImplemented... | Extracts USN V4 record information. | [
"Extracts",
"USN",
"V4",
"record",
"information",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/usnjrnl.py#L128-L133 |
noxdafox/vminspect | vminspect/usnjrnl.py | unpack_flags | def unpack_flags(value, flags):
"""Multiple flags might be packed in the same field."""
try:
return [flags[value]]
except KeyError:
return [flags[k] for k in sorted(flags.keys()) if k & value > 0] | python | def unpack_flags(value, flags):
"""Multiple flags might be packed in the same field."""
try:
return [flags[value]]
except KeyError:
return [flags[k] for k in sorted(flags.keys()) if k & value > 0] | [
"def",
"unpack_flags",
"(",
"value",
",",
"flags",
")",
":",
"try",
":",
"return",
"[",
"flags",
"[",
"value",
"]",
"]",
"except",
"KeyError",
":",
"return",
"[",
"flags",
"[",
"k",
"]",
"for",
"k",
"in",
"sorted",
"(",
"flags",
".",
"keys",
"(",
... | Multiple flags might be packed in the same field. | [
"Multiple",
"flags",
"might",
"be",
"packed",
"in",
"the",
"same",
"field",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/usnjrnl.py#L136-L141 |
noxdafox/vminspect | vminspect/usnjrnl.py | read_next_block | def read_next_block(infile, block_size=io.DEFAULT_BUFFER_SIZE):
"""Iterates over the file in blocks."""
chunk = infile.read(block_size)
while chunk:
yield chunk
chunk = infile.read(block_size) | python | def read_next_block(infile, block_size=io.DEFAULT_BUFFER_SIZE):
"""Iterates over the file in blocks."""
chunk = infile.read(block_size)
while chunk:
yield chunk
chunk = infile.read(block_size) | [
"def",
"read_next_block",
"(",
"infile",
",",
"block_size",
"=",
"io",
".",
"DEFAULT_BUFFER_SIZE",
")",
":",
"chunk",
"=",
"infile",
".",
"read",
"(",
"block_size",
")",
"while",
"chunk",
":",
"yield",
"chunk",
"chunk",
"=",
"infile",
".",
"read",
"(",
"... | Iterates over the file in blocks. | [
"Iterates",
"over",
"the",
"file",
"in",
"blocks",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/usnjrnl.py#L144-L151 |
noxdafox/vminspect | vminspect/usnjrnl.py | remove_nullchars | def remove_nullchars(block):
"""Strips NULL chars taking care of bytes alignment."""
data = block.lstrip(b'\00')
padding = b'\00' * ((len(block) - len(data)) % 8)
return padding + data | python | def remove_nullchars(block):
"""Strips NULL chars taking care of bytes alignment."""
data = block.lstrip(b'\00')
padding = b'\00' * ((len(block) - len(data)) % 8)
return padding + data | [
"def",
"remove_nullchars",
"(",
"block",
")",
":",
"data",
"=",
"block",
".",
"lstrip",
"(",
"b'\\00'",
")",
"padding",
"=",
"b'\\00'",
"*",
"(",
"(",
"len",
"(",
"block",
")",
"-",
"len",
"(",
"data",
")",
")",
"%",
"8",
")",
"return",
"padding",
... | Strips NULL chars taking care of bytes alignment. | [
"Strips",
"NULL",
"chars",
"taking",
"care",
"of",
"bytes",
"alignment",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/usnjrnl.py#L154-L160 |
jasonbot/arcrest | arcrest/utils.py | timetopythonvalue | def timetopythonvalue(time_val):
"Convert a time or time range from ArcGIS REST server format to Python"
if isinstance(time_val, sequence):
return map(timetopythonvalue, time_val)
elif isinstance(time_val, numeric):
return datetime.datetime(*(time.gmtime(time_val))[:6])
elif isinstance(time_val, numeric):
values = []
try:
values = map(long, time_val.split(","))
except:
pass
if values:
return map(timetopythonvalue, values)
raise ValueError(repr(time_val)) | python | def timetopythonvalue(time_val):
"Convert a time or time range from ArcGIS REST server format to Python"
if isinstance(time_val, sequence):
return map(timetopythonvalue, time_val)
elif isinstance(time_val, numeric):
return datetime.datetime(*(time.gmtime(time_val))[:6])
elif isinstance(time_val, numeric):
values = []
try:
values = map(long, time_val.split(","))
except:
pass
if values:
return map(timetopythonvalue, values)
raise ValueError(repr(time_val)) | [
"def",
"timetopythonvalue",
"(",
"time_val",
")",
":",
"if",
"isinstance",
"(",
"time_val",
",",
"sequence",
")",
":",
"return",
"map",
"(",
"timetopythonvalue",
",",
"time_val",
")",
"elif",
"isinstance",
"(",
"time_val",
",",
"numeric",
")",
":",
"return",... | Convert a time or time range from ArcGIS REST server format to Python | [
"Convert",
"a",
"time",
"or",
"time",
"range",
"from",
"ArcGIS",
"REST",
"server",
"format",
"to",
"Python"
] | train | https://github.com/jasonbot/arcrest/blob/b1ba71fd59bb6349415e7879d753d307dbc0da26/arcrest/utils.py#L19-L33 |
jasonbot/arcrest | arcrest/utils.py | pythonvaluetotime | def pythonvaluetotime(time_val):
"Convert a time or time range from Python datetime to ArcGIS REST server"
if time_val is None:
return None
elif isinstance(time_val, numeric):
return str(long(time_val * 1000.0))
elif isinstance(time_val, date):
dtlist = [time_val.year, time_val.month, time_val.day]
if isinstance(time_val, datetime.datetime):
dtlist += [time_val.hour, time_val.minute, time_val.second]
else:
dtlist += [0, 0, 0]
return long(calendar.timegm(dtlist) * 1000.0)
elif (isinstance(time_val, sequence)
and len(time_val) == 2):
if all(isinstance(x, numeric)
for x in time_val):
return ",".join(pythonvaluetotime(x)
for x in time_val)
elif all(isinstance(x, date)
for x in time_val):
return ",".join(pythonvaluetotime(x)
for x in time_val)
raise ValueError(repr(time_val)) | python | def pythonvaluetotime(time_val):
"Convert a time or time range from Python datetime to ArcGIS REST server"
if time_val is None:
return None
elif isinstance(time_val, numeric):
return str(long(time_val * 1000.0))
elif isinstance(time_val, date):
dtlist = [time_val.year, time_val.month, time_val.day]
if isinstance(time_val, datetime.datetime):
dtlist += [time_val.hour, time_val.minute, time_val.second]
else:
dtlist += [0, 0, 0]
return long(calendar.timegm(dtlist) * 1000.0)
elif (isinstance(time_val, sequence)
and len(time_val) == 2):
if all(isinstance(x, numeric)
for x in time_val):
return ",".join(pythonvaluetotime(x)
for x in time_val)
elif all(isinstance(x, date)
for x in time_val):
return ",".join(pythonvaluetotime(x)
for x in time_val)
raise ValueError(repr(time_val)) | [
"def",
"pythonvaluetotime",
"(",
"time_val",
")",
":",
"if",
"time_val",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"time_val",
",",
"numeric",
")",
":",
"return",
"str",
"(",
"long",
"(",
"time_val",
"*",
"1000.0",
")",
")",
"elif",... | Convert a time or time range from Python datetime to ArcGIS REST server | [
"Convert",
"a",
"time",
"or",
"time",
"range",
"from",
"Python",
"datetime",
"to",
"ArcGIS",
"REST",
"server"
] | train | https://github.com/jasonbot/arcrest/blob/b1ba71fd59bb6349415e7879d753d307dbc0da26/arcrest/utils.py#L35-L58 |
bdastur/spam | pyansible/ansiInventory.py | AnsibleInventory.get_hosts | def get_hosts(self, group=None):
'''
Get the hosts
'''
hostlist = []
if group:
groupobj = self.inventory.groups.get(group)
if not groupobj:
print "Group [%s] not found in inventory" % group
return None
groupdict = {}
groupdict['hostlist'] = []
for host in groupobj.get_hosts():
groupdict['hostlist'].append(host.name)
hostlist.append(groupdict)
else:
for group in self.inventory.groups:
groupdict = {}
groupdict['group'] = group
groupdict['hostlist'] = []
groupobj = self.inventory.groups.get(group)
for host in groupobj.get_hosts():
groupdict['hostlist'].append(host.name)
hostlist.append(groupdict)
return hostlist | python | def get_hosts(self, group=None):
'''
Get the hosts
'''
hostlist = []
if group:
groupobj = self.inventory.groups.get(group)
if not groupobj:
print "Group [%s] not found in inventory" % group
return None
groupdict = {}
groupdict['hostlist'] = []
for host in groupobj.get_hosts():
groupdict['hostlist'].append(host.name)
hostlist.append(groupdict)
else:
for group in self.inventory.groups:
groupdict = {}
groupdict['group'] = group
groupdict['hostlist'] = []
groupobj = self.inventory.groups.get(group)
for host in groupobj.get_hosts():
groupdict['hostlist'].append(host.name)
hostlist.append(groupdict)
return hostlist | [
"def",
"get_hosts",
"(",
"self",
",",
"group",
"=",
"None",
")",
":",
"hostlist",
"=",
"[",
"]",
"if",
"group",
":",
"groupobj",
"=",
"self",
".",
"inventory",
".",
"groups",
".",
"get",
"(",
"group",
")",
"if",
"not",
"groupobj",
":",
"print",
"\"... | Get the hosts | [
"Get",
"the",
"hosts"
] | train | https://github.com/bdastur/spam/blob/3c363302412d15bdb391f62bf90348243e456af2/pyansible/ansiInventory.py#L32-L59 |
raamana/pyradigm | pyradigm/utils.py | make_random_MLdataset | def make_random_MLdataset(max_num_classes = 20,
min_class_size = 20,
max_class_size = 50,
max_dim = 100,
stratified = True):
"Generates a random MLDataset for use in testing."
smallest = min(min_class_size, max_class_size)
max_class_size = max(min_class_size, max_class_size)
largest = max(50, max_class_size)
largest = max(smallest+3,largest)
if max_num_classes != 2:
num_classes = np.random.randint(2, max_num_classes, 1)
else:
num_classes = 2
if type(num_classes) == np.ndarray:
num_classes = num_classes[0]
if not stratified:
class_sizes = np.random.random_integers(smallest, largest, num_classes)
else:
class_sizes = np.repeat(np.random.randint(smallest, largest), num_classes)
num_features = np.random.randint(min(3, max_dim), max(3, max_dim), 1)[0]
# feat_names = [ str(x) for x in range(num_features)]
class_ids = list()
labels = list()
for cl in range(num_classes):
class_ids.append('class-{}'.format(cl))
labels.append(int(cl))
ds = MLDataset()
for cc, class_ in enumerate(class_ids):
subids = [ 's{}-c{}'.format(ix,cc) for ix in range(class_sizes[cc]) ]
for sid in subids:
ds.add_sample(sid, feat_generator(num_features), int(cc), class_)
return ds | python | def make_random_MLdataset(max_num_classes = 20,
min_class_size = 20,
max_class_size = 50,
max_dim = 100,
stratified = True):
"Generates a random MLDataset for use in testing."
smallest = min(min_class_size, max_class_size)
max_class_size = max(min_class_size, max_class_size)
largest = max(50, max_class_size)
largest = max(smallest+3,largest)
if max_num_classes != 2:
num_classes = np.random.randint(2, max_num_classes, 1)
else:
num_classes = 2
if type(num_classes) == np.ndarray:
num_classes = num_classes[0]
if not stratified:
class_sizes = np.random.random_integers(smallest, largest, num_classes)
else:
class_sizes = np.repeat(np.random.randint(smallest, largest), num_classes)
num_features = np.random.randint(min(3, max_dim), max(3, max_dim), 1)[0]
# feat_names = [ str(x) for x in range(num_features)]
class_ids = list()
labels = list()
for cl in range(num_classes):
class_ids.append('class-{}'.format(cl))
labels.append(int(cl))
ds = MLDataset()
for cc, class_ in enumerate(class_ids):
subids = [ 's{}-c{}'.format(ix,cc) for ix in range(class_sizes[cc]) ]
for sid in subids:
ds.add_sample(sid, feat_generator(num_features), int(cc), class_)
return ds | [
"def",
"make_random_MLdataset",
"(",
"max_num_classes",
"=",
"20",
",",
"min_class_size",
"=",
"20",
",",
"max_class_size",
"=",
"50",
",",
"max_dim",
"=",
"100",
",",
"stratified",
"=",
"True",
")",
":",
"smallest",
"=",
"min",
"(",
"min_class_size",
",",
... | Generates a random MLDataset for use in testing. | [
"Generates",
"a",
"random",
"MLDataset",
"for",
"use",
"in",
"testing",
"."
] | train | https://github.com/raamana/pyradigm/blob/8ffb7958329c88b09417087b86887a3c92f438c2/pyradigm/utils.py#L7-L46 |
jkokorian/pyqt2waybinding | pyqt2waybinding/__init__.py | BindingEndpoint.forProperty | def forProperty(instance,propertyName,useGetter=False):
"""
2-way binds to an instance property.
Parameters:
- instance -- the object instance
- propertyName -- the name of the property to bind to
- useGetter: when True, calls the getter method to obtain the value. When False, the signal argument is used as input for the target setter. (default False)
Notes:
2-way binds to an instance property according to one of the following naming conventions:
@property, propertyName.setter and pyqtSignal
- getter: propertyName
- setter: propertyName
- changedSignal: propertyNameChanged
getter, setter and pyqtSignal (this is used when binding to standard QWidgets like QSpinBox)
- getter: propertyName()
- setter: setPropertyName()
- changedSignal: propertyNameChanged
"""
assert isinstance(propertyName,str)
if propertyName.startswith("get") or propertyName.startswith("set"):
#property is a getter function or a setter function, assume a corresponding setter/getter function exists
getterName = "get" + propertyName[3:]
setterName = "set" + propertyName[3:]
if len(propertyName[3:]) > 1:
signalName = propertyName[3].lower() + propertyName[4:] + "Changed"
else:
signalName = propertyName.lower() + "Changed"
assert hasattr(instance,getterName)
assert hasattr(instance,setterName)
assert hasattr(instance,signalName)
getter = getattr(instance,getterName)
setter = getattr(instance,setterName)
signal = getattr(instance,signalName)
elif hasattr(instance, propertyName) and callable(getattr(instance,propertyName)):
#property is a getter function without the "get" prefix. Assume a corresponding setter method exists
getterName = propertyName
setterName = "set" + propertyName.capitalize()
signalName = propertyName + "Changed"
assert hasattr(instance,setterName)
assert hasattr(instance,signalName)
getter = getattr(instance,getterName)
setter = getattr(instance,setterName)
signal = getattr(instance,signalName)
elif hasattr(instance, propertyName):
#property is real property. Assume it is not readonly
signalName = propertyName + "Changed"
assert hasattr(instance,signalName)
getter = lambda: getattr(instance,propertyName)
setter = lambda value: setattr(instance,propertyName,value)
signal = getattr(instance,signalName)
else:
#property is a virtual property. There should be getPropertyName and setPropertyName methods
if len(propertyName) > 1:
getterName = "get" + propertyName[0].upper() + propertyName[1:]
setterName = "set" + propertyName[0].upper() + propertyName[1:]
signalName = propertyName + "Changed"
else:
getterName = "get" + propertyName.upper()
setterName = "set" + propertyName.upper()
signalName = propertyName.lower() + "Changed"
assert hasattr(instance,getterName)
assert hasattr(instance,setterName)
assert hasattr(instance,signalName)
getter = getattr(instance,getterName)
setter = getattr(instance,setterName)
signal = getattr(instance,signalName)
return BindingEndpoint(instance, setter, signal, getter = getter if useGetter else None) | python | def forProperty(instance,propertyName,useGetter=False):
"""
2-way binds to an instance property.
Parameters:
- instance -- the object instance
- propertyName -- the name of the property to bind to
- useGetter: when True, calls the getter method to obtain the value. When False, the signal argument is used as input for the target setter. (default False)
Notes:
2-way binds to an instance property according to one of the following naming conventions:
@property, propertyName.setter and pyqtSignal
- getter: propertyName
- setter: propertyName
- changedSignal: propertyNameChanged
getter, setter and pyqtSignal (this is used when binding to standard QWidgets like QSpinBox)
- getter: propertyName()
- setter: setPropertyName()
- changedSignal: propertyNameChanged
"""
assert isinstance(propertyName,str)
if propertyName.startswith("get") or propertyName.startswith("set"):
#property is a getter function or a setter function, assume a corresponding setter/getter function exists
getterName = "get" + propertyName[3:]
setterName = "set" + propertyName[3:]
if len(propertyName[3:]) > 1:
signalName = propertyName[3].lower() + propertyName[4:] + "Changed"
else:
signalName = propertyName.lower() + "Changed"
assert hasattr(instance,getterName)
assert hasattr(instance,setterName)
assert hasattr(instance,signalName)
getter = getattr(instance,getterName)
setter = getattr(instance,setterName)
signal = getattr(instance,signalName)
elif hasattr(instance, propertyName) and callable(getattr(instance,propertyName)):
#property is a getter function without the "get" prefix. Assume a corresponding setter method exists
getterName = propertyName
setterName = "set" + propertyName.capitalize()
signalName = propertyName + "Changed"
assert hasattr(instance,setterName)
assert hasattr(instance,signalName)
getter = getattr(instance,getterName)
setter = getattr(instance,setterName)
signal = getattr(instance,signalName)
elif hasattr(instance, propertyName):
#property is real property. Assume it is not readonly
signalName = propertyName + "Changed"
assert hasattr(instance,signalName)
getter = lambda: getattr(instance,propertyName)
setter = lambda value: setattr(instance,propertyName,value)
signal = getattr(instance,signalName)
else:
#property is a virtual property. There should be getPropertyName and setPropertyName methods
if len(propertyName) > 1:
getterName = "get" + propertyName[0].upper() + propertyName[1:]
setterName = "set" + propertyName[0].upper() + propertyName[1:]
signalName = propertyName + "Changed"
else:
getterName = "get" + propertyName.upper()
setterName = "set" + propertyName.upper()
signalName = propertyName.lower() + "Changed"
assert hasattr(instance,getterName)
assert hasattr(instance,setterName)
assert hasattr(instance,signalName)
getter = getattr(instance,getterName)
setter = getattr(instance,setterName)
signal = getattr(instance,signalName)
return BindingEndpoint(instance, setter, signal, getter = getter if useGetter else None) | [
"def",
"forProperty",
"(",
"instance",
",",
"propertyName",
",",
"useGetter",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"propertyName",
",",
"str",
")",
"if",
"propertyName",
".",
"startswith",
"(",
"\"get\"",
")",
"or",
"propertyName",
".",
"star... | 2-way binds to an instance property.
Parameters:
- instance -- the object instance
- propertyName -- the name of the property to bind to
- useGetter: when True, calls the getter method to obtain the value. When False, the signal argument is used as input for the target setter. (default False)
Notes:
2-way binds to an instance property according to one of the following naming conventions:
@property, propertyName.setter and pyqtSignal
- getter: propertyName
- setter: propertyName
- changedSignal: propertyNameChanged
getter, setter and pyqtSignal (this is used when binding to standard QWidgets like QSpinBox)
- getter: propertyName()
- setter: setPropertyName()
- changedSignal: propertyNameChanged | [
"2",
"-",
"way",
"binds",
"to",
"an",
"instance",
"property",
"."
] | train | https://github.com/jkokorian/pyqt2waybinding/blob/fb1fb84f55608cfbf99c6486650100ba81743117/pyqt2waybinding/__init__.py#L24-L105 |
jkokorian/pyqt2waybinding | pyqt2waybinding/__init__.py | Observer.bind | def bind(self,instance,setter,valueChangedSignal,getter = None):
"""
Creates an endpoint and call bindToEndpoint(endpoint). This is a convenience method.
Parameters:
instance -- the object instance to which the getter, setter and changedSignal belong
setter -- the value setter method
valueChangedSignal -- the pyqtSignal that is emitted with the value changes
getter -- the value getter method (default None)
If None, the signal argument(s) are passed to the setter method
"""
endpoint = BindingEndpoint(instance,setter,valueChangedSignal,getter=getter)
self.bindToEndPoint(endpoint) | python | def bind(self,instance,setter,valueChangedSignal,getter = None):
"""
Creates an endpoint and call bindToEndpoint(endpoint). This is a convenience method.
Parameters:
instance -- the object instance to which the getter, setter and changedSignal belong
setter -- the value setter method
valueChangedSignal -- the pyqtSignal that is emitted with the value changes
getter -- the value getter method (default None)
If None, the signal argument(s) are passed to the setter method
"""
endpoint = BindingEndpoint(instance,setter,valueChangedSignal,getter=getter)
self.bindToEndPoint(endpoint) | [
"def",
"bind",
"(",
"self",
",",
"instance",
",",
"setter",
",",
"valueChangedSignal",
",",
"getter",
"=",
"None",
")",
":",
"endpoint",
"=",
"BindingEndpoint",
"(",
"instance",
",",
"setter",
",",
"valueChangedSignal",
",",
"getter",
"=",
"getter",
")",
"... | Creates an endpoint and call bindToEndpoint(endpoint). This is a convenience method.
Parameters:
instance -- the object instance to which the getter, setter and changedSignal belong
setter -- the value setter method
valueChangedSignal -- the pyqtSignal that is emitted with the value changes
getter -- the value getter method (default None)
If None, the signal argument(s) are passed to the setter method | [
"Creates",
"an",
"endpoint",
"and",
"call",
"bindToEndpoint",
"(",
"endpoint",
")",
".",
"This",
"is",
"a",
"convenience",
"method",
"."
] | train | https://github.com/jkokorian/pyqt2waybinding/blob/fb1fb84f55608cfbf99c6486650100ba81743117/pyqt2waybinding/__init__.py#L119-L132 |
jkokorian/pyqt2waybinding | pyqt2waybinding/__init__.py | Observer.bindToEndPoint | def bindToEndPoint(self,bindingEndpoint):
"""
2-way binds the target endpoint to all other registered endpoints.
"""
self.bindings[bindingEndpoint.instanceId] = bindingEndpoint
bindingEndpoint.valueChangedSignal.connect(self._updateEndpoints) | python | def bindToEndPoint(self,bindingEndpoint):
"""
2-way binds the target endpoint to all other registered endpoints.
"""
self.bindings[bindingEndpoint.instanceId] = bindingEndpoint
bindingEndpoint.valueChangedSignal.connect(self._updateEndpoints) | [
"def",
"bindToEndPoint",
"(",
"self",
",",
"bindingEndpoint",
")",
":",
"self",
".",
"bindings",
"[",
"bindingEndpoint",
".",
"instanceId",
"]",
"=",
"bindingEndpoint",
"bindingEndpoint",
".",
"valueChangedSignal",
".",
"connect",
"(",
"self",
".",
"_updateEndpoin... | 2-way binds the target endpoint to all other registered endpoints. | [
"2",
"-",
"way",
"binds",
"the",
"target",
"endpoint",
"to",
"all",
"other",
"registered",
"endpoints",
"."
] | train | https://github.com/jkokorian/pyqt2waybinding/blob/fb1fb84f55608cfbf99c6486650100ba81743117/pyqt2waybinding/__init__.py#L134-L139 |
jkokorian/pyqt2waybinding | pyqt2waybinding/__init__.py | Observer.bindToProperty | def bindToProperty(self,instance,propertyName,useGetter=False):
"""
2-way binds to an instance property.
Parameters:
- instance -- the object instance
- propertyName -- the name of the property to bind to
- useGetter: when True, calls the getter method to obtain the value. When False, the signal argument is used as input for the target setter. (default False)
Notes:
2-way binds to an instance property according to one of the following naming conventions:
@property, propertyName.setter and pyqtSignal
- getter: propertyName
- setter: propertyName
- changedSignal: propertyNameChanged
getter, setter and pyqtSignal (this is used when binding to standard QWidgets like QSpinBox)
- getter: propertyName()
- setter: setPropertyName()
- changedSignal: propertyNameChanged
"""
endpoint = BindingEndpoint.forProperty(instance,propertyName,useGetter = useGetter)
self.bindToEndPoint(endpoint) | python | def bindToProperty(self,instance,propertyName,useGetter=False):
"""
2-way binds to an instance property.
Parameters:
- instance -- the object instance
- propertyName -- the name of the property to bind to
- useGetter: when True, calls the getter method to obtain the value. When False, the signal argument is used as input for the target setter. (default False)
Notes:
2-way binds to an instance property according to one of the following naming conventions:
@property, propertyName.setter and pyqtSignal
- getter: propertyName
- setter: propertyName
- changedSignal: propertyNameChanged
getter, setter and pyqtSignal (this is used when binding to standard QWidgets like QSpinBox)
- getter: propertyName()
- setter: setPropertyName()
- changedSignal: propertyNameChanged
"""
endpoint = BindingEndpoint.forProperty(instance,propertyName,useGetter = useGetter)
self.bindToEndPoint(endpoint) | [
"def",
"bindToProperty",
"(",
"self",
",",
"instance",
",",
"propertyName",
",",
"useGetter",
"=",
"False",
")",
":",
"endpoint",
"=",
"BindingEndpoint",
".",
"forProperty",
"(",
"instance",
",",
"propertyName",
",",
"useGetter",
"=",
"useGetter",
")",
"self",... | 2-way binds to an instance property.
Parameters:
- instance -- the object instance
- propertyName -- the name of the property to bind to
- useGetter: when True, calls the getter method to obtain the value. When False, the signal argument is used as input for the target setter. (default False)
Notes:
2-way binds to an instance property according to one of the following naming conventions:
@property, propertyName.setter and pyqtSignal
- getter: propertyName
- setter: propertyName
- changedSignal: propertyNameChanged
getter, setter and pyqtSignal (this is used when binding to standard QWidgets like QSpinBox)
- getter: propertyName()
- setter: setPropertyName()
- changedSignal: propertyNameChanged | [
"2",
"-",
"way",
"binds",
"to",
"an",
"instance",
"property",
"."
] | train | https://github.com/jkokorian/pyqt2waybinding/blob/fb1fb84f55608cfbf99c6486650100ba81743117/pyqt2waybinding/__init__.py#L142-L166 |
jkokorian/pyqt2waybinding | pyqt2waybinding/__init__.py | Observer._updateEndpoints | def _updateEndpoints(self,*args,**kwargs):
"""
Updates all endpoints except the one from which this slot was called.
Note: this method is probably not complete threadsafe. Maybe a lock is needed when setter self.ignoreEvents
"""
sender = self.sender()
if not self.ignoreEvents:
self.ignoreEvents = True
for binding in self.bindings.values():
if binding.instanceId == id(sender):
continue
if args:
binding.setter(*args,**kwargs)
else:
binding.setter(self.bindings[id(sender)].getter())
self.ignoreEvents = False | python | def _updateEndpoints(self,*args,**kwargs):
"""
Updates all endpoints except the one from which this slot was called.
Note: this method is probably not complete threadsafe. Maybe a lock is needed when setter self.ignoreEvents
"""
sender = self.sender()
if not self.ignoreEvents:
self.ignoreEvents = True
for binding in self.bindings.values():
if binding.instanceId == id(sender):
continue
if args:
binding.setter(*args,**kwargs)
else:
binding.setter(self.bindings[id(sender)].getter())
self.ignoreEvents = False | [
"def",
"_updateEndpoints",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"sender",
"=",
"self",
".",
"sender",
"(",
")",
"if",
"not",
"self",
".",
"ignoreEvents",
":",
"self",
".",
"ignoreEvents",
"=",
"True",
"for",
"binding",
"i... | Updates all endpoints except the one from which this slot was called.
Note: this method is probably not complete threadsafe. Maybe a lock is needed when setter self.ignoreEvents | [
"Updates",
"all",
"endpoints",
"except",
"the",
"one",
"from",
"which",
"this",
"slot",
"was",
"called",
"."
] | train | https://github.com/jkokorian/pyqt2waybinding/blob/fb1fb84f55608cfbf99c6486650100ba81743117/pyqt2waybinding/__init__.py#L168-L188 |
HDI-Project/RDT | rdt/hyper_transformer.py | HyperTransformer._anonymize_table | def _anonymize_table(cls, table_data, pii_fields):
"""Anonymize in `table_data` the fields in `pii_fields`.
Args:
table_data (pandas.DataFrame): Original dataframe/table.
pii_fields (list[dict]): Metadata for the fields to transform.
Result:
pandas.DataFrame: Anonymized table.
"""
for pii_field in pii_fields:
field_name = pii_field['name']
transformer = cls.get_class(TRANSFORMERS['categorical'])(pii_field)
table_data[field_name] = transformer.anonymize_column(table_data)
return table_data | python | def _anonymize_table(cls, table_data, pii_fields):
"""Anonymize in `table_data` the fields in `pii_fields`.
Args:
table_data (pandas.DataFrame): Original dataframe/table.
pii_fields (list[dict]): Metadata for the fields to transform.
Result:
pandas.DataFrame: Anonymized table.
"""
for pii_field in pii_fields:
field_name = pii_field['name']
transformer = cls.get_class(TRANSFORMERS['categorical'])(pii_field)
table_data[field_name] = transformer.anonymize_column(table_data)
return table_data | [
"def",
"_anonymize_table",
"(",
"cls",
",",
"table_data",
",",
"pii_fields",
")",
":",
"for",
"pii_field",
"in",
"pii_fields",
":",
"field_name",
"=",
"pii_field",
"[",
"'name'",
"]",
"transformer",
"=",
"cls",
".",
"get_class",
"(",
"TRANSFORMERS",
"[",
"'c... | Anonymize in `table_data` the fields in `pii_fields`.
Args:
table_data (pandas.DataFrame): Original dataframe/table.
pii_fields (list[dict]): Metadata for the fields to transform.
Result:
pandas.DataFrame: Anonymized table. | [
"Anonymize",
"in",
"table_data",
"the",
"fields",
"in",
"pii_fields",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L59-L74 |
HDI-Project/RDT | rdt/hyper_transformer.py | HyperTransformer._get_tables | def _get_tables(self, base_dir):
"""Load the contents of meta_file and the corresponding data.
If fields containing Personally Identifiable Information are detected in the metadata
they are anonymized before asign them into `table_dict`.
Args:
base_dir(str): Root folder of the dataset files.
Returns:
dict: Mapping str -> tuple(pandas.DataFrame, dict)
"""
table_dict = {}
for table in self.metadata['tables']:
if table['use']:
relative_path = os.path.join(base_dir, self.metadata['path'], table['path'])
data_table = pd.read_csv(relative_path)
pii_fields = self._get_pii_fields(table)
data_table = self._anonymize_table(data_table, pii_fields)
table_dict[table['name']] = (data_table, table)
return table_dict | python | def _get_tables(self, base_dir):
"""Load the contents of meta_file and the corresponding data.
If fields containing Personally Identifiable Information are detected in the metadata
they are anonymized before asign them into `table_dict`.
Args:
base_dir(str): Root folder of the dataset files.
Returns:
dict: Mapping str -> tuple(pandas.DataFrame, dict)
"""
table_dict = {}
for table in self.metadata['tables']:
if table['use']:
relative_path = os.path.join(base_dir, self.metadata['path'], table['path'])
data_table = pd.read_csv(relative_path)
pii_fields = self._get_pii_fields(table)
data_table = self._anonymize_table(data_table, pii_fields)
table_dict[table['name']] = (data_table, table)
return table_dict | [
"def",
"_get_tables",
"(",
"self",
",",
"base_dir",
")",
":",
"table_dict",
"=",
"{",
"}",
"for",
"table",
"in",
"self",
".",
"metadata",
"[",
"'tables'",
"]",
":",
"if",
"table",
"[",
"'use'",
"]",
":",
"relative_path",
"=",
"os",
".",
"path",
".",
... | Load the contents of meta_file and the corresponding data.
If fields containing Personally Identifiable Information are detected in the metadata
they are anonymized before asign them into `table_dict`.
Args:
base_dir(str): Root folder of the dataset files.
Returns:
dict: Mapping str -> tuple(pandas.DataFrame, dict) | [
"Load",
"the",
"contents",
"of",
"meta_file",
"and",
"the",
"corresponding",
"data",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L76-L99 |
HDI-Project/RDT | rdt/hyper_transformer.py | HyperTransformer._get_transformers | def _get_transformers(self):
"""Load the contents of meta_file and extract information about the transformers.
Returns:
dict: tuple(str, str) -> Transformer.
"""
transformer_dict = {}
for table in self.metadata['tables']:
table_name = table['name']
for field in table['fields']:
transformer_type = field.get('type')
if transformer_type:
col_name = field['name']
transformer_dict[(table_name, col_name)] = transformer_type
return transformer_dict | python | def _get_transformers(self):
"""Load the contents of meta_file and extract information about the transformers.
Returns:
dict: tuple(str, str) -> Transformer.
"""
transformer_dict = {}
for table in self.metadata['tables']:
table_name = table['name']
for field in table['fields']:
transformer_type = field.get('type')
if transformer_type:
col_name = field['name']
transformer_dict[(table_name, col_name)] = transformer_type
return transformer_dict | [
"def",
"_get_transformers",
"(",
"self",
")",
":",
"transformer_dict",
"=",
"{",
"}",
"for",
"table",
"in",
"self",
".",
"metadata",
"[",
"'tables'",
"]",
":",
"table_name",
"=",
"table",
"[",
"'name'",
"]",
"for",
"field",
"in",
"table",
"[",
"'fields'"... | Load the contents of meta_file and extract information about the transformers.
Returns:
dict: tuple(str, str) -> Transformer. | [
"Load",
"the",
"contents",
"of",
"meta_file",
"and",
"extract",
"information",
"about",
"the",
"transformers",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L101-L118 |
HDI-Project/RDT | rdt/hyper_transformer.py | HyperTransformer._fit_transform_column | def _fit_transform_column(self, table, metadata, transformer_name, table_name):
"""Transform a column from table using transformer and given parameters.
Args:
table (pandas.DataFrame): Dataframe containing column to transform.
metadata (dict): Metadata for given column.
transformer_name (str): Name of transformer to use on column.
table_name (str): Name of table in original dataset.
Returns:
pandas.DataFrame: Dataframe containing the transformed column. If self.missing=True,
it will contain a second column containing 0 and 1 marking if that
value was originally null or not.
"""
column_name = metadata['name']
content = {}
columns = []
if self.missing and table[column_name].isnull().any():
null_transformer = transformers.NullTransformer(metadata)
clean_column = null_transformer.fit_transform(table[column_name])
null_name = '?' + column_name
columns.append(null_name)
content[null_name] = clean_column[null_name].values
table[column_name] = clean_column[column_name]
transformer_class = self.get_class(transformer_name)
transformer = transformer_class(metadata)
self.transformers[(table_name, column_name)] = transformer
content[column_name] = transformer.fit_transform(table)[column_name].values
columns = [column_name] + columns
return pd.DataFrame(content, columns=columns) | python | def _fit_transform_column(self, table, metadata, transformer_name, table_name):
"""Transform a column from table using transformer and given parameters.
Args:
table (pandas.DataFrame): Dataframe containing column to transform.
metadata (dict): Metadata for given column.
transformer_name (str): Name of transformer to use on column.
table_name (str): Name of table in original dataset.
Returns:
pandas.DataFrame: Dataframe containing the transformed column. If self.missing=True,
it will contain a second column containing 0 and 1 marking if that
value was originally null or not.
"""
column_name = metadata['name']
content = {}
columns = []
if self.missing and table[column_name].isnull().any():
null_transformer = transformers.NullTransformer(metadata)
clean_column = null_transformer.fit_transform(table[column_name])
null_name = '?' + column_name
columns.append(null_name)
content[null_name] = clean_column[null_name].values
table[column_name] = clean_column[column_name]
transformer_class = self.get_class(transformer_name)
transformer = transformer_class(metadata)
self.transformers[(table_name, column_name)] = transformer
content[column_name] = transformer.fit_transform(table)[column_name].values
columns = [column_name] + columns
return pd.DataFrame(content, columns=columns) | [
"def",
"_fit_transform_column",
"(",
"self",
",",
"table",
",",
"metadata",
",",
"transformer_name",
",",
"table_name",
")",
":",
"column_name",
"=",
"metadata",
"[",
"'name'",
"]",
"content",
"=",
"{",
"}",
"columns",
"=",
"[",
"]",
"if",
"self",
".",
"... | Transform a column from table using transformer and given parameters.
Args:
table (pandas.DataFrame): Dataframe containing column to transform.
metadata (dict): Metadata for given column.
transformer_name (str): Name of transformer to use on column.
table_name (str): Name of table in original dataset.
Returns:
pandas.DataFrame: Dataframe containing the transformed column. If self.missing=True,
it will contain a second column containing 0 and 1 marking if that
value was originally null or not. | [
"Transform",
"a",
"column",
"from",
"table",
"using",
"transformer",
"and",
"given",
"parameters",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L141-L175 |
HDI-Project/RDT | rdt/hyper_transformer.py | HyperTransformer._reverse_transform_column | def _reverse_transform_column(self, table, metadata, table_name):
"""Reverses the transformtion on a column from table using the given parameters.
Args:
table (pandas.DataFrame): Dataframe containing column to transform.
metadata (dict): Metadata for given column.
table_name (str): Name of table in original dataset.
Returns:
pandas.DataFrame: Dataframe containing the transformed column. If self.missing=True,
it will contain a second column containing 0 and 1 marking if that
value was originally null or not.
It will return None in the case the column is not in the table.
"""
column_name = metadata['name']
if column_name not in table:
return
null_name = '?' + column_name
content = pd.DataFrame(columns=[column_name], index=table.index)
transformer = self.transformers[(table_name, column_name)]
content[column_name] = transformer.reverse_transform(table[column_name].to_frame())
if self.missing and null_name in table[column_name]:
content[null_name] = table.pop(null_name)
null_transformer = transformers.NullTransformer(metadata)
content[column_name] = null_transformer.reverse_transform(content)
return content | python | def _reverse_transform_column(self, table, metadata, table_name):
"""Reverses the transformtion on a column from table using the given parameters.
Args:
table (pandas.DataFrame): Dataframe containing column to transform.
metadata (dict): Metadata for given column.
table_name (str): Name of table in original dataset.
Returns:
pandas.DataFrame: Dataframe containing the transformed column. If self.missing=True,
it will contain a second column containing 0 and 1 marking if that
value was originally null or not.
It will return None in the case the column is not in the table.
"""
column_name = metadata['name']
if column_name not in table:
return
null_name = '?' + column_name
content = pd.DataFrame(columns=[column_name], index=table.index)
transformer = self.transformers[(table_name, column_name)]
content[column_name] = transformer.reverse_transform(table[column_name].to_frame())
if self.missing and null_name in table[column_name]:
content[null_name] = table.pop(null_name)
null_transformer = transformers.NullTransformer(metadata)
content[column_name] = null_transformer.reverse_transform(content)
return content | [
"def",
"_reverse_transform_column",
"(",
"self",
",",
"table",
",",
"metadata",
",",
"table_name",
")",
":",
"column_name",
"=",
"metadata",
"[",
"'name'",
"]",
"if",
"column_name",
"not",
"in",
"table",
":",
"return",
"null_name",
"=",
"'?'",
"+",
"column_n... | Reverses the transformtion on a column from table using the given parameters.
Args:
table (pandas.DataFrame): Dataframe containing column to transform.
metadata (dict): Metadata for given column.
table_name (str): Name of table in original dataset.
Returns:
pandas.DataFrame: Dataframe containing the transformed column. If self.missing=True,
it will contain a second column containing 0 and 1 marking if that
value was originally null or not.
It will return None in the case the column is not in the table. | [
"Reverses",
"the",
"transformtion",
"on",
"a",
"column",
"from",
"table",
"using",
"the",
"given",
"parameters",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L177-L207 |
HDI-Project/RDT | rdt/hyper_transformer.py | HyperTransformer.fit_transform_table | def fit_transform_table(
self, table, table_meta, transformer_dict=None, transformer_list=None, missing=None):
"""Create, apply and store the specified transformers for `table`.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
transformer_dict(dict): Mapping `tuple(str, str)` -> `str` where the tuple in the
keys represent the (table_name, column_name) and the value
the name of the assigned transformer.
transformer_list(list): List of transformers to use. Overrides the transformers in
the meta_file.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
pandas.DataFrame: Transformed table.
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(DEPRECATION_MESSAGE.format('fit_transform_table'), DeprecationWarning)
result = pd.DataFrame()
table_name = table_meta['name']
for field in table_meta['fields']:
col_name = field['name']
if transformer_list:
for transformer_name in transformer_list:
if field['type'] == self.get_class(transformer_name).type:
transformed = self._fit_transform_column(
table, field, transformer_name, table_name)
result = pd.concat([result, transformed], axis=1)
elif (table_name, col_name) in transformer_dict:
transformer_name = TRANSFORMERS[transformer_dict[(table_name, col_name)]]
transformed = self._fit_transform_column(
table, field, transformer_name, table_name)
result = pd.concat([result, transformed], axis=1)
return result | python | def fit_transform_table(
self, table, table_meta, transformer_dict=None, transformer_list=None, missing=None):
"""Create, apply and store the specified transformers for `table`.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
transformer_dict(dict): Mapping `tuple(str, str)` -> `str` where the tuple in the
keys represent the (table_name, column_name) and the value
the name of the assigned transformer.
transformer_list(list): List of transformers to use. Overrides the transformers in
the meta_file.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
pandas.DataFrame: Transformed table.
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(DEPRECATION_MESSAGE.format('fit_transform_table'), DeprecationWarning)
result = pd.DataFrame()
table_name = table_meta['name']
for field in table_meta['fields']:
col_name = field['name']
if transformer_list:
for transformer_name in transformer_list:
if field['type'] == self.get_class(transformer_name).type:
transformed = self._fit_transform_column(
table, field, transformer_name, table_name)
result = pd.concat([result, transformed], axis=1)
elif (table_name, col_name) in transformer_dict:
transformer_name = TRANSFORMERS[transformer_dict[(table_name, col_name)]]
transformed = self._fit_transform_column(
table, field, transformer_name, table_name)
result = pd.concat([result, transformed], axis=1)
return result | [
"def",
"fit_transform_table",
"(",
"self",
",",
"table",
",",
"table_meta",
",",
"transformer_dict",
"=",
"None",
",",
"transformer_list",
"=",
"None",
",",
"missing",
"=",
"None",
")",
":",
"if",
"missing",
"is",
"None",
":",
"missing",
"=",
"self",
".",
... | Create, apply and store the specified transformers for `table`.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
transformer_dict(dict): Mapping `tuple(str, str)` -> `str` where the tuple in the
keys represent the (table_name, column_name) and the value
the name of the assigned transformer.
transformer_list(list): List of transformers to use. Overrides the transformers in
the meta_file.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
pandas.DataFrame: Transformed table. | [
"Create",
"apply",
"and",
"store",
"the",
"specified",
"transformers",
"for",
"table",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L209-L259 |
HDI-Project/RDT | rdt/hyper_transformer.py | HyperTransformer.transform_table | def transform_table(self, table, table_meta, missing=None):
"""Apply the stored transformers to `table`.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
pandas.DataFrame: Transformed table.
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(DEPRECATION_MESSAGE.format('transform_table'), DeprecationWarning)
content = {}
columns = []
table_name = table_meta['name']
for field in table_meta['fields']:
column_name = field['name']
if missing and table[column_name].isnull().any():
null_transformer = transformers.NullTransformer(field)
clean_column = null_transformer.fit_transform(table[column_name])
null_name = '?' + column_name
columns.append(null_name)
content[null_name] = clean_column[null_name].values
column = clean_column[column_name]
else:
column = table[column_name].to_frame()
transformer = self.transformers[(table_name, column_name)]
content[column_name] = transformer.transform(column)[column_name].values
columns.append(column_name)
return pd.DataFrame(content, columns=columns) | python | def transform_table(self, table, table_meta, missing=None):
"""Apply the stored transformers to `table`.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
pandas.DataFrame: Transformed table.
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(DEPRECATION_MESSAGE.format('transform_table'), DeprecationWarning)
content = {}
columns = []
table_name = table_meta['name']
for field in table_meta['fields']:
column_name = field['name']
if missing and table[column_name].isnull().any():
null_transformer = transformers.NullTransformer(field)
clean_column = null_transformer.fit_transform(table[column_name])
null_name = '?' + column_name
columns.append(null_name)
content[null_name] = clean_column[null_name].values
column = clean_column[column_name]
else:
column = table[column_name].to_frame()
transformer = self.transformers[(table_name, column_name)]
content[column_name] = transformer.transform(column)[column_name].values
columns.append(column_name)
return pd.DataFrame(content, columns=columns) | [
"def",
"transform_table",
"(",
"self",
",",
"table",
",",
"table_meta",
",",
"missing",
"=",
"None",
")",
":",
"if",
"missing",
"is",
"None",
":",
"missing",
"=",
"self",
".",
"missing",
"else",
":",
"self",
".",
"missing",
"=",
"missing",
"warnings",
... | Apply the stored transformers to `table`.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
pandas.DataFrame: Transformed table. | [
"Apply",
"the",
"stored",
"transformers",
"to",
"table",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L261-L304 |
HDI-Project/RDT | rdt/hyper_transformer.py | HyperTransformer.reverse_transform_table | def reverse_transform_table(self, table, table_meta, missing=None):
"""Transform a `table` back to its original format.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
pandas.DataFrame: Table in original format.
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(
DEPRECATION_MESSAGE.format('reverse_transform_table'), DeprecationWarning)
result = pd.DataFrame(index=table.index)
table_name = table_meta['name']
for field in table_meta['fields']:
new_column = self._reverse_transform_column(table, field, table_name)
if new_column is not None:
result[field['name']] = new_column
return result | python | def reverse_transform_table(self, table, table_meta, missing=None):
"""Transform a `table` back to its original format.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
pandas.DataFrame: Table in original format.
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(
DEPRECATION_MESSAGE.format('reverse_transform_table'), DeprecationWarning)
result = pd.DataFrame(index=table.index)
table_name = table_meta['name']
for field in table_meta['fields']:
new_column = self._reverse_transform_column(table, field, table_name)
if new_column is not None:
result[field['name']] = new_column
return result | [
"def",
"reverse_transform_table",
"(",
"self",
",",
"table",
",",
"table_meta",
",",
"missing",
"=",
"None",
")",
":",
"if",
"missing",
"is",
"None",
":",
"missing",
"=",
"self",
".",
"missing",
"else",
":",
"self",
".",
"missing",
"=",
"missing",
"warni... | Transform a `table` back to its original format.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
pandas.DataFrame: Table in original format. | [
"Transform",
"a",
"table",
"back",
"to",
"its",
"original",
"format",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L306-L336 |
HDI-Project/RDT | rdt/hyper_transformer.py | HyperTransformer.fit_transform | def fit_transform(
self, tables=None, transformer_dict=None, transformer_list=None, missing=None):
"""Create, apply and store the specified transformers for the given tables.
Args:
tables(dict): Mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the table data
and the `dict` the corresponding meta information.
If not specified, the tables will be retrieved using the meta_file.
transformer_dict(dict): Mapping `tuple(str, str)` -> `str` where the tuple is
(table_name, column_name).
transformer_list(list): List of transformers to use. Overrides the transformers in
the meta_file.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data).
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(DEPRECATION_MESSAGE.format('fit_transform'), DeprecationWarning)
transformed = {}
if tables is None:
tables = self.table_dict
if transformer_dict is None and transformer_list is None:
transformer_dict = self.transformer_dict
for table_name in tables:
table, table_meta = tables[table_name]
transformed_table = self.fit_transform_table(
table, table_meta, transformer_dict, transformer_list)
transformed[table_name] = transformed_table
return transformed | python | def fit_transform(
self, tables=None, transformer_dict=None, transformer_list=None, missing=None):
"""Create, apply and store the specified transformers for the given tables.
Args:
tables(dict): Mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the table data
and the `dict` the corresponding meta information.
If not specified, the tables will be retrieved using the meta_file.
transformer_dict(dict): Mapping `tuple(str, str)` -> `str` where the tuple is
(table_name, column_name).
transformer_list(list): List of transformers to use. Overrides the transformers in
the meta_file.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data).
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(DEPRECATION_MESSAGE.format('fit_transform'), DeprecationWarning)
transformed = {}
if tables is None:
tables = self.table_dict
if transformer_dict is None and transformer_list is None:
transformer_dict = self.transformer_dict
for table_name in tables:
table, table_meta = tables[table_name]
transformed_table = self.fit_transform_table(
table, table_meta, transformer_dict, transformer_list)
transformed[table_name] = transformed_table
return transformed | [
"def",
"fit_transform",
"(",
"self",
",",
"tables",
"=",
"None",
",",
"transformer_dict",
"=",
"None",
",",
"transformer_list",
"=",
"None",
",",
"missing",
"=",
"None",
")",
":",
"if",
"missing",
"is",
"None",
":",
"missing",
"=",
"self",
".",
"missing"... | Create, apply and store the specified transformers for the given tables.
Args:
tables(dict): Mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the table data
and the `dict` the corresponding meta information.
If not specified, the tables will be retrieved using the meta_file.
transformer_dict(dict): Mapping `tuple(str, str)` -> `str` where the tuple is
(table_name, column_name).
transformer_list(list): List of transformers to use. Overrides the transformers in
the meta_file.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data). | [
"Create",
"apply",
"and",
"store",
"the",
"specified",
"transformers",
"for",
"the",
"given",
"tables",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L338-L382 |
HDI-Project/RDT | rdt/hyper_transformer.py | HyperTransformer.transform | def transform(self, tables, table_metas=None, missing=None):
"""Apply all the saved transformers to `tables`.
Args:
tables(dict): mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the table data
and the `dict` the corresponding meta information.
If not specified, the tables will be retrieved using the meta_file.
table_metas(dict): Full metadata file for the dataset.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data).
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(DEPRECATION_MESSAGE.format('transform'), DeprecationWarning)
transformed = {}
for table_name in tables:
table = tables[table_name]
if table_metas is None:
table_meta = self.table_dict[table_name][1]
else:
table_meta = table_metas[table_name]
transformed[table_name] = self.transform_table(table, table_meta)
return transformed | python | def transform(self, tables, table_metas=None, missing=None):
"""Apply all the saved transformers to `tables`.
Args:
tables(dict): mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the table data
and the `dict` the corresponding meta information.
If not specified, the tables will be retrieved using the meta_file.
table_metas(dict): Full metadata file for the dataset.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data).
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(DEPRECATION_MESSAGE.format('transform'), DeprecationWarning)
transformed = {}
for table_name in tables:
table = tables[table_name]
if table_metas is None:
table_meta = self.table_dict[table_name][1]
else:
table_meta = table_metas[table_name]
transformed[table_name] = self.transform_table(table, table_meta)
return transformed | [
"def",
"transform",
"(",
"self",
",",
"tables",
",",
"table_metas",
"=",
"None",
",",
"missing",
"=",
"None",
")",
":",
"if",
"missing",
"is",
"None",
":",
"missing",
"=",
"self",
".",
"missing",
"else",
":",
"self",
".",
"missing",
"=",
"missing",
"... | Apply all the saved transformers to `tables`.
Args:
tables(dict): mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the table data
and the `dict` the corresponding meta information.
If not specified, the tables will be retrieved using the meta_file.
table_metas(dict): Full metadata file for the dataset.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data). | [
"Apply",
"all",
"the",
"saved",
"transformers",
"to",
"tables",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L384-L420 |
HDI-Project/RDT | rdt/hyper_transformer.py | HyperTransformer.reverse_transform | def reverse_transform(self, tables, table_metas=None, missing=None):
"""Transform data back to its original format.
Args:
tables(dict): mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the transformed
data and the `dict` the corresponding meta information.
If not specified, the tables will be retrieved using the meta_file.
table_metas(dict): Full metadata file for the dataset.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data).
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(DEPRECATION_MESSAGE.format('reverse_transform'), DeprecationWarning)
reverse = {}
for table_name in tables:
table = tables[table_name]
if table_metas is None:
table_meta = self.table_dict[table_name][1]
else:
table_meta = table_metas[table_name]
reverse[table_name] = self.reverse_transform_table(table, table_meta)
return reverse | python | def reverse_transform(self, tables, table_metas=None, missing=None):
"""Transform data back to its original format.
Args:
tables(dict): mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the transformed
data and the `dict` the corresponding meta information.
If not specified, the tables will be retrieved using the meta_file.
table_metas(dict): Full metadata file for the dataset.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data).
"""
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(DEPRECATION_MESSAGE.format('reverse_transform'), DeprecationWarning)
reverse = {}
for table_name in tables:
table = tables[table_name]
if table_metas is None:
table_meta = self.table_dict[table_name][1]
else:
table_meta = table_metas[table_name]
reverse[table_name] = self.reverse_transform_table(table, table_meta)
return reverse | [
"def",
"reverse_transform",
"(",
"self",
",",
"tables",
",",
"table_metas",
"=",
"None",
",",
"missing",
"=",
"None",
")",
":",
"if",
"missing",
"is",
"None",
":",
"missing",
"=",
"self",
".",
"missing",
"else",
":",
"self",
".",
"missing",
"=",
"missi... | Transform data back to its original format.
Args:
tables(dict): mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the transformed
data and the `dict` the corresponding meta information.
If not specified, the tables will be retrieved using the meta_file.
table_metas(dict): Full metadata file for the dataset.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data). | [
"Transform",
"data",
"back",
"to",
"its",
"original",
"format",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/hyper_transformer.py#L422-L457 |
etalab/cada | cada/commands.py | echo | def echo(msg, *args, **kwargs):
'''Wraps click.echo, handles formatting and check encoding'''
file = kwargs.pop('file', None)
nl = kwargs.pop('nl', True)
err = kwargs.pop('err', False)
color = kwargs.pop('color', None)
msg = safe_unicode(msg).format(*args, **kwargs)
click.echo(msg, file=file, nl=nl, err=err, color=color) | python | def echo(msg, *args, **kwargs):
'''Wraps click.echo, handles formatting and check encoding'''
file = kwargs.pop('file', None)
nl = kwargs.pop('nl', True)
err = kwargs.pop('err', False)
color = kwargs.pop('color', None)
msg = safe_unicode(msg).format(*args, **kwargs)
click.echo(msg, file=file, nl=nl, err=err, color=color) | [
"def",
"echo",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"file",
"=",
"kwargs",
".",
"pop",
"(",
"'file'",
",",
"None",
")",
"nl",
"=",
"kwargs",
".",
"pop",
"(",
"'nl'",
",",
"True",
")",
"err",
"=",
"kwargs",
".",
"po... | Wraps click.echo, handles formatting and check encoding | [
"Wraps",
"click",
".",
"echo",
"handles",
"formatting",
"and",
"check",
"encoding"
] | train | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L60-L67 |
etalab/cada | cada/commands.py | header | def header(msg, *args, **kwargs):
'''Display an header'''
msg = ' '.join((yellow(HEADER), white(msg), yellow(HEADER)))
echo(msg, *args, **kwargs) | python | def header(msg, *args, **kwargs):
'''Display an header'''
msg = ' '.join((yellow(HEADER), white(msg), yellow(HEADER)))
echo(msg, *args, **kwargs) | [
"def",
"header",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"' '",
".",
"join",
"(",
"(",
"yellow",
"(",
"HEADER",
")",
",",
"white",
"(",
"msg",
")",
",",
"yellow",
"(",
"HEADER",
")",
")",
")",
"echo",
"(",... | Display an header | [
"Display",
"an",
"header"
] | train | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L70-L73 |
etalab/cada | cada/commands.py | success | def success(msg, *args, **kwargs):
'''Display a success message'''
echo('{0} {1}'.format(green(OK), white(msg)), *args, **kwargs) | python | def success(msg, *args, **kwargs):
'''Display a success message'''
echo('{0} {1}'.format(green(OK), white(msg)), *args, **kwargs) | [
"def",
"success",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"echo",
"(",
"'{0} {1}'",
".",
"format",
"(",
"green",
"(",
"OK",
")",
",",
"white",
"(",
"msg",
")",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Display a success message | [
"Display",
"a",
"success",
"message"
] | train | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L76-L78 |
etalab/cada | cada/commands.py | warning | def warning(msg, *args, **kwargs):
'''Display a warning message'''
msg = '{0} {1}'.format(yellow(WARNING), msg)
echo(msg, *args, **kwargs) | python | def warning(msg, *args, **kwargs):
'''Display a warning message'''
msg = '{0} {1}'.format(yellow(WARNING), msg)
echo(msg, *args, **kwargs) | [
"def",
"warning",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"'{0} {1}'",
".",
"format",
"(",
"yellow",
"(",
"WARNING",
")",
",",
"msg",
")",
"echo",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Display a warning message | [
"Display",
"a",
"warning",
"message"
] | train | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L81-L84 |
etalab/cada | cada/commands.py | error | def error(msg, details=None, *args, **kwargs):
'''Display an error message with optionnal details'''
msg = '{0} {1}'.format(red(KO), white(msg))
if details:
msg = '\n'.join((msg, safe_unicode(details)))
echo(format_multiline(msg), *args, **kwargs) | python | def error(msg, details=None, *args, **kwargs):
'''Display an error message with optionnal details'''
msg = '{0} {1}'.format(red(KO), white(msg))
if details:
msg = '\n'.join((msg, safe_unicode(details)))
echo(format_multiline(msg), *args, **kwargs) | [
"def",
"error",
"(",
"msg",
",",
"details",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"'{0} {1}'",
".",
"format",
"(",
"red",
"(",
"KO",
")",
",",
"white",
"(",
"msg",
")",
")",
"if",
"details",
":",
"msg",
... | Display an error message with optionnal details | [
"Display",
"an",
"error",
"message",
"with",
"optionnal",
"details"
] | train | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L87-L92 |
etalab/cada | cada/commands.py | exit_with_error | def exit_with_error(msg='Aborted', details=None, code=-1, *args, **kwargs):
'''Exit with error'''
error(msg, details=details, *args, **kwargs)
sys.exit(code) | python | def exit_with_error(msg='Aborted', details=None, code=-1, *args, **kwargs):
'''Exit with error'''
error(msg, details=details, *args, **kwargs)
sys.exit(code) | [
"def",
"exit_with_error",
"(",
"msg",
"=",
"'Aborted'",
",",
"details",
"=",
"None",
",",
"code",
"=",
"-",
"1",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"error",
"(",
"msg",
",",
"details",
"=",
"details",
",",
"*",
"args",
",",
"*",... | Exit with error | [
"Exit",
"with",
"error"
] | train | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L95-L98 |
etalab/cada | cada/commands.py | load | def load(patterns, full_reindex):
'''
Load one or more CADA CSV files matching patterns
'''
header('Loading CSV files')
for pattern in patterns:
for filename in iglob(pattern):
echo('Loading {}'.format(white(filename)))
with open(filename) as f:
reader = csv.reader(f)
# Skip header
reader.next()
for idx, row in enumerate(reader, 1):
try:
advice = csv.from_row(row)
skipped = False
if not full_reindex:
index(advice)
echo('.' if idx % 50 else white(idx), nl=False)
except Exception:
echo(cyan('s') if idx % 50 else white('{0}(s)'.format(idx)), nl=False)
skipped = True
if skipped:
echo(white('{}(s)'.format(idx)) if idx % 50 else '')
else:
echo(white(idx) if idx % 50 else '')
success('Processed {0} rows'.format(idx))
if full_reindex:
reindex() | python | def load(patterns, full_reindex):
'''
Load one or more CADA CSV files matching patterns
'''
header('Loading CSV files')
for pattern in patterns:
for filename in iglob(pattern):
echo('Loading {}'.format(white(filename)))
with open(filename) as f:
reader = csv.reader(f)
# Skip header
reader.next()
for idx, row in enumerate(reader, 1):
try:
advice = csv.from_row(row)
skipped = False
if not full_reindex:
index(advice)
echo('.' if idx % 50 else white(idx), nl=False)
except Exception:
echo(cyan('s') if idx % 50 else white('{0}(s)'.format(idx)), nl=False)
skipped = True
if skipped:
echo(white('{}(s)'.format(idx)) if idx % 50 else '')
else:
echo(white(idx) if idx % 50 else '')
success('Processed {0} rows'.format(idx))
if full_reindex:
reindex() | [
"def",
"load",
"(",
"patterns",
",",
"full_reindex",
")",
":",
"header",
"(",
"'Loading CSV files'",
")",
"for",
"pattern",
"in",
"patterns",
":",
"for",
"filename",
"in",
"iglob",
"(",
"pattern",
")",
":",
"echo",
"(",
"'Loading {}'",
".",
"format",
"(",
... | Load one or more CADA CSV files matching patterns | [
"Load",
"one",
"or",
"more",
"CADA",
"CSV",
"files",
"matching",
"patterns"
] | train | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L147-L175 |
etalab/cada | cada/commands.py | reindex | def reindex():
'''Reindex all advices'''
header('Reindexing all advices')
echo('Deleting index {0}', white(es.index_name))
if es.indices.exists(es.index_name):
es.indices.delete(index=es.index_name)
es.initialize()
idx = 0
for idx, advice in enumerate(Advice.objects, 1):
index(advice)
echo('.' if idx % 50 else white(idx), nl=False)
echo(white(idx) if idx % 50 else '')
es.indices.refresh(index=es.index_name)
success('Indexed {0} advices', idx) | python | def reindex():
'''Reindex all advices'''
header('Reindexing all advices')
echo('Deleting index {0}', white(es.index_name))
if es.indices.exists(es.index_name):
es.indices.delete(index=es.index_name)
es.initialize()
idx = 0
for idx, advice in enumerate(Advice.objects, 1):
index(advice)
echo('.' if idx % 50 else white(idx), nl=False)
echo(white(idx) if idx % 50 else '')
es.indices.refresh(index=es.index_name)
success('Indexed {0} advices', idx) | [
"def",
"reindex",
"(",
")",
":",
"header",
"(",
"'Reindexing all advices'",
")",
"echo",
"(",
"'Deleting index {0}'",
",",
"white",
"(",
"es",
".",
"index_name",
")",
")",
"if",
"es",
".",
"indices",
".",
"exists",
"(",
"es",
".",
"index_name",
")",
":",... | Reindex all advices | [
"Reindex",
"all",
"advices"
] | train | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L179-L193 |
etalab/cada | cada/commands.py | static | def static(path, no_input):
'''Compile and collect static files into path'''
log = logging.getLogger('webassets')
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
cmdenv = CommandLineEnvironment(assets, log)
cmdenv.build()
if exists(path):
warning('{0} directory already exists and will be {1}', white(path), white('erased'))
if not no_input and not click.confirm('Are you sure'):
exit_with_error()
shutil.rmtree(path)
echo('Copying assets into {0}', white(path))
shutil.copytree(assets.directory, path)
success('Done') | python | def static(path, no_input):
'''Compile and collect static files into path'''
log = logging.getLogger('webassets')
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
cmdenv = CommandLineEnvironment(assets, log)
cmdenv.build()
if exists(path):
warning('{0} directory already exists and will be {1}', white(path), white('erased'))
if not no_input and not click.confirm('Are you sure'):
exit_with_error()
shutil.rmtree(path)
echo('Copying assets into {0}', white(path))
shutil.copytree(assets.directory, path)
success('Done') | [
"def",
"static",
"(",
"path",
",",
"no_input",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'webassets'",
")",
"log",
".",
"addHandler",
"(",
"logging",
".",
"StreamHandler",
"(",
")",
")",
"log",
".",
"setLevel",
"(",
"logging",
".",
"DEBU... | Compile and collect static files into path | [
"Compile",
"and",
"collect",
"static",
"files",
"into",
"path"
] | train | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L199-L217 |
etalab/cada | cada/commands.py | anon | def anon():
'''Check for candidates to anonymization'''
header(anon.__doc__)
filename = 'urls_to_check.csv'
candidates = Advice.objects(__raw__={
'$or': [
{'subject': {
'$regex': '(Monsieur|Madame|Docteur|Mademoiselle)\s+[^X\s\.]{3}',
'$options': 'imx',
}},
{'content': {
'$regex': '(Monsieur|Madame|Docteur|Mademoiselle)\s+[^X\s\.]{3}',
'$options': 'imx',
}}
]
})
with open(filename, 'wb') as csvfile:
writer = csv.writer(csvfile)
# Generate header
writer.writerow(csv.ANON_HEADER)
for idx, advice in enumerate(candidates, 1):
writer.writerow(csv.to_anon_row(advice))
echo('.' if idx % 50 else white(idx), nl=False)
echo(white(idx) if idx % 50 else '')
success('Total: {0} candidates', len(candidates)) | python | def anon():
'''Check for candidates to anonymization'''
header(anon.__doc__)
filename = 'urls_to_check.csv'
candidates = Advice.objects(__raw__={
'$or': [
{'subject': {
'$regex': '(Monsieur|Madame|Docteur|Mademoiselle)\s+[^X\s\.]{3}',
'$options': 'imx',
}},
{'content': {
'$regex': '(Monsieur|Madame|Docteur|Mademoiselle)\s+[^X\s\.]{3}',
'$options': 'imx',
}}
]
})
with open(filename, 'wb') as csvfile:
writer = csv.writer(csvfile)
# Generate header
writer.writerow(csv.ANON_HEADER)
for idx, advice in enumerate(candidates, 1):
writer.writerow(csv.to_anon_row(advice))
echo('.' if idx % 50 else white(idx), nl=False)
echo(white(idx) if idx % 50 else '')
success('Total: {0} candidates', len(candidates)) | [
"def",
"anon",
"(",
")",
":",
"header",
"(",
"anon",
".",
"__doc__",
")",
"filename",
"=",
"'urls_to_check.csv'",
"candidates",
"=",
"Advice",
".",
"objects",
"(",
"__raw__",
"=",
"{",
"'$or'",
":",
"[",
"{",
"'subject'",
":",
"{",
"'$regex'",
":",
"'(... | Check for candidates to anonymization | [
"Check",
"for",
"candidates",
"to",
"anonymization"
] | train | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L221-L249 |
etalab/cada | cada/commands.py | fix | def fix(csvfile):
'''Apply a fix (ie. remove plain names)'''
header('Apply fixes from {}', csvfile.name)
bads = []
reader = csv.reader(csvfile)
reader.next() # Skip header
for id, _, sources, dests in reader:
advice = Advice.objects.get(id=id)
sources = [s.strip() for s in sources.split(',') if s.strip()]
dests = [d.strip() for d in dests.split(',') if d.strip()]
if not len(sources) == len(dests):
bads.append(id)
continue
for source, dest in zip(sources, dests):
echo('{0}: Replace {1} with {2}', white(id), white(source), white(dest))
advice.subject = advice.subject.replace(source, dest)
advice.content = advice.content.replace(source, dest)
advice.save()
index(advice)
for id in bads:
echo('{0}: Replacements length not matching', white(id))
success('Done') | python | def fix(csvfile):
'''Apply a fix (ie. remove plain names)'''
header('Apply fixes from {}', csvfile.name)
bads = []
reader = csv.reader(csvfile)
reader.next() # Skip header
for id, _, sources, dests in reader:
advice = Advice.objects.get(id=id)
sources = [s.strip() for s in sources.split(',') if s.strip()]
dests = [d.strip() for d in dests.split(',') if d.strip()]
if not len(sources) == len(dests):
bads.append(id)
continue
for source, dest in zip(sources, dests):
echo('{0}: Replace {1} with {2}', white(id), white(source), white(dest))
advice.subject = advice.subject.replace(source, dest)
advice.content = advice.content.replace(source, dest)
advice.save()
index(advice)
for id in bads:
echo('{0}: Replacements length not matching', white(id))
success('Done') | [
"def",
"fix",
"(",
"csvfile",
")",
":",
"header",
"(",
"'Apply fixes from {}'",
",",
"csvfile",
".",
"name",
")",
"bads",
"=",
"[",
"]",
"reader",
"=",
"csv",
".",
"reader",
"(",
"csvfile",
")",
"reader",
".",
"next",
"(",
")",
"# Skip header",
"for",
... | Apply a fix (ie. remove plain names) | [
"Apply",
"a",
"fix",
"(",
"ie",
".",
"remove",
"plain",
"names",
")"
] | train | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L254-L275 |
raphaelgyory/django-rest-messaging-centrifugo | rest_messaging_centrifugo/utils.py | build_channel | def build_channel(namespace, name, user_ids):
""" Creates complete channel information as described here https://fzambia.gitbooks.io/centrifugal/content/server/channels.html. """
ids = ','.join(map(str, user_ids))
return "{0}:{1}#{2}".format(namespace, name, ids) | python | def build_channel(namespace, name, user_ids):
""" Creates complete channel information as described here https://fzambia.gitbooks.io/centrifugal/content/server/channels.html. """
ids = ','.join(map(str, user_ids))
return "{0}:{1}#{2}".format(namespace, name, ids) | [
"def",
"build_channel",
"(",
"namespace",
",",
"name",
",",
"user_ids",
")",
":",
"ids",
"=",
"','",
".",
"join",
"(",
"map",
"(",
"str",
",",
"user_ids",
")",
")",
"return",
"\"{0}:{1}#{2}\"",
".",
"format",
"(",
"namespace",
",",
"name",
",",
"ids",
... | Creates complete channel information as described here https://fzambia.gitbooks.io/centrifugal/content/server/channels.html. | [
"Creates",
"complete",
"channel",
"information",
"as",
"described",
"here",
"https",
":",
"//",
"fzambia",
".",
"gitbooks",
".",
"io",
"/",
"centrifugal",
"/",
"content",
"/",
"server",
"/",
"channels",
".",
"html",
"."
] | train | https://github.com/raphaelgyory/django-rest-messaging-centrifugo/blob/f44022cd9fc83e84ab573fe8a8385c85f6e77380/rest_messaging_centrifugo/utils.py#L8-L11 |
deepgram/deepgram-brain-python | deepgram/connection.py | Brain.login | def login(self, **kwargs):
"""Logs the current user into the server with the passed in credentials. If successful the apiToken will be changed to match the passed in credentials.
:param apiToken: use the passed apiToken to authenticate
:param user_id: optional instead of apiToken, must be passed with token
:param token: optional instead of apiToken, must be passed with user_id
:param authenticate: only valid with apiToken. Force a call to the server to authenticate the passed credentials.
:return:
"""
if 'signed_username' in kwargs:
apiToken = kwargs['signed_username']
if kwargs.get('authenticate', False):
self._checkReturn(requests.get("{}/users?signed_username={}".format(self.url, apiToken)))
self.signedUsername = apiToken
else:
auth = (kwargs['user_id'], kwargs['token'])
self.signedUsername = self._checkReturn(requests.get("{}/users/login".format(self.url), auth=auth))[
'signed_username'] | python | def login(self, **kwargs):
"""Logs the current user into the server with the passed in credentials. If successful the apiToken will be changed to match the passed in credentials.
:param apiToken: use the passed apiToken to authenticate
:param user_id: optional instead of apiToken, must be passed with token
:param token: optional instead of apiToken, must be passed with user_id
:param authenticate: only valid with apiToken. Force a call to the server to authenticate the passed credentials.
:return:
"""
if 'signed_username' in kwargs:
apiToken = kwargs['signed_username']
if kwargs.get('authenticate', False):
self._checkReturn(requests.get("{}/users?signed_username={}".format(self.url, apiToken)))
self.signedUsername = apiToken
else:
auth = (kwargs['user_id'], kwargs['token'])
self.signedUsername = self._checkReturn(requests.get("{}/users/login".format(self.url), auth=auth))[
'signed_username'] | [
"def",
"login",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'signed_username'",
"in",
"kwargs",
":",
"apiToken",
"=",
"kwargs",
"[",
"'signed_username'",
"]",
"if",
"kwargs",
".",
"get",
"(",
"'authenticate'",
",",
"False",
")",
":",
"self",
... | Logs the current user into the server with the passed in credentials. If successful the apiToken will be changed to match the passed in credentials.
:param apiToken: use the passed apiToken to authenticate
:param user_id: optional instead of apiToken, must be passed with token
:param token: optional instead of apiToken, must be passed with user_id
:param authenticate: only valid with apiToken. Force a call to the server to authenticate the passed credentials.
:return: | [
"Logs",
"the",
"current",
"user",
"into",
"the",
"server",
"with",
"the",
"passed",
"in",
"credentials",
".",
"If",
"successful",
"the",
"apiToken",
"will",
"be",
"changed",
"to",
"match",
"the",
"passed",
"in",
"credentials",
"."
] | train | https://github.com/deepgram/deepgram-brain-python/blob/030ba241186a762a3faf73cec9af92063f3a7524/deepgram/connection.py#L48-L65 |
deepgram/deepgram-brain-python | deepgram/connection.py | Brain.createAssetFromURL | def createAssetFromURL(self, url, async=False, metadata=None, callback=None):
"""Users the passed URL to load data. If async=false a json with the result is returned otherwise a json with an asset_id is returned.
:param url:
:param metadata: arbitrary additional description information for the asset
:param async:
:param callback: Callback URL
:return:
"""
audio = {'uri': url}
config = {'async': async}
if callback is not None:
config['callback'] = callback
if metadata is not None:
body = {'audio': audio, 'config': config, 'metadata': metadata}
else:
body = {'audio': audio, 'config': config}
return self._checkReturn(
requests.post("{}/speech:recognize?signed_username={}".format(self.url, self.signedUsername), json=body)) | python | def createAssetFromURL(self, url, async=False, metadata=None, callback=None):
"""Users the passed URL to load data. If async=false a json with the result is returned otherwise a json with an asset_id is returned.
:param url:
:param metadata: arbitrary additional description information for the asset
:param async:
:param callback: Callback URL
:return:
"""
audio = {'uri': url}
config = {'async': async}
if callback is not None:
config['callback'] = callback
if metadata is not None:
body = {'audio': audio, 'config': config, 'metadata': metadata}
else:
body = {'audio': audio, 'config': config}
return self._checkReturn(
requests.post("{}/speech:recognize?signed_username={}".format(self.url, self.signedUsername), json=body)) | [
"def",
"createAssetFromURL",
"(",
"self",
",",
"url",
",",
"async",
"=",
"False",
",",
"metadata",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"audio",
"=",
"{",
"'uri'",
":",
"url",
"}",
"config",
"=",
"{",
"'async'",
":",
"async",
"}",
"... | Users the passed URL to load data. If async=false a json with the result is returned otherwise a json with an asset_id is returned.
:param url:
:param metadata: arbitrary additional description information for the asset
:param async:
:param callback: Callback URL
:return: | [
"Users",
"the",
"passed",
"URL",
"to",
"load",
"data",
".",
"If",
"async",
"=",
"false",
"a",
"json",
"with",
"the",
"result",
"is",
"returned",
"otherwise",
"a",
"json",
"with",
"an",
"asset_id",
"is",
"returned",
"."
] | train | https://github.com/deepgram/deepgram-brain-python/blob/030ba241186a762a3faf73cec9af92063f3a7524/deepgram/connection.py#L93-L112 |
deepgram/deepgram-brain-python | deepgram/connection.py | Brain.uploadAsset | def uploadAsset(self, data, async=False, metadata=None, callback=None):
"""Takes an array of bytes or a BufferedReader and uploads it. If async=false a json with the result is returned otherwise a json with an asset_id is returned.
:param data: array of bytes or BufferedReader
:param metadata: arbitrary additional description information for the asset
:param async:
:param callback: Callback URL
:return:
"""
#todo: has atter read would be better here
if isinstance(data, io.BufferedReader):
data = data.read()
assert isinstance(data, bytes)
data = base64.b64encode(data)
audio = {'content': data.decode("utf-8")}
config = {'async': async}
if callback is not None:
config['callback'] = callback
if metadata is not None:
body = {'audio': audio, 'config': config, 'metadata': metadata}
else:
body = {'audio': audio, 'config': config}
return self._checkReturn(
requests.post("{}/speech:recognize?signed_username={}".format(self.url, self.signedUsername), json=body)) | python | def uploadAsset(self, data, async=False, metadata=None, callback=None):
"""Takes an array of bytes or a BufferedReader and uploads it. If async=false a json with the result is returned otherwise a json with an asset_id is returned.
:param data: array of bytes or BufferedReader
:param metadata: arbitrary additional description information for the asset
:param async:
:param callback: Callback URL
:return:
"""
#todo: has atter read would be better here
if isinstance(data, io.BufferedReader):
data = data.read()
assert isinstance(data, bytes)
data = base64.b64encode(data)
audio = {'content': data.decode("utf-8")}
config = {'async': async}
if callback is not None:
config['callback'] = callback
if metadata is not None:
body = {'audio': audio, 'config': config, 'metadata': metadata}
else:
body = {'audio': audio, 'config': config}
return self._checkReturn(
requests.post("{}/speech:recognize?signed_username={}".format(self.url, self.signedUsername), json=body)) | [
"def",
"uploadAsset",
"(",
"self",
",",
"data",
",",
"async",
"=",
"False",
",",
"metadata",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"#todo: has atter read would be better here",
"if",
"isinstance",
"(",
"data",
",",
"io",
".",
"BufferedReader",
... | Takes an array of bytes or a BufferedReader and uploads it. If async=false a json with the result is returned otherwise a json with an asset_id is returned.
:param data: array of bytes or BufferedReader
:param metadata: arbitrary additional description information for the asset
:param async:
:param callback: Callback URL
:return: | [
"Takes",
"an",
"array",
"of",
"bytes",
"or",
"a",
"BufferedReader",
"and",
"uploads",
"it",
".",
"If",
"async",
"=",
"false",
"a",
"json",
"with",
"the",
"result",
"is",
"returned",
"otherwise",
"a",
"json",
"with",
"an",
"asset_id",
"is",
"returned",
".... | train | https://github.com/deepgram/deepgram-brain-python/blob/030ba241186a762a3faf73cec9af92063f3a7524/deepgram/connection.py#L117-L141 |
lambdalisue/e4u | e4u/__init__.py | load | def load(filename=None,
url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml",
loader_class=None):
u"""load google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library. this method never work twice if you want to reload, use `e4u.reload()` insted."""
if not has_loaded():
reload(filename, url, loader_class) | python | def load(filename=None,
url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml",
loader_class=None):
u"""load google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library. this method never work twice if you want to reload, use `e4u.reload()` insted."""
if not has_loaded():
reload(filename, url, loader_class) | [
"def",
"load",
"(",
"filename",
"=",
"None",
",",
"url",
"=",
"r\"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml\"",
",",
"loader_class",
"=",
"None",
")",
":",
"if",
"not",
"has_loaded",
"(",
")",
":",
"reload",
"(",
"filenam... | u"""load google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library. this method never work twice if you want to reload, use `e4u.reload()` insted. | [
"u",
"load",
"google",
"s",
"emoji4unicode",
"project",
"s",
"xml",
"file",
".",
"must",
"call",
"this",
"method",
"first",
"to",
"use",
"e4u",
"library",
".",
"this",
"method",
"never",
"work",
"twice",
"if",
"you",
"want",
"to",
"reload",
"use",
"e4u",... | train | https://github.com/lambdalisue/e4u/blob/108635c5ba37e7ae33001adbf07a95878f31fd50/e4u/__init__.py#L14-L19 |
lambdalisue/e4u | e4u/__init__.py | reload | def reload(filename=None,
url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml",
loader_class=None):
u"""reload google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library."""
if loader_class is None:
loader_class = loader.Loader
global _loader
_loader = loader_class()
_loader.load(filename, url) | python | def reload(filename=None,
url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml",
loader_class=None):
u"""reload google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library."""
if loader_class is None:
loader_class = loader.Loader
global _loader
_loader = loader_class()
_loader.load(filename, url) | [
"def",
"reload",
"(",
"filename",
"=",
"None",
",",
"url",
"=",
"r\"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml\"",
",",
"loader_class",
"=",
"None",
")",
":",
"if",
"loader_class",
"is",
"None",
":",
"loader_class",
"=",
"lo... | u"""reload google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library. | [
"u",
"reload",
"google",
"s",
"emoji4unicode",
"project",
"s",
"xml",
"file",
".",
"must",
"call",
"this",
"method",
"first",
"to",
"use",
"e4u",
"library",
"."
] | train | https://github.com/lambdalisue/e4u/blob/108635c5ba37e7ae33001adbf07a95878f31fd50/e4u/__init__.py#L21-L29 |
lambdalisue/e4u | e4u/__init__.py | translate_char | def translate_char(source_char, carrier, reverse=False, encoding=False):
u"""translate unicode emoji character to unicode carrier emoji character (or reverse)
Attributes:
source_char - emoji character. it must be unicode instance or have to set `encoding` attribute to decode
carrier - the target carrier
reverse - if you want to translate CARRIER => UNICODE, turn it True
encoding - encoding name for decode (Default is None)
"""
if not isinstance(source_char, unicode) and encoding:
source_char = source_char.decode(encoding, 'replace')
elif not isinstance(source_char, unicode):
raise AttributeError(u"`source_char` must be decoded to `unicode` or set `encoding` attribute to decode `source_char`")
if len(source_char) > 1:
raise AttributeError(u"`source_char` must be a letter. use `translate` method insted.")
translate_dictionary = _loader.translate_dictionaries[carrier]
if not reverse:
translate_dictionary = translate_dictionary[0]
else:
translate_dictionary = translate_dictionary[1]
if not translate_dictionary:
return source_char
return translate_dictionary.get(source_char, source_char) | python | def translate_char(source_char, carrier, reverse=False, encoding=False):
u"""translate unicode emoji character to unicode carrier emoji character (or reverse)
Attributes:
source_char - emoji character. it must be unicode instance or have to set `encoding` attribute to decode
carrier - the target carrier
reverse - if you want to translate CARRIER => UNICODE, turn it True
encoding - encoding name for decode (Default is None)
"""
if not isinstance(source_char, unicode) and encoding:
source_char = source_char.decode(encoding, 'replace')
elif not isinstance(source_char, unicode):
raise AttributeError(u"`source_char` must be decoded to `unicode` or set `encoding` attribute to decode `source_char`")
if len(source_char) > 1:
raise AttributeError(u"`source_char` must be a letter. use `translate` method insted.")
translate_dictionary = _loader.translate_dictionaries[carrier]
if not reverse:
translate_dictionary = translate_dictionary[0]
else:
translate_dictionary = translate_dictionary[1]
if not translate_dictionary:
return source_char
return translate_dictionary.get(source_char, source_char) | [
"def",
"translate_char",
"(",
"source_char",
",",
"carrier",
",",
"reverse",
"=",
"False",
",",
"encoding",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"source_char",
",",
"unicode",
")",
"and",
"encoding",
":",
"source_char",
"=",
"source_char",... | u"""translate unicode emoji character to unicode carrier emoji character (or reverse)
Attributes:
source_char - emoji character. it must be unicode instance or have to set `encoding` attribute to decode
carrier - the target carrier
reverse - if you want to translate CARRIER => UNICODE, turn it True
encoding - encoding name for decode (Default is None) | [
"u",
"translate",
"unicode",
"emoji",
"character",
"to",
"unicode",
"carrier",
"emoji",
"character",
"(",
"or",
"reverse",
")",
"Attributes",
":",
"source_char",
"-",
"emoji",
"character",
".",
"it",
"must",
"be",
"unicode",
"instance",
"or",
"have",
"to",
"... | train | https://github.com/lambdalisue/e4u/blob/108635c5ba37e7ae33001adbf07a95878f31fd50/e4u/__init__.py#L40-L63 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.