repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
rushter/heamy
heamy/pipeline.py
ModelsPipeline.weight
def weight(self, weights): """Applies weighted mean to models. Parameters ---------- weights : list Returns ------- np.ndarray Examples ---------- >>> pipeline = ModelsPipeline(model_rf,model_lr) >>> pipeline.weight([0.8,0.2]) """ return self.apply(lambda x: np.average(x, axis=0, weights=weights))
python
def weight(self, weights): """Applies weighted mean to models. Parameters ---------- weights : list Returns ------- np.ndarray Examples ---------- >>> pipeline = ModelsPipeline(model_rf,model_lr) >>> pipeline.weight([0.8,0.2]) """ return self.apply(lambda x: np.average(x, axis=0, weights=weights))
[ "def", "weight", "(", "self", ",", "weights", ")", ":", "return", "self", ".", "apply", "(", "lambda", "x", ":", "np", ".", "average", "(", "x", ",", "axis", "=", "0", ",", "weights", "=", "weights", ")", ")" ]
Applies weighted mean to models. Parameters ---------- weights : list Returns ------- np.ndarray Examples ---------- >>> pipeline = ModelsPipeline(model_rf,model_lr) >>> pipeline.weight([0.8,0.2])
[ "Applies", "weighted", "mean", "to", "models", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/pipeline.py#L230-L246
train
200,200
rushter/heamy
heamy/feature.py
onehot_features
def onehot_features(train, test, features, full=False, sparse=False, dummy_na=True): """Encode categorical features using a one-hot scheme. Parameters ---------- train : pd.DataFrame test : pd.DataFrame features : list Column names in the DataFrame to be encoded. full : bool, default False Whether use all columns from train/test or only from train. sparse : bool, default False Whether the dummy columns should be sparse or not. dummy_na : bool, default True Add a column to indicate NaNs, if False NaNs are ignored. Returns ------- train : pd.DataFrame test : pd.DataFrame """ features = [f for f in features if f in train.columns] for column in features: if full: categories = pd.concat([train[column], test[column]]).dropna().unique() else: categories = train[column].dropna().unique() train[column] = train[column].astype('category', categories=categories) test[column] = test[column].astype('category', categories=categories) train = pd.get_dummies(train, columns=features, dummy_na=dummy_na, sparse=sparse) test = pd.get_dummies(test, columns=features, dummy_na=dummy_na, sparse=sparse) # d_cols = train.columns[(train == 0).all()] # train.drop(d_cols, 1, inplace=True) # test.drop(d_cols, 1, inplace=True) return train, test
python
def onehot_features(train, test, features, full=False, sparse=False, dummy_na=True): """Encode categorical features using a one-hot scheme. Parameters ---------- train : pd.DataFrame test : pd.DataFrame features : list Column names in the DataFrame to be encoded. full : bool, default False Whether use all columns from train/test or only from train. sparse : bool, default False Whether the dummy columns should be sparse or not. dummy_na : bool, default True Add a column to indicate NaNs, if False NaNs are ignored. Returns ------- train : pd.DataFrame test : pd.DataFrame """ features = [f for f in features if f in train.columns] for column in features: if full: categories = pd.concat([train[column], test[column]]).dropna().unique() else: categories = train[column].dropna().unique() train[column] = train[column].astype('category', categories=categories) test[column] = test[column].astype('category', categories=categories) train = pd.get_dummies(train, columns=features, dummy_na=dummy_na, sparse=sparse) test = pd.get_dummies(test, columns=features, dummy_na=dummy_na, sparse=sparse) # d_cols = train.columns[(train == 0).all()] # train.drop(d_cols, 1, inplace=True) # test.drop(d_cols, 1, inplace=True) return train, test
[ "def", "onehot_features", "(", "train", ",", "test", ",", "features", ",", "full", "=", "False", ",", "sparse", "=", "False", ",", "dummy_na", "=", "True", ")", ":", "features", "=", "[", "f", "for", "f", "in", "features", "if", "f", "in", "train", ...
Encode categorical features using a one-hot scheme. Parameters ---------- train : pd.DataFrame test : pd.DataFrame features : list Column names in the DataFrame to be encoded. full : bool, default False Whether use all columns from train/test or only from train. sparse : bool, default False Whether the dummy columns should be sparse or not. dummy_na : bool, default True Add a column to indicate NaNs, if False NaNs are ignored. Returns ------- train : pd.DataFrame test : pd.DataFrame
[ "Encode", "categorical", "features", "using", "a", "one", "-", "hot", "scheme", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/feature.py#L10-L49
train
200,201
rushter/heamy
heamy/feature.py
factorize
def factorize(train, test, features, na_value=-9999, full=False, sort=True): """Factorize categorical features. Parameters ---------- train : pd.DataFrame test : pd.DataFrame features : list Column names in the DataFrame to be encoded. na_value : int, default -9999 full : bool, default False Whether use all columns from train/test or only from train. sort : bool, default True Sort by values. Returns ------- train : pd.DataFrame test : pd.DataFrame """ for column in features: if full: vs = pd.concat([train[column], test[column]]) labels, indexer = pd.factorize(vs, sort=sort) else: labels, indexer = pd.factorize(train[column], sort=sort) train[column] = indexer.get_indexer(train[column]) test[column] = indexer.get_indexer(test[column]) if na_value != -1: train[column] = train[column].replace(-1, na_value) test[column] = test[column].replace(-1, na_value) return train, test
python
def factorize(train, test, features, na_value=-9999, full=False, sort=True): """Factorize categorical features. Parameters ---------- train : pd.DataFrame test : pd.DataFrame features : list Column names in the DataFrame to be encoded. na_value : int, default -9999 full : bool, default False Whether use all columns from train/test or only from train. sort : bool, default True Sort by values. Returns ------- train : pd.DataFrame test : pd.DataFrame """ for column in features: if full: vs = pd.concat([train[column], test[column]]) labels, indexer = pd.factorize(vs, sort=sort) else: labels, indexer = pd.factorize(train[column], sort=sort) train[column] = indexer.get_indexer(train[column]) test[column] = indexer.get_indexer(test[column]) if na_value != -1: train[column] = train[column].replace(-1, na_value) test[column] = test[column].replace(-1, na_value) return train, test
[ "def", "factorize", "(", "train", ",", "test", ",", "features", ",", "na_value", "=", "-", "9999", ",", "full", "=", "False", ",", "sort", "=", "True", ")", ":", "for", "column", "in", "features", ":", "if", "full", ":", "vs", "=", "pd", ".", "co...
Factorize categorical features. Parameters ---------- train : pd.DataFrame test : pd.DataFrame features : list Column names in the DataFrame to be encoded. na_value : int, default -9999 full : bool, default False Whether use all columns from train/test or only from train. sort : bool, default True Sort by values. Returns ------- train : pd.DataFrame test : pd.DataFrame
[ "Factorize", "categorical", "features", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/feature.py#L52-L87
train
200,202
rushter/heamy
heamy/feature.py
woe
def woe(df, feature_name, target_name): """Calculate weight of evidence. Parameters ---------- df: Dataframe feature_name: str Column name to encode. target_name: str Target column name. Returns ------- Series """ def group_woe(group): event = float(group.sum()) non_event = group.shape[0] - event rel_event = event / event_total rel_non_event = non_event / non_event_total return np.log(rel_non_event / rel_event) * 100 if df[target_name].nunique() > 2: raise ValueError('Target column should be binary (1/0).') event_total = float(df[df[target_name] == 1.0].shape[0]) non_event_total = float(df.shape[0] - event_total) woe_vals = df.groupby(feature_name)[target_name].transform(group_woe) return woe_vals
python
def woe(df, feature_name, target_name): """Calculate weight of evidence. Parameters ---------- df: Dataframe feature_name: str Column name to encode. target_name: str Target column name. Returns ------- Series """ def group_woe(group): event = float(group.sum()) non_event = group.shape[0] - event rel_event = event / event_total rel_non_event = non_event / non_event_total return np.log(rel_non_event / rel_event) * 100 if df[target_name].nunique() > 2: raise ValueError('Target column should be binary (1/0).') event_total = float(df[df[target_name] == 1.0].shape[0]) non_event_total = float(df.shape[0] - event_total) woe_vals = df.groupby(feature_name)[target_name].transform(group_woe) return woe_vals
[ "def", "woe", "(", "df", ",", "feature_name", ",", "target_name", ")", ":", "def", "group_woe", "(", "group", ")", ":", "event", "=", "float", "(", "group", ".", "sum", "(", ")", ")", "non_event", "=", "group", ".", "shape", "[", "0", "]", "-", "...
Calculate weight of evidence. Parameters ---------- df: Dataframe feature_name: str Column name to encode. target_name: str Target column name. Returns ------- Series
[ "Calculate", "weight", "of", "evidence", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/feature.py#L90-L123
train
200,203
rushter/heamy
heamy/dataset.py
Dataset.kfold
def kfold(self, k=5, stratify=False, shuffle=True, seed=33): """K-Folds cross validation iterator. Parameters ---------- k : int, default 5 stratify : bool, default False shuffle : bool, default True seed : int, default 33 Yields ------- X_train, y_train, X_test, y_test, train_index, test_index """ if stratify: kf = StratifiedKFold(n_splits=k, random_state=seed, shuffle=shuffle) else: kf = KFold(n_splits=k, random_state=seed, shuffle=shuffle) for train_index, test_index in kf.split(self.X_train, self.y_train): X_train, y_train = idx(self.X_train, train_index), self.y_train[train_index] X_test, y_test = idx(self.X_train, test_index), self.y_train[test_index] yield X_train, y_train, X_test, y_test, train_index, test_index
python
def kfold(self, k=5, stratify=False, shuffle=True, seed=33): """K-Folds cross validation iterator. Parameters ---------- k : int, default 5 stratify : bool, default False shuffle : bool, default True seed : int, default 33 Yields ------- X_train, y_train, X_test, y_test, train_index, test_index """ if stratify: kf = StratifiedKFold(n_splits=k, random_state=seed, shuffle=shuffle) else: kf = KFold(n_splits=k, random_state=seed, shuffle=shuffle) for train_index, test_index in kf.split(self.X_train, self.y_train): X_train, y_train = idx(self.X_train, train_index), self.y_train[train_index] X_test, y_test = idx(self.X_train, test_index), self.y_train[test_index] yield X_train, y_train, X_test, y_test, train_index, test_index
[ "def", "kfold", "(", "self", ",", "k", "=", "5", ",", "stratify", "=", "False", ",", "shuffle", "=", "True", ",", "seed", "=", "33", ")", ":", "if", "stratify", ":", "kf", "=", "StratifiedKFold", "(", "n_splits", "=", "k", ",", "random_state", "=",...
K-Folds cross validation iterator. Parameters ---------- k : int, default 5 stratify : bool, default False shuffle : bool, default True seed : int, default 33 Yields ------- X_train, y_train, X_test, y_test, train_index, test_index
[ "K", "-", "Folds", "cross", "validation", "iterator", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/dataset.py#L217-L239
train
200,204
rushter/heamy
heamy/dataset.py
Dataset.hash
def hash(self): """Return md5 hash for current dataset.""" if self._hash is None: m = hashlib.new('md5') if self._preprocessor is None: # generate hash from numpy array m.update(numpy_buffer(self._X_train)) m.update(numpy_buffer(self._y_train)) if self._X_test is not None: m.update(numpy_buffer(self._X_test)) if self._y_test is not None: m.update(numpy_buffer(self._y_test)) elif callable(self._preprocessor): # generate hash from user defined object (source code) m.update(inspect.getsource(self._preprocessor).encode('utf-8')) self._hash = m.hexdigest() return self._hash
python
def hash(self): """Return md5 hash for current dataset.""" if self._hash is None: m = hashlib.new('md5') if self._preprocessor is None: # generate hash from numpy array m.update(numpy_buffer(self._X_train)) m.update(numpy_buffer(self._y_train)) if self._X_test is not None: m.update(numpy_buffer(self._X_test)) if self._y_test is not None: m.update(numpy_buffer(self._y_test)) elif callable(self._preprocessor): # generate hash from user defined object (source code) m.update(inspect.getsource(self._preprocessor).encode('utf-8')) self._hash = m.hexdigest() return self._hash
[ "def", "hash", "(", "self", ")", ":", "if", "self", ".", "_hash", "is", "None", ":", "m", "=", "hashlib", ".", "new", "(", "'md5'", ")", "if", "self", ".", "_preprocessor", "is", "None", ":", "# generate hash from numpy array", "m", ".", "update", "(",...
Return md5 hash for current dataset.
[ "Return", "md5", "hash", "for", "current", "dataset", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/dataset.py#L262-L280
train
200,205
rushter/heamy
heamy/dataset.py
Dataset.merge
def merge(self, ds, inplace=False, axis=1): """Merge two datasets. Parameters ---------- axis : {0,1} ds : `Dataset` inplace : bool, default False Returns ------- `Dataset` """ if not isinstance(ds, Dataset): raise ValueError('Expected `Dataset`, got %s.' % ds) X_train = concat(ds.X_train, self.X_train, axis=axis) y_train = concat(ds.y_train, self.y_train, axis=axis) if ds.X_test is not None: X_test = concat(ds.X_test, self.X_test, axis=axis) else: X_test = None if ds.y_test is not None: y_test = concat(ds.y_test, self.y_test, axis=axis) else: y_test = None if inplace: self._X_train = X_train self._y_train = y_train if X_test is not None: self._X_test = X_test if y_test is not None: self._y_test = y_test return None return Dataset(X_train, y_train, X_test, y_test)
python
def merge(self, ds, inplace=False, axis=1): """Merge two datasets. Parameters ---------- axis : {0,1} ds : `Dataset` inplace : bool, default False Returns ------- `Dataset` """ if not isinstance(ds, Dataset): raise ValueError('Expected `Dataset`, got %s.' % ds) X_train = concat(ds.X_train, self.X_train, axis=axis) y_train = concat(ds.y_train, self.y_train, axis=axis) if ds.X_test is not None: X_test = concat(ds.X_test, self.X_test, axis=axis) else: X_test = None if ds.y_test is not None: y_test = concat(ds.y_test, self.y_test, axis=axis) else: y_test = None if inplace: self._X_train = X_train self._y_train = y_train if X_test is not None: self._X_test = X_test if y_test is not None: self._y_test = y_test return None return Dataset(X_train, y_train, X_test, y_test)
[ "def", "merge", "(", "self", ",", "ds", ",", "inplace", "=", "False", ",", "axis", "=", "1", ")", ":", "if", "not", "isinstance", "(", "ds", ",", "Dataset", ")", ":", "raise", "ValueError", "(", "'Expected `Dataset`, got %s.'", "%", "ds", ")", "X_train...
Merge two datasets. Parameters ---------- axis : {0,1} ds : `Dataset` inplace : bool, default False Returns ------- `Dataset`
[ "Merge", "two", "datasets", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/dataset.py#L282-L324
train
200,206
rushter/heamy
heamy/dataset.py
Dataset.to_csc
def to_csc(self): """Convert Dataset to scipy's Compressed Sparse Column matrix.""" self._X_train = csc_matrix(self._X_train) self._X_test = csc_matrix(self._X_test)
python
def to_csc(self): """Convert Dataset to scipy's Compressed Sparse Column matrix.""" self._X_train = csc_matrix(self._X_train) self._X_test = csc_matrix(self._X_test)
[ "def", "to_csc", "(", "self", ")", ":", "self", ".", "_X_train", "=", "csc_matrix", "(", "self", ".", "_X_train", ")", "self", ".", "_X_test", "=", "csc_matrix", "(", "self", ".", "_X_test", ")" ]
Convert Dataset to scipy's Compressed Sparse Column matrix.
[ "Convert", "Dataset", "to", "scipy", "s", "Compressed", "Sparse", "Column", "matrix", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/dataset.py#L326-L329
train
200,207
rushter/heamy
heamy/dataset.py
Dataset.to_csr
def to_csr(self): """Convert Dataset to scipy's Compressed Sparse Row matrix.""" self._X_train = csr_matrix(self._X_train) self._X_test = csr_matrix(self._X_test)
python
def to_csr(self): """Convert Dataset to scipy's Compressed Sparse Row matrix.""" self._X_train = csr_matrix(self._X_train) self._X_test = csr_matrix(self._X_test)
[ "def", "to_csr", "(", "self", ")", ":", "self", ".", "_X_train", "=", "csr_matrix", "(", "self", ".", "_X_train", ")", "self", ".", "_X_test", "=", "csr_matrix", "(", "self", ".", "_X_test", ")" ]
Convert Dataset to scipy's Compressed Sparse Row matrix.
[ "Convert", "Dataset", "to", "scipy", "s", "Compressed", "Sparse", "Row", "matrix", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/dataset.py#L331-L334
train
200,208
rushter/heamy
heamy/dataset.py
Dataset.to_dense
def to_dense(self): """Convert sparse Dataset to dense matrix.""" if hasattr(self._X_train, 'todense'): self._X_train = self._X_train.todense() self._X_test = self._X_test.todense()
python
def to_dense(self): """Convert sparse Dataset to dense matrix.""" if hasattr(self._X_train, 'todense'): self._X_train = self._X_train.todense() self._X_test = self._X_test.todense()
[ "def", "to_dense", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "_X_train", ",", "'todense'", ")", ":", "self", ".", "_X_train", "=", "self", ".", "_X_train", ".", "todense", "(", ")", "self", ".", "_X_test", "=", "self", ".", "_X_test",...
Convert sparse Dataset to dense matrix.
[ "Convert", "sparse", "Dataset", "to", "dense", "matrix", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/dataset.py#L336-L340
train
200,209
rushter/heamy
heamy/estimator.py
BaseEstimator._dhash
def _dhash(self, params): """Generate hash of the dictionary object.""" m = hashlib.new('md5') m.update(self.hash.encode('utf-8')) for key in sorted(params.keys()): h_string = ('%s-%s' % (key, params[key])).encode('utf-8') m.update(h_string) return m.hexdigest()
python
def _dhash(self, params): """Generate hash of the dictionary object.""" m = hashlib.new('md5') m.update(self.hash.encode('utf-8')) for key in sorted(params.keys()): h_string = ('%s-%s' % (key, params[key])).encode('utf-8') m.update(h_string) return m.hexdigest()
[ "def", "_dhash", "(", "self", ",", "params", ")", ":", "m", "=", "hashlib", ".", "new", "(", "'md5'", ")", "m", ".", "update", "(", "self", ".", "hash", ".", "encode", "(", "'utf-8'", ")", ")", "for", "key", "in", "sorted", "(", "params", ".", ...
Generate hash of the dictionary object.
[ "Generate", "hash", "of", "the", "dictionary", "object", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/estimator.py#L142-L149
train
200,210
rushter/heamy
heamy/estimator.py
BaseEstimator.validate
def validate(self, scorer=None, k=1, test_size=0.1, stratify=False, shuffle=True, seed=100, indices=None): """Evaluate score by cross-validation. Parameters ---------- scorer : function(y_true,y_pred), default None Scikit-learn like metric that returns a score. k : int, default 1 The number of folds for validation. If k=1 then randomly split X_train into two parts otherwise use K-fold approach. test_size : float, default 0.1 Size of the test holdout if k=1. stratify : bool, default False shuffle : bool, default True seed : int, default 100 indices : list(np.array,np.array), default None Two numpy arrays that contain indices for train/test slicing. (train_index,test_index) Returns ------- y_true: list Actual labels. y_pred: list Predicted labels. Examples -------- >>> # Custom indices >>> train_index = np.array(range(250)) >>> test_index = np.array(range(250,333)) >>> res = model_rf.validate(mean_absolute_error,indices=(train_index,test_index)) """ if self.use_cache: pdict = {'k': k, 'stratify': stratify, 'shuffle': shuffle, 'seed': seed, 'test_size': test_size} if indices is not None: pdict['train_index'] = np_hash(indices[0]) pdict['test_index'] = np_hash(indices[1]) dhash = self._dhash(pdict) c = Cache(dhash, prefix='v') if c.available: logger.info('Loading %s\'s validation results from cache.' % self._name) elif (self.dataset.X_train is None) and (self.dataset.y_train is None): self.dataset.load() scores = [] y_true = [] y_pred = [] if k == 1: X_train, y_train, X_test, y_test = self.dataset.split(test_size=test_size, stratify=stratify, seed=seed, indices=indices) if self.use_cache and c.available: prediction = c.retrieve('0') else: prediction = self._predict(X_train, y_train, X_test, y_test) if self.use_cache: c.store('0', prediction) if scorer is not None: scores.append(scorer(y_test, prediction)) y_true.append(y_test) y_pred.append(prediction) else: for i, fold in enumerate(self.dataset.kfold(k, stratify=stratify, seed=seed, shuffle=shuffle)): X_train, y_train, X_test, y_test, train_index, test_index = fold if self.use_cache and c.available: prediction = c.retrieve(str(i)) else: prediction = None if prediction is None: logger.info('Calculating %s\'s fold #%s' % (self._name, i + 1)) prediction = self._predict(X_train, y_train, X_test, y_test) if self.use_cache: c.store(str(i), prediction) if scorer is not None: scores.append(scorer(y_test, prediction)) y_true.append(y_test) y_pred.append(prediction) if scorer is not None: report_score(scores, scorer) return y_true, y_pred
python
def validate(self, scorer=None, k=1, test_size=0.1, stratify=False, shuffle=True, seed=100, indices=None): """Evaluate score by cross-validation. Parameters ---------- scorer : function(y_true,y_pred), default None Scikit-learn like metric that returns a score. k : int, default 1 The number of folds for validation. If k=1 then randomly split X_train into two parts otherwise use K-fold approach. test_size : float, default 0.1 Size of the test holdout if k=1. stratify : bool, default False shuffle : bool, default True seed : int, default 100 indices : list(np.array,np.array), default None Two numpy arrays that contain indices for train/test slicing. (train_index,test_index) Returns ------- y_true: list Actual labels. y_pred: list Predicted labels. Examples -------- >>> # Custom indices >>> train_index = np.array(range(250)) >>> test_index = np.array(range(250,333)) >>> res = model_rf.validate(mean_absolute_error,indices=(train_index,test_index)) """ if self.use_cache: pdict = {'k': k, 'stratify': stratify, 'shuffle': shuffle, 'seed': seed, 'test_size': test_size} if indices is not None: pdict['train_index'] = np_hash(indices[0]) pdict['test_index'] = np_hash(indices[1]) dhash = self._dhash(pdict) c = Cache(dhash, prefix='v') if c.available: logger.info('Loading %s\'s validation results from cache.' % self._name) elif (self.dataset.X_train is None) and (self.dataset.y_train is None): self.dataset.load() scores = [] y_true = [] y_pred = [] if k == 1: X_train, y_train, X_test, y_test = self.dataset.split(test_size=test_size, stratify=stratify, seed=seed, indices=indices) if self.use_cache and c.available: prediction = c.retrieve('0') else: prediction = self._predict(X_train, y_train, X_test, y_test) if self.use_cache: c.store('0', prediction) if scorer is not None: scores.append(scorer(y_test, prediction)) y_true.append(y_test) y_pred.append(prediction) else: for i, fold in enumerate(self.dataset.kfold(k, stratify=stratify, seed=seed, shuffle=shuffle)): X_train, y_train, X_test, y_test, train_index, test_index = fold if self.use_cache and c.available: prediction = c.retrieve(str(i)) else: prediction = None if prediction is None: logger.info('Calculating %s\'s fold #%s' % (self._name, i + 1)) prediction = self._predict(X_train, y_train, X_test, y_test) if self.use_cache: c.store(str(i), prediction) if scorer is not None: scores.append(scorer(y_test, prediction)) y_true.append(y_test) y_pred.append(prediction) if scorer is not None: report_score(scores, scorer) return y_true, y_pred
[ "def", "validate", "(", "self", ",", "scorer", "=", "None", ",", "k", "=", "1", ",", "test_size", "=", "0.1", ",", "stratify", "=", "False", ",", "shuffle", "=", "True", ",", "seed", "=", "100", ",", "indices", "=", "None", ")", ":", "if", "self"...
Evaluate score by cross-validation. Parameters ---------- scorer : function(y_true,y_pred), default None Scikit-learn like metric that returns a score. k : int, default 1 The number of folds for validation. If k=1 then randomly split X_train into two parts otherwise use K-fold approach. test_size : float, default 0.1 Size of the test holdout if k=1. stratify : bool, default False shuffle : bool, default True seed : int, default 100 indices : list(np.array,np.array), default None Two numpy arrays that contain indices for train/test slicing. (train_index,test_index) Returns ------- y_true: list Actual labels. y_pred: list Predicted labels. Examples -------- >>> # Custom indices >>> train_index = np.array(range(250)) >>> test_index = np.array(range(250,333)) >>> res = model_rf.validate(mean_absolute_error,indices=(train_index,test_index))
[ "Evaluate", "score", "by", "cross", "-", "validation", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/estimator.py#L151-L237
train
200,211
rushter/heamy
heamy/estimator.py
BaseEstimator.stack
def stack(self, k=5, stratify=False, shuffle=True, seed=100, full_test=True): """Stack a single model. You should rarely be using this method. Use `ModelsPipeline.stack` instead. Parameters ---------- k : int, default 5 stratify : bool, default False shuffle : bool, default True seed : int, default 100 full_test : bool, default True If `True` then evaluate test dataset on the full data otherwise take the mean of every fold. Returns ------- `Dataset` with out of fold predictions. """ train = None test = [] if self.use_cache: pdict = {'k': k, 'stratify': stratify, 'shuffle': shuffle, 'seed': seed, 'full_test': full_test} dhash = self._dhash(pdict) c = Cache(dhash, prefix='s') if c.available: logger.info('Loading %s\'s stack results from cache.' % self._name) train = c.retrieve('train') test = c.retrieve('test') y_train = c.retrieve('y_train') return Dataset(X_train=train, y_train=y_train, X_test=test) elif not self.dataset.loaded: self.dataset.load() for i, fold in enumerate(self.dataset.kfold(k, stratify=stratify, seed=seed, shuffle=shuffle)): X_train, y_train, X_test, y_test, train_index, test_index = fold logger.info('Calculating %s\'s fold #%s' % (self._name, i + 1)) if full_test: prediction = reshape_1d(self._predict(X_train, y_train, X_test, y_test)) else: xt_shape = X_test.shape[0] x_t = concat(X_test, self.dataset.X_test) prediction_concat = reshape_1d(self._predict(X_train, y_train, x_t)) prediction, prediction_test = tsplit(prediction_concat, xt_shape) test.append(prediction_test) if train is None: train = np.zeros((self.dataset.X_train.shape[0], prediction.shape[1])) train[test_index] = prediction if full_test: logger.info('Calculating %s\'s test data' % self._name) test = self._predict(self.dataset.X_train, self.dataset.y_train, self.dataset.X_test) else: test = np.mean(test, axis=0) test = reshape_1d(test) if self.use_cache: c.store('train', train) c.store('test', test) c.store('y_train', self.dataset.y_train) return Dataset(X_train=train, y_train=self.dataset.y_train, X_test=test)
python
def stack(self, k=5, stratify=False, shuffle=True, seed=100, full_test=True): """Stack a single model. You should rarely be using this method. Use `ModelsPipeline.stack` instead. Parameters ---------- k : int, default 5 stratify : bool, default False shuffle : bool, default True seed : int, default 100 full_test : bool, default True If `True` then evaluate test dataset on the full data otherwise take the mean of every fold. Returns ------- `Dataset` with out of fold predictions. """ train = None test = [] if self.use_cache: pdict = {'k': k, 'stratify': stratify, 'shuffle': shuffle, 'seed': seed, 'full_test': full_test} dhash = self._dhash(pdict) c = Cache(dhash, prefix='s') if c.available: logger.info('Loading %s\'s stack results from cache.' % self._name) train = c.retrieve('train') test = c.retrieve('test') y_train = c.retrieve('y_train') return Dataset(X_train=train, y_train=y_train, X_test=test) elif not self.dataset.loaded: self.dataset.load() for i, fold in enumerate(self.dataset.kfold(k, stratify=stratify, seed=seed, shuffle=shuffle)): X_train, y_train, X_test, y_test, train_index, test_index = fold logger.info('Calculating %s\'s fold #%s' % (self._name, i + 1)) if full_test: prediction = reshape_1d(self._predict(X_train, y_train, X_test, y_test)) else: xt_shape = X_test.shape[0] x_t = concat(X_test, self.dataset.X_test) prediction_concat = reshape_1d(self._predict(X_train, y_train, x_t)) prediction, prediction_test = tsplit(prediction_concat, xt_shape) test.append(prediction_test) if train is None: train = np.zeros((self.dataset.X_train.shape[0], prediction.shape[1])) train[test_index] = prediction if full_test: logger.info('Calculating %s\'s test data' % self._name) test = self._predict(self.dataset.X_train, self.dataset.y_train, self.dataset.X_test) else: test = np.mean(test, axis=0) test = reshape_1d(test) if self.use_cache: c.store('train', train) c.store('test', test) c.store('y_train', self.dataset.y_train) return Dataset(X_train=train, y_train=self.dataset.y_train, X_test=test)
[ "def", "stack", "(", "self", ",", "k", "=", "5", ",", "stratify", "=", "False", ",", "shuffle", "=", "True", ",", "seed", "=", "100", ",", "full_test", "=", "True", ")", ":", "train", "=", "None", "test", "=", "[", "]", "if", "self", ".", "use_...
Stack a single model. You should rarely be using this method. Use `ModelsPipeline.stack` instead. Parameters ---------- k : int, default 5 stratify : bool, default False shuffle : bool, default True seed : int, default 100 full_test : bool, default True If `True` then evaluate test dataset on the full data otherwise take the mean of every fold. Returns ------- `Dataset` with out of fold predictions.
[ "Stack", "a", "single", "model", ".", "You", "should", "rarely", "be", "using", "this", "method", ".", "Use", "ModelsPipeline", ".", "stack", "instead", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/estimator.py#L239-L301
train
200,212
rushter/heamy
heamy/estimator.py
BaseEstimator.blend
def blend(self, proportion=0.2, stratify=False, seed=100, indices=None): """Blend a single model. You should rarely be using this method. Use `ModelsPipeline.blend` instead. Parameters ---------- proportion : float, default 0.2 Test size holdout. stratify : bool, default False seed : int, default 100 indices : list(np.ndarray,np.ndarray), default None Two numpy arrays that contain indices for train/test slicing. (train_index,test_index) Returns ------- `Dataset` """ if self.use_cache: pdict = {'proportion': proportion, 'stratify': stratify, 'seed': seed, 'indices': indices} if indices is not None: pdict['train_index'] = np_hash(indices[0]) pdict['test_index'] = np_hash(indices[1]) dhash = self._dhash(pdict) c = Cache(dhash, prefix='b') if c.available: logger.info('Loading %s\'s blend results from cache.' % self._name) train = c.retrieve('train') test = c.retrieve('test') y_train = c.retrieve('y_train') return Dataset(X_train=train, y_train=y_train, X_test=test) elif not self.dataset.loaded: self.dataset.load() X_train, y_train, X_test, y_test = self.dataset.split(test_size=proportion, stratify=stratify, seed=seed, indices=indices) xt_shape = X_test.shape[0] x_t = concat(X_test, self.dataset.X_test) prediction_concat = reshape_1d(self._predict(X_train, y_train, x_t)) new_train, new_test = tsplit(prediction_concat, xt_shape) if self.use_cache: c.store('train', new_train) c.store('test', new_test) c.store('y_train', y_test) return Dataset(new_train, y_test, new_test)
python
def blend(self, proportion=0.2, stratify=False, seed=100, indices=None): """Blend a single model. You should rarely be using this method. Use `ModelsPipeline.blend` instead. Parameters ---------- proportion : float, default 0.2 Test size holdout. stratify : bool, default False seed : int, default 100 indices : list(np.ndarray,np.ndarray), default None Two numpy arrays that contain indices for train/test slicing. (train_index,test_index) Returns ------- `Dataset` """ if self.use_cache: pdict = {'proportion': proportion, 'stratify': stratify, 'seed': seed, 'indices': indices} if indices is not None: pdict['train_index'] = np_hash(indices[0]) pdict['test_index'] = np_hash(indices[1]) dhash = self._dhash(pdict) c = Cache(dhash, prefix='b') if c.available: logger.info('Loading %s\'s blend results from cache.' % self._name) train = c.retrieve('train') test = c.retrieve('test') y_train = c.retrieve('y_train') return Dataset(X_train=train, y_train=y_train, X_test=test) elif not self.dataset.loaded: self.dataset.load() X_train, y_train, X_test, y_test = self.dataset.split(test_size=proportion, stratify=stratify, seed=seed, indices=indices) xt_shape = X_test.shape[0] x_t = concat(X_test, self.dataset.X_test) prediction_concat = reshape_1d(self._predict(X_train, y_train, x_t)) new_train, new_test = tsplit(prediction_concat, xt_shape) if self.use_cache: c.store('train', new_train) c.store('test', new_test) c.store('y_train', y_test) return Dataset(new_train, y_test, new_test)
[ "def", "blend", "(", "self", ",", "proportion", "=", "0.2", ",", "stratify", "=", "False", ",", "seed", "=", "100", ",", "indices", "=", "None", ")", ":", "if", "self", ".", "use_cache", ":", "pdict", "=", "{", "'proportion'", ":", "proportion", ",",...
Blend a single model. You should rarely be using this method. Use `ModelsPipeline.blend` instead. Parameters ---------- proportion : float, default 0.2 Test size holdout. stratify : bool, default False seed : int, default 100 indices : list(np.ndarray,np.ndarray), default None Two numpy arrays that contain indices for train/test slicing. (train_index,test_index) Returns ------- `Dataset`
[ "Blend", "a", "single", "model", ".", "You", "should", "rarely", "be", "using", "this", "method", ".", "Use", "ModelsPipeline", ".", "blend", "instead", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/estimator.py#L303-L350
train
200,213
rushter/heamy
heamy/cache.py
numpy_buffer
def numpy_buffer(ndarray): """Creates a buffer from c_contiguous numpy ndarray.""" # Credits to: https://github.com/joblib/joblib/blob/04b001861e1dd03a857b7b419c336de64e05714c/joblib/hashing.py if isinstance(ndarray, (pd.Series, pd.DataFrame)): ndarray = ndarray.values if ndarray.flags.c_contiguous: obj_c_contiguous = ndarray elif ndarray.flags.f_contiguous: obj_c_contiguous = ndarray.T else: obj_c_contiguous = ndarray.flatten() obj_c_contiguous = obj_c_contiguous.view(np.uint8) if hasattr(np, 'getbuffer'): return np.getbuffer(obj_c_contiguous) else: return memoryview(obj_c_contiguous)
python
def numpy_buffer(ndarray): """Creates a buffer from c_contiguous numpy ndarray.""" # Credits to: https://github.com/joblib/joblib/blob/04b001861e1dd03a857b7b419c336de64e05714c/joblib/hashing.py if isinstance(ndarray, (pd.Series, pd.DataFrame)): ndarray = ndarray.values if ndarray.flags.c_contiguous: obj_c_contiguous = ndarray elif ndarray.flags.f_contiguous: obj_c_contiguous = ndarray.T else: obj_c_contiguous = ndarray.flatten() obj_c_contiguous = obj_c_contiguous.view(np.uint8) if hasattr(np, 'getbuffer'): return np.getbuffer(obj_c_contiguous) else: return memoryview(obj_c_contiguous)
[ "def", "numpy_buffer", "(", "ndarray", ")", ":", "# Credits to: https://github.com/joblib/joblib/blob/04b001861e1dd03a857b7b419c336de64e05714c/joblib/hashing.py", "if", "isinstance", "(", "ndarray", ",", "(", "pd", ".", "Series", ",", "pd", ".", "DataFrame", ")", ")", ":"...
Creates a buffer from c_contiguous numpy ndarray.
[ "Creates", "a", "buffer", "from", "c_contiguous", "numpy", "ndarray", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/cache.py#L51-L70
train
200,214
rushter/heamy
heamy/cache.py
Cache.store
def store(self, key, data): """Takes an array and stores it in the cache.""" if not os.path.exists(self._hash_dir): os.makedirs(self._hash_dir) if isinstance(data, pd.DataFrame): columns = data.columns.tolist() np.save(os.path.join(self._hash_dir, key), data.values) json.dump(columns, open(os.path.join(self._hash_dir, '%s.json' % key), 'w')) else: np.save(os.path.join(self._hash_dir, key), data)
python
def store(self, key, data): """Takes an array and stores it in the cache.""" if not os.path.exists(self._hash_dir): os.makedirs(self._hash_dir) if isinstance(data, pd.DataFrame): columns = data.columns.tolist() np.save(os.path.join(self._hash_dir, key), data.values) json.dump(columns, open(os.path.join(self._hash_dir, '%s.json' % key), 'w')) else: np.save(os.path.join(self._hash_dir, key), data)
[ "def", "store", "(", "self", ",", "key", ",", "data", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_hash_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_hash_dir", ")", "if", "isinstance", "(", "data", ",...
Takes an array and stores it in the cache.
[ "Takes", "an", "array", "and", "stores", "it", "in", "the", "cache", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/cache.py#L18-L28
train
200,215
rushter/heamy
heamy/cache.py
Cache.retrieve
def retrieve(self, key): """Retrieves a cached array if possible.""" column_file = os.path.join(self._hash_dir, '%s.json' % key) cache_file = os.path.join(self._hash_dir, '%s.npy' % key) if os.path.exists(cache_file): data = np.load(cache_file) if os.path.exists(column_file): with open(column_file, 'r') as json_file: columns = json.load(json_file) data = pd.DataFrame(data, columns=columns) else: return None return data
python
def retrieve(self, key): """Retrieves a cached array if possible.""" column_file = os.path.join(self._hash_dir, '%s.json' % key) cache_file = os.path.join(self._hash_dir, '%s.npy' % key) if os.path.exists(cache_file): data = np.load(cache_file) if os.path.exists(column_file): with open(column_file, 'r') as json_file: columns = json.load(json_file) data = pd.DataFrame(data, columns=columns) else: return None return data
[ "def", "retrieve", "(", "self", ",", "key", ")", ":", "column_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_hash_dir", ",", "'%s.json'", "%", "key", ")", "cache_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_hash_...
Retrieves a cached array if possible.
[ "Retrieves", "a", "cached", "array", "if", "possible", "." ]
c330854cee3c547417eb353a4a4a23331b40b4bc
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/cache.py#L30-L44
train
200,216
wbond/asn1crypto
asn1crypto/keys.py
_ECPoint.from_coords
def from_coords(cls, x, y): """ Creates an ECPoint object from the X and Y integer coordinates of the point :param x: The X coordinate, as an integer :param y: The Y coordinate, as an integer :return: An ECPoint object """ x_bytes = int(math.ceil(math.log(x, 2) / 8.0)) y_bytes = int(math.ceil(math.log(y, 2) / 8.0)) num_bytes = max(x_bytes, y_bytes) byte_string = b'\x04' byte_string += int_to_bytes(x, width=num_bytes) byte_string += int_to_bytes(y, width=num_bytes) return cls(byte_string)
python
def from_coords(cls, x, y): """ Creates an ECPoint object from the X and Y integer coordinates of the point :param x: The X coordinate, as an integer :param y: The Y coordinate, as an integer :return: An ECPoint object """ x_bytes = int(math.ceil(math.log(x, 2) / 8.0)) y_bytes = int(math.ceil(math.log(y, 2) / 8.0)) num_bytes = max(x_bytes, y_bytes) byte_string = b'\x04' byte_string += int_to_bytes(x, width=num_bytes) byte_string += int_to_bytes(y, width=num_bytes) return cls(byte_string)
[ "def", "from_coords", "(", "cls", ",", "x", ",", "y", ")", ":", "x_bytes", "=", "int", "(", "math", ".", "ceil", "(", "math", ".", "log", "(", "x", ",", "2", ")", "/", "8.0", ")", ")", "y_bytes", "=", "int", "(", "math", ".", "ceil", "(", "...
Creates an ECPoint object from the X and Y integer coordinates of the point :param x: The X coordinate, as an integer :param y: The Y coordinate, as an integer :return: An ECPoint object
[ "Creates", "an", "ECPoint", "object", "from", "the", "X", "and", "Y", "integer", "coordinates", "of", "the", "point" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/keys.py#L145-L169
train
200,217
wbond/asn1crypto
asn1crypto/keys.py
_ECPoint.to_coords
def to_coords(self): """ Returns the X and Y coordinates for this EC point, as native Python integers :return: A 2-element tuple containing integers (X, Y) """ data = self.native first_byte = data[0:1] # Uncompressed if first_byte == b'\x04': remaining = data[1:] field_len = len(remaining) // 2 x = int_from_bytes(remaining[0:field_len]) y = int_from_bytes(remaining[field_len:]) return (x, y) if first_byte not in set([b'\x02', b'\x03']): raise ValueError(unwrap( ''' Invalid EC public key - first byte is incorrect ''' )) raise ValueError(unwrap( ''' Compressed representations of EC public keys are not supported due to patent US6252960 ''' ))
python
def to_coords(self): """ Returns the X and Y coordinates for this EC point, as native Python integers :return: A 2-element tuple containing integers (X, Y) """ data = self.native first_byte = data[0:1] # Uncompressed if first_byte == b'\x04': remaining = data[1:] field_len = len(remaining) // 2 x = int_from_bytes(remaining[0:field_len]) y = int_from_bytes(remaining[field_len:]) return (x, y) if first_byte not in set([b'\x02', b'\x03']): raise ValueError(unwrap( ''' Invalid EC public key - first byte is incorrect ''' )) raise ValueError(unwrap( ''' Compressed representations of EC public keys are not supported due to patent US6252960 ''' ))
[ "def", "to_coords", "(", "self", ")", ":", "data", "=", "self", ".", "native", "first_byte", "=", "data", "[", "0", ":", "1", "]", "# Uncompressed", "if", "first_byte", "==", "b'\\x04'", ":", "remaining", "=", "data", "[", "1", ":", "]", "field_len", ...
Returns the X and Y coordinates for this EC point, as native Python integers :return: A 2-element tuple containing integers (X, Y)
[ "Returns", "the", "X", "and", "Y", "coordinates", "for", "this", "EC", "point", "as", "native", "Python", "integers" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/keys.py#L171-L203
train
200,218
wbond/asn1crypto
asn1crypto/keys.py
PrivateKeyInfo.unwrap
def unwrap(self): """ Unwraps the private key into an RSAPrivateKey, DSAPrivateKey or ECPrivateKey object :return: An RSAPrivateKey, DSAPrivateKey or ECPrivateKey object """ if self.algorithm == 'rsa': return self['private_key'].parsed if self.algorithm == 'dsa': params = self['private_key_algorithm']['parameters'] return DSAPrivateKey({ 'version': 0, 'p': params['p'], 'q': params['q'], 'g': params['g'], 'public_key': self.public_key, 'private_key': self['private_key'].parsed, }) if self.algorithm == 'ec': output = self['private_key'].parsed output['parameters'] = self['private_key_algorithm']['parameters'] output['public_key'] = self.public_key return output
python
def unwrap(self): """ Unwraps the private key into an RSAPrivateKey, DSAPrivateKey or ECPrivateKey object :return: An RSAPrivateKey, DSAPrivateKey or ECPrivateKey object """ if self.algorithm == 'rsa': return self['private_key'].parsed if self.algorithm == 'dsa': params = self['private_key_algorithm']['parameters'] return DSAPrivateKey({ 'version': 0, 'p': params['p'], 'q': params['q'], 'g': params['g'], 'public_key': self.public_key, 'private_key': self['private_key'].parsed, }) if self.algorithm == 'ec': output = self['private_key'].parsed output['parameters'] = self['private_key_algorithm']['parameters'] output['public_key'] = self.public_key return output
[ "def", "unwrap", "(", "self", ")", ":", "if", "self", ".", "algorithm", "==", "'rsa'", ":", "return", "self", "[", "'private_key'", "]", ".", "parsed", "if", "self", ".", "algorithm", "==", "'dsa'", ":", "params", "=", "self", "[", "'private_key_algorith...
Unwraps the private key into an RSAPrivateKey, DSAPrivateKey or ECPrivateKey object :return: An RSAPrivateKey, DSAPrivateKey or ECPrivateKey object
[ "Unwraps", "the", "private", "key", "into", "an", "RSAPrivateKey", "DSAPrivateKey", "or", "ECPrivateKey", "object" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/keys.py#L663-L690
train
200,219
wbond/asn1crypto
asn1crypto/keys.py
PrivateKeyInfo.fingerprint
def fingerprint(self): """ Creates a fingerprint that can be compared with a public key to see if the two form a pair. This fingerprint is not compatible with fingerprints generated by any other software. :return: A byte string that is a sha256 hash of selected components (based on the key type) """ if self._fingerprint is None: params = self['private_key_algorithm']['parameters'] key = self['private_key'].parsed if self.algorithm == 'rsa': to_hash = '%d:%d' % ( key['modulus'].native, key['public_exponent'].native, ) elif self.algorithm == 'dsa': public_key = self.public_key to_hash = '%d:%d:%d:%d' % ( params['p'].native, params['q'].native, params['g'].native, public_key.native, ) elif self.algorithm == 'ec': public_key = key['public_key'].native if public_key is None: public_key = self.public_key.native if params.name == 'named': to_hash = '%s:' % params.chosen.native to_hash = to_hash.encode('utf-8') to_hash += public_key elif params.name == 'implicit_ca': to_hash = public_key elif params.name == 'specified': to_hash = '%s:' % params.chosen['field_id']['parameters'].native to_hash = to_hash.encode('utf-8') to_hash += b':' + params.chosen['curve']['a'].native to_hash += b':' + params.chosen['curve']['b'].native to_hash += public_key if isinstance(to_hash, str_cls): to_hash = to_hash.encode('utf-8') self._fingerprint = hashlib.sha256(to_hash).digest() return self._fingerprint
python
def fingerprint(self): """ Creates a fingerprint that can be compared with a public key to see if the two form a pair. This fingerprint is not compatible with fingerprints generated by any other software. :return: A byte string that is a sha256 hash of selected components (based on the key type) """ if self._fingerprint is None: params = self['private_key_algorithm']['parameters'] key = self['private_key'].parsed if self.algorithm == 'rsa': to_hash = '%d:%d' % ( key['modulus'].native, key['public_exponent'].native, ) elif self.algorithm == 'dsa': public_key = self.public_key to_hash = '%d:%d:%d:%d' % ( params['p'].native, params['q'].native, params['g'].native, public_key.native, ) elif self.algorithm == 'ec': public_key = key['public_key'].native if public_key is None: public_key = self.public_key.native if params.name == 'named': to_hash = '%s:' % params.chosen.native to_hash = to_hash.encode('utf-8') to_hash += public_key elif params.name == 'implicit_ca': to_hash = public_key elif params.name == 'specified': to_hash = '%s:' % params.chosen['field_id']['parameters'].native to_hash = to_hash.encode('utf-8') to_hash += b':' + params.chosen['curve']['a'].native to_hash += b':' + params.chosen['curve']['b'].native to_hash += public_key if isinstance(to_hash, str_cls): to_hash = to_hash.encode('utf-8') self._fingerprint = hashlib.sha256(to_hash).digest() return self._fingerprint
[ "def", "fingerprint", "(", "self", ")", ":", "if", "self", ".", "_fingerprint", "is", "None", ":", "params", "=", "self", "[", "'private_key_algorithm'", "]", "[", "'parameters'", "]", "key", "=", "self", "[", "'private_key'", "]", ".", "parsed", "if", "...
Creates a fingerprint that can be compared with a public key to see if the two form a pair. This fingerprint is not compatible with fingerprints generated by any other software. :return: A byte string that is a sha256 hash of selected components (based on the key type)
[ "Creates", "a", "fingerprint", "that", "can", "be", "compared", "with", "a", "public", "key", "to", "see", "if", "the", "two", "form", "a", "pair", "." ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/keys.py#L828-L885
train
200,220
wbond/asn1crypto
dev/coverage.py
run
def run(ci=False): """ Runs the tests while measuring coverage :param ci: If coverage is being run in a CI environment - this triggers trying to run the tests for the rest of modularcrypto and uploading coverage data :return: A bool - if the tests ran successfully """ xml_report_path = os.path.join(package_root, 'coverage.xml') if os.path.exists(xml_report_path): os.unlink(xml_report_path) cov = coverage.Coverage(include='%s/*.py' % package_name) cov.start() from .tests import run as run_tests result = run_tests() print() if ci: suite = unittest.TestSuite() loader = unittest.TestLoader() for other_package in other_packages: for test_class in _load_package_tests(other_package): suite.addTest(loader.loadTestsFromTestCase(test_class)) if suite.countTestCases() > 0: print('Running tests from other modularcrypto packages') sys.stdout.flush() runner_result = unittest.TextTestRunner(stream=sys.stdout, verbosity=1).run(suite) result = runner_result.wasSuccessful() and result print() sys.stdout.flush() cov.stop() cov.save() cov.report(show_missing=False) print() sys.stdout.flush() if ci: cov.xml_report() if ci and result and os.path.exists(xml_report_path): _codecov_submit() print() return result
python
def run(ci=False): """ Runs the tests while measuring coverage :param ci: If coverage is being run in a CI environment - this triggers trying to run the tests for the rest of modularcrypto and uploading coverage data :return: A bool - if the tests ran successfully """ xml_report_path = os.path.join(package_root, 'coverage.xml') if os.path.exists(xml_report_path): os.unlink(xml_report_path) cov = coverage.Coverage(include='%s/*.py' % package_name) cov.start() from .tests import run as run_tests result = run_tests() print() if ci: suite = unittest.TestSuite() loader = unittest.TestLoader() for other_package in other_packages: for test_class in _load_package_tests(other_package): suite.addTest(loader.loadTestsFromTestCase(test_class)) if suite.countTestCases() > 0: print('Running tests from other modularcrypto packages') sys.stdout.flush() runner_result = unittest.TextTestRunner(stream=sys.stdout, verbosity=1).run(suite) result = runner_result.wasSuccessful() and result print() sys.stdout.flush() cov.stop() cov.save() cov.report(show_missing=False) print() sys.stdout.flush() if ci: cov.xml_report() if ci and result and os.path.exists(xml_report_path): _codecov_submit() print() return result
[ "def", "run", "(", "ci", "=", "False", ")", ":", "xml_report_path", "=", "os", ".", "path", ".", "join", "(", "package_root", ",", "'coverage.xml'", ")", "if", "os", ".", "path", ".", "exists", "(", "xml_report_path", ")", ":", "os", ".", "unlink", "...
Runs the tests while measuring coverage :param ci: If coverage is being run in a CI environment - this triggers trying to run the tests for the rest of modularcrypto and uploading coverage data :return: A bool - if the tests ran successfully
[ "Runs", "the", "tests", "while", "measuring", "coverage" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/coverage.py#L30-L81
train
200,221
wbond/asn1crypto
dev/coverage.py
_git_command
def _git_command(params, cwd): """ Executes a git command, returning the output :param params: A list of the parameters to pass to git :param cwd: The working directory to execute git in :return: A 2-element tuple of (stdout, stderr) """ proc = subprocess.Popen( ['git'] + params, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd ) stdout, stderr = proc.communicate() code = proc.wait() if code != 0: e = OSError('git exit code was non-zero') e.stdout = stdout raise e return stdout.decode('utf-8').strip()
python
def _git_command(params, cwd): """ Executes a git command, returning the output :param params: A list of the parameters to pass to git :param cwd: The working directory to execute git in :return: A 2-element tuple of (stdout, stderr) """ proc = subprocess.Popen( ['git'] + params, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd ) stdout, stderr = proc.communicate() code = proc.wait() if code != 0: e = OSError('git exit code was non-zero') e.stdout = stdout raise e return stdout.decode('utf-8').strip()
[ "def", "_git_command", "(", "params", ",", "cwd", ")", ":", "proc", "=", "subprocess", ".", "Popen", "(", "[", "'git'", "]", "+", "params", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "cwd", "=...
Executes a git command, returning the output :param params: A list of the parameters to pass to git :param cwd: The working directory to execute git in :return: A 2-element tuple of (stdout, stderr)
[ "Executes", "a", "git", "command", "returning", "the", "output" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/coverage.py#L252-L278
train
200,222
wbond/asn1crypto
dev/coverage.py
_parse_env_var_file
def _parse_env_var_file(data): """ Parses a basic VAR="value data" file contents into a dict :param data: A unicode string of the file data :return: A dict of parsed name/value data """ output = {} for line in data.splitlines(): line = line.strip() if not line or '=' not in line: continue parts = line.split('=') if len(parts) != 2: continue name = parts[0] value = parts[1] if len(value) > 1: if value[0] == '"' and value[-1] == '"': value = value[1:-1] output[name] = value return output
python
def _parse_env_var_file(data): """ Parses a basic VAR="value data" file contents into a dict :param data: A unicode string of the file data :return: A dict of parsed name/value data """ output = {} for line in data.splitlines(): line = line.strip() if not line or '=' not in line: continue parts = line.split('=') if len(parts) != 2: continue name = parts[0] value = parts[1] if len(value) > 1: if value[0] == '"' and value[-1] == '"': value = value[1:-1] output[name] = value return output
[ "def", "_parse_env_var_file", "(", "data", ")", ":", "output", "=", "{", "}", "for", "line", "in", "data", ".", "splitlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", "or", "'='", "not", "in", "line", ":", ...
Parses a basic VAR="value data" file contents into a dict :param data: A unicode string of the file data :return: A dict of parsed name/value data
[ "Parses", "a", "basic", "VAR", "=", "value", "data", "file", "contents", "into", "a", "dict" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/coverage.py#L281-L306
train
200,223
wbond/asn1crypto
dev/coverage.py
_platform_name
def _platform_name(): """ Returns information about the current operating system and version :return: A unicode string containing the OS name and version """ if sys.platform == 'darwin': version = _plat.mac_ver()[0] _plat_ver_info = tuple(map(int, version.split('.'))) if _plat_ver_info < (10, 12): name = 'OS X' else: name = 'macOS' return '%s %s' % (name, version) elif sys.platform == 'win32': _win_ver = sys.getwindowsversion() _plat_ver_info = (_win_ver[0], _win_ver[1]) return 'Windows %s' % _plat.win32_ver()[0] elif sys.platform in ['linux', 'linux2']: if os.path.exists('/etc/os-release'): with open('/etc/os-release', 'r', encoding='utf-8') as f: pairs = _parse_env_var_file(f.read()) if 'NAME' in pairs and 'VERSION_ID' in pairs: return '%s %s' % (pairs['NAME'], pairs['VERSION_ID']) version = pairs['VERSION_ID'] elif 'PRETTY_NAME' in pairs: return pairs['PRETTY_NAME'] elif 'NAME' in pairs: return pairs['NAME'] else: raise ValueError('No suitable version info found in /etc/os-release') elif os.path.exists('/etc/lsb-release'): with open('/etc/lsb-release', 'r', encoding='utf-8') as f: pairs = _parse_env_var_file(f.read()) if 'DISTRIB_DESCRIPTION' in pairs: return pairs['DISTRIB_DESCRIPTION'] else: raise ValueError('No suitable version info found in /etc/lsb-release') else: return 'Linux' else: return '%s %s' % (_plat.system(), _plat.release())
python
def _platform_name(): """ Returns information about the current operating system and version :return: A unicode string containing the OS name and version """ if sys.platform == 'darwin': version = _plat.mac_ver()[0] _plat_ver_info = tuple(map(int, version.split('.'))) if _plat_ver_info < (10, 12): name = 'OS X' else: name = 'macOS' return '%s %s' % (name, version) elif sys.platform == 'win32': _win_ver = sys.getwindowsversion() _plat_ver_info = (_win_ver[0], _win_ver[1]) return 'Windows %s' % _plat.win32_ver()[0] elif sys.platform in ['linux', 'linux2']: if os.path.exists('/etc/os-release'): with open('/etc/os-release', 'r', encoding='utf-8') as f: pairs = _parse_env_var_file(f.read()) if 'NAME' in pairs and 'VERSION_ID' in pairs: return '%s %s' % (pairs['NAME'], pairs['VERSION_ID']) version = pairs['VERSION_ID'] elif 'PRETTY_NAME' in pairs: return pairs['PRETTY_NAME'] elif 'NAME' in pairs: return pairs['NAME'] else: raise ValueError('No suitable version info found in /etc/os-release') elif os.path.exists('/etc/lsb-release'): with open('/etc/lsb-release', 'r', encoding='utf-8') as f: pairs = _parse_env_var_file(f.read()) if 'DISTRIB_DESCRIPTION' in pairs: return pairs['DISTRIB_DESCRIPTION'] else: raise ValueError('No suitable version info found in /etc/lsb-release') else: return 'Linux' else: return '%s %s' % (_plat.system(), _plat.release())
[ "def", "_platform_name", "(", ")", ":", "if", "sys", ".", "platform", "==", "'darwin'", ":", "version", "=", "_plat", ".", "mac_ver", "(", ")", "[", "0", "]", "_plat_ver_info", "=", "tuple", "(", "map", "(", "int", ",", "version", ".", "split", "(", ...
Returns information about the current operating system and version :return: A unicode string containing the OS name and version
[ "Returns", "information", "about", "the", "current", "operating", "system", "and", "version" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/coverage.py#L309-L355
train
200,224
wbond/asn1crypto
dev/coverage.py
_list_files
def _list_files(root): """ Lists all of the files in a directory, taking into account any .gitignore file that is present :param root: A unicode filesystem path :return: A list of unicode strings, containing paths of all files not ignored by .gitignore with root, using relative paths """ dir_patterns, file_patterns = _gitignore(root) paths = [] prefix = os.path.abspath(root) + os.sep for base, dirs, files in os.walk(root): for d in dirs: for dir_pattern in dir_patterns: if fnmatch(d, dir_pattern): dirs.remove(d) break for f in files: skip = False for file_pattern in file_patterns: if fnmatch(f, file_pattern): skip = True break if skip: continue full_path = os.path.join(base, f) if full_path[:len(prefix)] == prefix: full_path = full_path[len(prefix):] paths.append(full_path) return sorted(paths)
python
def _list_files(root): """ Lists all of the files in a directory, taking into account any .gitignore file that is present :param root: A unicode filesystem path :return: A list of unicode strings, containing paths of all files not ignored by .gitignore with root, using relative paths """ dir_patterns, file_patterns = _gitignore(root) paths = [] prefix = os.path.abspath(root) + os.sep for base, dirs, files in os.walk(root): for d in dirs: for dir_pattern in dir_patterns: if fnmatch(d, dir_pattern): dirs.remove(d) break for f in files: skip = False for file_pattern in file_patterns: if fnmatch(f, file_pattern): skip = True break if skip: continue full_path = os.path.join(base, f) if full_path[:len(prefix)] == prefix: full_path = full_path[len(prefix):] paths.append(full_path) return sorted(paths)
[ "def", "_list_files", "(", "root", ")", ":", "dir_patterns", ",", "file_patterns", "=", "_gitignore", "(", "root", ")", "paths", "=", "[", "]", "prefix", "=", "os", ".", "path", ".", "abspath", "(", "root", ")", "+", "os", ".", "sep", "for", "base", ...
Lists all of the files in a directory, taking into account any .gitignore file that is present :param root: A unicode filesystem path :return: A list of unicode strings, containing paths of all files not ignored by .gitignore with root, using relative paths
[ "Lists", "all", "of", "the", "files", "in", "a", "directory", "taking", "into", "account", "any", ".", "gitignore", "file", "that", "is", "present" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/coverage.py#L358-L392
train
200,225
wbond/asn1crypto
dev/coverage.py
_execute
def _execute(params, cwd): """ Executes a subprocess :param params: A list of the executable and arguments to pass to it :param cwd: The working directory to execute the command in :return: A 2-element tuple of (stdout, stderr) """ proc = subprocess.Popen( params, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd ) stdout, stderr = proc.communicate() code = proc.wait() if code != 0: e = OSError('subprocess exit code for %r was %d: %s' % (params, code, stderr)) e.stdout = stdout e.stderr = stderr raise e return (stdout, stderr)
python
def _execute(params, cwd): """ Executes a subprocess :param params: A list of the executable and arguments to pass to it :param cwd: The working directory to execute the command in :return: A 2-element tuple of (stdout, stderr) """ proc = subprocess.Popen( params, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd ) stdout, stderr = proc.communicate() code = proc.wait() if code != 0: e = OSError('subprocess exit code for %r was %d: %s' % (params, code, stderr)) e.stdout = stdout e.stderr = stderr raise e return (stdout, stderr)
[ "def", "_execute", "(", "params", ",", "cwd", ")", ":", "proc", "=", "subprocess", ".", "Popen", "(", "params", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "cwd", "=", "cwd", ")", "stdout", ",", ...
Executes a subprocess :param params: A list of the executable and arguments to pass to it :param cwd: The working directory to execute the command in :return: A 2-element tuple of (stdout, stderr)
[ "Executes", "a", "subprocess" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/coverage.py#L569-L596
train
200,226
wbond/asn1crypto
dev/deps.py
run
def run(): """ Installs required development dependencies. Uses git to checkout other modularcrypto repos for more accurate coverage data. """ deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): shutil.rmtree(deps_dir, ignore_errors=True) os.mkdir(deps_dir) try: print("Staging ci dependencies") _stage_requirements(deps_dir, os.path.join(package_root, 'requires', 'ci')) print("Checking out modularcrypto packages for coverage") for other_package in other_packages: pkg_url = 'https://github.com/wbond/%s.git' % other_package pkg_dir = os.path.join(build_root, other_package) if os.path.exists(pkg_dir): print("%s is already present" % other_package) continue print("Cloning %s" % pkg_url) _execute(['git', 'clone', pkg_url], build_root) print() except (Exception): if os.path.exists(deps_dir): shutil.rmtree(deps_dir, ignore_errors=True) raise return True
python
def run(): """ Installs required development dependencies. Uses git to checkout other modularcrypto repos for more accurate coverage data. """ deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): shutil.rmtree(deps_dir, ignore_errors=True) os.mkdir(deps_dir) try: print("Staging ci dependencies") _stage_requirements(deps_dir, os.path.join(package_root, 'requires', 'ci')) print("Checking out modularcrypto packages for coverage") for other_package in other_packages: pkg_url = 'https://github.com/wbond/%s.git' % other_package pkg_dir = os.path.join(build_root, other_package) if os.path.exists(pkg_dir): print("%s is already present" % other_package) continue print("Cloning %s" % pkg_url) _execute(['git', 'clone', pkg_url], build_root) print() except (Exception): if os.path.exists(deps_dir): shutil.rmtree(deps_dir, ignore_errors=True) raise return True
[ "def", "run", "(", ")", ":", "deps_dir", "=", "os", ".", "path", ".", "join", "(", "build_root", ",", "'modularcrypto-deps'", ")", "if", "os", ".", "path", ".", "exists", "(", "deps_dir", ")", ":", "shutil", ".", "rmtree", "(", "deps_dir", ",", "igno...
Installs required development dependencies. Uses git to checkout other modularcrypto repos for more accurate coverage data.
[ "Installs", "required", "development", "dependencies", ".", "Uses", "git", "to", "checkout", "other", "modularcrypto", "repos", "for", "more", "accurate", "coverage", "data", "." ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/deps.py#L22-L53
train
200,227
wbond/asn1crypto
dev/deps.py
_download
def _download(url, dest): """ Downloads a URL to a directory :param url: The URL to download :param dest: The path to the directory to save the file in :return: The filesystem path to the saved file """ print('Downloading %s' % url) filename = os.path.basename(url) dest_path = os.path.join(dest, filename) if sys.platform == 'win32': powershell_exe = os.path.join('system32\\WindowsPowerShell\\v1.0\\powershell.exe') code = "[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;" code += "(New-Object Net.WebClient).DownloadFile('%s', '%s');" % (url, dest_path) _execute([powershell_exe, '-Command', code], dest) else: _execute(['curl', '-L', '--silent', '--show-error', '-O', url], dest) return dest_path
python
def _download(url, dest): """ Downloads a URL to a directory :param url: The URL to download :param dest: The path to the directory to save the file in :return: The filesystem path to the saved file """ print('Downloading %s' % url) filename = os.path.basename(url) dest_path = os.path.join(dest, filename) if sys.platform == 'win32': powershell_exe = os.path.join('system32\\WindowsPowerShell\\v1.0\\powershell.exe') code = "[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;" code += "(New-Object Net.WebClient).DownloadFile('%s', '%s');" % (url, dest_path) _execute([powershell_exe, '-Command', code], dest) else: _execute(['curl', '-L', '--silent', '--show-error', '-O', url], dest) return dest_path
[ "def", "_download", "(", "url", ",", "dest", ")", ":", "print", "(", "'Downloading %s'", "%", "url", ")", "filename", "=", "os", ".", "path", ".", "basename", "(", "url", ")", "dest_path", "=", "os", ".", "path", ".", "join", "(", "dest", ",", "fil...
Downloads a URL to a directory :param url: The URL to download :param dest: The path to the directory to save the file in :return: The filesystem path to the saved file
[ "Downloads", "a", "URL", "to", "a", "directory" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/deps.py#L56-L83
train
200,228
wbond/asn1crypto
dev/deps.py
_archive_single_dir
def _archive_single_dir(archive): """ Check if all members of the archive are in a single top-level directory :param archive: An archive from _open_archive() :return: None if not a single top level directory in archive, otherwise a unicode string of the top level directory name """ common_root = None for info in _list_archive_members(archive): fn = _info_name(info) if fn in set(['.', '/']): continue sep = None if '/' in fn: sep = '/' elif '\\' in fn: sep = '\\' if sep is None: root_dir = fn else: root_dir, _ = fn.split(sep, 1) if common_root is None: common_root = root_dir else: if common_root != root_dir: return None return common_root
python
def _archive_single_dir(archive): """ Check if all members of the archive are in a single top-level directory :param archive: An archive from _open_archive() :return: None if not a single top level directory in archive, otherwise a unicode string of the top level directory name """ common_root = None for info in _list_archive_members(archive): fn = _info_name(info) if fn in set(['.', '/']): continue sep = None if '/' in fn: sep = '/' elif '\\' in fn: sep = '\\' if sep is None: root_dir = fn else: root_dir, _ = fn.split(sep, 1) if common_root is None: common_root = root_dir else: if common_root != root_dir: return None return common_root
[ "def", "_archive_single_dir", "(", "archive", ")", ":", "common_root", "=", "None", "for", "info", "in", "_list_archive_members", "(", "archive", ")", ":", "fn", "=", "_info_name", "(", "info", ")", "if", "fn", "in", "set", "(", "[", "'.'", ",", "'/'", ...
Check if all members of the archive are in a single top-level directory :param archive: An archive from _open_archive() :return: None if not a single top level directory in archive, otherwise a unicode string of the top level directory name
[ "Check", "if", "all", "members", "of", "the", "archive", "are", "in", "a", "single", "top", "-", "level", "directory" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/deps.py#L126-L157
train
200,229
wbond/asn1crypto
dev/deps.py
_info_name
def _info_name(info): """ Returns a normalized file path for an archive info object :param info: An info object from _list_archive_members() :return: A unicode string with all directory separators normalized to "/" """ if isinstance(info, zipfile.ZipInfo): return info.filename.replace('\\', '/') return info.name.replace('\\', '/')
python
def _info_name(info): """ Returns a normalized file path for an archive info object :param info: An info object from _list_archive_members() :return: A unicode string with all directory separators normalized to "/" """ if isinstance(info, zipfile.ZipInfo): return info.filename.replace('\\', '/') return info.name.replace('\\', '/')
[ "def", "_info_name", "(", "info", ")", ":", "if", "isinstance", "(", "info", ",", "zipfile", ".", "ZipInfo", ")", ":", "return", "info", ".", "filename", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "return", "info", ".", "name", ".", "replace", "...
Returns a normalized file path for an archive info object :param info: An info object from _list_archive_members() :return: A unicode string with all directory separators normalized to "/"
[ "Returns", "a", "normalized", "file", "path", "for", "an", "archive", "info", "object" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/deps.py#L160-L173
train
200,230
wbond/asn1crypto
dev/deps.py
_extract_info
def _extract_info(archive, info): """ Extracts the contents of an archive info object ;param archive: An archive from _open_archive() :param info: An info object from _list_archive_members() :return: None, or a byte string of the file contents """ if isinstance(archive, zipfile.ZipFile): fn = info.filename is_dir = fn.endswith('/') or fn.endswith('\\') out = archive.read(info) if is_dir and out == b'': return None return out info_file = archive.extractfile(info) if info_file: return info_file.read() return None
python
def _extract_info(archive, info): """ Extracts the contents of an archive info object ;param archive: An archive from _open_archive() :param info: An info object from _list_archive_members() :return: None, or a byte string of the file contents """ if isinstance(archive, zipfile.ZipFile): fn = info.filename is_dir = fn.endswith('/') or fn.endswith('\\') out = archive.read(info) if is_dir and out == b'': return None return out info_file = archive.extractfile(info) if info_file: return info_file.read() return None
[ "def", "_extract_info", "(", "archive", ",", "info", ")", ":", "if", "isinstance", "(", "archive", ",", "zipfile", ".", "ZipFile", ")", ":", "fn", "=", "info", ".", "filename", "is_dir", "=", "fn", ".", "endswith", "(", "'/'", ")", "or", "fn", ".", ...
Extracts the contents of an archive info object ;param archive: An archive from _open_archive() :param info: An info object from _list_archive_members() :return: None, or a byte string of the file contents
[ "Extracts", "the", "contents", "of", "an", "archive", "info", "object" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/deps.py#L176-L201
train
200,231
wbond/asn1crypto
dev/deps.py
_extract_package
def _extract_package(deps_dir, pkg_path): """ Extract a .whl, .zip, .tar.gz or .tar.bz2 into a package path to use when running CI tasks :param deps_dir: A unicode string of the directory the package should be extracted to :param pkg_path: A unicode string of the path to the archive """ if pkg_path.endswith('.exe'): try: zf = None zf = zipfile.ZipFile(pkg_path, 'r') # Exes have a PLATLIB folder containing everything we want for zi in zf.infolist(): if not zi.filename.startswith('PLATLIB'): continue data = _extract_info(zf, zi) if data is not None: dst_path = os.path.join(deps_dir, zi.filename[8:]) dst_dir = os.path.dirname(dst_path) if not os.path.exists(dst_dir): os.makedirs(dst_dir) with open(dst_path, 'wb') as f: f.write(data) finally: if zf: zf.close() return if pkg_path.endswith('.whl'): try: zf = None zf = zipfile.ZipFile(pkg_path, 'r') # Wheels contain exactly what we need and nothing else zf.extractall(deps_dir) finally: if zf: zf.close() return # Source archives may contain a bunch of other things. # The following code works for the packages coverage and # configparser, which are the two we currently require that # do not provide wheels try: ar = None ar = _open_archive(pkg_path) pkg_name = None base_path = _archive_single_dir(ar) or '' if len(base_path): if '-' in base_path: pkg_name, _ = base_path.split('-', 1) base_path += '/' base_pkg_path = None if pkg_name is not None: base_pkg_path = base_path + pkg_name + '/' src_path = base_path + 'src/' members = [] for info in _list_archive_members(ar): fn = _info_name(info) if base_pkg_path is not None and fn.startswith(base_pkg_path): dst_path = fn[len(base_pkg_path) - len(pkg_name) - 1:] members.append((info, dst_path)) continue if fn.startswith(src_path): members.append((info, fn[len(src_path):])) continue for info, path in members: info_data = _extract_info(ar, info) # Dirs won't return a file if info_data is not None: dst_path = os.path.join(deps_dir, path) dst_dir = os.path.dirname(dst_path) if not os.path.exists(dst_dir): os.makedirs(dst_dir) with open(dst_path, 'wb') as f: f.write(info_data) finally: if ar: ar.close()
python
def _extract_package(deps_dir, pkg_path): """ Extract a .whl, .zip, .tar.gz or .tar.bz2 into a package path to use when running CI tasks :param deps_dir: A unicode string of the directory the package should be extracted to :param pkg_path: A unicode string of the path to the archive """ if pkg_path.endswith('.exe'): try: zf = None zf = zipfile.ZipFile(pkg_path, 'r') # Exes have a PLATLIB folder containing everything we want for zi in zf.infolist(): if not zi.filename.startswith('PLATLIB'): continue data = _extract_info(zf, zi) if data is not None: dst_path = os.path.join(deps_dir, zi.filename[8:]) dst_dir = os.path.dirname(dst_path) if not os.path.exists(dst_dir): os.makedirs(dst_dir) with open(dst_path, 'wb') as f: f.write(data) finally: if zf: zf.close() return if pkg_path.endswith('.whl'): try: zf = None zf = zipfile.ZipFile(pkg_path, 'r') # Wheels contain exactly what we need and nothing else zf.extractall(deps_dir) finally: if zf: zf.close() return # Source archives may contain a bunch of other things. # The following code works for the packages coverage and # configparser, which are the two we currently require that # do not provide wheels try: ar = None ar = _open_archive(pkg_path) pkg_name = None base_path = _archive_single_dir(ar) or '' if len(base_path): if '-' in base_path: pkg_name, _ = base_path.split('-', 1) base_path += '/' base_pkg_path = None if pkg_name is not None: base_pkg_path = base_path + pkg_name + '/' src_path = base_path + 'src/' members = [] for info in _list_archive_members(ar): fn = _info_name(info) if base_pkg_path is not None and fn.startswith(base_pkg_path): dst_path = fn[len(base_pkg_path) - len(pkg_name) - 1:] members.append((info, dst_path)) continue if fn.startswith(src_path): members.append((info, fn[len(src_path):])) continue for info, path in members: info_data = _extract_info(ar, info) # Dirs won't return a file if info_data is not None: dst_path = os.path.join(deps_dir, path) dst_dir = os.path.dirname(dst_path) if not os.path.exists(dst_dir): os.makedirs(dst_dir) with open(dst_path, 'wb') as f: f.write(info_data) finally: if ar: ar.close()
[ "def", "_extract_package", "(", "deps_dir", ",", "pkg_path", ")", ":", "if", "pkg_path", ".", "endswith", "(", "'.exe'", ")", ":", "try", ":", "zf", "=", "None", "zf", "=", "zipfile", ".", "ZipFile", "(", "pkg_path", ",", "'r'", ")", "# Exes have a PLATL...
Extract a .whl, .zip, .tar.gz or .tar.bz2 into a package path to use when running CI tasks :param deps_dir: A unicode string of the directory the package should be extracted to :param pkg_path: A unicode string of the path to the archive
[ "Extract", "a", ".", "whl", ".", "zip", ".", "tar", ".", "gz", "or", ".", "tar", ".", "bz2", "into", "a", "package", "path", "to", "use", "when", "running", "CI", "tasks" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/deps.py#L204-L292
train
200,232
wbond/asn1crypto
dev/deps.py
_parse_requires
def _parse_requires(path): """ Does basic parsing of pip requirements files, to allow for using something other than Python to do actual TLS requests :param path: A path to a requirements file :return: A list of dict objects containing the keys: - 'type' ('any', 'url', '==', '>=') - 'pkg' - 'ver' (if 'type' == '==' or 'type' == '>=') """ python_version = '.'.join(map(str_cls, sys.version_info[0:2])) sys_platform = sys.platform packages = [] with open(path, 'rb') as f: contents = f.read().decode('utf-8') for line in re.split(r'\r?\n', contents): line = line.strip() if not len(line): continue if re.match(r'^\s*#', line): continue if ';' in line: package, cond = line.split(';', 1) package = package.strip() cond = cond.strip() cond = cond.replace('sys_platform', repr(sys_platform)) cond = cond.replace('python_version', repr(python_version)) if not eval(cond): continue else: package = line.strip() if re.match(r'^\s*-r\s*', package): sub_req_file = re.sub(r'^\s*-r\s*', '', package) sub_req_file = os.path.abspath(os.path.join(os.path.dirname(path), sub_req_file)) packages.extend(_parse_requires(sub_req_file)) continue if re.match(r'https?://', package): packages.append({'type': 'url', 'pkg': package}) continue if '>=' in package: parts = package.split('>=') package = parts[0].strip() ver = parts[1].strip() packages.append({'type': '>=', 'pkg': package, 'ver': ver}) continue if '==' in package: parts = package.split('==') package = parts[0].strip() ver = parts[1].strip() packages.append({'type': '==', 'pkg': package, 'ver': ver}) continue if re.search(r'[^ a-zA-Z0-9\-]', package): raise Exception('Unsupported requirements format version constraint: %s' % package) packages.append({'type': 'any', 'pkg': package}) return packages
python
def _parse_requires(path): """ Does basic parsing of pip requirements files, to allow for using something other than Python to do actual TLS requests :param path: A path to a requirements file :return: A list of dict objects containing the keys: - 'type' ('any', 'url', '==', '>=') - 'pkg' - 'ver' (if 'type' == '==' or 'type' == '>=') """ python_version = '.'.join(map(str_cls, sys.version_info[0:2])) sys_platform = sys.platform packages = [] with open(path, 'rb') as f: contents = f.read().decode('utf-8') for line in re.split(r'\r?\n', contents): line = line.strip() if not len(line): continue if re.match(r'^\s*#', line): continue if ';' in line: package, cond = line.split(';', 1) package = package.strip() cond = cond.strip() cond = cond.replace('sys_platform', repr(sys_platform)) cond = cond.replace('python_version', repr(python_version)) if not eval(cond): continue else: package = line.strip() if re.match(r'^\s*-r\s*', package): sub_req_file = re.sub(r'^\s*-r\s*', '', package) sub_req_file = os.path.abspath(os.path.join(os.path.dirname(path), sub_req_file)) packages.extend(_parse_requires(sub_req_file)) continue if re.match(r'https?://', package): packages.append({'type': 'url', 'pkg': package}) continue if '>=' in package: parts = package.split('>=') package = parts[0].strip() ver = parts[1].strip() packages.append({'type': '>=', 'pkg': package, 'ver': ver}) continue if '==' in package: parts = package.split('==') package = parts[0].strip() ver = parts[1].strip() packages.append({'type': '==', 'pkg': package, 'ver': ver}) continue if re.search(r'[^ a-zA-Z0-9\-]', package): raise Exception('Unsupported requirements format version constraint: %s' % package) packages.append({'type': 'any', 'pkg': package}) return packages
[ "def", "_parse_requires", "(", "path", ")", ":", "python_version", "=", "'.'", ".", "join", "(", "map", "(", "str_cls", ",", "sys", ".", "version_info", "[", "0", ":", "2", "]", ")", ")", "sys_platform", "=", "sys", ".", "platform", "packages", "=", ...
Does basic parsing of pip requirements files, to allow for using something other than Python to do actual TLS requests :param path: A path to a requirements file :return: A list of dict objects containing the keys: - 'type' ('any', 'url', '==', '>=') - 'pkg' - 'ver' (if 'type' == '==' or 'type' == '>=')
[ "Does", "basic", "parsing", "of", "pip", "requirements", "files", "to", "allow", "for", "using", "something", "other", "than", "Python", "to", "do", "actual", "TLS", "requests" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/deps.py#L387-L456
train
200,233
wbond/asn1crypto
asn1crypto/pem.py
unarmor
def unarmor(pem_bytes, multiple=False): """ Convert a PEM-encoded byte string into a DER-encoded byte string :param pem_bytes: A byte string of the PEM-encoded data :param multiple: If True, function will return a generator :raises: ValueError - when the pem_bytes do not appear to be PEM-encoded bytes :return: A 3-element tuple (object_name, headers, der_bytes). The object_name is a unicode string of what is between "-----BEGIN " and "-----". Examples include: "CERTIFICATE", "PUBLIC KEY", "PRIVATE KEY". The headers is a dict containing any lines in the form "Name: Value" that are right after the begin line. """ generator = _unarmor(pem_bytes) if not multiple: return next(generator) return generator
python
def unarmor(pem_bytes, multiple=False): """ Convert a PEM-encoded byte string into a DER-encoded byte string :param pem_bytes: A byte string of the PEM-encoded data :param multiple: If True, function will return a generator :raises: ValueError - when the pem_bytes do not appear to be PEM-encoded bytes :return: A 3-element tuple (object_name, headers, der_bytes). The object_name is a unicode string of what is between "-----BEGIN " and "-----". Examples include: "CERTIFICATE", "PUBLIC KEY", "PRIVATE KEY". The headers is a dict containing any lines in the form "Name: Value" that are right after the begin line. """ generator = _unarmor(pem_bytes) if not multiple: return next(generator) return generator
[ "def", "unarmor", "(", "pem_bytes", ",", "multiple", "=", "False", ")", ":", "generator", "=", "_unarmor", "(", "pem_bytes", ")", "if", "not", "multiple", ":", "return", "next", "(", "generator", ")", "return", "generator" ]
Convert a PEM-encoded byte string into a DER-encoded byte string :param pem_bytes: A byte string of the PEM-encoded data :param multiple: If True, function will return a generator :raises: ValueError - when the pem_bytes do not appear to be PEM-encoded bytes :return: A 3-element tuple (object_name, headers, der_bytes). The object_name is a unicode string of what is between "-----BEGIN " and "-----". Examples include: "CERTIFICATE", "PUBLIC KEY", "PRIVATE KEY". The headers is a dict containing any lines in the form "Name: Value" that are right after the begin line.
[ "Convert", "a", "PEM", "-", "encoded", "byte", "string", "into", "a", "DER", "-", "encoded", "byte", "string" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/pem.py#L196-L222
train
200,234
wbond/asn1crypto
asn1crypto/x509.py
NameType.preferred_ordinal
def preferred_ordinal(cls, attr_name): """ Returns an ordering value for a particular attribute key. Unrecognized attributes and OIDs will be sorted lexically at the end. :return: An orderable value. """ attr_name = cls.map(attr_name) if attr_name in cls.preferred_order: ordinal = cls.preferred_order.index(attr_name) else: ordinal = len(cls.preferred_order) return (ordinal, attr_name)
python
def preferred_ordinal(cls, attr_name): """ Returns an ordering value for a particular attribute key. Unrecognized attributes and OIDs will be sorted lexically at the end. :return: An orderable value. """ attr_name = cls.map(attr_name) if attr_name in cls.preferred_order: ordinal = cls.preferred_order.index(attr_name) else: ordinal = len(cls.preferred_order) return (ordinal, attr_name)
[ "def", "preferred_ordinal", "(", "cls", ",", "attr_name", ")", ":", "attr_name", "=", "cls", ".", "map", "(", "attr_name", ")", "if", "attr_name", "in", "cls", ".", "preferred_order", ":", "ordinal", "=", "cls", ".", "preferred_order", ".", "index", "(", ...
Returns an ordering value for a particular attribute key. Unrecognized attributes and OIDs will be sorted lexically at the end. :return: An orderable value.
[ "Returns", "an", "ordering", "value", "for", "a", "particular", "attribute", "key", "." ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L584-L601
train
200,235
wbond/asn1crypto
asn1crypto/x509.py
NameTypeAndValue.prepped_value
def prepped_value(self): """ Returns the value after being processed by the internationalized string preparation as specified by RFC 5280 :return: A unicode string """ if self._prepped is None: self._prepped = self._ldap_string_prep(self['value'].native) return self._prepped
python
def prepped_value(self): """ Returns the value after being processed by the internationalized string preparation as specified by RFC 5280 :return: A unicode string """ if self._prepped is None: self._prepped = self._ldap_string_prep(self['value'].native) return self._prepped
[ "def", "prepped_value", "(", "self", ")", ":", "if", "self", ".", "_prepped", "is", "None", ":", "self", ".", "_prepped", "=", "self", ".", "_ldap_string_prep", "(", "self", "[", "'value'", "]", ".", "native", ")", "return", "self", ".", "_prepped" ]
Returns the value after being processed by the internationalized string preparation as specified by RFC 5280 :return: A unicode string
[ "Returns", "the", "value", "after", "being", "processed", "by", "the", "internationalized", "string", "preparation", "as", "specified", "by", "RFC", "5280" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L695-L706
train
200,236
wbond/asn1crypto
asn1crypto/x509.py
RelativeDistinguishedName._get_values
def _get_values(self, rdn): """ Returns a dict of prepped values contained in an RDN :param rdn: A RelativeDistinguishedName object :return: A dict object with unicode strings of NameTypeAndValue value field values that have been prepped for comparison """ output = {} [output.update([(ntv['type'].native, ntv.prepped_value)]) for ntv in rdn] return output
python
def _get_values(self, rdn): """ Returns a dict of prepped values contained in an RDN :param rdn: A RelativeDistinguishedName object :return: A dict object with unicode strings of NameTypeAndValue value field values that have been prepped for comparison """ output = {} [output.update([(ntv['type'].native, ntv.prepped_value)]) for ntv in rdn] return output
[ "def", "_get_values", "(", "self", ",", "rdn", ")", ":", "output", "=", "{", "}", "[", "output", ".", "update", "(", "[", "(", "ntv", "[", "'type'", "]", ".", "native", ",", "ntv", ".", "prepped_value", ")", "]", ")", "for", "ntv", "in", "rdn", ...
Returns a dict of prepped values contained in an RDN :param rdn: A RelativeDistinguishedName object :return: A dict object with unicode strings of NameTypeAndValue value field values that have been prepped for comparison
[ "Returns", "a", "dict", "of", "prepped", "values", "contained", "in", "an", "RDN" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L907-L921
train
200,237
wbond/asn1crypto
asn1crypto/x509.py
Name.build
def build(cls, name_dict, use_printable=False): """ Creates a Name object from a dict of unicode string keys and values. The keys should be from NameType._map, or a dotted-integer OID unicode string. :param name_dict: A dict of name information, e.g. {"common_name": "Will Bond", "country_name": "US", "organization": "Codex Non Sufficit LC"} :param use_printable: A bool - if PrintableString should be used for encoding instead of UTF8String. This is for backwards compatibility with old software. :return: An x509.Name object """ rdns = [] if not use_printable: encoding_name = 'utf8_string' encoding_class = UTF8String else: encoding_name = 'printable_string' encoding_class = PrintableString # Sort the attributes according to NameType.preferred_order name_dict = OrderedDict( sorted( name_dict.items(), key=lambda item: NameType.preferred_ordinal(item[0]) ) ) for attribute_name, attribute_value in name_dict.items(): attribute_name = NameType.map(attribute_name) if attribute_name == 'email_address': value = EmailAddress(attribute_value) elif attribute_name == 'domain_component': value = DNSName(attribute_value) elif attribute_name in set(['dn_qualifier', 'country_name', 'serial_number']): value = DirectoryString( name='printable_string', value=PrintableString(attribute_value) ) else: value = DirectoryString( name=encoding_name, value=encoding_class(attribute_value) ) rdns.append(RelativeDistinguishedName([ NameTypeAndValue({ 'type': attribute_name, 'value': value }) ])) return cls(name='', value=RDNSequence(rdns))
python
def build(cls, name_dict, use_printable=False): """ Creates a Name object from a dict of unicode string keys and values. The keys should be from NameType._map, or a dotted-integer OID unicode string. :param name_dict: A dict of name information, e.g. {"common_name": "Will Bond", "country_name": "US", "organization": "Codex Non Sufficit LC"} :param use_printable: A bool - if PrintableString should be used for encoding instead of UTF8String. This is for backwards compatibility with old software. :return: An x509.Name object """ rdns = [] if not use_printable: encoding_name = 'utf8_string' encoding_class = UTF8String else: encoding_name = 'printable_string' encoding_class = PrintableString # Sort the attributes according to NameType.preferred_order name_dict = OrderedDict( sorted( name_dict.items(), key=lambda item: NameType.preferred_ordinal(item[0]) ) ) for attribute_name, attribute_value in name_dict.items(): attribute_name = NameType.map(attribute_name) if attribute_name == 'email_address': value = EmailAddress(attribute_value) elif attribute_name == 'domain_component': value = DNSName(attribute_value) elif attribute_name in set(['dn_qualifier', 'country_name', 'serial_number']): value = DirectoryString( name='printable_string', value=PrintableString(attribute_value) ) else: value = DirectoryString( name=encoding_name, value=encoding_class(attribute_value) ) rdns.append(RelativeDistinguishedName([ NameTypeAndValue({ 'type': attribute_name, 'value': value }) ])) return cls(name='', value=RDNSequence(rdns))
[ "def", "build", "(", "cls", ",", "name_dict", ",", "use_printable", "=", "False", ")", ":", "rdns", "=", "[", "]", "if", "not", "use_printable", ":", "encoding_name", "=", "'utf8_string'", "encoding_class", "=", "UTF8String", "else", ":", "encoding_name", "=...
Creates a Name object from a dict of unicode string keys and values. The keys should be from NameType._map, or a dotted-integer OID unicode string. :param name_dict: A dict of name information, e.g. {"common_name": "Will Bond", "country_name": "US", "organization": "Codex Non Sufficit LC"} :param use_printable: A bool - if PrintableString should be used for encoding instead of UTF8String. This is for backwards compatibility with old software. :return: An x509.Name object
[ "Creates", "a", "Name", "object", "from", "a", "dict", "of", "unicode", "string", "keys", "and", "values", ".", "The", "keys", "should", "be", "from", "NameType", ".", "_map", "or", "a", "dotted", "-", "integer", "OID", "unicode", "string", "." ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L976-L1034
train
200,238
wbond/asn1crypto
asn1crypto/x509.py
Name._recursive_humanize
def _recursive_humanize(self, value): """ Recursively serializes data compiled from the RDNSequence :param value: An Asn1Value object, or a list of Asn1Value objects :return: A unicode string """ if isinstance(value, list): return', '.join( reversed([self._recursive_humanize(sub_value) for sub_value in value]) ) return value.native
python
def _recursive_humanize(self, value): """ Recursively serializes data compiled from the RDNSequence :param value: An Asn1Value object, or a list of Asn1Value objects :return: A unicode string """ if isinstance(value, list): return', '.join( reversed([self._recursive_humanize(sub_value) for sub_value in value]) ) return value.native
[ "def", "_recursive_humanize", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "', '", ".", "join", "(", "reversed", "(", "[", "self", ".", "_recursive_humanize", "(", "sub_value", ")", "for", "sub_v...
Recursively serializes data compiled from the RDNSequence :param value: An Asn1Value object, or a list of Asn1Value objects :return: A unicode string
[ "Recursively", "serializes", "data", "compiled", "from", "the", "RDNSequence" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L1121-L1136
train
200,239
wbond/asn1crypto
asn1crypto/x509.py
Certificate.crl_distribution_points
def crl_distribution_points(self): """ Returns complete CRL URLs - does not include delta CRLs :return: A list of zero or more DistributionPoint objects """ if self._crl_distribution_points is None: self._crl_distribution_points = self._get_http_crl_distribution_points(self.crl_distribution_points_value) return self._crl_distribution_points
python
def crl_distribution_points(self): """ Returns complete CRL URLs - does not include delta CRLs :return: A list of zero or more DistributionPoint objects """ if self._crl_distribution_points is None: self._crl_distribution_points = self._get_http_crl_distribution_points(self.crl_distribution_points_value) return self._crl_distribution_points
[ "def", "crl_distribution_points", "(", "self", ")", ":", "if", "self", ".", "_crl_distribution_points", "is", "None", ":", "self", ".", "_crl_distribution_points", "=", "self", ".", "_get_http_crl_distribution_points", "(", "self", ".", "crl_distribution_points_value", ...
Returns complete CRL URLs - does not include delta CRLs :return: A list of zero or more DistributionPoint objects
[ "Returns", "complete", "CRL", "URLs", "-", "does", "not", "include", "delta", "CRLs" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L2634-L2644
train
200,240
wbond/asn1crypto
asn1crypto/x509.py
Certificate.delta_crl_distribution_points
def delta_crl_distribution_points(self): """ Returns delta CRL URLs - does not include complete CRLs :return: A list of zero or more DistributionPoint objects """ if self._delta_crl_distribution_points is None: self._delta_crl_distribution_points = self._get_http_crl_distribution_points(self.freshest_crl_value) return self._delta_crl_distribution_points
python
def delta_crl_distribution_points(self): """ Returns delta CRL URLs - does not include complete CRLs :return: A list of zero or more DistributionPoint objects """ if self._delta_crl_distribution_points is None: self._delta_crl_distribution_points = self._get_http_crl_distribution_points(self.freshest_crl_value) return self._delta_crl_distribution_points
[ "def", "delta_crl_distribution_points", "(", "self", ")", ":", "if", "self", ".", "_delta_crl_distribution_points", "is", "None", ":", "self", ".", "_delta_crl_distribution_points", "=", "self", ".", "_get_http_crl_distribution_points", "(", "self", ".", "freshest_crl_v...
Returns delta CRL URLs - does not include complete CRLs :return: A list of zero or more DistributionPoint objects
[ "Returns", "delta", "CRL", "URLs", "-", "does", "not", "include", "complete", "CRLs" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L2647-L2657
train
200,241
wbond/asn1crypto
asn1crypto/x509.py
Certificate._get_http_crl_distribution_points
def _get_http_crl_distribution_points(self, crl_distribution_points): """ Fetches the DistributionPoint object for non-relative, HTTP CRLs referenced by the certificate :param crl_distribution_points: A CRLDistributionPoints object to grab the DistributionPoints from :return: A list of zero or more DistributionPoint objects """ output = [] if crl_distribution_points is None: return [] for distribution_point in crl_distribution_points: distribution_point_name = distribution_point['distribution_point'] if distribution_point_name is VOID: continue # RFC 5280 indicates conforming CA should not use the relative form if distribution_point_name.name == 'name_relative_to_crl_issuer': continue # This library is currently only concerned with HTTP-based CRLs for general_name in distribution_point_name.chosen: if general_name.name == 'uniform_resource_identifier': output.append(distribution_point) return output
python
def _get_http_crl_distribution_points(self, crl_distribution_points): """ Fetches the DistributionPoint object for non-relative, HTTP CRLs referenced by the certificate :param crl_distribution_points: A CRLDistributionPoints object to grab the DistributionPoints from :return: A list of zero or more DistributionPoint objects """ output = [] if crl_distribution_points is None: return [] for distribution_point in crl_distribution_points: distribution_point_name = distribution_point['distribution_point'] if distribution_point_name is VOID: continue # RFC 5280 indicates conforming CA should not use the relative form if distribution_point_name.name == 'name_relative_to_crl_issuer': continue # This library is currently only concerned with HTTP-based CRLs for general_name in distribution_point_name.chosen: if general_name.name == 'uniform_resource_identifier': output.append(distribution_point) return output
[ "def", "_get_http_crl_distribution_points", "(", "self", ",", "crl_distribution_points", ")", ":", "output", "=", "[", "]", "if", "crl_distribution_points", "is", "None", ":", "return", "[", "]", "for", "distribution_point", "in", "crl_distribution_points", ":", "di...
Fetches the DistributionPoint object for non-relative, HTTP CRLs referenced by the certificate :param crl_distribution_points: A CRLDistributionPoints object to grab the DistributionPoints from :return: A list of zero or more DistributionPoint objects
[ "Fetches", "the", "DistributionPoint", "object", "for", "non", "-", "relative", "HTTP", "CRLs", "referenced", "by", "the", "certificate" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L2659-L2688
train
200,242
wbond/asn1crypto
asn1crypto/x509.py
Certificate._is_wildcard_match
def _is_wildcard_match(self, domain_labels, valid_domain_labels): """ Determines if the labels in a domain are a match for labels from a wildcard valid domain name :param domain_labels: A list of unicode strings, with A-label form for IDNs, of the labels in the domain name to check :param valid_domain_labels: A list of unicode strings, with A-label form for IDNs, of the labels in a wildcard domain pattern :return: A boolean - if the domain matches the valid domain """ first_domain_label = domain_labels[0] other_domain_labels = domain_labels[1:] wildcard_label = valid_domain_labels[0] other_valid_domain_labels = valid_domain_labels[1:] # The wildcard is only allowed in the first label, so if # The subsequent labels are not equal, there is no match if other_domain_labels != other_valid_domain_labels: return False if wildcard_label == '*': return True wildcard_regex = re.compile('^' + wildcard_label.replace('*', '.*') + '$') if wildcard_regex.match(first_domain_label): return True return False
python
def _is_wildcard_match(self, domain_labels, valid_domain_labels): """ Determines if the labels in a domain are a match for labels from a wildcard valid domain name :param domain_labels: A list of unicode strings, with A-label form for IDNs, of the labels in the domain name to check :param valid_domain_labels: A list of unicode strings, with A-label form for IDNs, of the labels in a wildcard domain pattern :return: A boolean - if the domain matches the valid domain """ first_domain_label = domain_labels[0] other_domain_labels = domain_labels[1:] wildcard_label = valid_domain_labels[0] other_valid_domain_labels = valid_domain_labels[1:] # The wildcard is only allowed in the first label, so if # The subsequent labels are not equal, there is no match if other_domain_labels != other_valid_domain_labels: return False if wildcard_label == '*': return True wildcard_regex = re.compile('^' + wildcard_label.replace('*', '.*') + '$') if wildcard_regex.match(first_domain_label): return True return False
[ "def", "_is_wildcard_match", "(", "self", ",", "domain_labels", ",", "valid_domain_labels", ")", ":", "first_domain_label", "=", "domain_labels", "[", "0", "]", "other_domain_labels", "=", "domain_labels", "[", "1", ":", "]", "wildcard_label", "=", "valid_domain_lab...
Determines if the labels in a domain are a match for labels from a wildcard valid domain name :param domain_labels: A list of unicode strings, with A-label form for IDNs, of the labels in the domain name to check :param valid_domain_labels: A list of unicode strings, with A-label form for IDNs, of the labels in a wildcard domain pattern :return: A boolean - if the domain matches the valid domain
[ "Determines", "if", "the", "labels", "in", "a", "domain", "are", "a", "match", "for", "labels", "from", "a", "wildcard", "valid", "domain", "name" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L2964-L2999
train
200,243
wbond/asn1crypto
dev/lint.py
run
def run(): """ Runs flake8 lint :return: A bool - if flake8 did not find any errors """ print('Running flake8 %s' % flake8.__version__) flake8_style = get_style_guide(config_file=os.path.join(package_root, 'tox.ini')) paths = [] for _dir in [package_name, 'dev', 'tests']: for root, _, filenames in os.walk(_dir): for filename in filenames: if not filename.endswith('.py'): continue paths.append(os.path.join(root, filename)) report = flake8_style.check_files(paths) success = report.total_errors == 0 if success: print('OK') return success
python
def run(): """ Runs flake8 lint :return: A bool - if flake8 did not find any errors """ print('Running flake8 %s' % flake8.__version__) flake8_style = get_style_guide(config_file=os.path.join(package_root, 'tox.ini')) paths = [] for _dir in [package_name, 'dev', 'tests']: for root, _, filenames in os.walk(_dir): for filename in filenames: if not filename.endswith('.py'): continue paths.append(os.path.join(root, filename)) report = flake8_style.check_files(paths) success = report.total_errors == 0 if success: print('OK') return success
[ "def", "run", "(", ")", ":", "print", "(", "'Running flake8 %s'", "%", "flake8", ".", "__version__", ")", "flake8_style", "=", "get_style_guide", "(", "config_file", "=", "os", ".", "path", ".", "join", "(", "package_root", ",", "'tox.ini'", ")", ")", "pat...
Runs flake8 lint :return: A bool - if flake8 did not find any errors
[ "Runs", "flake8", "lint" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/lint.py#L15-L38
train
200,244
wbond/asn1crypto
dev/ci.py
run
def run(): """ Runs the linter and tests :return: A bool - if the linter and tests ran successfully """ print('Python ' + sys.version.replace('\n', '')) try: oscrypto_tests_module_info = imp.find_module('tests', [os.path.join(build_root, 'oscrypto')]) oscrypto_tests = imp.load_module('oscrypto.tests', *oscrypto_tests_module_info) oscrypto = oscrypto_tests.local_oscrypto() print('\noscrypto backend: %s' % oscrypto.backend()) except (ImportError): pass if run_lint: print('') lint_result = run_lint() else: lint_result = True if run_coverage: print('\nRunning tests (via coverage.py)') sys.stdout.flush() tests_result = run_coverage(ci=True) else: print('\nRunning tests') sys.stdout.flush() tests_result = run_tests() sys.stdout.flush() return lint_result and tests_result
python
def run(): """ Runs the linter and tests :return: A bool - if the linter and tests ran successfully """ print('Python ' + sys.version.replace('\n', '')) try: oscrypto_tests_module_info = imp.find_module('tests', [os.path.join(build_root, 'oscrypto')]) oscrypto_tests = imp.load_module('oscrypto.tests', *oscrypto_tests_module_info) oscrypto = oscrypto_tests.local_oscrypto() print('\noscrypto backend: %s' % oscrypto.backend()) except (ImportError): pass if run_lint: print('') lint_result = run_lint() else: lint_result = True if run_coverage: print('\nRunning tests (via coverage.py)') sys.stdout.flush() tests_result = run_coverage(ci=True) else: print('\nRunning tests') sys.stdout.flush() tests_result = run_tests() sys.stdout.flush() return lint_result and tests_result
[ "def", "run", "(", ")", ":", "print", "(", "'Python '", "+", "sys", ".", "version", ".", "replace", "(", "'\\n'", ",", "''", ")", ")", "try", ":", "oscrypto_tests_module_info", "=", "imp", ".", "find_module", "(", "'tests'", ",", "[", "os", ".", "pat...
Runs the linter and tests :return: A bool - if the linter and tests ran successfully
[ "Runs", "the", "linter", "and", "tests" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/ci.py#L29-L63
train
200,245
wbond/asn1crypto
asn1crypto/util.py
extended_date.replace
def replace(self, year=None, month=None, day=None): """ Returns a new datetime.date or asn1crypto.util.extended_date object with the specified components replaced :return: A datetime.date or asn1crypto.util.extended_date object """ if year is None: year = self.year if month is None: month = self.month if day is None: day = self.day if year > 0: cls = date else: cls = extended_date return cls( year, month, day )
python
def replace(self, year=None, month=None, day=None): """ Returns a new datetime.date or asn1crypto.util.extended_date object with the specified components replaced :return: A datetime.date or asn1crypto.util.extended_date object """ if year is None: year = self.year if month is None: month = self.month if day is None: day = self.day if year > 0: cls = date else: cls = extended_date return cls( year, month, day )
[ "def", "replace", "(", "self", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ")", ":", "if", "year", "is", "None", ":", "year", "=", "self", ".", "year", "if", "month", "is", "None", ":", "month", "=", "self", "....
Returns a new datetime.date or asn1crypto.util.extended_date object with the specified components replaced :return: A datetime.date or asn1crypto.util.extended_date object
[ "Returns", "a", "new", "datetime", ".", "date", "or", "asn1crypto", ".", "util", ".", "extended_date", "object", "with", "the", "specified", "components", "replaced" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/util.py#L295-L320
train
200,246
wbond/asn1crypto
asn1crypto/util.py
extended_datetime.replace
def replace(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): """ Returns a new datetime.datetime or asn1crypto.util.extended_datetime object with the specified components replaced :return: A datetime.datetime or asn1crypto.util.extended_datetime object """ if year is None: year = self.year if month is None: month = self.month if day is None: day = self.day if hour is None: hour = self.hour if minute is None: minute = self.minute if second is None: second = self.second if microsecond is None: microsecond = self.microsecond if tzinfo is None: tzinfo = self.tzinfo if year > 0: cls = datetime else: cls = extended_datetime return cls( year, month, day, hour, minute, second, microsecond, tzinfo )
python
def replace(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): """ Returns a new datetime.datetime or asn1crypto.util.extended_datetime object with the specified components replaced :return: A datetime.datetime or asn1crypto.util.extended_datetime object """ if year is None: year = self.year if month is None: month = self.month if day is None: day = self.day if hour is None: hour = self.hour if minute is None: minute = self.minute if second is None: second = self.second if microsecond is None: microsecond = self.microsecond if tzinfo is None: tzinfo = self.tzinfo if year > 0: cls = datetime else: cls = extended_datetime return cls( year, month, day, hour, minute, second, microsecond, tzinfo )
[ "def", "replace", "(", "self", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "hour", "=", "None", ",", "minute", "=", "None", ",", "second", "=", "None", ",", "microsecond", "=", "None", ",", "tzinfo", "=", "N...
Returns a new datetime.datetime or asn1crypto.util.extended_datetime object with the specified components replaced :return: A datetime.datetime or asn1crypto.util.extended_datetime object
[ "Returns", "a", "new", "datetime", ".", "datetime", "or", "asn1crypto", ".", "util", ".", "extended_datetime", "object", "with", "the", "specified", "components", "replaced" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/util.py#L578-L619
train
200,247
wbond/asn1crypto
asn1crypto/crl.py
CertificateList.delta_crl_distribution_points
def delta_crl_distribution_points(self): """ Returns delta CRL URLs - only applies to complete CRLs :return: A list of zero or more DistributionPoint objects """ if self._delta_crl_distribution_points is None: self._delta_crl_distribution_points = [] if self.freshest_crl_value is not None: for distribution_point in self.freshest_crl_value: distribution_point_name = distribution_point['distribution_point'] # RFC 5280 indicates conforming CA should not use the relative form if distribution_point_name.name == 'name_relative_to_crl_issuer': continue # This library is currently only concerned with HTTP-based CRLs for general_name in distribution_point_name.chosen: if general_name.name == 'uniform_resource_identifier': self._delta_crl_distribution_points.append(distribution_point) return self._delta_crl_distribution_points
python
def delta_crl_distribution_points(self): """ Returns delta CRL URLs - only applies to complete CRLs :return: A list of zero or more DistributionPoint objects """ if self._delta_crl_distribution_points is None: self._delta_crl_distribution_points = [] if self.freshest_crl_value is not None: for distribution_point in self.freshest_crl_value: distribution_point_name = distribution_point['distribution_point'] # RFC 5280 indicates conforming CA should not use the relative form if distribution_point_name.name == 'name_relative_to_crl_issuer': continue # This library is currently only concerned with HTTP-based CRLs for general_name in distribution_point_name.chosen: if general_name.name == 'uniform_resource_identifier': self._delta_crl_distribution_points.append(distribution_point) return self._delta_crl_distribution_points
[ "def", "delta_crl_distribution_points", "(", "self", ")", ":", "if", "self", ".", "_delta_crl_distribution_points", "is", "None", ":", "self", ".", "_delta_crl_distribution_points", "=", "[", "]", "if", "self", ".", "freshest_crl_value", "is", "not", "None", ":", ...
Returns delta CRL URLs - only applies to complete CRLs :return: A list of zero or more DistributionPoint objects
[ "Returns", "delta", "CRL", "URLs", "-", "only", "applies", "to", "complete", "CRLs" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/crl.py#L483-L505
train
200,248
wbond/asn1crypto
asn1crypto/ocsp.py
SingleResponse._set_extensions
def _set_extensions(self): """ Sets common named extensions to private attributes and creates a list of critical extensions """ self._critical_extensions = set() for extension in self['single_extensions']: name = extension['extn_id'].native attribute_name = '_%s_value' % name if hasattr(self, attribute_name): setattr(self, attribute_name, extension['extn_value'].parsed) if extension['critical'].native: self._critical_extensions.add(name) self._processed_extensions = True
python
def _set_extensions(self): """ Sets common named extensions to private attributes and creates a list of critical extensions """ self._critical_extensions = set() for extension in self['single_extensions']: name = extension['extn_id'].native attribute_name = '_%s_value' % name if hasattr(self, attribute_name): setattr(self, attribute_name, extension['extn_value'].parsed) if extension['critical'].native: self._critical_extensions.add(name) self._processed_extensions = True
[ "def", "_set_extensions", "(", "self", ")", ":", "self", ".", "_critical_extensions", "=", "set", "(", ")", "for", "extension", "in", "self", "[", "'single_extensions'", "]", ":", "name", "=", "extension", "[", "'extn_id'", "]", ".", "native", "attribute_nam...
Sets common named extensions to private attributes and creates a list of critical extensions
[ "Sets", "common", "named", "extensions", "to", "private", "attributes", "and", "creates", "a", "list", "of", "critical", "extensions" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/ocsp.py#L398-L414
train
200,249
wbond/asn1crypto
asn1crypto/core.py
_basic_debug
def _basic_debug(prefix, self): """ Prints out basic information about an Asn1Value object. Extracted for reuse among different classes that customize the debug information. :param prefix: A unicode string of spaces to prefix output line with :param self: The object to print the debugging information about """ print('%s%s Object #%s' % (prefix, type_name(self), id(self))) if self._header: print('%s Header: 0x%s' % (prefix, binascii.hexlify(self._header or b'').decode('utf-8'))) has_header = self.method is not None and self.class_ is not None and self.tag is not None if has_header: method_name = METHOD_NUM_TO_NAME_MAP.get(self.method) class_name = CLASS_NUM_TO_NAME_MAP.get(self.class_) if self.explicit is not None: for class_, tag in self.explicit: print( '%s %s tag %s (explicitly tagged)' % ( prefix, CLASS_NUM_TO_NAME_MAP.get(class_), tag ) ) if has_header: print('%s %s %s %s' % (prefix, method_name, class_name, self.tag)) elif self.implicit: if has_header: print('%s %s %s tag %s (implicitly tagged)' % (prefix, method_name, class_name, self.tag)) elif has_header: print('%s %s %s tag %s' % (prefix, method_name, class_name, self.tag)) print('%s Data: 0x%s' % (prefix, binascii.hexlify(self.contents or b'').decode('utf-8')))
python
def _basic_debug(prefix, self): """ Prints out basic information about an Asn1Value object. Extracted for reuse among different classes that customize the debug information. :param prefix: A unicode string of spaces to prefix output line with :param self: The object to print the debugging information about """ print('%s%s Object #%s' % (prefix, type_name(self), id(self))) if self._header: print('%s Header: 0x%s' % (prefix, binascii.hexlify(self._header or b'').decode('utf-8'))) has_header = self.method is not None and self.class_ is not None and self.tag is not None if has_header: method_name = METHOD_NUM_TO_NAME_MAP.get(self.method) class_name = CLASS_NUM_TO_NAME_MAP.get(self.class_) if self.explicit is not None: for class_, tag in self.explicit: print( '%s %s tag %s (explicitly tagged)' % ( prefix, CLASS_NUM_TO_NAME_MAP.get(class_), tag ) ) if has_header: print('%s %s %s %s' % (prefix, method_name, class_name, self.tag)) elif self.implicit: if has_header: print('%s %s %s tag %s (implicitly tagged)' % (prefix, method_name, class_name, self.tag)) elif has_header: print('%s %s %s tag %s' % (prefix, method_name, class_name, self.tag)) print('%s Data: 0x%s' % (prefix, binascii.hexlify(self.contents or b'').decode('utf-8')))
[ "def", "_basic_debug", "(", "prefix", ",", "self", ")", ":", "print", "(", "'%s%s Object #%s'", "%", "(", "prefix", ",", "type_name", "(", "self", ")", ",", "id", "(", "self", ")", ")", ")", "if", "self", ".", "_header", ":", "print", "(", "'%s Head...
Prints out basic information about an Asn1Value object. Extracted for reuse among different classes that customize the debug information. :param prefix: A unicode string of spaces to prefix output line with :param self: The object to print the debugging information about
[ "Prints", "out", "basic", "information", "about", "an", "Asn1Value", "object", ".", "Extracted", "for", "reuse", "among", "different", "classes", "that", "customize", "the", "debug", "information", "." ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L4850-L4891
train
200,250
wbond/asn1crypto
asn1crypto/core.py
_tag_type_to_explicit_implicit
def _tag_type_to_explicit_implicit(params): """ Converts old-style "tag_type" and "tag" params to "explicit" and "implicit" :param params: A dict of parameters to convert from tag_type/tag to explicit/implicit """ if 'tag_type' in params: if params['tag_type'] == 'explicit': params['explicit'] = (params.get('class', 2), params['tag']) elif params['tag_type'] == 'implicit': params['implicit'] = (params.get('class', 2), params['tag']) del params['tag_type'] del params['tag'] if 'class' in params: del params['class']
python
def _tag_type_to_explicit_implicit(params): """ Converts old-style "tag_type" and "tag" params to "explicit" and "implicit" :param params: A dict of parameters to convert from tag_type/tag to explicit/implicit """ if 'tag_type' in params: if params['tag_type'] == 'explicit': params['explicit'] = (params.get('class', 2), params['tag']) elif params['tag_type'] == 'implicit': params['implicit'] = (params.get('class', 2), params['tag']) del params['tag_type'] del params['tag'] if 'class' in params: del params['class']
[ "def", "_tag_type_to_explicit_implicit", "(", "params", ")", ":", "if", "'tag_type'", "in", "params", ":", "if", "params", "[", "'tag_type'", "]", "==", "'explicit'", ":", "params", "[", "'explicit'", "]", "=", "(", "params", ".", "get", "(", "'class'", ",...
Converts old-style "tag_type" and "tag" params to "explicit" and "implicit" :param params: A dict of parameters to convert from tag_type/tag to explicit/implicit
[ "Converts", "old", "-", "style", "tag_type", "and", "tag", "params", "to", "explicit", "and", "implicit" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L4894-L4910
train
200,251
wbond/asn1crypto
asn1crypto/core.py
_build_id_tuple
def _build_id_tuple(params, spec): """ Builds a 2-element tuple used to identify fields by grabbing the class_ and tag from an Asn1Value class and the params dict being passed to it :param params: A dict of params to pass to spec :param spec: An Asn1Value class :return: A 2-element integer tuple in the form (class_, tag) """ # Handle situations where the spec is not known at setup time if spec is None: return (None, None) required_class = spec.class_ required_tag = spec.tag _tag_type_to_explicit_implicit(params) if 'explicit' in params: if isinstance(params['explicit'], tuple): required_class, required_tag = params['explicit'] else: required_class = 2 required_tag = params['explicit'] elif 'implicit' in params: if isinstance(params['implicit'], tuple): required_class, required_tag = params['implicit'] else: required_class = 2 required_tag = params['implicit'] if required_class is not None and not isinstance(required_class, int_types): required_class = CLASS_NAME_TO_NUM_MAP[required_class] required_class = params.get('class_', required_class) required_tag = params.get('tag', required_tag) return (required_class, required_tag)
python
def _build_id_tuple(params, spec): """ Builds a 2-element tuple used to identify fields by grabbing the class_ and tag from an Asn1Value class and the params dict being passed to it :param params: A dict of params to pass to spec :param spec: An Asn1Value class :return: A 2-element integer tuple in the form (class_, tag) """ # Handle situations where the spec is not known at setup time if spec is None: return (None, None) required_class = spec.class_ required_tag = spec.tag _tag_type_to_explicit_implicit(params) if 'explicit' in params: if isinstance(params['explicit'], tuple): required_class, required_tag = params['explicit'] else: required_class = 2 required_tag = params['explicit'] elif 'implicit' in params: if isinstance(params['implicit'], tuple): required_class, required_tag = params['implicit'] else: required_class = 2 required_tag = params['implicit'] if required_class is not None and not isinstance(required_class, int_types): required_class = CLASS_NAME_TO_NUM_MAP[required_class] required_class = params.get('class_', required_class) required_tag = params.get('tag', required_tag) return (required_class, required_tag)
[ "def", "_build_id_tuple", "(", "params", ",", "spec", ")", ":", "# Handle situations where the spec is not known at setup time", "if", "spec", "is", "None", ":", "return", "(", "None", ",", "None", ")", "required_class", "=", "spec", ".", "class_", "required_tag", ...
Builds a 2-element tuple used to identify fields by grabbing the class_ and tag from an Asn1Value class and the params dict being passed to it :param params: A dict of params to pass to spec :param spec: An Asn1Value class :return: A 2-element integer tuple in the form (class_, tag)
[ "Builds", "a", "2", "-", "element", "tuple", "used", "to", "identify", "fields", "by", "grabbing", "the", "class_", "and", "tag", "from", "an", "Asn1Value", "class", "and", "the", "params", "dict", "being", "passed", "to", "it" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L4953-L4995
train
200,252
wbond/asn1crypto
asn1crypto/core.py
_parse_build
def _parse_build(encoded_data, pointer=0, spec=None, spec_params=None, strict=False): """ Parses a byte string generically, or using a spec with optional params :param encoded_data: A byte string that contains BER-encoded data :param pointer: The index in the byte string to parse from :param spec: A class derived from Asn1Value that defines what class_ and tag the value should have, and the semantics of the encoded value. The return value will be of this type. If omitted, the encoded value will be decoded using the standard universal tag based on the encoded tag number. :param spec_params: A dict of params to pass to the spec object :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :return: A 2-element tuple: - 0: An object of the type spec, or if not specified, a child of Asn1Value - 1: An integer indicating how many bytes were consumed """ encoded_len = len(encoded_data) info, new_pointer = _parse(encoded_data, encoded_len, pointer) if strict and new_pointer != pointer + encoded_len: extra_bytes = pointer + encoded_len - new_pointer raise ValueError('Extra data - %d bytes of trailing data were provided' % extra_bytes) return (_build(*info, spec=spec, spec_params=spec_params), new_pointer)
python
def _parse_build(encoded_data, pointer=0, spec=None, spec_params=None, strict=False): """ Parses a byte string generically, or using a spec with optional params :param encoded_data: A byte string that contains BER-encoded data :param pointer: The index in the byte string to parse from :param spec: A class derived from Asn1Value that defines what class_ and tag the value should have, and the semantics of the encoded value. The return value will be of this type. If omitted, the encoded value will be decoded using the standard universal tag based on the encoded tag number. :param spec_params: A dict of params to pass to the spec object :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :return: A 2-element tuple: - 0: An object of the type spec, or if not specified, a child of Asn1Value - 1: An integer indicating how many bytes were consumed """ encoded_len = len(encoded_data) info, new_pointer = _parse(encoded_data, encoded_len, pointer) if strict and new_pointer != pointer + encoded_len: extra_bytes = pointer + encoded_len - new_pointer raise ValueError('Extra data - %d bytes of trailing data were provided' % extra_bytes) return (_build(*info, spec=spec, spec_params=spec_params), new_pointer)
[ "def", "_parse_build", "(", "encoded_data", ",", "pointer", "=", "0", ",", "spec", "=", "None", ",", "spec_params", "=", "None", ",", "strict", "=", "False", ")", ":", "encoded_len", "=", "len", "(", "encoded_data", ")", "info", ",", "new_pointer", "=", ...
Parses a byte string generically, or using a spec with optional params :param encoded_data: A byte string that contains BER-encoded data :param pointer: The index in the byte string to parse from :param spec: A class derived from Asn1Value that defines what class_ and tag the value should have, and the semantics of the encoded value. The return value will be of this type. If omitted, the encoded value will be decoded using the standard universal tag based on the encoded tag number. :param spec_params: A dict of params to pass to the spec object :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :return: A 2-element tuple: - 0: An object of the type spec, or if not specified, a child of Asn1Value - 1: An integer indicating how many bytes were consumed
[ "Parses", "a", "byte", "string", "generically", "or", "using", "a", "spec", "with", "optional", "params" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L5258-L5293
train
200,253
wbond/asn1crypto
asn1crypto/core.py
Asn1Value._new_instance
def _new_instance(self): """ Constructs a new copy of the current object, preserving any tagging :return: An Asn1Value object """ new_obj = self.__class__() new_obj.class_ = self.class_ new_obj.tag = self.tag new_obj.implicit = self.implicit new_obj.explicit = self.explicit return new_obj
python
def _new_instance(self): """ Constructs a new copy of the current object, preserving any tagging :return: An Asn1Value object """ new_obj = self.__class__() new_obj.class_ = self.class_ new_obj.tag = self.tag new_obj.implicit = self.implicit new_obj.explicit = self.explicit return new_obj
[ "def", "_new_instance", "(", "self", ")", ":", "new_obj", "=", "self", ".", "__class__", "(", ")", "new_obj", ".", "class_", "=", "self", ".", "class_", "new_obj", ".", "tag", "=", "self", ".", "tag", "new_obj", ".", "implicit", "=", "self", ".", "im...
Constructs a new copy of the current object, preserving any tagging :return: An Asn1Value object
[ "Constructs", "a", "new", "copy", "of", "the", "current", "object", "preserving", "any", "tagging" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L459-L472
train
200,254
wbond/asn1crypto
asn1crypto/core.py
Asn1Value.retag
def retag(self, tagging, tag=None): """ Copies the object, applying a new tagging to it :param tagging: A dict containing the keys "explicit" and "implicit". Legacy API allows a unicode string of "implicit" or "explicit". :param tag: A integer tag number. Only used when tagging is a unicode string. :return: An Asn1Value object """ # This is required to preserve the old API if not isinstance(tagging, dict): tagging = {tagging: tag} new_obj = self.__class__(explicit=tagging.get('explicit'), implicit=tagging.get('implicit')) new_obj._copy(self, copy.deepcopy) return new_obj
python
def retag(self, tagging, tag=None): """ Copies the object, applying a new tagging to it :param tagging: A dict containing the keys "explicit" and "implicit". Legacy API allows a unicode string of "implicit" or "explicit". :param tag: A integer tag number. Only used when tagging is a unicode string. :return: An Asn1Value object """ # This is required to preserve the old API if not isinstance(tagging, dict): tagging = {tagging: tag} new_obj = self.__class__(explicit=tagging.get('explicit'), implicit=tagging.get('implicit')) new_obj._copy(self, copy.deepcopy) return new_obj
[ "def", "retag", "(", "self", ",", "tagging", ",", "tag", "=", "None", ")", ":", "# This is required to preserve the old API", "if", "not", "isinstance", "(", "tagging", ",", "dict", ")", ":", "tagging", "=", "{", "tagging", ":", "tag", "}", "new_obj", "=",...
Copies the object, applying a new tagging to it :param tagging: A dict containing the keys "explicit" and "implicit". Legacy API allows a unicode string of "implicit" or "explicit". :param tag: A integer tag number. Only used when tagging is a unicode string. :return: An Asn1Value object
[ "Copies", "the", "object", "applying", "a", "new", "tagging", "to", "it" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L512-L532
train
200,255
wbond/asn1crypto
asn1crypto/core.py
Asn1Value.untag
def untag(self): """ Copies the object, removing any special tagging from it :return: An Asn1Value object """ new_obj = self.__class__() new_obj._copy(self, copy.deepcopy) return new_obj
python
def untag(self): """ Copies the object, removing any special tagging from it :return: An Asn1Value object """ new_obj = self.__class__() new_obj._copy(self, copy.deepcopy) return new_obj
[ "def", "untag", "(", "self", ")", ":", "new_obj", "=", "self", ".", "__class__", "(", ")", "new_obj", ".", "_copy", "(", "self", ",", "copy", ".", "deepcopy", ")", "return", "new_obj" ]
Copies the object, removing any special tagging from it :return: An Asn1Value object
[ "Copies", "the", "object", "removing", "any", "special", "tagging", "from", "it" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L534-L544
train
200,256
wbond/asn1crypto
asn1crypto/core.py
Constructable._as_chunk
def _as_chunk(self): """ A method to return a chunk of data that can be combined for constructed method values :return: A native Python value that can be added together. Examples include byte strings, unicode strings or tuples. """ if self._chunks_offset == 0: return self.contents return self.contents[self._chunks_offset:]
python
def _as_chunk(self): """ A method to return a chunk of data that can be combined for constructed method values :return: A native Python value that can be added together. Examples include byte strings, unicode strings or tuples. """ if self._chunks_offset == 0: return self.contents return self.contents[self._chunks_offset:]
[ "def", "_as_chunk", "(", "self", ")", ":", "if", "self", ".", "_chunks_offset", "==", "0", ":", "return", "self", ".", "contents", "return", "self", ".", "contents", "[", "self", ".", "_chunks_offset", ":", "]" ]
A method to return a chunk of data that can be combined for constructed method values :return: A native Python value that can be added together. Examples include byte strings, unicode strings or tuples.
[ "A", "method", "to", "return", "a", "chunk", "of", "data", "that", "can", "be", "combined", "for", "constructed", "method", "values" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L733-L745
train
200,257
wbond/asn1crypto
asn1crypto/core.py
Constructable._copy
def _copy(self, other, copy_func): """ Copies the contents of another Constructable object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Constructable, self)._copy(other, copy_func) self.method = other.method self._indefinite = other._indefinite
python
def _copy(self, other, copy_func): """ Copies the contents of another Constructable object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Constructable, self)._copy(other, copy_func) self.method = other.method self._indefinite = other._indefinite
[ "def", "_copy", "(", "self", ",", "other", ",", "copy_func", ")", ":", "super", "(", "Constructable", ",", "self", ")", ".", "_copy", "(", "other", ",", "copy_func", ")", "self", ".", "method", "=", "other", ".", "method", "self", ".", "_indefinite", ...
Copies the contents of another Constructable object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
[ "Copies", "the", "contents", "of", "another", "Constructable", "object", "to", "itself" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L747-L761
train
200,258
wbond/asn1crypto
asn1crypto/core.py
Any._copy
def _copy(self, other, copy_func): """ Copies the contents of another Any object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Any, self)._copy(other, copy_func) self._parsed = copy_func(other._parsed)
python
def _copy(self, other, copy_func): """ Copies the contents of another Any object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Any, self)._copy(other, copy_func) self._parsed = copy_func(other._parsed)
[ "def", "_copy", "(", "self", ",", "other", ",", "copy_func", ")", ":", "super", "(", "Any", ",", "self", ")", ".", "_copy", "(", "other", ",", "copy_func", ")", "self", ".", "_parsed", "=", "copy_func", "(", "other", ".", "_parsed", ")" ]
Copies the contents of another Any object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
[ "Copies", "the", "contents", "of", "another", "Any", "object", "to", "itself" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L938-L951
train
200,259
wbond/asn1crypto
asn1crypto/core.py
Choice._setup
def _setup(self): """ Generates _id_map from _alternatives to allow validating contents """ cls = self.__class__ cls._id_map = {} cls._name_map = {} for index, info in enumerate(cls._alternatives): if len(info) < 3: info = info + ({},) cls._alternatives[index] = info id_ = _build_id_tuple(info[2], info[1]) cls._id_map[id_] = index cls._name_map[info[0]] = index
python
def _setup(self): """ Generates _id_map from _alternatives to allow validating contents """ cls = self.__class__ cls._id_map = {} cls._name_map = {} for index, info in enumerate(cls._alternatives): if len(info) < 3: info = info + ({},) cls._alternatives[index] = info id_ = _build_id_tuple(info[2], info[1]) cls._id_map[id_] = index cls._name_map[info[0]] = index
[ "def", "_setup", "(", "self", ")", ":", "cls", "=", "self", ".", "__class__", "cls", ".", "_id_map", "=", "{", "}", "cls", ".", "_name_map", "=", "{", "}", "for", "index", ",", "info", "in", "enumerate", "(", "cls", ".", "_alternatives", ")", ":", ...
Generates _id_map from _alternatives to allow validating contents
[ "Generates", "_id_map", "from", "_alternatives", "to", "allow", "validating", "contents" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L1028-L1042
train
200,260
wbond/asn1crypto
asn1crypto/core.py
Choice.parse
def parse(self): """ Parses the detected alternative :return: An Asn1Value object of the chosen alternative """ if self._parsed is not None: return self._parsed try: _, spec, params = self._alternatives[self._choice] self._parsed, _ = _parse_build(self._contents, spec=spec, spec_params=params) except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e
python
def parse(self): """ Parses the detected alternative :return: An Asn1Value object of the chosen alternative """ if self._parsed is not None: return self._parsed try: _, spec, params = self._alternatives[self._choice] self._parsed, _ = _parse_build(self._contents, spec=spec, spec_params=params) except (ValueError, TypeError) as e: args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e
[ "def", "parse", "(", "self", ")", ":", "if", "self", ".", "_parsed", "is", "not", "None", ":", "return", "self", ".", "_parsed", "try", ":", "_", ",", "spec", ",", "params", "=", "self", ".", "_alternatives", "[", "self", ".", "_choice", "]", "self...
Parses the detected alternative :return: An Asn1Value object of the chosen alternative
[ "Parses", "the", "detected", "alternative" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L1159-L1176
train
200,261
wbond/asn1crypto
asn1crypto/core.py
Choice._copy
def _copy(self, other, copy_func): """ Copies the contents of another Choice object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Choice, self)._copy(other, copy_func) self._choice = other._choice self._name = other._name self._parsed = copy_func(other._parsed)
python
def _copy(self, other, copy_func): """ Copies the contents of another Choice object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Choice, self)._copy(other, copy_func) self._choice = other._choice self._name = other._name self._parsed = copy_func(other._parsed)
[ "def", "_copy", "(", "self", ",", "other", ",", "copy_func", ")", ":", "super", "(", "Choice", ",", "self", ")", ".", "_copy", "(", "other", ",", "copy_func", ")", "self", ".", "_choice", "=", "other", ".", "_choice", "self", ".", "_name", "=", "ot...
Copies the contents of another Choice object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
[ "Copies", "the", "contents", "of", "another", "Choice", "object", "to", "itself" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L1270-L1285
train
200,262
wbond/asn1crypto
asn1crypto/core.py
AbstractString._copy
def _copy(self, other, copy_func): """ Copies the contents of another AbstractString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(AbstractString, self)._copy(other, copy_func) self._unicode = other._unicode
python
def _copy(self, other, copy_func): """ Copies the contents of another AbstractString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(AbstractString, self)._copy(other, copy_func) self._unicode = other._unicode
[ "def", "_copy", "(", "self", ",", "other", ",", "copy_func", ")", ":", "super", "(", "AbstractString", ",", "self", ")", ".", "_copy", "(", "other", ",", "copy_func", ")", "self", ".", "_unicode", "=", "other", ".", "_unicode" ]
Copies the contents of another AbstractString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
[ "Copies", "the", "contents", "of", "another", "AbstractString", "object", "to", "itself" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L1771-L1784
train
200,263
wbond/asn1crypto
asn1crypto/core.py
OctetBitString._copy
def _copy(self, other, copy_func): """ Copies the contents of another OctetBitString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(OctetBitString, self)._copy(other, copy_func) self._bytes = other._bytes
python
def _copy(self, other, copy_func): """ Copies the contents of another OctetBitString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(OctetBitString, self)._copy(other, copy_func) self._bytes = other._bytes
[ "def", "_copy", "(", "self", ",", "other", ",", "copy_func", ")", ":", "super", "(", "OctetBitString", ",", "self", ")", ".", "_copy", "(", "other", ",", "copy_func", ")", "self", ".", "_bytes", "=", "other", ".", "_bytes" ]
Copies the contents of another OctetBitString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
[ "Copies", "the", "contents", "of", "another", "OctetBitString", "object", "to", "itself" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L2281-L2294
train
200,264
wbond/asn1crypto
asn1crypto/core.py
OctetString._copy
def _copy(self, other, copy_func): """ Copies the contents of another OctetString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(OctetString, self)._copy(other, copy_func) self._bytes = other._bytes
python
def _copy(self, other, copy_func): """ Copies the contents of another OctetString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(OctetString, self)._copy(other, copy_func) self._bytes = other._bytes
[ "def", "_copy", "(", "self", ",", "other", ",", "copy_func", ")", ":", "super", "(", "OctetString", ",", "self", ")", ".", "_copy", "(", "other", ",", "copy_func", ")", "self", ".", "_bytes", "=", "other", ".", "_bytes" ]
Copies the contents of another OctetString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
[ "Copies", "the", "contents", "of", "another", "OctetString", "object", "to", "itself" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L2443-L2456
train
200,265
wbond/asn1crypto
asn1crypto/core.py
ParsableOctetString._copy
def _copy(self, other, copy_func): """ Copies the contents of another ParsableOctetString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(ParsableOctetString, self)._copy(other, copy_func) self._bytes = other._bytes self._parsed = copy_func(other._parsed)
python
def _copy(self, other, copy_func): """ Copies the contents of another ParsableOctetString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(ParsableOctetString, self)._copy(other, copy_func) self._bytes = other._bytes self._parsed = copy_func(other._parsed)
[ "def", "_copy", "(", "self", ",", "other", ",", "copy_func", ")", ":", "super", "(", "ParsableOctetString", ",", "self", ")", ".", "_copy", "(", "other", ",", "copy_func", ")", "self", ".", "_bytes", "=", "other", ".", "_bytes", "self", ".", "_parsed",...
Copies the contents of another ParsableOctetString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
[ "Copies", "the", "contents", "of", "another", "ParsableOctetString", "object", "to", "itself" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L2620-L2634
train
200,266
wbond/asn1crypto
asn1crypto/core.py
Sequence._lazy_child
def _lazy_child(self, index): """ Builds a child object if the child has only been parsed into a tuple so far """ child = self.children[index] if child.__class__ == tuple: child = self.children[index] = _build(*child) return child
python
def _lazy_child(self, index): """ Builds a child object if the child has only been parsed into a tuple so far """ child = self.children[index] if child.__class__ == tuple: child = self.children[index] = _build(*child) return child
[ "def", "_lazy_child", "(", "self", ",", "index", ")", ":", "child", "=", "self", ".", "children", "[", "index", "]", "if", "child", ".", "__class__", "==", "tuple", ":", "child", "=", "self", ".", "children", "[", "index", "]", "=", "_build", "(", ...
Builds a child object if the child has only been parsed into a tuple so far
[ "Builds", "a", "child", "object", "if", "the", "child", "has", "only", "been", "parsed", "into", "a", "tuple", "so", "far" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L3236-L3244
train
200,267
wbond/asn1crypto
asn1crypto/core.py
Sequence._set_contents
def _set_contents(self, force=False): """ Updates the .contents attribute of the value with the encoded value of all of the child objects :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data """ if self.children is None: self._parse_children() contents = BytesIO() for index, info in enumerate(self._fields): child = self.children[index] if child is None: child_dump = b'' elif child.__class__ == tuple: if force: child_dump = self._lazy_child(index).dump(force=force) else: child_dump = child[3] + child[4] + child[5] else: child_dump = child.dump(force=force) # Skip values that are the same as the default if info[2] and 'default' in info[2]: default_value = info[1](**info[2]) if default_value.dump() == child_dump: continue contents.write(child_dump) self._contents = contents.getvalue() self._header = None if self._trailer != b'': self._trailer = b''
python
def _set_contents(self, force=False): """ Updates the .contents attribute of the value with the encoded value of all of the child objects :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data """ if self.children is None: self._parse_children() contents = BytesIO() for index, info in enumerate(self._fields): child = self.children[index] if child is None: child_dump = b'' elif child.__class__ == tuple: if force: child_dump = self._lazy_child(index).dump(force=force) else: child_dump = child[3] + child[4] + child[5] else: child_dump = child.dump(force=force) # Skip values that are the same as the default if info[2] and 'default' in info[2]: default_value = info[1](**info[2]) if default_value.dump() == child_dump: continue contents.write(child_dump) self._contents = contents.getvalue() self._header = None if self._trailer != b'': self._trailer = b''
[ "def", "_set_contents", "(", "self", ",", "force", "=", "False", ")", ":", "if", "self", ".", "children", "is", "None", ":", "self", ".", "_parse_children", "(", ")", "contents", "=", "BytesIO", "(", ")", "for", "index", ",", "info", "in", "enumerate",...
Updates the .contents attribute of the value with the encoded value of all of the child objects :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data
[ "Updates", "the", ".", "contents", "attribute", "of", "the", "value", "with", "the", "encoded", "value", "of", "all", "of", "the", "child", "objects" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L3412-L3447
train
200,268
wbond/asn1crypto
asn1crypto/core.py
Sequence._setup
def _setup(self): """ Generates _field_map, _field_ids and _oid_nums for use in parsing """ cls = self.__class__ cls._field_map = {} cls._field_ids = [] cls._precomputed_specs = [] for index, field in enumerate(cls._fields): if len(field) < 3: field = field + ({},) cls._fields[index] = field cls._field_map[field[0]] = index cls._field_ids.append(_build_id_tuple(field[2], field[1])) if cls._oid_pair is not None: cls._oid_nums = (cls._field_map[cls._oid_pair[0]], cls._field_map[cls._oid_pair[1]]) for index, field in enumerate(cls._fields): has_callback = cls._spec_callbacks is not None and field[0] in cls._spec_callbacks is_mapped_oid = cls._oid_nums is not None and cls._oid_nums[1] == index if has_callback or is_mapped_oid: cls._precomputed_specs.append(None) else: cls._precomputed_specs.append((field[0], field[1], field[1], field[2], None))
python
def _setup(self): """ Generates _field_map, _field_ids and _oid_nums for use in parsing """ cls = self.__class__ cls._field_map = {} cls._field_ids = [] cls._precomputed_specs = [] for index, field in enumerate(cls._fields): if len(field) < 3: field = field + ({},) cls._fields[index] = field cls._field_map[field[0]] = index cls._field_ids.append(_build_id_tuple(field[2], field[1])) if cls._oid_pair is not None: cls._oid_nums = (cls._field_map[cls._oid_pair[0]], cls._field_map[cls._oid_pair[1]]) for index, field in enumerate(cls._fields): has_callback = cls._spec_callbacks is not None and field[0] in cls._spec_callbacks is_mapped_oid = cls._oid_nums is not None and cls._oid_nums[1] == index if has_callback or is_mapped_oid: cls._precomputed_specs.append(None) else: cls._precomputed_specs.append((field[0], field[1], field[1], field[2], None))
[ "def", "_setup", "(", "self", ")", ":", "cls", "=", "self", ".", "__class__", "cls", ".", "_field_map", "=", "{", "}", "cls", ".", "_field_ids", "=", "[", "]", "cls", ".", "_precomputed_specs", "=", "[", "]", "for", "index", ",", "field", "in", "en...
Generates _field_map, _field_ids and _oid_nums for use in parsing
[ "Generates", "_field_map", "_field_ids", "and", "_oid_nums", "for", "use", "in", "parsing" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L3449-L3474
train
200,269
wbond/asn1crypto
asn1crypto/core.py
Sequence._determine_spec
def _determine_spec(self, index): """ Determine how a value for a field should be constructed :param index: The field number :return: A tuple containing the following elements: - unicode string of the field name - Asn1Value class of the field spec - Asn1Value class of the value spec - None or dict of params to pass to the field spec - None or Asn1Value class indicating the value spec was derived from an OID or a spec callback """ name, field_spec, field_params = self._fields[index] value_spec = field_spec spec_override = None if self._spec_callbacks is not None and name in self._spec_callbacks: callback = self._spec_callbacks[name] spec_override = callback(self) if spec_override: # Allow a spec callback to specify both the base spec and # the override, for situations such as OctetString and parse_as if spec_override.__class__ == tuple and len(spec_override) == 2: field_spec, value_spec = spec_override if value_spec is None: value_spec = field_spec spec_override = None # When no field spec is specified, use a single return value as that elif field_spec is None: field_spec = spec_override value_spec = field_spec spec_override = None else: value_spec = spec_override elif self._oid_nums is not None and self._oid_nums[1] == index: oid = self._lazy_child(self._oid_nums[0]).native if oid in self._oid_specs: spec_override = self._oid_specs[oid] value_spec = spec_override return (name, field_spec, value_spec, field_params, spec_override)
python
def _determine_spec(self, index): """ Determine how a value for a field should be constructed :param index: The field number :return: A tuple containing the following elements: - unicode string of the field name - Asn1Value class of the field spec - Asn1Value class of the value spec - None or dict of params to pass to the field spec - None or Asn1Value class indicating the value spec was derived from an OID or a spec callback """ name, field_spec, field_params = self._fields[index] value_spec = field_spec spec_override = None if self._spec_callbacks is not None and name in self._spec_callbacks: callback = self._spec_callbacks[name] spec_override = callback(self) if spec_override: # Allow a spec callback to specify both the base spec and # the override, for situations such as OctetString and parse_as if spec_override.__class__ == tuple and len(spec_override) == 2: field_spec, value_spec = spec_override if value_spec is None: value_spec = field_spec spec_override = None # When no field spec is specified, use a single return value as that elif field_spec is None: field_spec = spec_override value_spec = field_spec spec_override = None else: value_spec = spec_override elif self._oid_nums is not None and self._oid_nums[1] == index: oid = self._lazy_child(self._oid_nums[0]).native if oid in self._oid_specs: spec_override = self._oid_specs[oid] value_spec = spec_override return (name, field_spec, value_spec, field_params, spec_override)
[ "def", "_determine_spec", "(", "self", ",", "index", ")", ":", "name", ",", "field_spec", ",", "field_params", "=", "self", ".", "_fields", "[", "index", "]", "value_spec", "=", "field_spec", "spec_override", "=", "None", "if", "self", ".", "_spec_callbacks"...
Determine how a value for a field should be constructed :param index: The field number :return: A tuple containing the following elements: - unicode string of the field name - Asn1Value class of the field spec - Asn1Value class of the value spec - None or dict of params to pass to the field spec - None or Asn1Value class indicating the value spec was derived from an OID or a spec callback
[ "Determine", "how", "a", "value", "for", "a", "field", "should", "be", "constructed" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L3476-L3521
train
200,270
wbond/asn1crypto
asn1crypto/core.py
Sequence._copy
def _copy(self, other, copy_func): """ Copies the contents of another Sequence object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Sequence, self)._copy(other, copy_func) if self.children is not None: self.children = [] for child in other.children: if child.__class__ == tuple: self.children.append(child) else: self.children.append(child.copy())
python
def _copy(self, other, copy_func): """ Copies the contents of another Sequence object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Sequence, self)._copy(other, copy_func) if self.children is not None: self.children = [] for child in other.children: if child.__class__ == tuple: self.children.append(child) else: self.children.append(child.copy())
[ "def", "_copy", "(", "self", ",", "other", ",", "copy_func", ")", ":", "super", "(", "Sequence", ",", "self", ")", ".", "_copy", "(", "other", ",", "copy_func", ")", "if", "self", ".", "children", "is", "not", "None", ":", "self", ".", "children", ...
Copies the contents of another Sequence object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
[ "Copies", "the", "contents", "of", "another", "Sequence", "object", "to", "itself" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L3828-L3847
train
200,271
wbond/asn1crypto
asn1crypto/core.py
SequenceOf.append
def append(self, value): """ Allows adding a child to the end of the sequence :param value: Native python datatype that will be passed to _child_spec to create new child object """ # We inline this checks to prevent method invocation each time if self.children is None: self._parse_children() self.children.append(self._make_value(value)) if self._native is not None: self._native.append(self.children[-1].native) self._mutated = True
python
def append(self, value): """ Allows adding a child to the end of the sequence :param value: Native python datatype that will be passed to _child_spec to create new child object """ # We inline this checks to prevent method invocation each time if self.children is None: self._parse_children() self.children.append(self._make_value(value)) if self._native is not None: self._native.append(self.children[-1].native) self._mutated = True
[ "def", "append", "(", "self", ",", "value", ")", ":", "# We inline this checks to prevent method invocation each time", "if", "self", ".", "children", "is", "None", ":", "self", ".", "_parse_children", "(", ")", "self", ".", "children", ".", "append", "(", "self...
Allows adding a child to the end of the sequence :param value: Native python datatype that will be passed to _child_spec to create new child object
[ "Allows", "adding", "a", "child", "to", "the", "end", "of", "the", "sequence" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L4184-L4202
train
200,272
wbond/asn1crypto
asn1crypto/core.py
SequenceOf._set_contents
def _set_contents(self, force=False): """ Encodes all child objects into the contents for this object :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data """ if self.children is None: self._parse_children() contents = BytesIO() for child in self: contents.write(child.dump(force=force)) self._contents = contents.getvalue() self._header = None if self._trailer != b'': self._trailer = b''
python
def _set_contents(self, force=False): """ Encodes all child objects into the contents for this object :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data """ if self.children is None: self._parse_children() contents = BytesIO() for child in self: contents.write(child.dump(force=force)) self._contents = contents.getvalue() self._header = None if self._trailer != b'': self._trailer = b''
[ "def", "_set_contents", "(", "self", ",", "force", "=", "False", ")", ":", "if", "self", ".", "children", "is", "None", ":", "self", ".", "_parse_children", "(", ")", "contents", "=", "BytesIO", "(", ")", "for", "child", "in", "self", ":", "contents", ...
Encodes all child objects into the contents for this object :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data
[ "Encodes", "all", "child", "objects", "into", "the", "contents", "for", "this", "object" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L4204-L4222
train
200,273
wbond/asn1crypto
asn1crypto/core.py
SequenceOf._parse_children
def _parse_children(self, recurse=False): """ Parses the contents and generates Asn1Value objects based on the definitions from _child_spec. :param recurse: If child objects that are Sequence or SequenceOf objects should be recursively parsed :raises: ValueError - when an error occurs parsing child objects """ try: self.children = [] if self._contents is None: return contents_length = len(self._contents) child_pointer = 0 while child_pointer < contents_length: parts, child_pointer = _parse(self._contents, contents_length, pointer=child_pointer) if self._child_spec: child = parts + (self._child_spec,) else: child = parts if recurse: child = _build(*child) if isinstance(child, (Sequence, SequenceOf)): child._parse_children(recurse=True) self.children.append(child) except (ValueError, TypeError) as e: self.children = None args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e
python
def _parse_children(self, recurse=False): """ Parses the contents and generates Asn1Value objects based on the definitions from _child_spec. :param recurse: If child objects that are Sequence or SequenceOf objects should be recursively parsed :raises: ValueError - when an error occurs parsing child objects """ try: self.children = [] if self._contents is None: return contents_length = len(self._contents) child_pointer = 0 while child_pointer < contents_length: parts, child_pointer = _parse(self._contents, contents_length, pointer=child_pointer) if self._child_spec: child = parts + (self._child_spec,) else: child = parts if recurse: child = _build(*child) if isinstance(child, (Sequence, SequenceOf)): child._parse_children(recurse=True) self.children.append(child) except (ValueError, TypeError) as e: self.children = None args = e.args[1:] e.args = (e.args[0] + '\n while parsing %s' % type_name(self),) + args raise e
[ "def", "_parse_children", "(", "self", ",", "recurse", "=", "False", ")", ":", "try", ":", "self", ".", "children", "=", "[", "]", "if", "self", ".", "_contents", "is", "None", ":", "return", "contents_length", "=", "len", "(", "self", ".", "_contents"...
Parses the contents and generates Asn1Value objects based on the definitions from _child_spec. :param recurse: If child objects that are Sequence or SequenceOf objects should be recursively parsed :raises: ValueError - when an error occurs parsing child objects
[ "Parses", "the", "contents", "and", "generates", "Asn1Value", "objects", "based", "on", "the", "definitions", "from", "_child_spec", "." ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L4224-L4258
train
200,274
wbond/asn1crypto
asn1crypto/_types.py
type_name
def type_name(value): """ Returns a user-readable name for the type of an object :param value: A value to get the type name of :return: A unicode string of the object's type name """ if inspect.isclass(value): cls = value else: cls = value.__class__ if cls.__module__ in set(['builtins', '__builtin__']): return cls.__name__ return '%s.%s' % (cls.__module__, cls.__name__)
python
def type_name(value): """ Returns a user-readable name for the type of an object :param value: A value to get the type name of :return: A unicode string of the object's type name """ if inspect.isclass(value): cls = value else: cls = value.__class__ if cls.__module__ in set(['builtins', '__builtin__']): return cls.__name__ return '%s.%s' % (cls.__module__, cls.__name__)
[ "def", "type_name", "(", "value", ")", ":", "if", "inspect", ".", "isclass", "(", "value", ")", ":", "cls", "=", "value", "else", ":", "cls", "=", "value", ".", "__class__", "if", "cls", ".", "__module__", "in", "set", "(", "[", "'builtins'", ",", ...
Returns a user-readable name for the type of an object :param value: A value to get the type name of :return: A unicode string of the object's type name
[ "Returns", "a", "user", "-", "readable", "name", "for", "the", "type", "of", "an", "object" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/_types.py#L29-L46
train
200,275
wbond/asn1crypto
asn1crypto/parser.py
emit
def emit(class_, method, tag, contents): """ Constructs a byte string of an ASN.1 DER-encoded value This is typically not useful. Instead, use one of the standard classes from asn1crypto.core, or construct a new class with specific fields, and call the .dump() method. :param class_: An integer ASN.1 class value: 0 (universal), 1 (application), 2 (context), 3 (private) :param method: An integer ASN.1 method value: 0 (primitive), 1 (constructed) :param tag: An integer ASN.1 tag value :param contents: A byte string of the encoded byte contents :return: A byte string of the ASN.1 DER value (header and contents) """ if not isinstance(class_, int): raise TypeError('class_ must be an integer, not %s' % type_name(class_)) if class_ < 0 or class_ > 3: raise ValueError('class_ must be one of 0, 1, 2 or 3, not %s' % class_) if not isinstance(method, int): raise TypeError('method must be an integer, not %s' % type_name(method)) if method < 0 or method > 1: raise ValueError('method must be 0 or 1, not %s' % method) if not isinstance(tag, int): raise TypeError('tag must be an integer, not %s' % type_name(tag)) if tag < 0: raise ValueError('tag must be greater than zero, not %s' % tag) if not isinstance(contents, byte_cls): raise TypeError('contents must be a byte string, not %s' % type_name(contents)) return _dump_header(class_, method, tag, contents) + contents
python
def emit(class_, method, tag, contents): """ Constructs a byte string of an ASN.1 DER-encoded value This is typically not useful. Instead, use one of the standard classes from asn1crypto.core, or construct a new class with specific fields, and call the .dump() method. :param class_: An integer ASN.1 class value: 0 (universal), 1 (application), 2 (context), 3 (private) :param method: An integer ASN.1 method value: 0 (primitive), 1 (constructed) :param tag: An integer ASN.1 tag value :param contents: A byte string of the encoded byte contents :return: A byte string of the ASN.1 DER value (header and contents) """ if not isinstance(class_, int): raise TypeError('class_ must be an integer, not %s' % type_name(class_)) if class_ < 0 or class_ > 3: raise ValueError('class_ must be one of 0, 1, 2 or 3, not %s' % class_) if not isinstance(method, int): raise TypeError('method must be an integer, not %s' % type_name(method)) if method < 0 or method > 1: raise ValueError('method must be 0 or 1, not %s' % method) if not isinstance(tag, int): raise TypeError('tag must be an integer, not %s' % type_name(tag)) if tag < 0: raise ValueError('tag must be greater than zero, not %s' % tag) if not isinstance(contents, byte_cls): raise TypeError('contents must be a byte string, not %s' % type_name(contents)) return _dump_header(class_, method, tag, contents) + contents
[ "def", "emit", "(", "class_", ",", "method", ",", "tag", ",", "contents", ")", ":", "if", "not", "isinstance", "(", "class_", ",", "int", ")", ":", "raise", "TypeError", "(", "'class_ must be an integer, not %s'", "%", "type_name", "(", "class_", ")", ")",...
Constructs a byte string of an ASN.1 DER-encoded value This is typically not useful. Instead, use one of the standard classes from asn1crypto.core, or construct a new class with specific fields, and call the .dump() method. :param class_: An integer ASN.1 class value: 0 (universal), 1 (application), 2 (context), 3 (private) :param method: An integer ASN.1 method value: 0 (primitive), 1 (constructed) :param tag: An integer ASN.1 tag value :param contents: A byte string of the encoded byte contents :return: A byte string of the ASN.1 DER value (header and contents)
[ "Constructs", "a", "byte", "string", "of", "an", "ASN", ".", "1", "DER", "-", "encoded", "value" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/parser.py#L25-L71
train
200,276
wbond/asn1crypto
asn1crypto/parser.py
_parse
def _parse(encoded_data, data_len, pointer=0, lengths_only=False): """ Parses a byte string into component parts :param encoded_data: A byte string that contains BER-encoded data :param data_len: The integer length of the encoded data :param pointer: The index in the byte string to parse from :param lengths_only: A boolean to cause the call to return a 2-element tuple of the integer number of bytes in the header and the integer number of bytes in the contents. Internal use only. :return: A 2-element tuple: - 0: A tuple of (class_, method, tag, header, content, trailer) - 1: An integer indicating how many bytes were consumed """ if data_len < pointer + 2: raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (2, data_len - pointer)) start = pointer first_octet = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer] pointer += 1 tag = first_octet & 31 # Base 128 length using 8th bit as continuation indicator if tag == 31: tag = 0 while True: num = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer] pointer += 1 tag *= 128 tag += num & 127 if num >> 7 == 0: break length_octet = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer] pointer += 1 if length_octet >> 7 == 0: if lengths_only: return (pointer, pointer + (length_octet & 127)) contents_end = pointer + (length_octet & 127) else: length_octets = length_octet & 127 if length_octets: pointer += length_octets contents_end = pointer + int_from_bytes(encoded_data[pointer - length_octets:pointer], signed=False) if lengths_only: return (pointer, contents_end) else: # To properly parse indefinite length values, we need to scan forward # parsing headers until we find a value with a length of zero. If we # just scanned looking for \x00\x00, nested indefinite length values # would not work. contents_end = pointer # Unfortunately we need to understand the contents of the data to # properly scan forward, which bleeds some representation info into # the parser. This condition handles the unused bits byte in # constructed bit strings. if tag == 3: contents_end += 1 while contents_end < data_len: sub_header_end, contents_end = _parse(encoded_data, data_len, contents_end, lengths_only=True) if contents_end == sub_header_end and encoded_data[contents_end - 2:contents_end] == b'\x00\x00': break if lengths_only: return (pointer, contents_end) if contents_end > data_len: raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (contents_end, data_len)) return ( ( first_octet >> 6, (first_octet >> 5) & 1, tag, encoded_data[start:pointer], encoded_data[pointer:contents_end - 2], b'\x00\x00' ), contents_end ) if contents_end > data_len: raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (contents_end, data_len)) return ( ( first_octet >> 6, (first_octet >> 5) & 1, tag, encoded_data[start:pointer], encoded_data[pointer:contents_end], b'' ), contents_end )
python
def _parse(encoded_data, data_len, pointer=0, lengths_only=False): """ Parses a byte string into component parts :param encoded_data: A byte string that contains BER-encoded data :param data_len: The integer length of the encoded data :param pointer: The index in the byte string to parse from :param lengths_only: A boolean to cause the call to return a 2-element tuple of the integer number of bytes in the header and the integer number of bytes in the contents. Internal use only. :return: A 2-element tuple: - 0: A tuple of (class_, method, tag, header, content, trailer) - 1: An integer indicating how many bytes were consumed """ if data_len < pointer + 2: raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (2, data_len - pointer)) start = pointer first_octet = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer] pointer += 1 tag = first_octet & 31 # Base 128 length using 8th bit as continuation indicator if tag == 31: tag = 0 while True: num = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer] pointer += 1 tag *= 128 tag += num & 127 if num >> 7 == 0: break length_octet = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer] pointer += 1 if length_octet >> 7 == 0: if lengths_only: return (pointer, pointer + (length_octet & 127)) contents_end = pointer + (length_octet & 127) else: length_octets = length_octet & 127 if length_octets: pointer += length_octets contents_end = pointer + int_from_bytes(encoded_data[pointer - length_octets:pointer], signed=False) if lengths_only: return (pointer, contents_end) else: # To properly parse indefinite length values, we need to scan forward # parsing headers until we find a value with a length of zero. If we # just scanned looking for \x00\x00, nested indefinite length values # would not work. contents_end = pointer # Unfortunately we need to understand the contents of the data to # properly scan forward, which bleeds some representation info into # the parser. This condition handles the unused bits byte in # constructed bit strings. if tag == 3: contents_end += 1 while contents_end < data_len: sub_header_end, contents_end = _parse(encoded_data, data_len, contents_end, lengths_only=True) if contents_end == sub_header_end and encoded_data[contents_end - 2:contents_end] == b'\x00\x00': break if lengths_only: return (pointer, contents_end) if contents_end > data_len: raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (contents_end, data_len)) return ( ( first_octet >> 6, (first_octet >> 5) & 1, tag, encoded_data[start:pointer], encoded_data[pointer:contents_end - 2], b'\x00\x00' ), contents_end ) if contents_end > data_len: raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (contents_end, data_len)) return ( ( first_octet >> 6, (first_octet >> 5) & 1, tag, encoded_data[start:pointer], encoded_data[pointer:contents_end], b'' ), contents_end )
[ "def", "_parse", "(", "encoded_data", ",", "data_len", ",", "pointer", "=", "0", ",", "lengths_only", "=", "False", ")", ":", "if", "data_len", "<", "pointer", "+", "2", ":", "raise", "ValueError", "(", "_INSUFFICIENT_DATA_MESSAGE", "%", "(", "2", ",", "...
Parses a byte string into component parts :param encoded_data: A byte string that contains BER-encoded data :param data_len: The integer length of the encoded data :param pointer: The index in the byte string to parse from :param lengths_only: A boolean to cause the call to return a 2-element tuple of the integer number of bytes in the header and the integer number of bytes in the contents. Internal use only. :return: A 2-element tuple: - 0: A tuple of (class_, method, tag, header, content, trailer) - 1: An integer indicating how many bytes were consumed
[ "Parses", "a", "byte", "string", "into", "component", "parts" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/parser.py#L139-L242
train
200,277
wbond/asn1crypto
asn1crypto/parser.py
_dump_header
def _dump_header(class_, method, tag, contents): """ Constructs the header bytes for an ASN.1 object :param class_: An integer ASN.1 class value: 0 (universal), 1 (application), 2 (context), 3 (private) :param method: An integer ASN.1 method value: 0 (primitive), 1 (constructed) :param tag: An integer ASN.1 tag value :param contents: A byte string of the encoded byte contents :return: A byte string of the ASN.1 DER header """ header = b'' id_num = 0 id_num |= class_ << 6 id_num |= method << 5 if tag >= 31: header += chr_cls(id_num | 31) while tag > 0: continuation_bit = 0x80 if tag > 0x7F else 0 header += chr_cls(continuation_bit | (tag & 0x7F)) tag = tag >> 7 else: header += chr_cls(id_num | tag) length = len(contents) if length <= 127: header += chr_cls(length) else: length_bytes = int_to_bytes(length) header += chr_cls(0x80 | len(length_bytes)) header += length_bytes return header
python
def _dump_header(class_, method, tag, contents): """ Constructs the header bytes for an ASN.1 object :param class_: An integer ASN.1 class value: 0 (universal), 1 (application), 2 (context), 3 (private) :param method: An integer ASN.1 method value: 0 (primitive), 1 (constructed) :param tag: An integer ASN.1 tag value :param contents: A byte string of the encoded byte contents :return: A byte string of the ASN.1 DER header """ header = b'' id_num = 0 id_num |= class_ << 6 id_num |= method << 5 if tag >= 31: header += chr_cls(id_num | 31) while tag > 0: continuation_bit = 0x80 if tag > 0x7F else 0 header += chr_cls(continuation_bit | (tag & 0x7F)) tag = tag >> 7 else: header += chr_cls(id_num | tag) length = len(contents) if length <= 127: header += chr_cls(length) else: length_bytes = int_to_bytes(length) header += chr_cls(0x80 | len(length_bytes)) header += length_bytes return header
[ "def", "_dump_header", "(", "class_", ",", "method", ",", "tag", ",", "contents", ")", ":", "header", "=", "b''", "id_num", "=", "0", "id_num", "|=", "class_", "<<", "6", "id_num", "|=", "method", "<<", "5", "if", "tag", ">=", "31", ":", "header", ...
Constructs the header bytes for an ASN.1 object :param class_: An integer ASN.1 class value: 0 (universal), 1 (application), 2 (context), 3 (private) :param method: An integer ASN.1 method value: 0 (primitive), 1 (constructed) :param tag: An integer ASN.1 tag value :param contents: A byte string of the encoded byte contents :return: A byte string of the ASN.1 DER header
[ "Constructs", "the", "header", "bytes", "for", "an", "ASN", ".", "1", "object" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/parser.py#L245-L289
train
200,278
wbond/asn1crypto
asn1crypto/_iri.py
_iri_utf8_errors_handler
def _iri_utf8_errors_handler(exc): """ Error handler for decoding UTF-8 parts of a URI into an IRI. Leaves byte sequences encoded in %XX format, but as part of a unicode string. :param exc: The UnicodeDecodeError exception :return: A 2-element tuple of (replacement unicode string, integer index to resume at) """ bytes_as_ints = bytes_to_list(exc.object[exc.start:exc.end]) replacements = ['%%%02x' % num for num in bytes_as_ints] return (''.join(replacements), exc.end)
python
def _iri_utf8_errors_handler(exc): """ Error handler for decoding UTF-8 parts of a URI into an IRI. Leaves byte sequences encoded in %XX format, but as part of a unicode string. :param exc: The UnicodeDecodeError exception :return: A 2-element tuple of (replacement unicode string, integer index to resume at) """ bytes_as_ints = bytes_to_list(exc.object[exc.start:exc.end]) replacements = ['%%%02x' % num for num in bytes_as_ints] return (''.join(replacements), exc.end)
[ "def", "_iri_utf8_errors_handler", "(", "exc", ")", ":", "bytes_as_ints", "=", "bytes_to_list", "(", "exc", ".", "object", "[", "exc", ".", "start", ":", "exc", ".", "end", "]", ")", "replacements", "=", "[", "'%%%02x'", "%", "num", "for", "num", "in", ...
Error handler for decoding UTF-8 parts of a URI into an IRI. Leaves byte sequences encoded in %XX format, but as part of a unicode string. :param exc: The UnicodeDecodeError exception :return: A 2-element tuple of (replacement unicode string, integer index to resume at)
[ "Error", "handler", "for", "decoding", "UTF", "-", "8", "parts", "of", "a", "URI", "into", "an", "IRI", ".", "Leaves", "byte", "sequences", "encoded", "in", "%XX", "format", "but", "as", "part", "of", "a", "unicode", "string", "." ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/_iri.py#L172-L187
train
200,279
wbond/asn1crypto
asn1crypto/_iri.py
_urlquote
def _urlquote(string, safe=''): """ Quotes a unicode string for use in a URL :param string: A unicode string :param safe: A unicode string of character to not encode :return: None (if string is None) or an ASCII byte string of the quoted string """ if string is None or string == '': return None # Anything already hex quoted is pulled out of the URL and unquoted if # possible escapes = [] if re.search('%[0-9a-fA-F]{2}', string): # Try to unquote any percent values, restoring them if they are not # valid UTF-8. Also, requote any safe chars since encoded versions of # those are functionally different than the unquoted ones. def _try_unescape(match): byte_string = unquote_to_bytes(match.group(0)) unicode_string = byte_string.decode('utf-8', 'iriutf8') for safe_char in list(safe): unicode_string = unicode_string.replace(safe_char, '%%%02x' % ord(safe_char)) return unicode_string string = re.sub('(?:%[0-9a-fA-F]{2})+', _try_unescape, string) # Once we have the minimal set of hex quoted values, removed them from # the string so that they are not double quoted def _extract_escape(match): escapes.append(match.group(0).encode('ascii')) return '\x00' string = re.sub('%[0-9a-fA-F]{2}', _extract_escape, string) output = urlquote(string.encode('utf-8'), safe=safe.encode('utf-8')) if not isinstance(output, byte_cls): output = output.encode('ascii') # Restore the existing quoted values that we extracted if len(escapes) > 0: def _return_escape(_): return escapes.pop(0) output = re.sub(b'%00', _return_escape, output) return output
python
def _urlquote(string, safe=''): """ Quotes a unicode string for use in a URL :param string: A unicode string :param safe: A unicode string of character to not encode :return: None (if string is None) or an ASCII byte string of the quoted string """ if string is None or string == '': return None # Anything already hex quoted is pulled out of the URL and unquoted if # possible escapes = [] if re.search('%[0-9a-fA-F]{2}', string): # Try to unquote any percent values, restoring them if they are not # valid UTF-8. Also, requote any safe chars since encoded versions of # those are functionally different than the unquoted ones. def _try_unescape(match): byte_string = unquote_to_bytes(match.group(0)) unicode_string = byte_string.decode('utf-8', 'iriutf8') for safe_char in list(safe): unicode_string = unicode_string.replace(safe_char, '%%%02x' % ord(safe_char)) return unicode_string string = re.sub('(?:%[0-9a-fA-F]{2})+', _try_unescape, string) # Once we have the minimal set of hex quoted values, removed them from # the string so that they are not double quoted def _extract_escape(match): escapes.append(match.group(0).encode('ascii')) return '\x00' string = re.sub('%[0-9a-fA-F]{2}', _extract_escape, string) output = urlquote(string.encode('utf-8'), safe=safe.encode('utf-8')) if not isinstance(output, byte_cls): output = output.encode('ascii') # Restore the existing quoted values that we extracted if len(escapes) > 0: def _return_escape(_): return escapes.pop(0) output = re.sub(b'%00', _return_escape, output) return output
[ "def", "_urlquote", "(", "string", ",", "safe", "=", "''", ")", ":", "if", "string", "is", "None", "or", "string", "==", "''", ":", "return", "None", "# Anything already hex quoted is pulled out of the URL and unquoted if", "# possible", "escapes", "=", "[", "]", ...
Quotes a unicode string for use in a URL :param string: A unicode string :param safe: A unicode string of character to not encode :return: None (if string is None) or an ASCII byte string of the quoted string
[ "Quotes", "a", "unicode", "string", "for", "use", "in", "a", "URL" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/_iri.py#L193-L242
train
200,280
wbond/asn1crypto
asn1crypto/_iri.py
_urlunquote
def _urlunquote(byte_string, remap=None, preserve=None): """ Unquotes a URI portion from a byte string into unicode using UTF-8 :param byte_string: A byte string of the data to unquote :param remap: A list of characters (as unicode) that should be re-mapped to a %XX encoding. This is used when characters are not valid in part of a URL. :param preserve: A bool - indicates that the chars to be remapped if they occur in non-hex form, should be preserved. E.g. / for URL path. :return: A unicode string """ if byte_string is None: return byte_string if byte_string == b'': return '' if preserve: replacements = ['\x1A', '\x1C', '\x1D', '\x1E', '\x1F'] preserve_unmap = {} for char in remap: replacement = replacements.pop(0) preserve_unmap[replacement] = char byte_string = byte_string.replace(char.encode('ascii'), replacement.encode('ascii')) byte_string = unquote_to_bytes(byte_string) if remap: for char in remap: byte_string = byte_string.replace(char.encode('ascii'), ('%%%02x' % ord(char)).encode('ascii')) output = byte_string.decode('utf-8', 'iriutf8') if preserve: for replacement, original in preserve_unmap.items(): output = output.replace(replacement, original) return output
python
def _urlunquote(byte_string, remap=None, preserve=None): """ Unquotes a URI portion from a byte string into unicode using UTF-8 :param byte_string: A byte string of the data to unquote :param remap: A list of characters (as unicode) that should be re-mapped to a %XX encoding. This is used when characters are not valid in part of a URL. :param preserve: A bool - indicates that the chars to be remapped if they occur in non-hex form, should be preserved. E.g. / for URL path. :return: A unicode string """ if byte_string is None: return byte_string if byte_string == b'': return '' if preserve: replacements = ['\x1A', '\x1C', '\x1D', '\x1E', '\x1F'] preserve_unmap = {} for char in remap: replacement = replacements.pop(0) preserve_unmap[replacement] = char byte_string = byte_string.replace(char.encode('ascii'), replacement.encode('ascii')) byte_string = unquote_to_bytes(byte_string) if remap: for char in remap: byte_string = byte_string.replace(char.encode('ascii'), ('%%%02x' % ord(char)).encode('ascii')) output = byte_string.decode('utf-8', 'iriutf8') if preserve: for replacement, original in preserve_unmap.items(): output = output.replace(replacement, original) return output
[ "def", "_urlunquote", "(", "byte_string", ",", "remap", "=", "None", ",", "preserve", "=", "None", ")", ":", "if", "byte_string", "is", "None", ":", "return", "byte_string", "if", "byte_string", "==", "b''", ":", "return", "''", "if", "preserve", ":", "r...
Unquotes a URI portion from a byte string into unicode using UTF-8 :param byte_string: A byte string of the data to unquote :param remap: A list of characters (as unicode) that should be re-mapped to a %XX encoding. This is used when characters are not valid in part of a URL. :param preserve: A bool - indicates that the chars to be remapped if they occur in non-hex form, should be preserved. E.g. / for URL path. :return: A unicode string
[ "Unquotes", "a", "URI", "portion", "from", "a", "byte", "string", "into", "unicode", "using", "UTF", "-", "8" ]
ecda20176f55d37021cbca1f6da9083a8e491197
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/_iri.py#L245-L291
train
200,281
mkaz/termgraph
termgraph/termgraph.py
init_args
def init_args(): """Parse and return the arguments.""" parser = argparse.ArgumentParser( description='draw basic graphs on terminal') parser.add_argument( 'filename', nargs='?', default="-", help='data file name (comma or space separated). Defaults to stdin.') parser.add_argument( '--title', help='Title of graph' ) parser.add_argument( '--width', type=int, default=50, help='width of graph in characters default:50' ) parser.add_argument( '--format', default='{:<5.2f}', help='format specifier to use.' ) parser.add_argument( '--suffix', default='', help='string to add as a suffix to all data points.' ) parser.add_argument( '--no-labels', action='store_true', help='Do not print the label column' ) parser.add_argument( '--color', nargs='*', choices=AVAILABLE_COLORS, help='Graph bar color( s )' ) parser.add_argument( '--vertical', action='store_true', help='Vertical graph' ) parser.add_argument( '--stacked', action='store_true', help='Stacked bar graph' ) parser.add_argument( '--different-scale', action='store_true', help='Categories have different scales.' ) parser.add_argument( '--calendar', action='store_true', help='Calendar Heatmap chart' ) parser.add_argument( '--start-dt', help='Start date for Calendar chart' ) parser.add_argument( '--custom-tick', default='', help='Custom tick mark, emoji approved' ) parser.add_argument( '--delim', default='', help='Custom delimiter, default , or space' ) parser.add_argument( '--verbose', action='store_true', help='Verbose output, helpful for debugging' ) parser.add_argument( '--version', action='store_true', help='Display version and exit' ) if len(sys.argv) == 1: if sys.stdin.isatty(): parser.print_usage() sys.exit(2) args = vars(parser.parse_args()) if args['custom_tick'] != '': global TICK, SM_TICK TICK = args['custom_tick'] SM_TICK = '' if args['delim'] != '': global DELIM DELIM = args['delim'] return args
python
def init_args(): """Parse and return the arguments.""" parser = argparse.ArgumentParser( description='draw basic graphs on terminal') parser.add_argument( 'filename', nargs='?', default="-", help='data file name (comma or space separated). Defaults to stdin.') parser.add_argument( '--title', help='Title of graph' ) parser.add_argument( '--width', type=int, default=50, help='width of graph in characters default:50' ) parser.add_argument( '--format', default='{:<5.2f}', help='format specifier to use.' ) parser.add_argument( '--suffix', default='', help='string to add as a suffix to all data points.' ) parser.add_argument( '--no-labels', action='store_true', help='Do not print the label column' ) parser.add_argument( '--color', nargs='*', choices=AVAILABLE_COLORS, help='Graph bar color( s )' ) parser.add_argument( '--vertical', action='store_true', help='Vertical graph' ) parser.add_argument( '--stacked', action='store_true', help='Stacked bar graph' ) parser.add_argument( '--different-scale', action='store_true', help='Categories have different scales.' ) parser.add_argument( '--calendar', action='store_true', help='Calendar Heatmap chart' ) parser.add_argument( '--start-dt', help='Start date for Calendar chart' ) parser.add_argument( '--custom-tick', default='', help='Custom tick mark, emoji approved' ) parser.add_argument( '--delim', default='', help='Custom delimiter, default , or space' ) parser.add_argument( '--verbose', action='store_true', help='Verbose output, helpful for debugging' ) parser.add_argument( '--version', action='store_true', help='Display version and exit' ) if len(sys.argv) == 1: if sys.stdin.isatty(): parser.print_usage() sys.exit(2) args = vars(parser.parse_args()) if args['custom_tick'] != '': global TICK, SM_TICK TICK = args['custom_tick'] SM_TICK = '' if args['delim'] != '': global DELIM DELIM = args['delim'] return args
[ "def", "init_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'draw basic graphs on terminal'", ")", "parser", ".", "add_argument", "(", "'filename'", ",", "nargs", "=", "'?'", ",", "default", "=", "\"-\"", ",",...
Parse and return the arguments.
[ "Parse", "and", "return", "the", "arguments", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L41-L141
train
200,282
mkaz/termgraph
termgraph/termgraph.py
find_max_label_length
def find_max_label_length(labels): """Return the maximum length for the labels.""" length = 0 for i in range(len(labels)): if len(labels[i]) > length: length = len(labels[i]) return length
python
def find_max_label_length(labels): """Return the maximum length for the labels.""" length = 0 for i in range(len(labels)): if len(labels[i]) > length: length = len(labels[i]) return length
[ "def", "find_max_label_length", "(", "labels", ")", ":", "length", "=", "0", "for", "i", "in", "range", "(", "len", "(", "labels", ")", ")", ":", "if", "len", "(", "labels", "[", "i", "]", ")", ">", "length", ":", "length", "=", "len", "(", "labe...
Return the maximum length for the labels.
[ "Return", "the", "maximum", "length", "for", "the", "labels", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L166-L173
train
200,283
mkaz/termgraph
termgraph/termgraph.py
normalize
def normalize(data, width): """Normalize the data and return it.""" min_dat = find_min(data) # We offset by the minimum if there's a negative. off_data = [] if min_dat < 0: min_dat = abs(min_dat) for dat in data: off_data.append([_d + min_dat for _d in dat]) else: off_data = data min_dat = find_min(off_data) max_dat = find_max(off_data) if max_dat < width: # Don't need to normalize if the max value # is less than the width we allow. return off_data # max_dat / width is the value for a single tick. norm_factor is the # inverse of this value # If you divide a number to the value of single tick, you will find how # many ticks it does contain basically. norm_factor = width / float(max_dat) normal_dat = [] for dat in off_data: normal_dat.append([_v * norm_factor for _v in dat]) return normal_dat
python
def normalize(data, width): """Normalize the data and return it.""" min_dat = find_min(data) # We offset by the minimum if there's a negative. off_data = [] if min_dat < 0: min_dat = abs(min_dat) for dat in data: off_data.append([_d + min_dat for _d in dat]) else: off_data = data min_dat = find_min(off_data) max_dat = find_max(off_data) if max_dat < width: # Don't need to normalize if the max value # is less than the width we allow. return off_data # max_dat / width is the value for a single tick. norm_factor is the # inverse of this value # If you divide a number to the value of single tick, you will find how # many ticks it does contain basically. norm_factor = width / float(max_dat) normal_dat = [] for dat in off_data: normal_dat.append([_v * norm_factor for _v in dat]) return normal_dat
[ "def", "normalize", "(", "data", ",", "width", ")", ":", "min_dat", "=", "find_min", "(", "data", ")", "# We offset by the minimum if there's a negative.", "off_data", "=", "[", "]", "if", "min_dat", "<", "0", ":", "min_dat", "=", "abs", "(", "min_dat", ")",...
Normalize the data and return it.
[ "Normalize", "the", "data", "and", "return", "it", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L175-L203
train
200,284
mkaz/termgraph
termgraph/termgraph.py
horiz_rows
def horiz_rows(labels, data, normal_dat, args, colors): """Prepare the horizontal graph. Each row is printed through the print_row function.""" val_min = find_min(data) for i in range(len(labels)): if args['no_labels']: # Hide the labels. label = '' else: label = "{:<{x}}: ".format(labels[i], x=find_max_label_length(labels)) values = data[i] num_blocks = normal_dat[i] for j in range(len(values)): # In Multiple series graph 1st category has label at the beginning, # whereas the rest categories have only spaces. if j > 0: len_label = len(label) label = ' ' * len_label tail = ' {}{}'.format(args['format'].format(values[j]), args['suffix']) if colors: color = colors[j] else: color = None if not args['vertical']: print(label, end="") yield(values[j], int(num_blocks[j]), val_min, color) if not args['vertical']: print(tail)
python
def horiz_rows(labels, data, normal_dat, args, colors): """Prepare the horizontal graph. Each row is printed through the print_row function.""" val_min = find_min(data) for i in range(len(labels)): if args['no_labels']: # Hide the labels. label = '' else: label = "{:<{x}}: ".format(labels[i], x=find_max_label_length(labels)) values = data[i] num_blocks = normal_dat[i] for j in range(len(values)): # In Multiple series graph 1st category has label at the beginning, # whereas the rest categories have only spaces. if j > 0: len_label = len(label) label = ' ' * len_label tail = ' {}{}'.format(args['format'].format(values[j]), args['suffix']) if colors: color = colors[j] else: color = None if not args['vertical']: print(label, end="") yield(values[j], int(num_blocks[j]), val_min, color) if not args['vertical']: print(tail)
[ "def", "horiz_rows", "(", "labels", ",", "data", ",", "normal_dat", ",", "args", ",", "colors", ")", ":", "val_min", "=", "find_min", "(", "data", ")", "for", "i", "in", "range", "(", "len", "(", "labels", ")", ")", ":", "if", "args", "[", "'no_lab...
Prepare the horizontal graph. Each row is printed through the print_row function.
[ "Prepare", "the", "horizontal", "graph", ".", "Each", "row", "is", "printed", "through", "the", "print_row", "function", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L205-L240
train
200,285
mkaz/termgraph
termgraph/termgraph.py
print_row
def print_row(value, num_blocks, val_min, color): """A method to print a row for a horizontal graphs. i.e: 1: ▇▇ 2 2: ▇▇▇ 3 3: ▇▇▇▇ 4 """ if color: sys.stdout.write(f'\033[{color}m') # Start to write colorized. if num_blocks < 1 and (value > val_min or value > 0): # Print something if it's not the smallest # and the normal value is less than one. sys.stdout.write(SM_TICK) else: for _ in range(num_blocks): sys.stdout.write(TICK) if color: sys.stdout.write('\033[0m')
python
def print_row(value, num_blocks, val_min, color): """A method to print a row for a horizontal graphs. i.e: 1: ▇▇ 2 2: ▇▇▇ 3 3: ▇▇▇▇ 4 """ if color: sys.stdout.write(f'\033[{color}m') # Start to write colorized. if num_blocks < 1 and (value > val_min or value > 0): # Print something if it's not the smallest # and the normal value is less than one. sys.stdout.write(SM_TICK) else: for _ in range(num_blocks): sys.stdout.write(TICK) if color: sys.stdout.write('\033[0m')
[ "def", "print_row", "(", "value", ",", "num_blocks", ",", "val_min", ",", "color", ")", ":", "if", "color", ":", "sys", ".", "stdout", ".", "write", "(", "f'\\033[{color}m'", ")", "# Start to write colorized.", "if", "num_blocks", "<", "1", "and", "(", "va...
A method to print a row for a horizontal graphs. i.e: 1: ▇▇ 2 2: ▇▇▇ 3 3: ▇▇▇▇ 4
[ "A", "method", "to", "print", "a", "row", "for", "a", "horizontal", "graphs", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L243-L263
train
200,286
mkaz/termgraph
termgraph/termgraph.py
stacked_graph
def stacked_graph(labels, data, normal_data, len_categories, args, colors): """Prepare the horizontal stacked graph. Each row is printed through the print_row function.""" val_min = find_min(data) for i in range(len(labels)): if args['no_labels']: # Hide the labels. label = '' else: label = "{:<{x}}: ".format(labels[i], x=find_max_label_length(labels)) print(label, end="") values = data[i] num_blocks = normal_data[i] for j in range(len(values)): print_row(values[j], int(num_blocks[j]), val_min, colors[j]) tail = ' {}{}'.format(args['format'].format(sum(values)), args['suffix']) print(tail)
python
def stacked_graph(labels, data, normal_data, len_categories, args, colors): """Prepare the horizontal stacked graph. Each row is printed through the print_row function.""" val_min = find_min(data) for i in range(len(labels)): if args['no_labels']: # Hide the labels. label = '' else: label = "{:<{x}}: ".format(labels[i], x=find_max_label_length(labels)) print(label, end="") values = data[i] num_blocks = normal_data[i] for j in range(len(values)): print_row(values[j], int(num_blocks[j]), val_min, colors[j]) tail = ' {}{}'.format(args['format'].format(sum(values)), args['suffix']) print(tail)
[ "def", "stacked_graph", "(", "labels", ",", "data", ",", "normal_data", ",", "len_categories", ",", "args", ",", "colors", ")", ":", "val_min", "=", "find_min", "(", "data", ")", "for", "i", "in", "range", "(", "len", "(", "labels", ")", ")", ":", "i...
Prepare the horizontal stacked graph. Each row is printed through the print_row function.
[ "Prepare", "the", "horizontal", "stacked", "graph", ".", "Each", "row", "is", "printed", "through", "the", "print_row", "function", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L265-L287
train
200,287
mkaz/termgraph
termgraph/termgraph.py
vertically
def vertically(value, num_blocks, val_min, color, args): """Prepare the vertical graph. The whole graph is printed through the print_vertical function.""" global maxi, value_list value_list.append(str(value)) # In case the number of blocks at the end of the normalization is less # than the default number, use the maxi variable to escape. if maxi < num_blocks: maxi = num_blocks if num_blocks > 0: vertical_list.append((TICK * num_blocks)) else: vertical_list.append(SM_TICK) # Zip_longest method in order to turn them vertically. for row in zip_longest(*vertical_list, fillvalue=' '): zipped_list.append(row) counter, result_list = 0, [] # Combined with the maxi variable, escapes the appending method at # the correct point or the default one (width). for i in reversed(zipped_list): result_list.append(i) counter += 1 if maxi == args['width']: if counter == (args['width']): break else: if counter == maxi: break # Return a list of rows which will be used to print the result vertically. return result_list
python
def vertically(value, num_blocks, val_min, color, args): """Prepare the vertical graph. The whole graph is printed through the print_vertical function.""" global maxi, value_list value_list.append(str(value)) # In case the number of blocks at the end of the normalization is less # than the default number, use the maxi variable to escape. if maxi < num_blocks: maxi = num_blocks if num_blocks > 0: vertical_list.append((TICK * num_blocks)) else: vertical_list.append(SM_TICK) # Zip_longest method in order to turn them vertically. for row in zip_longest(*vertical_list, fillvalue=' '): zipped_list.append(row) counter, result_list = 0, [] # Combined with the maxi variable, escapes the appending method at # the correct point or the default one (width). for i in reversed(zipped_list): result_list.append(i) counter += 1 if maxi == args['width']: if counter == (args['width']): break else: if counter == maxi: break # Return a list of rows which will be used to print the result vertically. return result_list
[ "def", "vertically", "(", "value", ",", "num_blocks", ",", "val_min", ",", "color", ",", "args", ")", ":", "global", "maxi", ",", "value_list", "value_list", ".", "append", "(", "str", "(", "value", ")", ")", "# In case the number of blocks at the end of the nor...
Prepare the vertical graph. The whole graph is printed through the print_vertical function.
[ "Prepare", "the", "vertical", "graph", ".", "The", "whole", "graph", "is", "printed", "through", "the", "print_vertical", "function", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L291-L328
train
200,288
mkaz/termgraph
termgraph/termgraph.py
print_vertical
def print_vertical(vertical_rows, labels, color, args): """Print the whole vertical graph.""" if color: sys.stdout.write(f'\033[{color}m') # Start to write colorized. for row in vertical_rows: print(*row) sys.stdout.write('\033[0m') # End of printing colored print("-" * len(row) + "Values" + "-" * len(row)) # Print Values for value in zip_longest(*value_list, fillvalue=' '): print(" ".join(value)) if args['no_labels'] == False: print("-" * len(row) + "Labels" + "-" * len(row)) # Print Labels for label in zip_longest(*labels, fillvalue=''): print(" ".join(label))
python
def print_vertical(vertical_rows, labels, color, args): """Print the whole vertical graph.""" if color: sys.stdout.write(f'\033[{color}m') # Start to write colorized. for row in vertical_rows: print(*row) sys.stdout.write('\033[0m') # End of printing colored print("-" * len(row) + "Values" + "-" * len(row)) # Print Values for value in zip_longest(*value_list, fillvalue=' '): print(" ".join(value)) if args['no_labels'] == False: print("-" * len(row) + "Labels" + "-" * len(row)) # Print Labels for label in zip_longest(*labels, fillvalue=''): print(" ".join(label))
[ "def", "print_vertical", "(", "vertical_rows", ",", "labels", ",", "color", ",", "args", ")", ":", "if", "color", ":", "sys", ".", "stdout", ".", "write", "(", "f'\\033[{color}m'", ")", "# Start to write colorized.", "for", "row", "in", "vertical_rows", ":", ...
Print the whole vertical graph.
[ "Print", "the", "whole", "vertical", "graph", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L330-L349
train
200,289
mkaz/termgraph
termgraph/termgraph.py
chart
def chart(colors, data, args, labels): """Handle the normalization of data and the printing of the graph.""" len_categories = len(data[0]) if len_categories > 1: # Stacked graph if args['stacked']: normal_dat = normalize(data, args['width']) stacked_graph(labels, data, normal_dat, len_categories, args, colors) return if not colors: colors = [None] * len_categories # Multiple series graph with different scales # Normalization per category if args['different_scale']: for i in range(len_categories): cat_data = [] for dat in data: cat_data.append([dat[i]]) # Normalize data, handle negatives. normal_cat_data = normalize(cat_data, args['width']) # Generate data for a row. for row in horiz_rows(labels, cat_data, normal_cat_data, args, [colors[i]]): # Print the row if not args['vertical']: print_row(*row) else: vertic = vertically(*row, args=args) # Vertical graph if args['vertical']: print_vertical(vertic, labels, colors[i], args) print() value_list.clear(), zipped_list.clear(), vertical_list.clear() return # One category/Multiple series graph with same scale # All-together normalization if not args['stacked']: normal_dat = normalize(data, args['width']) for row in horiz_rows(labels, data, normal_dat, args, colors): if not args['vertical']: print_row(*row) else: vertic = vertically(*row, args=args) if args['vertical'] and len_categories == 1: if colors: color = colors[0] else: color = None print_vertical(vertic, labels, color, args) print()
python
def chart(colors, data, args, labels): """Handle the normalization of data and the printing of the graph.""" len_categories = len(data[0]) if len_categories > 1: # Stacked graph if args['stacked']: normal_dat = normalize(data, args['width']) stacked_graph(labels, data, normal_dat, len_categories, args, colors) return if not colors: colors = [None] * len_categories # Multiple series graph with different scales # Normalization per category if args['different_scale']: for i in range(len_categories): cat_data = [] for dat in data: cat_data.append([dat[i]]) # Normalize data, handle negatives. normal_cat_data = normalize(cat_data, args['width']) # Generate data for a row. for row in horiz_rows(labels, cat_data, normal_cat_data, args, [colors[i]]): # Print the row if not args['vertical']: print_row(*row) else: vertic = vertically(*row, args=args) # Vertical graph if args['vertical']: print_vertical(vertic, labels, colors[i], args) print() value_list.clear(), zipped_list.clear(), vertical_list.clear() return # One category/Multiple series graph with same scale # All-together normalization if not args['stacked']: normal_dat = normalize(data, args['width']) for row in horiz_rows(labels, data, normal_dat, args, colors): if not args['vertical']: print_row(*row) else: vertic = vertically(*row, args=args) if args['vertical'] and len_categories == 1: if colors: color = colors[0] else: color = None print_vertical(vertic, labels, color, args) print()
[ "def", "chart", "(", "colors", ",", "data", ",", "args", ",", "labels", ")", ":", "len_categories", "=", "len", "(", "data", "[", "0", "]", ")", "if", "len_categories", ">", "1", ":", "# Stacked graph", "if", "args", "[", "'stacked'", "]", ":", "norm...
Handle the normalization of data and the printing of the graph.
[ "Handle", "the", "normalization", "of", "data", "and", "the", "printing", "of", "the", "graph", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L351-L411
train
200,290
mkaz/termgraph
termgraph/termgraph.py
check_data
def check_data(labels, data, args): """Check that all data were inserted correctly. Return the colors.""" len_categories = len(data[0]) # Check that there are data for all labels. if len(labels) != len(data): print(">> Error: Label and data array sizes don't match") sys.exit(1) # Check that there are data for all categories per label. for dat in data: if len(dat) != len_categories: print(">> Error: There are missing values") sys.exit(1) colors = [] # If user inserts colors, they should be as many as the categories. if args['color'] is not None: if len(args['color']) != len_categories: print(">> Error: Color and category array sizes don't match") sys.exit(1) for color in args['color']: colors.append(AVAILABLE_COLORS.get(color)) # Vertical graph for multiple series of same scale is not supported yet. if args['vertical'] and len_categories > 1 and not args['different_scale']: print(">> Error: Vertical graph for multiple series of same " "scale is not supported yet.") sys.exit(1) # If user hasn't inserted colors, pick the first n colors # from the dict (n = number of categories). if args['stacked'] and not colors: colors = [v for v in list(AVAILABLE_COLORS.values())[:len_categories]] return colors
python
def check_data(labels, data, args): """Check that all data were inserted correctly. Return the colors.""" len_categories = len(data[0]) # Check that there are data for all labels. if len(labels) != len(data): print(">> Error: Label and data array sizes don't match") sys.exit(1) # Check that there are data for all categories per label. for dat in data: if len(dat) != len_categories: print(">> Error: There are missing values") sys.exit(1) colors = [] # If user inserts colors, they should be as many as the categories. if args['color'] is not None: if len(args['color']) != len_categories: print(">> Error: Color and category array sizes don't match") sys.exit(1) for color in args['color']: colors.append(AVAILABLE_COLORS.get(color)) # Vertical graph for multiple series of same scale is not supported yet. if args['vertical'] and len_categories > 1 and not args['different_scale']: print(">> Error: Vertical graph for multiple series of same " "scale is not supported yet.") sys.exit(1) # If user hasn't inserted colors, pick the first n colors # from the dict (n = number of categories). if args['stacked'] and not colors: colors = [v for v in list(AVAILABLE_COLORS.values())[:len_categories]] return colors
[ "def", "check_data", "(", "labels", ",", "data", ",", "args", ")", ":", "len_categories", "=", "len", "(", "data", "[", "0", "]", ")", "# Check that there are data for all labels.", "if", "len", "(", "labels", ")", "!=", "len", "(", "data", ")", ":", "pr...
Check that all data were inserted correctly. Return the colors.
[ "Check", "that", "all", "data", "were", "inserted", "correctly", ".", "Return", "the", "colors", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L413-L450
train
200,291
mkaz/termgraph
termgraph/termgraph.py
print_categories
def print_categories(categories, colors): """Print a tick and the category's name for each category above the graph.""" for i in range(len(categories)): if colors: sys.stdout.write(f'\033[{colors[i]}m') # Start to write colorized. sys.stdout.write(TICK + ' ' + categories[i] + ' ') if colors: sys.stdout.write('\033[0m') # Back to original. print('\n\n')
python
def print_categories(categories, colors): """Print a tick and the category's name for each category above the graph.""" for i in range(len(categories)): if colors: sys.stdout.write(f'\033[{colors[i]}m') # Start to write colorized. sys.stdout.write(TICK + ' ' + categories[i] + ' ') if colors: sys.stdout.write('\033[0m') # Back to original. print('\n\n')
[ "def", "print_categories", "(", "categories", ",", "colors", ")", ":", "for", "i", "in", "range", "(", "len", "(", "categories", ")", ")", ":", "if", "colors", ":", "sys", ".", "stdout", ".", "write", "(", "f'\\033[{colors[i]}m'", ")", "# Start to write co...
Print a tick and the category's name for each category above the graph.
[ "Print", "a", "tick", "and", "the", "category", "s", "name", "for", "each", "category", "above", "the", "graph", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L452-L463
train
200,292
mkaz/termgraph
termgraph/termgraph.py
read_data
def read_data(args): """Read data from a file or stdin and returns it. Filename includes (categories), labels and data. We append categories and labels to lists. Data are inserted to a list of lists due to the categories. i.e. labels = ['2001', '2002', '2003', ...] categories = ['boys', 'girls'] data = [ [20.4, 40.5], [30.7, 100.0], ...]""" filename = args['filename'] stdin = filename == '-' if args['verbose']: print(f'>> Reading data from {( "stdin" if stdin else filename )}') print('') if args['title']: print('# ' + args['title'] + '\n') categories, labels, data, colors = ([] for i in range(4)) f = sys.stdin if stdin else open(filename, "r") for line in f: line = line.strip() if line: if not line.startswith('#'): if line.find(DELIM) > 0: cols = line.split(DELIM) else: cols = line.split() # Line contains categories. if line.startswith('@'): cols[0] = cols[0].replace("@ ", "") categories = cols # Line contains label and values. else: labels.append(cols[0].strip()) data_points = [] for i in range(1, len(cols)): data_points.append(float(cols[i].strip())) data.append(data_points) f.close() # Check that all data are valid. (i.e. There are no missing values.) colors = check_data(labels, data, args) if categories: # Print categories' names above the graph. print_categories(categories, colors) return categories, labels, data, colors
python
def read_data(args): """Read data from a file or stdin and returns it. Filename includes (categories), labels and data. We append categories and labels to lists. Data are inserted to a list of lists due to the categories. i.e. labels = ['2001', '2002', '2003', ...] categories = ['boys', 'girls'] data = [ [20.4, 40.5], [30.7, 100.0], ...]""" filename = args['filename'] stdin = filename == '-' if args['verbose']: print(f'>> Reading data from {( "stdin" if stdin else filename )}') print('') if args['title']: print('# ' + args['title'] + '\n') categories, labels, data, colors = ([] for i in range(4)) f = sys.stdin if stdin else open(filename, "r") for line in f: line = line.strip() if line: if not line.startswith('#'): if line.find(DELIM) > 0: cols = line.split(DELIM) else: cols = line.split() # Line contains categories. if line.startswith('@'): cols[0] = cols[0].replace("@ ", "") categories = cols # Line contains label and values. else: labels.append(cols[0].strip()) data_points = [] for i in range(1, len(cols)): data_points.append(float(cols[i].strip())) data.append(data_points) f.close() # Check that all data are valid. (i.e. There are no missing values.) colors = check_data(labels, data, args) if categories: # Print categories' names above the graph. print_categories(categories, colors) return categories, labels, data, colors
[ "def", "read_data", "(", "args", ")", ":", "filename", "=", "args", "[", "'filename'", "]", "stdin", "=", "filename", "==", "'-'", "if", "args", "[", "'verbose'", "]", ":", "print", "(", "f'>> Reading data from {( \"stdin\" if stdin else filename )}'", ")", "pri...
Read data from a file or stdin and returns it. Filename includes (categories), labels and data. We append categories and labels to lists. Data are inserted to a list of lists due to the categories. i.e. labels = ['2001', '2002', '2003', ...] categories = ['boys', 'girls'] data = [ [20.4, 40.5], [30.7, 100.0], ...]
[ "Read", "data", "from", "a", "file", "or", "stdin", "and", "returns", "it", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L465-L519
train
200,293
mkaz/termgraph
termgraph/termgraph.py
calendar_heatmap
def calendar_heatmap(data, labels, args): """Print a calendar heatmap.""" if args['color']: colornum = AVAILABLE_COLORS.get(args['color'][0]) else: colornum = AVAILABLE_COLORS.get('blue') dt_dict = {} for i in range(len(labels)): dt_dict[labels[i]] = data[i][0] # get max value max_val = float(max(data)[0]) tick_1 = "â–‘" tick_2 = "â–’" tick_3 = "â–“" tick_4 = "â–ˆ" if args['custom_tick']: tick_1 = tick_2 = tick_3 = tick_4 = args['custom_tick'] # check if start day set, otherwise use one year ago if args['start_dt']: start_dt = datetime.strptime(args['start_dt'], '%Y-%m-%d') else: start = datetime.now() start_dt = datetime(year=start.year-1, month=start.month, day=start.day) # modify start date to be a Monday, subtract weekday() from day start_dt = start_dt - timedelta(start_dt.weekday()) # TODO: legend doesn't line up properly for all start dates/data # top legend for months sys.stdout.write(" ") for month in range(13): month_dt = datetime(year=start_dt.year, month=start_dt.month, day=1) +\ timedelta(days=month*31) sys.stdout.write(month_dt.strftime("%b") + " ") if args['custom_tick']: #assume custom tick is emoji which is one wider sys.stdout.write(" ") sys.stdout.write('\n') for day in range(7): sys.stdout.write(DAYS[day] + ': ') for week in range(53): day_ = start_dt + timedelta(days=day + week*7) day_str = day_.strftime("%Y-%m-%d") if day_str in dt_dict: if dt_dict[day_str] > max_val * 0.75: tick = tick_4 elif dt_dict[day_str] > max_val * 0.50: tick = tick_3 elif dt_dict[day_str] > max_val * 0.25: tick = tick_2 else: tick = tick_1 else: tick = ' ' if colornum: sys.stdout.write(f'\033[{colornum}m') sys.stdout.write(tick) if colornum: sys.stdout.write('\033[0m') sys.stdout.write('\n')
python
def calendar_heatmap(data, labels, args): """Print a calendar heatmap.""" if args['color']: colornum = AVAILABLE_COLORS.get(args['color'][0]) else: colornum = AVAILABLE_COLORS.get('blue') dt_dict = {} for i in range(len(labels)): dt_dict[labels[i]] = data[i][0] # get max value max_val = float(max(data)[0]) tick_1 = "â–‘" tick_2 = "â–’" tick_3 = "â–“" tick_4 = "â–ˆ" if args['custom_tick']: tick_1 = tick_2 = tick_3 = tick_4 = args['custom_tick'] # check if start day set, otherwise use one year ago if args['start_dt']: start_dt = datetime.strptime(args['start_dt'], '%Y-%m-%d') else: start = datetime.now() start_dt = datetime(year=start.year-1, month=start.month, day=start.day) # modify start date to be a Monday, subtract weekday() from day start_dt = start_dt - timedelta(start_dt.weekday()) # TODO: legend doesn't line up properly for all start dates/data # top legend for months sys.stdout.write(" ") for month in range(13): month_dt = datetime(year=start_dt.year, month=start_dt.month, day=1) +\ timedelta(days=month*31) sys.stdout.write(month_dt.strftime("%b") + " ") if args['custom_tick']: #assume custom tick is emoji which is one wider sys.stdout.write(" ") sys.stdout.write('\n') for day in range(7): sys.stdout.write(DAYS[day] + ': ') for week in range(53): day_ = start_dt + timedelta(days=day + week*7) day_str = day_.strftime("%Y-%m-%d") if day_str in dt_dict: if dt_dict[day_str] > max_val * 0.75: tick = tick_4 elif dt_dict[day_str] > max_val * 0.50: tick = tick_3 elif dt_dict[day_str] > max_val * 0.25: tick = tick_2 else: tick = tick_1 else: tick = ' ' if colornum: sys.stdout.write(f'\033[{colornum}m') sys.stdout.write(tick) if colornum: sys.stdout.write('\033[0m') sys.stdout.write('\n')
[ "def", "calendar_heatmap", "(", "data", ",", "labels", ",", "args", ")", ":", "if", "args", "[", "'color'", "]", ":", "colornum", "=", "AVAILABLE_COLORS", ".", "get", "(", "args", "[", "'color'", "]", "[", "0", "]", ")", "else", ":", "colornum", "=",...
Print a calendar heatmap.
[ "Print", "a", "calendar", "heatmap", "." ]
c40b86454d380d685785b98834364b111734c163
https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L521-L591
train
200,294
fusepy/fusepy
fuse.py
FUSE._wrapper
def _wrapper(func, *args, **kwargs): 'Decorator for the methods that follow' try: if func.__name__ == "init": # init may not fail, as its return code is just stored as # private_data field of struct fuse_context return func(*args, **kwargs) or 0 else: try: return func(*args, **kwargs) or 0 except OSError as e: if e.errno > 0: log.debug( "FUSE operation %s raised a %s, returning errno %s.", func.__name__, type(e), e.errno, exc_info=True) return -e.errno else: log.error( "FUSE operation %s raised an OSError with negative " "errno %s, returning errno.EINVAL.", func.__name__, e.errno, exc_info=True) return -errno.EINVAL except Exception: log.error("Uncaught exception from FUSE operation %s, " "returning errno.EINVAL.", func.__name__, exc_info=True) return -errno.EINVAL except BaseException as e: self.__critical_exception = e log.critical( "Uncaught critical exception from FUSE operation %s, aborting.", func.__name__, exc_info=True) # the raised exception (even SystemExit) will be caught by FUSE # potentially causing SIGSEGV, so tell system to stop/interrupt FUSE fuse_exit() return -errno.EFAULT
python
def _wrapper(func, *args, **kwargs): 'Decorator for the methods that follow' try: if func.__name__ == "init": # init may not fail, as its return code is just stored as # private_data field of struct fuse_context return func(*args, **kwargs) or 0 else: try: return func(*args, **kwargs) or 0 except OSError as e: if e.errno > 0: log.debug( "FUSE operation %s raised a %s, returning errno %s.", func.__name__, type(e), e.errno, exc_info=True) return -e.errno else: log.error( "FUSE operation %s raised an OSError with negative " "errno %s, returning errno.EINVAL.", func.__name__, e.errno, exc_info=True) return -errno.EINVAL except Exception: log.error("Uncaught exception from FUSE operation %s, " "returning errno.EINVAL.", func.__name__, exc_info=True) return -errno.EINVAL except BaseException as e: self.__critical_exception = e log.critical( "Uncaught critical exception from FUSE operation %s, aborting.", func.__name__, exc_info=True) # the raised exception (even SystemExit) will be caught by FUSE # potentially causing SIGSEGV, so tell system to stop/interrupt FUSE fuse_exit() return -errno.EFAULT
[ "def", "_wrapper", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "func", ".", "__name__", "==", "\"init\"", ":", "# init may not fail, as its return code is just stored as", "# private_data field of struct fuse_context", "return",...
Decorator for the methods that follow
[ "Decorator", "for", "the", "methods", "that", "follow" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fuse.py#L723-L763
train
200,295
fusepy/fusepy
fusell.py
FUSELL.lookup
def lookup(self, req, parent, name): """Look up a directory entry by name and get its attributes. Valid replies: reply_entry reply_err """ self.reply_err(req, errno.ENOENT)
python
def lookup(self, req, parent, name): """Look up a directory entry by name and get its attributes. Valid replies: reply_entry reply_err """ self.reply_err(req, errno.ENOENT)
[ "def", "lookup", "(", "self", ",", "req", ",", "parent", ",", "name", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "ENOENT", ")" ]
Look up a directory entry by name and get its attributes. Valid replies: reply_entry reply_err
[ "Look", "up", "a", "directory", "entry", "by", "name", "and", "get", "its", "attributes", "." ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L690-L697
train
200,296
fusepy/fusepy
fusell.py
FUSELL.getattr
def getattr(self, req, ino, fi): """Get file attributes Valid replies: reply_attr reply_err """ if ino == 1: attr = {'st_ino': 1, 'st_mode': S_IFDIR | 0o755, 'st_nlink': 2} self.reply_attr(req, attr, 1.0) else: self.reply_err(req, errno.ENOENT)
python
def getattr(self, req, ino, fi): """Get file attributes Valid replies: reply_attr reply_err """ if ino == 1: attr = {'st_ino': 1, 'st_mode': S_IFDIR | 0o755, 'st_nlink': 2} self.reply_attr(req, attr, 1.0) else: self.reply_err(req, errno.ENOENT)
[ "def", "getattr", "(", "self", ",", "req", ",", "ino", ",", "fi", ")", ":", "if", "ino", "==", "1", ":", "attr", "=", "{", "'st_ino'", ":", "1", ",", "'st_mode'", ":", "S_IFDIR", "|", "0o755", ",", "'st_nlink'", ":", "2", "}", "self", ".", "rep...
Get file attributes Valid replies: reply_attr reply_err
[ "Get", "file", "attributes" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L707-L718
train
200,297
fusepy/fusepy
fusell.py
FUSELL.setattr
def setattr(self, req, ino, attr, to_set, fi): """Set file attributes Valid replies: reply_attr reply_err """ self.reply_err(req, errno.EROFS)
python
def setattr(self, req, ino, attr, to_set, fi): """Set file attributes Valid replies: reply_attr reply_err """ self.reply_err(req, errno.EROFS)
[ "def", "setattr", "(", "self", ",", "req", ",", "ino", ",", "attr", ",", "to_set", ",", "fi", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "EROFS", ")" ]
Set file attributes Valid replies: reply_attr reply_err
[ "Set", "file", "attributes" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L720-L727
train
200,298
fusepy/fusepy
fusell.py
FUSELL.mknod
def mknod(self, req, parent, name, mode, rdev): """Create file node Valid replies: reply_entry reply_err """ self.reply_err(req, errno.EROFS)
python
def mknod(self, req, parent, name, mode, rdev): """Create file node Valid replies: reply_entry reply_err """ self.reply_err(req, errno.EROFS)
[ "def", "mknod", "(", "self", ",", "req", ",", "parent", ",", "name", ",", "mode", ",", "rdev", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "EROFS", ")" ]
Create file node Valid replies: reply_entry reply_err
[ "Create", "file", "node" ]
5d997d6706cc0204e1b3ca679651485a7e7dda49
https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L738-L745
train
200,299