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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
msmbuilder/msmbuilder | msmbuilder/io/io.py | save_generic | def save_generic(obj, fn):
"""Save Python objects, including msmbuilder Estimators.
This is a convenience wrapper around Python's ``pickle``
serialization scheme. This protocol is backwards-compatible
among Python versions, but may not be "forwards-compatible".
A file saved with Python 3 won't be able to be opened under Python 2.
Please read the pickle docs (specifically related to the ``protocol``
parameter) to specify broader compatibility.
If a file already exists at the given filename, it will be backed
up.
Parameters
----------
obj : object
A Python object to serialize (save to disk)
fn : str
Filename to save the object. We recommend using the '.pickl'
extension, but don't do anything to enforce that convention.
"""
backup(fn)
with open(fn, 'wb') as f:
pickle.dump(obj, f) | python | def save_generic(obj, fn):
"""Save Python objects, including msmbuilder Estimators.
This is a convenience wrapper around Python's ``pickle``
serialization scheme. This protocol is backwards-compatible
among Python versions, but may not be "forwards-compatible".
A file saved with Python 3 won't be able to be opened under Python 2.
Please read the pickle docs (specifically related to the ``protocol``
parameter) to specify broader compatibility.
If a file already exists at the given filename, it will be backed
up.
Parameters
----------
obj : object
A Python object to serialize (save to disk)
fn : str
Filename to save the object. We recommend using the '.pickl'
extension, but don't do anything to enforce that convention.
"""
backup(fn)
with open(fn, 'wb') as f:
pickle.dump(obj, f) | [
"def",
"save_generic",
"(",
"obj",
",",
"fn",
")",
":",
"backup",
"(",
"fn",
")",
"with",
"open",
"(",
"fn",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"obj",
",",
"f",
")"
] | Save Python objects, including msmbuilder Estimators.
This is a convenience wrapper around Python's ``pickle``
serialization scheme. This protocol is backwards-compatible
among Python versions, but may not be "forwards-compatible".
A file saved with Python 3 won't be able to be opened under Python 2.
Please read the pickle docs (specifically related to the ``protocol``
parameter) to specify broader compatibility.
If a file already exists at the given filename, it will be backed
up.
Parameters
----------
obj : object
A Python object to serialize (save to disk)
fn : str
Filename to save the object. We recommend using the '.pickl'
extension, but don't do anything to enforce that convention. | [
"Save",
"Python",
"objects",
"including",
"msmbuilder",
"Estimators",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/io.py#L225-L248 | train | 212,800 |
msmbuilder/msmbuilder | msmbuilder/io/io.py | save_trajs | def save_trajs(trajs, fn, meta, key_to_path=None):
"""Save trajectory-like data
Data is stored in individual numpy binary files in the
directory given by ``fn``.
This method will automatically back up existing files named ``fn``.
Parameters
----------
trajs : dict of (key, np.ndarray)
Dictionary of trajectory-like ndarray's keyed on ``meta.index``
values.
fn : str
Where to save the data. This will be a directory containing
one file per trajectory
meta : pd.DataFrame
The DataFrame of metadata
"""
if key_to_path is None:
key_to_path = default_key_to_path
validate_keys(meta.index, key_to_path)
backup(fn)
os.mkdir(fn)
for k in meta.index:
v = trajs[k]
npy_fn = os.path.join(fn, key_to_path(k))
os.makedirs(os.path.dirname(npy_fn), exist_ok=True)
np.save(npy_fn, v) | python | def save_trajs(trajs, fn, meta, key_to_path=None):
"""Save trajectory-like data
Data is stored in individual numpy binary files in the
directory given by ``fn``.
This method will automatically back up existing files named ``fn``.
Parameters
----------
trajs : dict of (key, np.ndarray)
Dictionary of trajectory-like ndarray's keyed on ``meta.index``
values.
fn : str
Where to save the data. This will be a directory containing
one file per trajectory
meta : pd.DataFrame
The DataFrame of metadata
"""
if key_to_path is None:
key_to_path = default_key_to_path
validate_keys(meta.index, key_to_path)
backup(fn)
os.mkdir(fn)
for k in meta.index:
v = trajs[k]
npy_fn = os.path.join(fn, key_to_path(k))
os.makedirs(os.path.dirname(npy_fn), exist_ok=True)
np.save(npy_fn, v) | [
"def",
"save_trajs",
"(",
"trajs",
",",
"fn",
",",
"meta",
",",
"key_to_path",
"=",
"None",
")",
":",
"if",
"key_to_path",
"is",
"None",
":",
"key_to_path",
"=",
"default_key_to_path",
"validate_keys",
"(",
"meta",
".",
"index",
",",
"key_to_path",
")",
"b... | Save trajectory-like data
Data is stored in individual numpy binary files in the
directory given by ``fn``.
This method will automatically back up existing files named ``fn``.
Parameters
----------
trajs : dict of (key, np.ndarray)
Dictionary of trajectory-like ndarray's keyed on ``meta.index``
values.
fn : str
Where to save the data. This will be a directory containing
one file per trajectory
meta : pd.DataFrame
The DataFrame of metadata | [
"Save",
"trajectory",
"-",
"like",
"data"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/io.py#L271-L300 | train | 212,801 |
msmbuilder/msmbuilder | msmbuilder/io/io.py | load_trajs | def load_trajs(fn, meta='meta.pandas.pickl', key_to_path=None):
"""Load trajectory-like data
Data is expected to be stored as if saved by ``save_trajs``.
This method finds trajectories based on the ``meta`` dataframe.
If you remove a file (trajectory) from disk, be sure to remove
its row from the dataframe. If you remove a row from the dataframe,
be aware that that trajectory (file) will not be loaded, even if
it exists on disk.
Parameters
----------
fn : str
Where the data is saved. This should be a directory containing
one file per trajectory.
meta : pd.DataFrame or str
The DataFrame of metadata. If this is a string, it is interpreted
as a filename and the dataframe is loaded from disk.
Returns
-------
meta : pd.DataFrame
The DataFrame of metadata. If you passed in a string (filename)
to the ``meta`` input, this will be the loaded DataFrame. If
you gave a DataFrame object, this will just be a reference back
to that object
trajs : dict
Dictionary of trajectory-like np.ndarray's keyed on the values
of ``meta.index``.
"""
if key_to_path is None:
key_to_path = default_key_to_path
if isinstance(meta, str):
meta = load_meta(meta_fn=meta)
trajs = {}
for k in meta.index:
trajs[k] = np.load(os.path.join(fn, key_to_path(k)))
return meta, trajs | python | def load_trajs(fn, meta='meta.pandas.pickl', key_to_path=None):
"""Load trajectory-like data
Data is expected to be stored as if saved by ``save_trajs``.
This method finds trajectories based on the ``meta`` dataframe.
If you remove a file (trajectory) from disk, be sure to remove
its row from the dataframe. If you remove a row from the dataframe,
be aware that that trajectory (file) will not be loaded, even if
it exists on disk.
Parameters
----------
fn : str
Where the data is saved. This should be a directory containing
one file per trajectory.
meta : pd.DataFrame or str
The DataFrame of metadata. If this is a string, it is interpreted
as a filename and the dataframe is loaded from disk.
Returns
-------
meta : pd.DataFrame
The DataFrame of metadata. If you passed in a string (filename)
to the ``meta`` input, this will be the loaded DataFrame. If
you gave a DataFrame object, this will just be a reference back
to that object
trajs : dict
Dictionary of trajectory-like np.ndarray's keyed on the values
of ``meta.index``.
"""
if key_to_path is None:
key_to_path = default_key_to_path
if isinstance(meta, str):
meta = load_meta(meta_fn=meta)
trajs = {}
for k in meta.index:
trajs[k] = np.load(os.path.join(fn, key_to_path(k)))
return meta, trajs | [
"def",
"load_trajs",
"(",
"fn",
",",
"meta",
"=",
"'meta.pandas.pickl'",
",",
"key_to_path",
"=",
"None",
")",
":",
"if",
"key_to_path",
"is",
"None",
":",
"key_to_path",
"=",
"default_key_to_path",
"if",
"isinstance",
"(",
"meta",
",",
"str",
")",
":",
"m... | Load trajectory-like data
Data is expected to be stored as if saved by ``save_trajs``.
This method finds trajectories based on the ``meta`` dataframe.
If you remove a file (trajectory) from disk, be sure to remove
its row from the dataframe. If you remove a row from the dataframe,
be aware that that trajectory (file) will not be loaded, even if
it exists on disk.
Parameters
----------
fn : str
Where the data is saved. This should be a directory containing
one file per trajectory.
meta : pd.DataFrame or str
The DataFrame of metadata. If this is a string, it is interpreted
as a filename and the dataframe is loaded from disk.
Returns
-------
meta : pd.DataFrame
The DataFrame of metadata. If you passed in a string (filename)
to the ``meta`` input, this will be the loaded DataFrame. If
you gave a DataFrame object, this will just be a reference back
to that object
trajs : dict
Dictionary of trajectory-like np.ndarray's keyed on the values
of ``meta.index``. | [
"Load",
"trajectory",
"-",
"like",
"data"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/io.py#L303-L342 | train | 212,802 |
msmbuilder/msmbuilder | msmbuilder/utils/nearest.py | KDTree.query | def query(self, x, k=1, p=2, distance_upper_bound=np.inf):
"""Query the kd-tree for nearest neighbors
Parameters
----------
x : array_like, last dimension self.m
An array of points to query.
k : int, optional
The number of nearest neighbors to return.
eps : nonnegative float, optional
Return approximate nearest neighbors; the kth returned value
is guaranteed to be no further than (1+eps) times the
distance to the real kth nearest neighbor.
p : float, 1<=p<=infinity, optional
Which Minkowski p-norm to use.
1 is the sum-of-absolute-values "Manhattan" distance
2 is the usual Euclidean distance
infinity is the maximum-coordinate-difference distance
distance_upper_bound : nonnegative float, optional
Return only neighbors within this distance. This is used to prune
tree searches, so if you are doing a series of nearest-neighbor
queries, it may help to supply the distance to the nearest neighbor
of the most recent point.
Returns
-------
d : float or array of floats
The distances to the nearest neighbors.
If x has shape tuple+(self.m,), then d has shape tuple if
k is one, or tuple+(k,) if k is larger than one. Missing
neighbors (e.g. when k > n or distance_upper_bound is
given) are indicated with infinite distances. If k is None,
then d is an object array of shape tuple, containing lists
of distances. In either case the hits are sorted by distance
(nearest first).
i : tuple(int, int) or array of tuple(int, int)
The locations of the neighbors in self.data. Locations are
given by tuples of (traj_i, frame_i)
Examples
--------
>>> from msmbuilder.utils import KDTree
>>> X1 = 0.3 * np.random.RandomState(0).randn(500, 2)
>>> X2 = 0.3 * np.random.RandomState(1).randn(1000, 2) + 10
>>> tree = KDTree([X1, X2])
>>> pts = np.array([[0, 0], [10, 10]])
>>> tree.query(pts)
(array([ 0.0034, 0.0102]), array([[ 0, 410], [ 1, 670]]))
>>> tree.query(pts[0])
(0.0034, array([ 0, 410]))
"""
cdists, cinds = self._kdtree.query(x, k, p, distance_upper_bound)
return cdists, self._split_indices(cinds) | python | def query(self, x, k=1, p=2, distance_upper_bound=np.inf):
"""Query the kd-tree for nearest neighbors
Parameters
----------
x : array_like, last dimension self.m
An array of points to query.
k : int, optional
The number of nearest neighbors to return.
eps : nonnegative float, optional
Return approximate nearest neighbors; the kth returned value
is guaranteed to be no further than (1+eps) times the
distance to the real kth nearest neighbor.
p : float, 1<=p<=infinity, optional
Which Minkowski p-norm to use.
1 is the sum-of-absolute-values "Manhattan" distance
2 is the usual Euclidean distance
infinity is the maximum-coordinate-difference distance
distance_upper_bound : nonnegative float, optional
Return only neighbors within this distance. This is used to prune
tree searches, so if you are doing a series of nearest-neighbor
queries, it may help to supply the distance to the nearest neighbor
of the most recent point.
Returns
-------
d : float or array of floats
The distances to the nearest neighbors.
If x has shape tuple+(self.m,), then d has shape tuple if
k is one, or tuple+(k,) if k is larger than one. Missing
neighbors (e.g. when k > n or distance_upper_bound is
given) are indicated with infinite distances. If k is None,
then d is an object array of shape tuple, containing lists
of distances. In either case the hits are sorted by distance
(nearest first).
i : tuple(int, int) or array of tuple(int, int)
The locations of the neighbors in self.data. Locations are
given by tuples of (traj_i, frame_i)
Examples
--------
>>> from msmbuilder.utils import KDTree
>>> X1 = 0.3 * np.random.RandomState(0).randn(500, 2)
>>> X2 = 0.3 * np.random.RandomState(1).randn(1000, 2) + 10
>>> tree = KDTree([X1, X2])
>>> pts = np.array([[0, 0], [10, 10]])
>>> tree.query(pts)
(array([ 0.0034, 0.0102]), array([[ 0, 410], [ 1, 670]]))
>>> tree.query(pts[0])
(0.0034, array([ 0, 410]))
"""
cdists, cinds = self._kdtree.query(x, k, p, distance_upper_bound)
return cdists, self._split_indices(cinds) | [
"def",
"query",
"(",
"self",
",",
"x",
",",
"k",
"=",
"1",
",",
"p",
"=",
"2",
",",
"distance_upper_bound",
"=",
"np",
".",
"inf",
")",
":",
"cdists",
",",
"cinds",
"=",
"self",
".",
"_kdtree",
".",
"query",
"(",
"x",
",",
"k",
",",
"p",
",",... | Query the kd-tree for nearest neighbors
Parameters
----------
x : array_like, last dimension self.m
An array of points to query.
k : int, optional
The number of nearest neighbors to return.
eps : nonnegative float, optional
Return approximate nearest neighbors; the kth returned value
is guaranteed to be no further than (1+eps) times the
distance to the real kth nearest neighbor.
p : float, 1<=p<=infinity, optional
Which Minkowski p-norm to use.
1 is the sum-of-absolute-values "Manhattan" distance
2 is the usual Euclidean distance
infinity is the maximum-coordinate-difference distance
distance_upper_bound : nonnegative float, optional
Return only neighbors within this distance. This is used to prune
tree searches, so if you are doing a series of nearest-neighbor
queries, it may help to supply the distance to the nearest neighbor
of the most recent point.
Returns
-------
d : float or array of floats
The distances to the nearest neighbors.
If x has shape tuple+(self.m,), then d has shape tuple if
k is one, or tuple+(k,) if k is larger than one. Missing
neighbors (e.g. when k > n or distance_upper_bound is
given) are indicated with infinite distances. If k is None,
then d is an object array of shape tuple, containing lists
of distances. In either case the hits are sorted by distance
(nearest first).
i : tuple(int, int) or array of tuple(int, int)
The locations of the neighbors in self.data. Locations are
given by tuples of (traj_i, frame_i)
Examples
--------
>>> from msmbuilder.utils import KDTree
>>> X1 = 0.3 * np.random.RandomState(0).randn(500, 2)
>>> X2 = 0.3 * np.random.RandomState(1).randn(1000, 2) + 10
>>> tree = KDTree([X1, X2])
>>> pts = np.array([[0, 0], [10, 10]])
>>> tree.query(pts)
(array([ 0.0034, 0.0102]), array([[ 0, 410], [ 1, 670]]))
>>> tree.query(pts[0])
(0.0034, array([ 0, 410])) | [
"Query",
"the",
"kd",
"-",
"tree",
"for",
"nearest",
"neighbors"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/utils/nearest.py#L73-L125 | train | 212,803 |
msmbuilder/msmbuilder | msmbuilder/decomposition/base.py | MultiSequenceDecompositionMixin.transform | def transform(self, sequences):
"""Apply dimensionality reduction to sequences
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Sequence data to transform, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
Returns
-------
sequence_new : list of array-like, each of shape (n_samples_i, n_components)
"""
check_iter_of_sequences(sequences)
transforms = []
for X in sequences:
transforms.append(self.partial_transform(X))
return transforms | python | def transform(self, sequences):
"""Apply dimensionality reduction to sequences
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Sequence data to transform, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
Returns
-------
sequence_new : list of array-like, each of shape (n_samples_i, n_components)
"""
check_iter_of_sequences(sequences)
transforms = []
for X in sequences:
transforms.append(self.partial_transform(X))
return transforms | [
"def",
"transform",
"(",
"self",
",",
"sequences",
")",
":",
"check_iter_of_sequences",
"(",
"sequences",
")",
"transforms",
"=",
"[",
"]",
"for",
"X",
"in",
"sequences",
":",
"transforms",
".",
"append",
"(",
"self",
".",
"partial_transform",
"(",
"X",
")... | Apply dimensionality reduction to sequences
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Sequence data to transform, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
Returns
-------
sequence_new : list of array-like, each of shape (n_samples_i, n_components) | [
"Apply",
"dimensionality",
"reduction",
"to",
"sequences"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/decomposition/base.py#L75-L92 | train | 212,804 |
msmbuilder/msmbuilder | msmbuilder/decomposition/base.py | MultiSequenceDecompositionMixin.fit_transform | def fit_transform(self, sequences, y=None):
"""Fit the model and apply dimensionality reduction
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
y : None
Ignored
Returns
-------
sequence_new : list of array-like, each of shape (n_samples_i, n_components)
"""
self.fit(sequences)
transforms = self.transform(sequences)
return transforms | python | def fit_transform(self, sequences, y=None):
"""Fit the model and apply dimensionality reduction
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
y : None
Ignored
Returns
-------
sequence_new : list of array-like, each of shape (n_samples_i, n_components)
"""
self.fit(sequences)
transforms = self.transform(sequences)
return transforms | [
"def",
"fit_transform",
"(",
"self",
",",
"sequences",
",",
"y",
"=",
"None",
")",
":",
"self",
".",
"fit",
"(",
"sequences",
")",
"transforms",
"=",
"self",
".",
"transform",
"(",
"sequences",
")",
"return",
"transforms"
] | Fit the model and apply dimensionality reduction
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
y : None
Ignored
Returns
-------
sequence_new : list of array-like, each of shape (n_samples_i, n_components) | [
"Fit",
"the",
"model",
"and",
"apply",
"dimensionality",
"reduction"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/decomposition/base.py#L94-L112 | train | 212,805 |
msmbuilder/msmbuilder | msmbuilder/cluster/base.py | MultiSequenceClusterMixin.fit | def fit(self, sequences, y=None):
"""Fit the clustering on the data
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries. Each sequence may have
a different length, but they all must have the same number
of features.
Returns
-------
self
"""
check_iter_of_sequences(sequences, allow_trajectory=self._allow_trajectory)
super(MultiSequenceClusterMixin, self).fit(self._concat(sequences))
if hasattr(self, 'labels_'):
self.labels_ = self._split(self.labels_)
return self | python | def fit(self, sequences, y=None):
"""Fit the clustering on the data
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries. Each sequence may have
a different length, but they all must have the same number
of features.
Returns
-------
self
"""
check_iter_of_sequences(sequences, allow_trajectory=self._allow_trajectory)
super(MultiSequenceClusterMixin, self).fit(self._concat(sequences))
if hasattr(self, 'labels_'):
self.labels_ = self._split(self.labels_)
return self | [
"def",
"fit",
"(",
"self",
",",
"sequences",
",",
"y",
"=",
"None",
")",
":",
"check_iter_of_sequences",
"(",
"sequences",
",",
"allow_trajectory",
"=",
"self",
".",
"_allow_trajectory",
")",
"super",
"(",
"MultiSequenceClusterMixin",
",",
"self",
")",
".",
... | Fit the clustering on the data
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries. Each sequence may have
a different length, but they all must have the same number
of features.
Returns
-------
self | [
"Fit",
"the",
"clustering",
"on",
"the",
"data"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/cluster/base.py#L33-L53 | train | 212,806 |
msmbuilder/msmbuilder | msmbuilder/cluster/base.py | MultiSequenceClusterMixin.predict | def predict(self, sequences, y=None):
"""Predict the closest cluster each sample in each sequence in
sequences belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in the code book.
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries. Each sequence may have
a different length, but they all must have the same number
of features.
Returns
-------
Y : list of arrays, each of shape [sequence_length,]
Index of the closest center each sample belongs to.
"""
predictions = []
check_iter_of_sequences(sequences, allow_trajectory=self._allow_trajectory)
for X in sequences:
predictions.append(self.partial_predict(X))
return predictions | python | def predict(self, sequences, y=None):
"""Predict the closest cluster each sample in each sequence in
sequences belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in the code book.
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries. Each sequence may have
a different length, but they all must have the same number
of features.
Returns
-------
Y : list of arrays, each of shape [sequence_length,]
Index of the closest center each sample belongs to.
"""
predictions = []
check_iter_of_sequences(sequences, allow_trajectory=self._allow_trajectory)
for X in sequences:
predictions.append(self.partial_predict(X))
return predictions | [
"def",
"predict",
"(",
"self",
",",
"sequences",
",",
"y",
"=",
"None",
")",
":",
"predictions",
"=",
"[",
"]",
"check_iter_of_sequences",
"(",
"sequences",
",",
"allow_trajectory",
"=",
"self",
".",
"_allow_trajectory",
")",
"for",
"X",
"in",
"sequences",
... | Predict the closest cluster each sample in each sequence in
sequences belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in the code book.
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries. Each sequence may have
a different length, but they all must have the same number
of features.
Returns
-------
Y : list of arrays, each of shape [sequence_length,]
Index of the closest center each sample belongs to. | [
"Predict",
"the",
"closest",
"cluster",
"each",
"sample",
"in",
"each",
"sequence",
"in",
"sequences",
"belongs",
"to",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/cluster/base.py#L90-L114 | train | 212,807 |
msmbuilder/msmbuilder | msmbuilder/cluster/base.py | MultiSequenceClusterMixin.fit_predict | def fit_predict(self, sequences, y=None):
"""Performs clustering on X and returns cluster labels.
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries. Each sequence may have
a different length, but they all must have the same number
of features.
Returns
-------
Y : list of ndarray, each of shape [sequence_length, ]
Cluster labels
"""
if hasattr(super(MultiSequenceClusterMixin, self), 'fit_predict'):
check_iter_of_sequences(sequences, allow_trajectory=self._allow_trajectory)
labels = super(MultiSequenceClusterMixin, self).fit_predict(sequences)
else:
self.fit(sequences)
labels = self.predict(sequences)
if not isinstance(labels, list):
labels = self._split(labels)
return labels | python | def fit_predict(self, sequences, y=None):
"""Performs clustering on X and returns cluster labels.
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries. Each sequence may have
a different length, but they all must have the same number
of features.
Returns
-------
Y : list of ndarray, each of shape [sequence_length, ]
Cluster labels
"""
if hasattr(super(MultiSequenceClusterMixin, self), 'fit_predict'):
check_iter_of_sequences(sequences, allow_trajectory=self._allow_trajectory)
labels = super(MultiSequenceClusterMixin, self).fit_predict(sequences)
else:
self.fit(sequences)
labels = self.predict(sequences)
if not isinstance(labels, list):
labels = self._split(labels)
return labels | [
"def",
"fit_predict",
"(",
"self",
",",
"sequences",
",",
"y",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"super",
"(",
"MultiSequenceClusterMixin",
",",
"self",
")",
",",
"'fit_predict'",
")",
":",
"check_iter_of_sequences",
"(",
"sequences",
",",
"allow_... | Performs clustering on X and returns cluster labels.
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries. Each sequence may have
a different length, but they all must have the same number
of features.
Returns
-------
Y : list of ndarray, each of shape [sequence_length, ]
Cluster labels | [
"Performs",
"clustering",
"on",
"X",
"and",
"returns",
"cluster",
"labels",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/cluster/base.py#L137-L161 | train | 212,808 |
msmbuilder/msmbuilder | msmbuilder/example_datasets/muller.py | MullerPotential.plot | def plot(self, minx=-1.5, maxx=1.2, miny=-0.2, maxy=2, **kwargs):
"""Helper function to plot the Muller potential
"""
import matplotlib.pyplot as pp
grid_width = max(maxx-minx, maxy-miny) / 200.0
ax = kwargs.pop('ax', None)
xx, yy = np.mgrid[minx:maxx:grid_width, miny:maxy:grid_width]
V = self.potential(xx, yy)
# clip off any values greater than 200, since they mess up
# the color scheme
if ax is None:
ax = pp
ax.contourf(xx, yy, V.clip(max=200), 40, **kwargs) | python | def plot(self, minx=-1.5, maxx=1.2, miny=-0.2, maxy=2, **kwargs):
"""Helper function to plot the Muller potential
"""
import matplotlib.pyplot as pp
grid_width = max(maxx-minx, maxy-miny) / 200.0
ax = kwargs.pop('ax', None)
xx, yy = np.mgrid[minx:maxx:grid_width, miny:maxy:grid_width]
V = self.potential(xx, yy)
# clip off any values greater than 200, since they mess up
# the color scheme
if ax is None:
ax = pp
ax.contourf(xx, yy, V.clip(max=200), 40, **kwargs) | [
"def",
"plot",
"(",
"self",
",",
"minx",
"=",
"-",
"1.5",
",",
"maxx",
"=",
"1.2",
",",
"miny",
"=",
"-",
"0.2",
",",
"maxy",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"pp",
"grid_width",
"=",
"ma... | Helper function to plot the Muller potential | [
"Helper",
"function",
"to",
"plot",
"the",
"Muller",
"potential"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/example_datasets/muller.py#L99-L114 | train | 212,809 |
msmbuilder/msmbuilder | msmbuilder/io/gather_metadata.py | gather_metadata | def gather_metadata(fn_glob, parser):
"""Given a glob and a parser object, create a metadata dataframe.
Parameters
----------
fn_glob : str
Glob string to find trajectory files.
parser : descendant of _Parser
Object that handles conversion of filenames to metadata rows.
"""
meta = pd.DataFrame(parser.parse_fn(fn) for fn in glob.iglob(fn_glob))
return meta.set_index(parser.index).sort_index() | python | def gather_metadata(fn_glob, parser):
"""Given a glob and a parser object, create a metadata dataframe.
Parameters
----------
fn_glob : str
Glob string to find trajectory files.
parser : descendant of _Parser
Object that handles conversion of filenames to metadata rows.
"""
meta = pd.DataFrame(parser.parse_fn(fn) for fn in glob.iglob(fn_glob))
return meta.set_index(parser.index).sort_index() | [
"def",
"gather_metadata",
"(",
"fn_glob",
",",
"parser",
")",
":",
"meta",
"=",
"pd",
".",
"DataFrame",
"(",
"parser",
".",
"parse_fn",
"(",
"fn",
")",
"for",
"fn",
"in",
"glob",
".",
"iglob",
"(",
"fn_glob",
")",
")",
"return",
"meta",
".",
"set_ind... | Given a glob and a parser object, create a metadata dataframe.
Parameters
----------
fn_glob : str
Glob string to find trajectory files.
parser : descendant of _Parser
Object that handles conversion of filenames to metadata rows. | [
"Given",
"a",
"glob",
"and",
"a",
"parser",
"object",
"create",
"a",
"metadata",
"dataframe",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/gather_metadata.py#L193-L204 | train | 212,810 |
msmbuilder/msmbuilder | msmbuilder/msm/msm.py | MarkovStateModel.eigtransform | def eigtransform(self, sequences, right=True, mode='clip'):
r"""Transform a list of sequences by projecting the sequences onto
the first `n_timescales` dynamical eigenvectors.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
right : bool
Which eigenvectors to map onto. Both the left (:math:`\Phi`) and
the right (:math`\Psi`) eigenvectors of the transition matrix are
commonly used, and differ in their normalization. The two sets of
eigenvectors are related by the stationary distribution ::
\Phi_i(x) = \Psi_i(x) * \mu(x)
In the MSM literature, the right vectors (default here) are
approximations to the transfer operator eigenfunctions, whereas
the left eigenfunction are approximations to the propagator
eigenfunctions. For more details, refer to reference [1].
mode : {'clip', 'fill'}
Method by which to treat labels in `sequences` which do not have
a corresponding index. This can be due, for example, to the ergodic
trimming step.
``clip``
Unmapped labels are removed during transform. If they occur
at the beginning or end of a sequence, the resulting transformed
sequence will be shorted. If they occur in the middle of a
sequence, that sequence will be broken into two (or more)
sequences. (Default)
``fill``
Unmapped labels will be replaced with NaN, to signal missing
data. [The use of NaN to signal missing data is not fantastic,
but it's consistent with current behavior of the ``pandas``
library.]
Returns
-------
transformed : list of 2d arrays
Each element of transformed is an array of shape ``(n_samples,
n_timescales)`` containing the transformed data.
References
----------
.. [1] Prinz, Jan-Hendrik, et al. "Markov models of molecular kinetics:
Generation and validation." J. Chem. Phys. 134.17 (2011): 174105.
"""
result = []
for y in self.transform(sequences, mode=mode):
if right:
op = self.right_eigenvectors_[:, 1:]
else:
op = self.left_eigenvectors_[:, 1:]
is_finite = np.isfinite(y)
if not np.all(is_finite):
value = np.empty((y.shape[0], op.shape[1]))
value[is_finite, :] = np.take(op, y[is_finite].astype(np.int), axis=0)
value[~is_finite, :] = np.nan
else:
value = np.take(op, y, axis=0)
result.append(value)
return result | python | def eigtransform(self, sequences, right=True, mode='clip'):
r"""Transform a list of sequences by projecting the sequences onto
the first `n_timescales` dynamical eigenvectors.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
right : bool
Which eigenvectors to map onto. Both the left (:math:`\Phi`) and
the right (:math`\Psi`) eigenvectors of the transition matrix are
commonly used, and differ in their normalization. The two sets of
eigenvectors are related by the stationary distribution ::
\Phi_i(x) = \Psi_i(x) * \mu(x)
In the MSM literature, the right vectors (default here) are
approximations to the transfer operator eigenfunctions, whereas
the left eigenfunction are approximations to the propagator
eigenfunctions. For more details, refer to reference [1].
mode : {'clip', 'fill'}
Method by which to treat labels in `sequences` which do not have
a corresponding index. This can be due, for example, to the ergodic
trimming step.
``clip``
Unmapped labels are removed during transform. If they occur
at the beginning or end of a sequence, the resulting transformed
sequence will be shorted. If they occur in the middle of a
sequence, that sequence will be broken into two (or more)
sequences. (Default)
``fill``
Unmapped labels will be replaced with NaN, to signal missing
data. [The use of NaN to signal missing data is not fantastic,
but it's consistent with current behavior of the ``pandas``
library.]
Returns
-------
transformed : list of 2d arrays
Each element of transformed is an array of shape ``(n_samples,
n_timescales)`` containing the transformed data.
References
----------
.. [1] Prinz, Jan-Hendrik, et al. "Markov models of molecular kinetics:
Generation and validation." J. Chem. Phys. 134.17 (2011): 174105.
"""
result = []
for y in self.transform(sequences, mode=mode):
if right:
op = self.right_eigenvectors_[:, 1:]
else:
op = self.left_eigenvectors_[:, 1:]
is_finite = np.isfinite(y)
if not np.all(is_finite):
value = np.empty((y.shape[0], op.shape[1]))
value[is_finite, :] = np.take(op, y[is_finite].astype(np.int), axis=0)
value[~is_finite, :] = np.nan
else:
value = np.take(op, y, axis=0)
result.append(value)
return result | [
"def",
"eigtransform",
"(",
"self",
",",
"sequences",
",",
"right",
"=",
"True",
",",
"mode",
"=",
"'clip'",
")",
":",
"result",
"=",
"[",
"]",
"for",
"y",
"in",
"self",
".",
"transform",
"(",
"sequences",
",",
"mode",
"=",
"mode",
")",
":",
"if",
... | r"""Transform a list of sequences by projecting the sequences onto
the first `n_timescales` dynamical eigenvectors.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
right : bool
Which eigenvectors to map onto. Both the left (:math:`\Phi`) and
the right (:math`\Psi`) eigenvectors of the transition matrix are
commonly used, and differ in their normalization. The two sets of
eigenvectors are related by the stationary distribution ::
\Phi_i(x) = \Psi_i(x) * \mu(x)
In the MSM literature, the right vectors (default here) are
approximations to the transfer operator eigenfunctions, whereas
the left eigenfunction are approximations to the propagator
eigenfunctions. For more details, refer to reference [1].
mode : {'clip', 'fill'}
Method by which to treat labels in `sequences` which do not have
a corresponding index. This can be due, for example, to the ergodic
trimming step.
``clip``
Unmapped labels are removed during transform. If they occur
at the beginning or end of a sequence, the resulting transformed
sequence will be shorted. If they occur in the middle of a
sequence, that sequence will be broken into two (or more)
sequences. (Default)
``fill``
Unmapped labels will be replaced with NaN, to signal missing
data. [The use of NaN to signal missing data is not fantastic,
but it's consistent with current behavior of the ``pandas``
library.]
Returns
-------
transformed : list of 2d arrays
Each element of transformed is an array of shape ``(n_samples,
n_timescales)`` containing the transformed data.
References
----------
.. [1] Prinz, Jan-Hendrik, et al. "Markov models of molecular kinetics:
Generation and validation." J. Chem. Phys. 134.17 (2011): 174105. | [
"r",
"Transform",
"a",
"list",
"of",
"sequences",
"by",
"projecting",
"the",
"sequences",
"onto",
"the",
"first",
"n_timescales",
"dynamical",
"eigenvectors",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/msm.py#L212-L281 | train | 212,811 |
msmbuilder/msmbuilder | msmbuilder/msm/msm.py | MarkovStateModel.score_ll | def score_ll(self, sequences):
r"""log of the likelihood of sequences with respect to the model
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
Returns
-------
loglikelihood : float
The natural log of the likelihood, computed as
:math:`\sum_{ij} C_{ij} \log(P_{ij})`
where C is a matrix of counts computed from the input sequences.
"""
counts, mapping = _transition_counts(sequences)
if not set(self.mapping_.keys()).issuperset(mapping.keys()):
return -np.inf
inverse_mapping = {v: k for k, v in mapping.items()}
# maps indices in counts to indices in transmat
m2 = _dict_compose(inverse_mapping, self.mapping_)
indices = [e[1] for e in sorted(m2.items())]
transmat_slice = self.transmat_[np.ix_(indices, indices)]
return np.nansum(np.log(transmat_slice) * counts) | python | def score_ll(self, sequences):
r"""log of the likelihood of sequences with respect to the model
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
Returns
-------
loglikelihood : float
The natural log of the likelihood, computed as
:math:`\sum_{ij} C_{ij} \log(P_{ij})`
where C is a matrix of counts computed from the input sequences.
"""
counts, mapping = _transition_counts(sequences)
if not set(self.mapping_.keys()).issuperset(mapping.keys()):
return -np.inf
inverse_mapping = {v: k for k, v in mapping.items()}
# maps indices in counts to indices in transmat
m2 = _dict_compose(inverse_mapping, self.mapping_)
indices = [e[1] for e in sorted(m2.items())]
transmat_slice = self.transmat_[np.ix_(indices, indices)]
return np.nansum(np.log(transmat_slice) * counts) | [
"def",
"score_ll",
"(",
"self",
",",
"sequences",
")",
":",
"counts",
",",
"mapping",
"=",
"_transition_counts",
"(",
"sequences",
")",
"if",
"not",
"set",
"(",
"self",
".",
"mapping_",
".",
"keys",
"(",
")",
")",
".",
"issuperset",
"(",
"mapping",
"."... | r"""log of the likelihood of sequences with respect to the model
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
Returns
-------
loglikelihood : float
The natural log of the likelihood, computed as
:math:`\sum_{ij} C_{ij} \log(P_{ij})`
where C is a matrix of counts computed from the input sequences. | [
"r",
"log",
"of",
"the",
"likelihood",
"of",
"sequences",
"with",
"respect",
"to",
"the",
"model"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/msm.py#L288-L315 | train | 212,812 |
msmbuilder/msmbuilder | msmbuilder/msm/msm.py | MarkovStateModel.summarize | def summarize(self):
"""Return some diagnostic summary statistics about this Markov model
"""
doc = '''Markov state model
------------------
Lag time : {lag_time}
Reversible type : {reversible_type}
Ergodic cutoff : {ergodic_cutoff}
Prior counts : {prior_counts}
Number of states : {n_states}
Number of nonzero entries in counts matrix : {counts_nz} ({percent_counts_nz}%)
Nonzero counts matrix entries:
Min. : {cnz_min:.1f}
1st Qu.: {cnz_1st:.1f}
Median : {cnz_med:.1f}
Mean : {cnz_mean:.1f}
3rd Qu.: {cnz_3rd:.1f}
Max. : {cnz_max:.1f}
Total transition counts :
{cnz_sum} counts
Total transition counts / lag_time:
{cnz_sum_per_lag} units
Timescales:
[{ts}] units
'''
counts_nz = np.count_nonzero(self.countsmat_)
cnz = self.countsmat_[np.nonzero(self.countsmat_)]
return doc.format(
lag_time=self.lag_time,
reversible_type=self.reversible_type,
ergodic_cutoff=self.ergodic_cutoff,
prior_counts=self.prior_counts,
n_states=self.n_states_,
counts_nz=counts_nz,
percent_counts_nz=(100 * counts_nz / self.countsmat_.size),
cnz_min=np.min(cnz),
cnz_1st=np.percentile(cnz, 25),
cnz_med=np.percentile(cnz, 50),
cnz_mean=np.mean(cnz),
cnz_3rd=np.percentile(cnz, 75),
cnz_max=np.max(cnz),
cnz_sum=np.sum(cnz),
cnz_sum_per_lag=np.sum(cnz)/self.lag_time,
ts=', '.join(['{:.2f}'.format(t) for t in self.timescales_]),
) | python | def summarize(self):
"""Return some diagnostic summary statistics about this Markov model
"""
doc = '''Markov state model
------------------
Lag time : {lag_time}
Reversible type : {reversible_type}
Ergodic cutoff : {ergodic_cutoff}
Prior counts : {prior_counts}
Number of states : {n_states}
Number of nonzero entries in counts matrix : {counts_nz} ({percent_counts_nz}%)
Nonzero counts matrix entries:
Min. : {cnz_min:.1f}
1st Qu.: {cnz_1st:.1f}
Median : {cnz_med:.1f}
Mean : {cnz_mean:.1f}
3rd Qu.: {cnz_3rd:.1f}
Max. : {cnz_max:.1f}
Total transition counts :
{cnz_sum} counts
Total transition counts / lag_time:
{cnz_sum_per_lag} units
Timescales:
[{ts}] units
'''
counts_nz = np.count_nonzero(self.countsmat_)
cnz = self.countsmat_[np.nonzero(self.countsmat_)]
return doc.format(
lag_time=self.lag_time,
reversible_type=self.reversible_type,
ergodic_cutoff=self.ergodic_cutoff,
prior_counts=self.prior_counts,
n_states=self.n_states_,
counts_nz=counts_nz,
percent_counts_nz=(100 * counts_nz / self.countsmat_.size),
cnz_min=np.min(cnz),
cnz_1st=np.percentile(cnz, 25),
cnz_med=np.percentile(cnz, 50),
cnz_mean=np.mean(cnz),
cnz_3rd=np.percentile(cnz, 75),
cnz_max=np.max(cnz),
cnz_sum=np.sum(cnz),
cnz_sum_per_lag=np.sum(cnz)/self.lag_time,
ts=', '.join(['{:.2f}'.format(t) for t in self.timescales_]),
) | [
"def",
"summarize",
"(",
"self",
")",
":",
"doc",
"=",
"'''Markov state model\n------------------\nLag time : {lag_time}\nReversible type : {reversible_type}\nErgodic cutoff : {ergodic_cutoff}\nPrior counts : {prior_counts}\n\nNumber of states : {n_states}\nNumber of nonzero entries i... | Return some diagnostic summary statistics about this Markov model | [
"Return",
"some",
"diagnostic",
"summary",
"statistics",
"about",
"this",
"Markov",
"model"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/msm.py#L336-L384 | train | 212,813 |
msmbuilder/msmbuilder | msmbuilder/msm/msm.py | MarkovStateModel.timescales_ | def timescales_(self):
"""Implied relaxation timescales of the model.
The relaxation of any initial distribution towards equilibrium is
given, according to this model, by a sum of terms -- each corresponding
to the relaxation along a specific direction (eigenvector) in state
space -- which decay exponentially in time. See equation 19. from [1].
Returns
-------
timescales : array-like, shape = (n_timescales,)
The longest implied relaxation timescales of the model, expressed
in units of time-step between indices in the source data supplied
to ``fit()``.
References
----------
.. [1] Prinz, Jan-Hendrik, et al. "Markov models of molecular kinetics:
Generation and validation." J. Chem. Phys. 134.17 (2011): 174105.
"""
u, lv, rv = self._get_eigensystem()
# make sure to leave off equilibrium distribution
with np.errstate(invalid='ignore', divide='ignore'):
timescales = - self.lag_time / np.log(u[1:])
return timescales | python | def timescales_(self):
"""Implied relaxation timescales of the model.
The relaxation of any initial distribution towards equilibrium is
given, according to this model, by a sum of terms -- each corresponding
to the relaxation along a specific direction (eigenvector) in state
space -- which decay exponentially in time. See equation 19. from [1].
Returns
-------
timescales : array-like, shape = (n_timescales,)
The longest implied relaxation timescales of the model, expressed
in units of time-step between indices in the source data supplied
to ``fit()``.
References
----------
.. [1] Prinz, Jan-Hendrik, et al. "Markov models of molecular kinetics:
Generation and validation." J. Chem. Phys. 134.17 (2011): 174105.
"""
u, lv, rv = self._get_eigensystem()
# make sure to leave off equilibrium distribution
with np.errstate(invalid='ignore', divide='ignore'):
timescales = - self.lag_time / np.log(u[1:])
return timescales | [
"def",
"timescales_",
"(",
"self",
")",
":",
"u",
",",
"lv",
",",
"rv",
"=",
"self",
".",
"_get_eigensystem",
"(",
")",
"# make sure to leave off equilibrium distribution",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
",",
"divide",
"=",
"... | Implied relaxation timescales of the model.
The relaxation of any initial distribution towards equilibrium is
given, according to this model, by a sum of terms -- each corresponding
to the relaxation along a specific direction (eigenvector) in state
space -- which decay exponentially in time. See equation 19. from [1].
Returns
-------
timescales : array-like, shape = (n_timescales,)
The longest implied relaxation timescales of the model, expressed
in units of time-step between indices in the source data supplied
to ``fit()``.
References
----------
.. [1] Prinz, Jan-Hendrik, et al. "Markov models of molecular kinetics:
Generation and validation." J. Chem. Phys. 134.17 (2011): 174105. | [
"Implied",
"relaxation",
"timescales",
"of",
"the",
"model",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/msm.py#L455-L480 | train | 212,814 |
msmbuilder/msmbuilder | msmbuilder/msm/msm.py | MarkovStateModel.uncertainty_eigenvalues | def uncertainty_eigenvalues(self):
"""Estimate of the element-wise asymptotic standard deviation
in the model eigenvalues.
Returns
-------
sigma_eigs : np.array, shape=(n_timescales+1,)
The estimated symptotic standard deviation in the eigenvalues.
References
----------
.. [1] Hinrichs, Nina Singhal, and Vijay S. Pande. "Calculation of
the distribution of eigenvalues and eigenvectors in Markovian state
models for molecular dynamics." J. Chem. Phys. 126.24 (2007): 244101.
"""
if self.reversible_type is None:
raise NotImplementedError('reversible_type must be "mle" or "transpose"')
n_timescales = min(self.n_timescales if self.n_timescales is not None
else self.n_states_ - 1, self.n_states_ - 1)
u, lv, rv = self._get_eigensystem()
sigma2 = np.zeros(n_timescales + 1)
for k in range(n_timescales + 1):
dLambda_dT = np.outer(lv[:, k], rv[:, k])
for i in range(self.n_states_):
ui = self.countsmat_[:, i]
wi = np.sum(ui)
cov = wi*np.diag(ui) - np.outer(ui, ui)
quad_form = dLambda_dT[i].dot(cov).dot(dLambda_dT[i])
sigma2[k] += quad_form / (wi**2*(wi+1))
return np.sqrt(sigma2) | python | def uncertainty_eigenvalues(self):
"""Estimate of the element-wise asymptotic standard deviation
in the model eigenvalues.
Returns
-------
sigma_eigs : np.array, shape=(n_timescales+1,)
The estimated symptotic standard deviation in the eigenvalues.
References
----------
.. [1] Hinrichs, Nina Singhal, and Vijay S. Pande. "Calculation of
the distribution of eigenvalues and eigenvectors in Markovian state
models for molecular dynamics." J. Chem. Phys. 126.24 (2007): 244101.
"""
if self.reversible_type is None:
raise NotImplementedError('reversible_type must be "mle" or "transpose"')
n_timescales = min(self.n_timescales if self.n_timescales is not None
else self.n_states_ - 1, self.n_states_ - 1)
u, lv, rv = self._get_eigensystem()
sigma2 = np.zeros(n_timescales + 1)
for k in range(n_timescales + 1):
dLambda_dT = np.outer(lv[:, k], rv[:, k])
for i in range(self.n_states_):
ui = self.countsmat_[:, i]
wi = np.sum(ui)
cov = wi*np.diag(ui) - np.outer(ui, ui)
quad_form = dLambda_dT[i].dot(cov).dot(dLambda_dT[i])
sigma2[k] += quad_form / (wi**2*(wi+1))
return np.sqrt(sigma2) | [
"def",
"uncertainty_eigenvalues",
"(",
"self",
")",
":",
"if",
"self",
".",
"reversible_type",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'reversible_type must be \"mle\" or \"transpose\"'",
")",
"n_timescales",
"=",
"min",
"(",
"self",
".",
"n_timescale... | Estimate of the element-wise asymptotic standard deviation
in the model eigenvalues.
Returns
-------
sigma_eigs : np.array, shape=(n_timescales+1,)
The estimated symptotic standard deviation in the eigenvalues.
References
----------
.. [1] Hinrichs, Nina Singhal, and Vijay S. Pande. "Calculation of
the distribution of eigenvalues and eigenvectors in Markovian state
models for molecular dynamics." J. Chem. Phys. 126.24 (2007): 244101. | [
"Estimate",
"of",
"the",
"element",
"-",
"wise",
"asymptotic",
"standard",
"deviation",
"in",
"the",
"model",
"eigenvalues",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/msm.py#L535-L567 | train | 212,815 |
msmbuilder/msmbuilder | msmbuilder/msm/msm.py | MarkovStateModel.uncertainty_timescales | def uncertainty_timescales(self):
"""Estimate of the element-wise asymptotic standard deviation
in the model implied timescales.
Returns
-------
sigma_timescales : np.array, shape=(n_timescales,)
The estimated symptotic standard deviation in the implied
timescales.
References
----------
.. [1] Hinrichs, Nina Singhal, and Vijay S. Pande. "Calculation of
the distribution of eigenvalues and eigenvectors in Markovian state
models for molecular dynamics." J. Chem. Phys. 126.24 (2007): 244101.
"""
# drop the first eigenvalue
u = self.eigenvalues_[1:]
sigma_eigs = self.uncertainty_eigenvalues()[1:]
sigma_ts = sigma_eigs / (u * np.log(u)**2)
return sigma_ts | python | def uncertainty_timescales(self):
"""Estimate of the element-wise asymptotic standard deviation
in the model implied timescales.
Returns
-------
sigma_timescales : np.array, shape=(n_timescales,)
The estimated symptotic standard deviation in the implied
timescales.
References
----------
.. [1] Hinrichs, Nina Singhal, and Vijay S. Pande. "Calculation of
the distribution of eigenvalues and eigenvectors in Markovian state
models for molecular dynamics." J. Chem. Phys. 126.24 (2007): 244101.
"""
# drop the first eigenvalue
u = self.eigenvalues_[1:]
sigma_eigs = self.uncertainty_eigenvalues()[1:]
sigma_ts = sigma_eigs / (u * np.log(u)**2)
return sigma_ts | [
"def",
"uncertainty_timescales",
"(",
"self",
")",
":",
"# drop the first eigenvalue",
"u",
"=",
"self",
".",
"eigenvalues_",
"[",
"1",
":",
"]",
"sigma_eigs",
"=",
"self",
".",
"uncertainty_eigenvalues",
"(",
")",
"[",
"1",
":",
"]",
"sigma_ts",
"=",
"sigma... | Estimate of the element-wise asymptotic standard deviation
in the model implied timescales.
Returns
-------
sigma_timescales : np.array, shape=(n_timescales,)
The estimated symptotic standard deviation in the implied
timescales.
References
----------
.. [1] Hinrichs, Nina Singhal, and Vijay S. Pande. "Calculation of
the distribution of eigenvalues and eigenvectors in Markovian state
models for molecular dynamics." J. Chem. Phys. 126.24 (2007): 244101. | [
"Estimate",
"of",
"the",
"element",
"-",
"wise",
"asymptotic",
"standard",
"deviation",
"in",
"the",
"model",
"implied",
"timescales",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/msm.py#L569-L590 | train | 212,816 |
msmbuilder/msmbuilder | msmbuilder/feature_selection/featureselector.py | FeatureSelector.describe_features | def describe_features(self, traj):
""" Return a list of dictionaries describing the features. Follows
the ordering of featurizers in self.which_feat.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each feature
- resnames: unique names of residues
- atominds: atom indicies involved in the feature
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: featurizer dependent
- featuregroup: other info for the featurizer
"""
all_res = []
for feat in self.which_feat:
all_res.extend(self.features[feat].describe_features(traj))
return all_res | python | def describe_features(self, traj):
""" Return a list of dictionaries describing the features. Follows
the ordering of featurizers in self.which_feat.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each feature
- resnames: unique names of residues
- atominds: atom indicies involved in the feature
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: featurizer dependent
- featuregroup: other info for the featurizer
"""
all_res = []
for feat in self.which_feat:
all_res.extend(self.features[feat].describe_features(traj))
return all_res | [
"def",
"describe_features",
"(",
"self",
",",
"traj",
")",
":",
"all_res",
"=",
"[",
"]",
"for",
"feat",
"in",
"self",
".",
"which_feat",
":",
"all_res",
".",
"extend",
"(",
"self",
".",
"features",
"[",
"feat",
"]",
".",
"describe_features",
"(",
"tra... | Return a list of dictionaries describing the features. Follows
the ordering of featurizers in self.which_feat.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each feature
- resnames: unique names of residues
- atominds: atom indicies involved in the feature
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: featurizer dependent
- featuregroup: other info for the featurizer | [
"Return",
"a",
"list",
"of",
"dictionaries",
"describing",
"the",
"features",
".",
"Follows",
"the",
"ordering",
"of",
"featurizers",
"in",
"self",
".",
"which_feat",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/feature_selection/featureselector.py#L70-L95 | train | 212,817 |
msmbuilder/msmbuilder | msmbuilder/preprocessing/base.py | MultiSequencePreprocessingMixin.partial_transform | def partial_transform(self, sequence):
"""Apply preprocessing to single sequence
Parameters
----------
sequence: array like, shape (n_samples, n_features)
A single sequence to transform
Returns
-------
out : array like, shape (n_samples, n_features)
"""
s = super(MultiSequencePreprocessingMixin, self)
return s.transform(sequence) | python | def partial_transform(self, sequence):
"""Apply preprocessing to single sequence
Parameters
----------
sequence: array like, shape (n_samples, n_features)
A single sequence to transform
Returns
-------
out : array like, shape (n_samples, n_features)
"""
s = super(MultiSequencePreprocessingMixin, self)
return s.transform(sequence) | [
"def",
"partial_transform",
"(",
"self",
",",
"sequence",
")",
":",
"s",
"=",
"super",
"(",
"MultiSequencePreprocessingMixin",
",",
"self",
")",
"return",
"s",
".",
"transform",
"(",
"sequence",
")"
] | Apply preprocessing to single sequence
Parameters
----------
sequence: array like, shape (n_samples, n_features)
A single sequence to transform
Returns
-------
out : array like, shape (n_samples, n_features) | [
"Apply",
"preprocessing",
"to",
"single",
"sequence"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/preprocessing/base.py#L114-L127 | train | 212,818 |
msmbuilder/msmbuilder | msmbuilder/example_datasets/base.py | retry | def retry(max_retries=1):
""" Retry a function `max_retries` times. """
def retry_func(func):
@wraps(func)
def wrapper(*args, **kwargs):
num_retries = 0
while num_retries <= max_retries:
try:
ret = func(*args, **kwargs)
break
except HTTPError:
if num_retries == max_retries:
raise
num_retries += 1
time.sleep(5)
return ret
return wrapper
return retry_func | python | def retry(max_retries=1):
""" Retry a function `max_retries` times. """
def retry_func(func):
@wraps(func)
def wrapper(*args, **kwargs):
num_retries = 0
while num_retries <= max_retries:
try:
ret = func(*args, **kwargs)
break
except HTTPError:
if num_retries == max_retries:
raise
num_retries += 1
time.sleep(5)
return ret
return wrapper
return retry_func | [
"def",
"retry",
"(",
"max_retries",
"=",
"1",
")",
":",
"def",
"retry_func",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"num_retries",
"=",
"0",
"while",
"num_retrie... | Retry a function `max_retries` times. | [
"Retry",
"a",
"function",
"max_retries",
"times",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/example_datasets/base.py#L20-L40 | train | 212,819 |
msmbuilder/msmbuilder | msmbuilder/example_datasets/base.py | get_data_home | def get_data_home(data_home=None):
"""Return the path of the msmbuilder data dir.
As of msmbuilder v3.6, this function will prefer data downloaded via
the msmb_data conda package (and located within the python installation
directory). If this package exists, we will use its data directory as
the data home. Otherwise, we use the old logic:
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'msmbuilder_data'
in the user's home folder.
Alternatively, it can be set by the 'MSMBUILDER_DATA' environment
variable or programmatically by giving an explicit folder path. The
'~' symbol is expanded to the user home folder.
If the folder does not already exist, it is automatically created.
"""
if data_home is not None:
return _expand_and_makedir(data_home)
msmb_data = has_msmb_data()
if msmb_data is not None:
return _expand_and_makedir(msmb_data)
data_home = environ.get('MSMBUILDER_DATA', join('~', 'msmbuilder_data'))
return _expand_and_makedir(data_home) | python | def get_data_home(data_home=None):
"""Return the path of the msmbuilder data dir.
As of msmbuilder v3.6, this function will prefer data downloaded via
the msmb_data conda package (and located within the python installation
directory). If this package exists, we will use its data directory as
the data home. Otherwise, we use the old logic:
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'msmbuilder_data'
in the user's home folder.
Alternatively, it can be set by the 'MSMBUILDER_DATA' environment
variable or programmatically by giving an explicit folder path. The
'~' symbol is expanded to the user home folder.
If the folder does not already exist, it is automatically created.
"""
if data_home is not None:
return _expand_and_makedir(data_home)
msmb_data = has_msmb_data()
if msmb_data is not None:
return _expand_and_makedir(msmb_data)
data_home = environ.get('MSMBUILDER_DATA', join('~', 'msmbuilder_data'))
return _expand_and_makedir(data_home) | [
"def",
"get_data_home",
"(",
"data_home",
"=",
"None",
")",
":",
"if",
"data_home",
"is",
"not",
"None",
":",
"return",
"_expand_and_makedir",
"(",
"data_home",
")",
"msmb_data",
"=",
"has_msmb_data",
"(",
")",
"if",
"msmb_data",
"is",
"not",
"None",
":",
... | Return the path of the msmbuilder data dir.
As of msmbuilder v3.6, this function will prefer data downloaded via
the msmb_data conda package (and located within the python installation
directory). If this package exists, we will use its data directory as
the data home. Otherwise, we use the old logic:
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'msmbuilder_data'
in the user's home folder.
Alternatively, it can be set by the 'MSMBUILDER_DATA' environment
variable or programmatically by giving an explicit folder path. The
'~' symbol is expanded to the user home folder.
If the folder does not already exist, it is automatically created. | [
"Return",
"the",
"path",
"of",
"the",
"msmbuilder",
"data",
"dir",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/example_datasets/base.py#L233-L261 | train | 212,820 |
msmbuilder/msmbuilder | msmbuilder/example_datasets/base.py | Dataset.description | def description(cls):
"""Get a description from the Notes section of the docstring."""
lines = [s.strip() for s in cls.__doc__.splitlines()]
note_i = lines.index("Notes")
return "\n".join(lines[note_i + 2:]) | python | def description(cls):
"""Get a description from the Notes section of the docstring."""
lines = [s.strip() for s in cls.__doc__.splitlines()]
note_i = lines.index("Notes")
return "\n".join(lines[note_i + 2:]) | [
"def",
"description",
"(",
"cls",
")",
":",
"lines",
"=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"cls",
".",
"__doc__",
".",
"splitlines",
"(",
")",
"]",
"note_i",
"=",
"lines",
".",
"index",
"(",
"\"Notes\"",
")",
"return",
"\"\\n\"",... | Get a description from the Notes section of the docstring. | [
"Get",
"a",
"description",
"from",
"the",
"Notes",
"section",
"of",
"the",
"docstring",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/example_datasets/base.py#L45-L49 | train | 212,821 |
Skyscanner/pycfmodel | pycfmodel/model/resources/properties/policy_document.py | PolicyDocument.wildcard_allowed_actions | def wildcard_allowed_actions(self, pattern=None):
"""
Find statements which allow wildcard actions.
A pattern can be specified for the wildcard action
"""
wildcard_allowed = []
for statement in self.statements:
if statement.wildcard_actions(pattern) and statement.effect == "Allow":
wildcard_allowed.append(statement)
return wildcard_allowed | python | def wildcard_allowed_actions(self, pattern=None):
"""
Find statements which allow wildcard actions.
A pattern can be specified for the wildcard action
"""
wildcard_allowed = []
for statement in self.statements:
if statement.wildcard_actions(pattern) and statement.effect == "Allow":
wildcard_allowed.append(statement)
return wildcard_allowed | [
"def",
"wildcard_allowed_actions",
"(",
"self",
",",
"pattern",
"=",
"None",
")",
":",
"wildcard_allowed",
"=",
"[",
"]",
"for",
"statement",
"in",
"self",
".",
"statements",
":",
"if",
"statement",
".",
"wildcard_actions",
"(",
"pattern",
")",
"and",
"state... | Find statements which allow wildcard actions.
A pattern can be specified for the wildcard action | [
"Find",
"statements",
"which",
"allow",
"wildcard",
"actions",
"."
] | e3da4db96f59c0a5dba06ae66ad25645775e5500 | https://github.com/Skyscanner/pycfmodel/blob/e3da4db96f59c0a5dba06ae66ad25645775e5500/pycfmodel/model/resources/properties/policy_document.py#L176-L189 | train | 212,822 |
Skyscanner/pycfmodel | pycfmodel/model/resources/properties/policy_document.py | PolicyDocument.wildcard_allowed_principals | def wildcard_allowed_principals(self, pattern=None):
"""
Find statements which allow wildcard principals.
A pattern can be specified for the wildcard principal
"""
wildcard_allowed = []
for statement in self.statements:
if statement.wildcard_principals(pattern) and statement.effect == "Allow":
wildcard_allowed.append(statement)
return wildcard_allowed | python | def wildcard_allowed_principals(self, pattern=None):
"""
Find statements which allow wildcard principals.
A pattern can be specified for the wildcard principal
"""
wildcard_allowed = []
for statement in self.statements:
if statement.wildcard_principals(pattern) and statement.effect == "Allow":
wildcard_allowed.append(statement)
return wildcard_allowed | [
"def",
"wildcard_allowed_principals",
"(",
"self",
",",
"pattern",
"=",
"None",
")",
":",
"wildcard_allowed",
"=",
"[",
"]",
"for",
"statement",
"in",
"self",
".",
"statements",
":",
"if",
"statement",
".",
"wildcard_principals",
"(",
"pattern",
")",
"and",
... | Find statements which allow wildcard principals.
A pattern can be specified for the wildcard principal | [
"Find",
"statements",
"which",
"allow",
"wildcard",
"principals",
"."
] | e3da4db96f59c0a5dba06ae66ad25645775e5500 | https://github.com/Skyscanner/pycfmodel/blob/e3da4db96f59c0a5dba06ae66ad25645775e5500/pycfmodel/model/resources/properties/policy_document.py#L191-L204 | train | 212,823 |
Skyscanner/pycfmodel | pycfmodel/model/resources/properties/policy_document.py | PolicyDocument.nonwhitelisted_allowed_principals | def nonwhitelisted_allowed_principals(self, whitelist=None):
"""Find non whitelisted allowed principals."""
if not whitelist:
return []
nonwhitelisted = []
for statement in self.statements:
if statement.non_whitelisted_principals(whitelist) and statement.effect == "Allow":
nonwhitelisted.append(statement)
return nonwhitelisted | python | def nonwhitelisted_allowed_principals(self, whitelist=None):
"""Find non whitelisted allowed principals."""
if not whitelist:
return []
nonwhitelisted = []
for statement in self.statements:
if statement.non_whitelisted_principals(whitelist) and statement.effect == "Allow":
nonwhitelisted.append(statement)
return nonwhitelisted | [
"def",
"nonwhitelisted_allowed_principals",
"(",
"self",
",",
"whitelist",
"=",
"None",
")",
":",
"if",
"not",
"whitelist",
":",
"return",
"[",
"]",
"nonwhitelisted",
"=",
"[",
"]",
"for",
"statement",
"in",
"self",
".",
"statements",
":",
"if",
"statement",... | Find non whitelisted allowed principals. | [
"Find",
"non",
"whitelisted",
"allowed",
"principals",
"."
] | e3da4db96f59c0a5dba06ae66ad25645775e5500 | https://github.com/Skyscanner/pycfmodel/blob/e3da4db96f59c0a5dba06ae66ad25645775e5500/pycfmodel/model/resources/properties/policy_document.py#L206-L217 | train | 212,824 |
Skyscanner/pycfmodel | pycfmodel/model/resources/properties/policy_document.py | PolicyDocument.allows_not_principal | def allows_not_principal(self):
"""Find allowed not-principals."""
not_principals = []
for statement in self.statements:
if statement.not_principal and statement.effect == "Allow":
not_principals.append(statement)
return not_principals | python | def allows_not_principal(self):
"""Find allowed not-principals."""
not_principals = []
for statement in self.statements:
if statement.not_principal and statement.effect == "Allow":
not_principals.append(statement)
return not_principals | [
"def",
"allows_not_principal",
"(",
"self",
")",
":",
"not_principals",
"=",
"[",
"]",
"for",
"statement",
"in",
"self",
".",
"statements",
":",
"if",
"statement",
".",
"not_principal",
"and",
"statement",
".",
"effect",
"==",
"\"Allow\"",
":",
"not_principals... | Find allowed not-principals. | [
"Find",
"allowed",
"not",
"-",
"principals",
"."
] | e3da4db96f59c0a5dba06ae66ad25645775e5500 | https://github.com/Skyscanner/pycfmodel/blob/e3da4db96f59c0a5dba06ae66ad25645775e5500/pycfmodel/model/resources/properties/policy_document.py#L219-L226 | train | 212,825 |
Skyscanner/pycfmodel | pycfmodel/model/cf_model.py | CFModel.parse_parameters | def parse_parameters(self, parameters):
"""Parses and sets parameters in the model."""
self.parameters = []
for param_name, param_value in parameters.items():
p = Parameter(param_name, param_value)
if p:
self.parameters.append(p) | python | def parse_parameters(self, parameters):
"""Parses and sets parameters in the model."""
self.parameters = []
for param_name, param_value in parameters.items():
p = Parameter(param_name, param_value)
if p:
self.parameters.append(p) | [
"def",
"parse_parameters",
"(",
"self",
",",
"parameters",
")",
":",
"self",
".",
"parameters",
"=",
"[",
"]",
"for",
"param_name",
",",
"param_value",
"in",
"parameters",
".",
"items",
"(",
")",
":",
"p",
"=",
"Parameter",
"(",
"param_name",
",",
"param... | Parses and sets parameters in the model. | [
"Parses",
"and",
"sets",
"parameters",
"in",
"the",
"model",
"."
] | e3da4db96f59c0a5dba06ae66ad25645775e5500 | https://github.com/Skyscanner/pycfmodel/blob/e3da4db96f59c0a5dba06ae66ad25645775e5500/pycfmodel/model/cf_model.py#L32-L39 | train | 212,826 |
Skyscanner/pycfmodel | pycfmodel/model/cf_model.py | CFModel.parse_resources | def parse_resources(self, resources):
"""Parses and sets resources in the model using a factory."""
self.resources = {}
resource_factory = ResourceFactory()
for res_id, res_value in resources.items():
r = resource_factory.create_resource(res_id, res_value)
if r:
if r.resource_type in self.resources:
self.resources[r.resource_type].append(r)
else:
self.resources[r.resource_type] = [r] | python | def parse_resources(self, resources):
"""Parses and sets resources in the model using a factory."""
self.resources = {}
resource_factory = ResourceFactory()
for res_id, res_value in resources.items():
r = resource_factory.create_resource(res_id, res_value)
if r:
if r.resource_type in self.resources:
self.resources[r.resource_type].append(r)
else:
self.resources[r.resource_type] = [r] | [
"def",
"parse_resources",
"(",
"self",
",",
"resources",
")",
":",
"self",
".",
"resources",
"=",
"{",
"}",
"resource_factory",
"=",
"ResourceFactory",
"(",
")",
"for",
"res_id",
",",
"res_value",
"in",
"resources",
".",
"items",
"(",
")",
":",
"r",
"=",... | Parses and sets resources in the model using a factory. | [
"Parses",
"and",
"sets",
"resources",
"in",
"the",
"model",
"using",
"a",
"factory",
"."
] | e3da4db96f59c0a5dba06ae66ad25645775e5500 | https://github.com/Skyscanner/pycfmodel/blob/e3da4db96f59c0a5dba06ae66ad25645775e5500/pycfmodel/model/cf_model.py#L41-L52 | train | 212,827 |
Peter-Slump/python-keycloak-client | src/keycloak/client.py | KeycloakClient.session | def session(self):
"""
Get session object to benefit from connection pooling.
http://docs.python-requests.org/en/master/user/advanced/#session-objects
:rtype: requests.Session
"""
if self._session is None:
self._session = requests.Session()
self._session.headers.update(self._headers)
return self._session | python | def session(self):
"""
Get session object to benefit from connection pooling.
http://docs.python-requests.org/en/master/user/advanced/#session-objects
:rtype: requests.Session
"""
if self._session is None:
self._session = requests.Session()
self._session.headers.update(self._headers)
return self._session | [
"def",
"session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"is",
"None",
":",
"self",
".",
"_session",
"=",
"requests",
".",
"Session",
"(",
")",
"self",
".",
"_session",
".",
"headers",
".",
"update",
"(",
"self",
".",
"_headers",
")",
... | Get session object to benefit from connection pooling.
http://docs.python-requests.org/en/master/user/advanced/#session-objects
:rtype: requests.Session | [
"Get",
"session",
"object",
"to",
"benefit",
"from",
"connection",
"pooling",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/client.py#L45-L56 | train | 212,828 |
Peter-Slump/python-keycloak-client | src/keycloak/realm.py | KeycloakRealm.open_id_connect | def open_id_connect(self, client_id, client_secret):
"""
Get OpenID Connect client
:param str client_id:
:param str client_secret:
:rtype: keycloak.openid_connect.KeycloakOpenidConnect
"""
return KeycloakOpenidConnect(realm=self, client_id=client_id,
client_secret=client_secret) | python | def open_id_connect(self, client_id, client_secret):
"""
Get OpenID Connect client
:param str client_id:
:param str client_secret:
:rtype: keycloak.openid_connect.KeycloakOpenidConnect
"""
return KeycloakOpenidConnect(realm=self, client_id=client_id,
client_secret=client_secret) | [
"def",
"open_id_connect",
"(",
"self",
",",
"client_id",
",",
"client_secret",
")",
":",
"return",
"KeycloakOpenidConnect",
"(",
"realm",
"=",
"self",
",",
"client_id",
"=",
"client_id",
",",
"client_secret",
"=",
"client_secret",
")"
] | Get OpenID Connect client
:param str client_id:
:param str client_secret:
:rtype: keycloak.openid_connect.KeycloakOpenidConnect | [
"Get",
"OpenID",
"Connect",
"client"
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/realm.py#L51-L60 | train | 212,829 |
Peter-Slump/python-keycloak-client | src/keycloak/admin/users.py | Users.create | def create(self, username, **kwargs):
"""
Create a user in Keycloak
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource
:param str username:
:param object credentials: (optional)
:param str first_name: (optional)
:param str last_name: (optional)
:param str email: (optional)
:param boolean enabled: (optional)
"""
payload = OrderedDict(username=username)
for key in USER_KWARGS:
from keycloak.admin.clientroles import to_camel_case
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
return self._client.post(
url=self._client.get_full_url(
self.get_path('collection', realm=self._realm_name)
),
data=json.dumps(payload, sort_keys=True)
) | python | def create(self, username, **kwargs):
"""
Create a user in Keycloak
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource
:param str username:
:param object credentials: (optional)
:param str first_name: (optional)
:param str last_name: (optional)
:param str email: (optional)
:param boolean enabled: (optional)
"""
payload = OrderedDict(username=username)
for key in USER_KWARGS:
from keycloak.admin.clientroles import to_camel_case
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
return self._client.post(
url=self._client.get_full_url(
self.get_path('collection', realm=self._realm_name)
),
data=json.dumps(payload, sort_keys=True)
) | [
"def",
"create",
"(",
"self",
",",
"username",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"OrderedDict",
"(",
"username",
"=",
"username",
")",
"for",
"key",
"in",
"USER_KWARGS",
":",
"from",
"keycloak",
".",
"admin",
".",
"clientroles",
"import"... | Create a user in Keycloak
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource
:param str username:
:param object credentials: (optional)
:param str first_name: (optional)
:param str last_name: (optional)
:param str email: (optional)
:param boolean enabled: (optional) | [
"Create",
"a",
"user",
"in",
"Keycloak"
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/admin/users.py#L33-L58 | train | 212,830 |
Peter-Slump/python-keycloak-client | src/keycloak/admin/users.py | Users.all | def all(self):
"""
Return all registered users
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource
"""
return self._client.get(
url=self._client.get_full_url(
self.get_path('collection', realm=self._realm_name)
)
) | python | def all(self):
"""
Return all registered users
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource
"""
return self._client.get(
url=self._client.get_full_url(
self.get_path('collection', realm=self._realm_name)
)
) | [
"def",
"all",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"get",
"(",
"url",
"=",
"self",
".",
"_client",
".",
"get_full_url",
"(",
"self",
".",
"get_path",
"(",
"'collection'",
",",
"realm",
"=",
"self",
".",
"_realm_name",
")",
")... | Return all registered users
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource | [
"Return",
"all",
"registered",
"users"
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/admin/users.py#L60-L70 | train | 212,831 |
Peter-Slump/python-keycloak-client | src/keycloak/admin/users.py | User.get | def get(self):
"""
Return registered user with the given user id.
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource
"""
self._user = self._client.get(
url=self._client.get_full_url(
self.get_path(
'single', realm=self._realm_name, user_id=self._user_id
)
)
)
self._user_id = self.user["id"]
return self._user | python | def get(self):
"""
Return registered user with the given user id.
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource
"""
self._user = self._client.get(
url=self._client.get_full_url(
self.get_path(
'single', realm=self._realm_name, user_id=self._user_id
)
)
)
self._user_id = self.user["id"]
return self._user | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"_user",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"url",
"=",
"self",
".",
"_client",
".",
"get_full_url",
"(",
"self",
".",
"get_path",
"(",
"'single'",
",",
"realm",
"=",
"self",
".",
"_realm... | Return registered user with the given user id.
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource | [
"Return",
"registered",
"user",
"with",
"the",
"given",
"user",
"id",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/admin/users.py#L110-L124 | train | 212,832 |
Peter-Slump/python-keycloak-client | src/keycloak/admin/users.py | User.update | def update(self, **kwargs):
"""
Update existing user.
https://www.keycloak.org/docs-api/2.5/rest-api/index.html#_userrepresentation
:param str first_name: first_name for user
:param str last_name: last_name for user
:param str email: Email for user
:param bool email_verified: User email verified
:param Map attributes: Atributes in user
:param string array realm_roles: Realm Roles
:param Map client_roles: Client Roles
:param string array groups: Groups for user
"""
payload = {}
for k, v in self.user.items():
payload[k] = v
for key in USER_KWARGS:
from keycloak.admin.clientroles import to_camel_case
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
result = self._client.put(
url=self._client.get_full_url(
self.get_path(
'single', realm=self._realm_name, user_id=self._user_id
)
),
data=json.dumps(payload, sort_keys=True)
)
self.get()
return result | python | def update(self, **kwargs):
"""
Update existing user.
https://www.keycloak.org/docs-api/2.5/rest-api/index.html#_userrepresentation
:param str first_name: first_name for user
:param str last_name: last_name for user
:param str email: Email for user
:param bool email_verified: User email verified
:param Map attributes: Atributes in user
:param string array realm_roles: Realm Roles
:param Map client_roles: Client Roles
:param string array groups: Groups for user
"""
payload = {}
for k, v in self.user.items():
payload[k] = v
for key in USER_KWARGS:
from keycloak.admin.clientroles import to_camel_case
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
result = self._client.put(
url=self._client.get_full_url(
self.get_path(
'single', realm=self._realm_name, user_id=self._user_id
)
),
data=json.dumps(payload, sort_keys=True)
)
self.get()
return result | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"user",
".",
"items",
"(",
")",
":",
"payload",
"[",
"k",
"]",
"=",
"v",
"for",
"key",
"in",
"USER_KWARGS",
":... | Update existing user.
https://www.keycloak.org/docs-api/2.5/rest-api/index.html#_userrepresentation
:param str first_name: first_name for user
:param str last_name: last_name for user
:param str email: Email for user
:param bool email_verified: User email verified
:param Map attributes: Atributes in user
:param string array realm_roles: Realm Roles
:param Map client_roles: Client Roles
:param string array groups: Groups for user | [
"Update",
"existing",
"user",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/admin/users.py#L126-L157 | train | 212,833 |
Peter-Slump/python-keycloak-client | src/keycloak/uma.py | KeycloakUMA.resource_set_create | def resource_set_create(self, token, name, **kwargs):
"""
Create a resource set.
https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#rfc.section.2.2.1
:param str token: client access token
:param str id: Identifier of the resource set
:param str name:
:param str uri: (optional)
:param str type: (optional)
:param list scopes: (optional)
:param str icon_url: (optional)
:param str DisplayName: (optional)
:param boolean ownerManagedAccess: (optional)
:param str owner: (optional)
:rtype: str
"""
return self._realm.client.post(
self.well_known['resource_registration_endpoint'],
data=self._get_data(name=name, **kwargs),
headers=self.get_headers(token)
) | python | def resource_set_create(self, token, name, **kwargs):
"""
Create a resource set.
https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#rfc.section.2.2.1
:param str token: client access token
:param str id: Identifier of the resource set
:param str name:
:param str uri: (optional)
:param str type: (optional)
:param list scopes: (optional)
:param str icon_url: (optional)
:param str DisplayName: (optional)
:param boolean ownerManagedAccess: (optional)
:param str owner: (optional)
:rtype: str
"""
return self._realm.client.post(
self.well_known['resource_registration_endpoint'],
data=self._get_data(name=name, **kwargs),
headers=self.get_headers(token)
) | [
"def",
"resource_set_create",
"(",
"self",
",",
"token",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_realm",
".",
"client",
".",
"post",
"(",
"self",
".",
"well_known",
"[",
"'resource_registration_endpoint'",
"]",
",",
"data",... | Create a resource set.
https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#rfc.section.2.2.1
:param str token: client access token
:param str id: Identifier of the resource set
:param str name:
:param str uri: (optional)
:param str type: (optional)
:param list scopes: (optional)
:param str icon_url: (optional)
:param str DisplayName: (optional)
:param boolean ownerManagedAccess: (optional)
:param str owner: (optional)
:rtype: str | [
"Create",
"a",
"resource",
"set",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/uma.py#L26-L48 | train | 212,834 |
Peter-Slump/python-keycloak-client | src/keycloak/uma.py | KeycloakUMA.resource_set_update | def resource_set_update(self, token, id, name, **kwargs):
"""
Update a resource set.
https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#update-resource-set
:param str token: client access token
:param str id: Identifier of the resource set
:param str name:
:param str uri: (optional)
:param str type: (optional)
:param list scopes: (optional)
:param str icon_url: (optional)
:rtype: str
"""
return self._realm.client.put(
'{}/{}'.format(
self.well_known['resource_registration_endpoint'], id),
data=self._get_data(name=name, **kwargs),
headers=self.get_headers(token)
) | python | def resource_set_update(self, token, id, name, **kwargs):
"""
Update a resource set.
https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#update-resource-set
:param str token: client access token
:param str id: Identifier of the resource set
:param str name:
:param str uri: (optional)
:param str type: (optional)
:param list scopes: (optional)
:param str icon_url: (optional)
:rtype: str
"""
return self._realm.client.put(
'{}/{}'.format(
self.well_known['resource_registration_endpoint'], id),
data=self._get_data(name=name, **kwargs),
headers=self.get_headers(token)
) | [
"def",
"resource_set_update",
"(",
"self",
",",
"token",
",",
"id",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_realm",
".",
"client",
".",
"put",
"(",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"well_known",
"[",
"'reso... | Update a resource set.
https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#update-resource-set
:param str token: client access token
:param str id: Identifier of the resource set
:param str name:
:param str uri: (optional)
:param str type: (optional)
:param list scopes: (optional)
:param str icon_url: (optional)
:rtype: str | [
"Update",
"a",
"resource",
"set",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/uma.py#L50-L70 | train | 212,835 |
Peter-Slump/python-keycloak-client | src/keycloak/uma.py | KeycloakUMA.resource_set_read | def resource_set_read(self, token, id):
"""
Read a resource set.
https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#read-resource-set
:param str token: client access token
:param str id: Identifier of the resource set
:rtype: dict
"""
return self._realm.client.get(
'{}/{}'.format(
self.well_known['resource_registration_endpoint'], id),
headers=self.get_headers(token)
) | python | def resource_set_read(self, token, id):
"""
Read a resource set.
https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#read-resource-set
:param str token: client access token
:param str id: Identifier of the resource set
:rtype: dict
"""
return self._realm.client.get(
'{}/{}'.format(
self.well_known['resource_registration_endpoint'], id),
headers=self.get_headers(token)
) | [
"def",
"resource_set_read",
"(",
"self",
",",
"token",
",",
"id",
")",
":",
"return",
"self",
".",
"_realm",
".",
"client",
".",
"get",
"(",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"well_known",
"[",
"'resource_registration_endpoint'",
"]",
",",
"id",
... | Read a resource set.
https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#read-resource-set
:param str token: client access token
:param str id: Identifier of the resource set
:rtype: dict | [
"Read",
"a",
"resource",
"set",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/uma.py#L72-L86 | train | 212,836 |
Peter-Slump/python-keycloak-client | src/keycloak/uma.py | KeycloakUMA.resource_create_ticket | def resource_create_ticket(self, token, id, scopes, **kwargs):
"""
Create a ticket form permission to resource.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_permission_api_papi
:param str token: user access token
:param str id: resource id
:param list scopes: scopes access is wanted
:param dict claims: (optional)
:rtype: dict
"""
data = dict(resource_id=id, resource_scopes=scopes, **kwargs)
return self._realm.client.post(
self.well_known['permission_endpoint'],
data=self._dumps([data]),
headers=self.get_headers(token)
) | python | def resource_create_ticket(self, token, id, scopes, **kwargs):
"""
Create a ticket form permission to resource.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_permission_api_papi
:param str token: user access token
:param str id: resource id
:param list scopes: scopes access is wanted
:param dict claims: (optional)
:rtype: dict
"""
data = dict(resource_id=id, resource_scopes=scopes, **kwargs)
return self._realm.client.post(
self.well_known['permission_endpoint'],
data=self._dumps([data]),
headers=self.get_headers(token)
) | [
"def",
"resource_create_ticket",
"(",
"self",
",",
"token",
",",
"id",
",",
"scopes",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"dict",
"(",
"resource_id",
"=",
"id",
",",
"resource_scopes",
"=",
"scopes",
",",
"*",
"*",
"kwargs",
")",
"return",
... | Create a ticket form permission to resource.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_permission_api_papi
:param str token: user access token
:param str id: resource id
:param list scopes: scopes access is wanted
:param dict claims: (optional)
:rtype: dict | [
"Create",
"a",
"ticket",
"form",
"permission",
"to",
"resource",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/uma.py#L123-L140 | train | 212,837 |
Peter-Slump/python-keycloak-client | src/keycloak/uma.py | KeycloakUMA.resource_associate_permission | def resource_associate_permission(self, token, id, name, scopes, **kwargs):
"""
Associates a permission with a Resource.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_authorization_uma_policy_api
:param str token: client access token
:param str id: resource id
:param str name: permission name
:param list scopes: scopes access is wanted
:param str description:optional
:param list roles: (optional)
:param list groups: (optional)
:param list clients: (optional)
:param str condition: (optional)
:rtype: dict
"""
return self._realm.client.post(
'{}/{}'.format(self.well_known['policy_endpoint'], id),
data=self._get_data(name=name, scopes=scopes, **kwargs),
headers=self.get_headers(token)
) | python | def resource_associate_permission(self, token, id, name, scopes, **kwargs):
"""
Associates a permission with a Resource.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_authorization_uma_policy_api
:param str token: client access token
:param str id: resource id
:param str name: permission name
:param list scopes: scopes access is wanted
:param str description:optional
:param list roles: (optional)
:param list groups: (optional)
:param list clients: (optional)
:param str condition: (optional)
:rtype: dict
"""
return self._realm.client.post(
'{}/{}'.format(self.well_known['policy_endpoint'], id),
data=self._get_data(name=name, scopes=scopes, **kwargs),
headers=self.get_headers(token)
) | [
"def",
"resource_associate_permission",
"(",
"self",
",",
"token",
",",
"id",
",",
"name",
",",
"scopes",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_realm",
".",
"client",
".",
"post",
"(",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
... | Associates a permission with a Resource.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_authorization_uma_policy_api
:param str token: client access token
:param str id: resource id
:param str name: permission name
:param list scopes: scopes access is wanted
:param str description:optional
:param list roles: (optional)
:param list groups: (optional)
:param list clients: (optional)
:param str condition: (optional)
:rtype: dict | [
"Associates",
"a",
"permission",
"with",
"a",
"Resource",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/uma.py#L142-L163 | train | 212,838 |
Peter-Slump/python-keycloak-client | src/keycloak/uma.py | KeycloakUMA.permission_update | def permission_update(self, token, id, **kwargs):
"""
To update an existing permission.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_authorization_uma_policy_api
:param str token: client access token
:param str id: permission id
:rtype: dict
"""
return self._realm.client.put(
'{}/{}'.format(self.well_known['policy_endpoint'], id),
data=self._dumps(kwargs),
headers=self.get_headers(token)
) | python | def permission_update(self, token, id, **kwargs):
"""
To update an existing permission.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_authorization_uma_policy_api
:param str token: client access token
:param str id: permission id
:rtype: dict
"""
return self._realm.client.put(
'{}/{}'.format(self.well_known['policy_endpoint'], id),
data=self._dumps(kwargs),
headers=self.get_headers(token)
) | [
"def",
"permission_update",
"(",
"self",
",",
"token",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_realm",
".",
"client",
".",
"put",
"(",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"well_known",
"[",
"'policy_endpoint'",
"]... | To update an existing permission.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_authorization_uma_policy_api
:param str token: client access token
:param str id: permission id
:rtype: dict | [
"To",
"update",
"an",
"existing",
"permission",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/uma.py#L165-L180 | train | 212,839 |
Peter-Slump/python-keycloak-client | src/keycloak/uma.py | KeycloakUMA.permission_delete | def permission_delete(self, token, id):
"""
Removing a Permission.
https://www.keycloak.org/docs/latest/authorization_services/index.html#removing-a-permission
:param str token: client access token
:param str id: permission id
:rtype: dict
"""
return self._realm.client.delete(
'{}/{}'.format(self.well_known['policy_endpoint'], id),
headers=self.get_headers(token)
) | python | def permission_delete(self, token, id):
"""
Removing a Permission.
https://www.keycloak.org/docs/latest/authorization_services/index.html#removing-a-permission
:param str token: client access token
:param str id: permission id
:rtype: dict
"""
return self._realm.client.delete(
'{}/{}'.format(self.well_known['policy_endpoint'], id),
headers=self.get_headers(token)
) | [
"def",
"permission_delete",
"(",
"self",
",",
"token",
",",
"id",
")",
":",
"return",
"self",
".",
"_realm",
".",
"client",
".",
"delete",
"(",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"well_known",
"[",
"'policy_endpoint'",
"]",
",",
"id",
")",
","... | Removing a Permission.
https://www.keycloak.org/docs/latest/authorization_services/index.html#removing-a-permission
:param str token: client access token
:param str id: permission id
:rtype: dict | [
"Removing",
"a",
"Permission",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/uma.py#L182-L196 | train | 212,840 |
Peter-Slump/python-keycloak-client | src/keycloak/authz.py | KeycloakAuthz._decode_token | def _decode_token(cls, token):
"""
Permission information is encoded in an authorization token.
"""
missing_padding = len(token) % 4
if missing_padding != 0:
token += '=' * (4 - missing_padding)
return json.loads(base64.b64decode(token).decode('utf-8')) | python | def _decode_token(cls, token):
"""
Permission information is encoded in an authorization token.
"""
missing_padding = len(token) % 4
if missing_padding != 0:
token += '=' * (4 - missing_padding)
return json.loads(base64.b64decode(token).decode('utf-8')) | [
"def",
"_decode_token",
"(",
"cls",
",",
"token",
")",
":",
"missing_padding",
"=",
"len",
"(",
"token",
")",
"%",
"4",
"if",
"missing_padding",
"!=",
"0",
":",
"token",
"+=",
"'='",
"*",
"(",
"4",
"-",
"missing_padding",
")",
"return",
"json",
".",
... | Permission information is encoded in an authorization token. | [
"Permission",
"information",
"is",
"encoded",
"in",
"an",
"authorization",
"token",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/authz.py#L59-L66 | train | 212,841 |
Peter-Slump/python-keycloak-client | src/keycloak/authz.py | KeycloakAuthz.get_permissions | def get_permissions(self, token, resource_scopes_tuples=None,
submit_request=False, ticket=None):
"""
Request permissions for user from keycloak server.
https://www.keycloak.org/docs/latest/authorization_services/index
.html#_service_protection_permission_api_papi
:param str token: client access token
:param Iterable[Tuple[str, str]] resource_scopes_tuples:
list of tuples (resource, scope)
:param boolean submit_request: submit request if not allowed to access?
:param str ticket: Permissions ticket
rtype: dict
"""
headers = {
"Authorization": "Bearer %s" % token,
'Content-type': 'application/x-www-form-urlencoded',
}
data = [
('grant_type', 'urn:ietf:params:oauth:grant-type:uma-ticket'),
('audience', self._client_id),
('response_include_resource_name', True),
]
if resource_scopes_tuples:
for atuple in resource_scopes_tuples:
data.append(('permission', '#'.join(atuple)))
data.append(('submit_request', submit_request))
elif ticket:
data.append(('ticket', ticket))
authz_info = {}
try:
response = self._realm.client.post(
self.well_known['token_endpoint'],
data=urlencode(data),
headers=headers,
)
error = response.get('error')
if error:
self.logger.warning(
'%s: %s',
error,
response.get('error_description')
)
else:
token = response.get('refresh_token')
decoded_token = self._decode_token(token.split('.')[1])
authz_info = decoded_token.get('authorization', {})
except KeycloakClientError as error:
self.logger.warning(str(error))
return authz_info | python | def get_permissions(self, token, resource_scopes_tuples=None,
submit_request=False, ticket=None):
"""
Request permissions for user from keycloak server.
https://www.keycloak.org/docs/latest/authorization_services/index
.html#_service_protection_permission_api_papi
:param str token: client access token
:param Iterable[Tuple[str, str]] resource_scopes_tuples:
list of tuples (resource, scope)
:param boolean submit_request: submit request if not allowed to access?
:param str ticket: Permissions ticket
rtype: dict
"""
headers = {
"Authorization": "Bearer %s" % token,
'Content-type': 'application/x-www-form-urlencoded',
}
data = [
('grant_type', 'urn:ietf:params:oauth:grant-type:uma-ticket'),
('audience', self._client_id),
('response_include_resource_name', True),
]
if resource_scopes_tuples:
for atuple in resource_scopes_tuples:
data.append(('permission', '#'.join(atuple)))
data.append(('submit_request', submit_request))
elif ticket:
data.append(('ticket', ticket))
authz_info = {}
try:
response = self._realm.client.post(
self.well_known['token_endpoint'],
data=urlencode(data),
headers=headers,
)
error = response.get('error')
if error:
self.logger.warning(
'%s: %s',
error,
response.get('error_description')
)
else:
token = response.get('refresh_token')
decoded_token = self._decode_token(token.split('.')[1])
authz_info = decoded_token.get('authorization', {})
except KeycloakClientError as error:
self.logger.warning(str(error))
return authz_info | [
"def",
"get_permissions",
"(",
"self",
",",
"token",
",",
"resource_scopes_tuples",
"=",
"None",
",",
"submit_request",
"=",
"False",
",",
"ticket",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"\"Bearer %s\"",
"%",
"token",
",",
"'C... | Request permissions for user from keycloak server.
https://www.keycloak.org/docs/latest/authorization_services/index
.html#_service_protection_permission_api_papi
:param str token: client access token
:param Iterable[Tuple[str, str]] resource_scopes_tuples:
list of tuples (resource, scope)
:param boolean submit_request: submit request if not allowed to access?
:param str ticket: Permissions ticket
rtype: dict | [
"Request",
"permissions",
"for",
"user",
"from",
"keycloak",
"server",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/authz.py#L68-L123 | train | 212,842 |
Peter-Slump/python-keycloak-client | src/keycloak/authz.py | KeycloakAuthz.eval_permission | def eval_permission(self, token, resource, scope, submit_request=False):
"""
Evalutes if user has permission for scope on resource.
:param str token: client access token
:param str resource: resource to access
:param str scope: scope on resource
:param boolean submit_request: submit request if not allowed to access?
rtype: boolean
"""
return self.eval_permissions(
token=token,
resource_scopes_tuples=[(resource, scope)],
submit_request=submit_request
) | python | def eval_permission(self, token, resource, scope, submit_request=False):
"""
Evalutes if user has permission for scope on resource.
:param str token: client access token
:param str resource: resource to access
:param str scope: scope on resource
:param boolean submit_request: submit request if not allowed to access?
rtype: boolean
"""
return self.eval_permissions(
token=token,
resource_scopes_tuples=[(resource, scope)],
submit_request=submit_request
) | [
"def",
"eval_permission",
"(",
"self",
",",
"token",
",",
"resource",
",",
"scope",
",",
"submit_request",
"=",
"False",
")",
":",
"return",
"self",
".",
"eval_permissions",
"(",
"token",
"=",
"token",
",",
"resource_scopes_tuples",
"=",
"[",
"(",
"resource"... | Evalutes if user has permission for scope on resource.
:param str token: client access token
:param str resource: resource to access
:param str scope: scope on resource
:param boolean submit_request: submit request if not allowed to access?
rtype: boolean | [
"Evalutes",
"if",
"user",
"has",
"permission",
"for",
"scope",
"on",
"resource",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/authz.py#L125-L139 | train | 212,843 |
Peter-Slump/python-keycloak-client | src/keycloak/authz.py | KeycloakAuthz.eval_permissions | def eval_permissions(self, token, resource_scopes_tuples=None,
submit_request=False):
"""
Evaluates if user has permission for all the resource scope
combinations.
:param str token: client access token
:param Iterable[Tuple[str, str]] resource_scopes_tuples: resource to
access
:param boolean submit_request: submit request if not allowed to access?
rtype: boolean
"""
permissions = self.get_permissions(
token=token,
resource_scopes_tuples=resource_scopes_tuples,
submit_request=submit_request
)
res = []
for permission in permissions.get('permissions', []):
for scope in permission.get('scopes', []):
ptuple = (permission.get('rsname'), scope)
if ptuple in resource_scopes_tuples:
res.append(ptuple)
return res == resource_scopes_tuples | python | def eval_permissions(self, token, resource_scopes_tuples=None,
submit_request=False):
"""
Evaluates if user has permission for all the resource scope
combinations.
:param str token: client access token
:param Iterable[Tuple[str, str]] resource_scopes_tuples: resource to
access
:param boolean submit_request: submit request if not allowed to access?
rtype: boolean
"""
permissions = self.get_permissions(
token=token,
resource_scopes_tuples=resource_scopes_tuples,
submit_request=submit_request
)
res = []
for permission in permissions.get('permissions', []):
for scope in permission.get('scopes', []):
ptuple = (permission.get('rsname'), scope)
if ptuple in resource_scopes_tuples:
res.append(ptuple)
return res == resource_scopes_tuples | [
"def",
"eval_permissions",
"(",
"self",
",",
"token",
",",
"resource_scopes_tuples",
"=",
"None",
",",
"submit_request",
"=",
"False",
")",
":",
"permissions",
"=",
"self",
".",
"get_permissions",
"(",
"token",
"=",
"token",
",",
"resource_scopes_tuples",
"=",
... | Evaluates if user has permission for all the resource scope
combinations.
:param str token: client access token
:param Iterable[Tuple[str, str]] resource_scopes_tuples: resource to
access
:param boolean submit_request: submit request if not allowed to access?
rtype: boolean | [
"Evaluates",
"if",
"user",
"has",
"permission",
"for",
"all",
"the",
"resource",
"scope",
"combinations",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/authz.py#L141-L166 | train | 212,844 |
Peter-Slump/python-keycloak-client | src/keycloak/openid_connect.py | KeycloakOpenidConnect.logout | def logout(self, refresh_token):
"""
The logout endpoint logs out the authenticated user.
:param str refresh_token:
"""
return self._realm.client.post(self.get_url('end_session_endpoint'),
data={
'refresh_token': refresh_token,
'client_id': self._client_id,
'client_secret': self._client_secret
}) | python | def logout(self, refresh_token):
"""
The logout endpoint logs out the authenticated user.
:param str refresh_token:
"""
return self._realm.client.post(self.get_url('end_session_endpoint'),
data={
'refresh_token': refresh_token,
'client_id': self._client_id,
'client_secret': self._client_secret
}) | [
"def",
"logout",
"(",
"self",
",",
"refresh_token",
")",
":",
"return",
"self",
".",
"_realm",
".",
"client",
".",
"post",
"(",
"self",
".",
"get_url",
"(",
"'end_session_endpoint'",
")",
",",
"data",
"=",
"{",
"'refresh_token'",
":",
"refresh_token",
",",... | The logout endpoint logs out the authenticated user.
:param str refresh_token: | [
"The",
"logout",
"endpoint",
"logs",
"out",
"the",
"authenticated",
"user",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/openid_connect.py#L99-L110 | train | 212,845 |
Peter-Slump/python-keycloak-client | src/keycloak/openid_connect.py | KeycloakOpenidConnect.userinfo | def userinfo(self, token):
"""
The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns
Claims about the authenticated End-User. To obtain the requested Claims
about the End-User, the Client makes a request to the UserInfo Endpoint
using an Access Token obtained through OpenID Connect Authentication.
These Claims are normally represented by a JSON object that contains a
collection of name and value pairs for the Claims.
http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
:param str token:
:rtype: dict
"""
url = self.well_known['userinfo_endpoint']
return self._realm.client.get(url, headers={
"Authorization": "Bearer {}".format(
token
)
}) | python | def userinfo(self, token):
"""
The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns
Claims about the authenticated End-User. To obtain the requested Claims
about the End-User, the Client makes a request to the UserInfo Endpoint
using an Access Token obtained through OpenID Connect Authentication.
These Claims are normally represented by a JSON object that contains a
collection of name and value pairs for the Claims.
http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
:param str token:
:rtype: dict
"""
url = self.well_known['userinfo_endpoint']
return self._realm.client.get(url, headers={
"Authorization": "Bearer {}".format(
token
)
}) | [
"def",
"userinfo",
"(",
"self",
",",
"token",
")",
":",
"url",
"=",
"self",
".",
"well_known",
"[",
"'userinfo_endpoint'",
"]",
"return",
"self",
".",
"_realm",
".",
"client",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"{",
"\"Authorization\"",
":",
... | The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns
Claims about the authenticated End-User. To obtain the requested Claims
about the End-User, the Client makes a request to the UserInfo Endpoint
using an Access Token obtained through OpenID Connect Authentication.
These Claims are normally represented by a JSON object that contains a
collection of name and value pairs for the Claims.
http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
:param str token:
:rtype: dict | [
"The",
"UserInfo",
"Endpoint",
"is",
"an",
"OAuth",
"2",
".",
"0",
"Protected",
"Resource",
"that",
"returns",
"Claims",
"about",
"the",
"authenticated",
"End",
"-",
"User",
".",
"To",
"obtain",
"the",
"requested",
"Claims",
"about",
"the",
"End",
"-",
"Us... | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/openid_connect.py#L124-L144 | train | 212,846 |
Peter-Slump/python-keycloak-client | src/keycloak/openid_connect.py | KeycloakOpenidConnect.authorization_url | def authorization_url(self, **kwargs):
"""
Get authorization URL to redirect the resource owner to.
https://tools.ietf.org/html/rfc6749#section-4.1.1
:param str redirect_uri: (optional) Absolute URL of the client where
the user-agent will be redirected to.
:param str scope: (optional) Space delimited list of strings.
:param str state: (optional) An opaque value used by the client to
maintain state between the request and callback
:return: URL to redirect the resource owner to
:rtype: str
"""
payload = {'response_type': 'code', 'client_id': self._client_id}
for key in kwargs.keys():
# Add items in a sorted way for unittest purposes.
payload[key] = kwargs[key]
payload = sorted(payload.items(), key=lambda val: val[0])
params = urlencode(payload)
url = self.get_url('authorization_endpoint')
return '{}?{}'.format(url, params) | python | def authorization_url(self, **kwargs):
"""
Get authorization URL to redirect the resource owner to.
https://tools.ietf.org/html/rfc6749#section-4.1.1
:param str redirect_uri: (optional) Absolute URL of the client where
the user-agent will be redirected to.
:param str scope: (optional) Space delimited list of strings.
:param str state: (optional) An opaque value used by the client to
maintain state between the request and callback
:return: URL to redirect the resource owner to
:rtype: str
"""
payload = {'response_type': 'code', 'client_id': self._client_id}
for key in kwargs.keys():
# Add items in a sorted way for unittest purposes.
payload[key] = kwargs[key]
payload = sorted(payload.items(), key=lambda val: val[0])
params = urlencode(payload)
url = self.get_url('authorization_endpoint')
return '{}?{}'.format(url, params) | [
"def",
"authorization_url",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"'response_type'",
":",
"'code'",
",",
"'client_id'",
":",
"self",
".",
"_client_id",
"}",
"for",
"key",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"# Add... | Get authorization URL to redirect the resource owner to.
https://tools.ietf.org/html/rfc6749#section-4.1.1
:param str redirect_uri: (optional) Absolute URL of the client where
the user-agent will be redirected to.
:param str scope: (optional) Space delimited list of strings.
:param str state: (optional) An opaque value used by the client to
maintain state between the request and callback
:return: URL to redirect the resource owner to
:rtype: str | [
"Get",
"authorization",
"URL",
"to",
"redirect",
"the",
"resource",
"owner",
"to",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/openid_connect.py#L146-L169 | train | 212,847 |
Peter-Slump/python-keycloak-client | src/keycloak/openid_connect.py | KeycloakOpenidConnect.authorization_code | def authorization_code(self, code, redirect_uri):
"""
Retrieve access token by `authorization_code` grant.
https://tools.ietf.org/html/rfc6749#section-4.1.3
:param str code: The authorization code received from the authorization
server.
:param str redirect_uri: the identical value of the "redirect_uri"
parameter in the authorization request.
:rtype: dict
:return: Access token response
"""
return self._token_request(grant_type='authorization_code', code=code,
redirect_uri=redirect_uri) | python | def authorization_code(self, code, redirect_uri):
"""
Retrieve access token by `authorization_code` grant.
https://tools.ietf.org/html/rfc6749#section-4.1.3
:param str code: The authorization code received from the authorization
server.
:param str redirect_uri: the identical value of the "redirect_uri"
parameter in the authorization request.
:rtype: dict
:return: Access token response
"""
return self._token_request(grant_type='authorization_code', code=code,
redirect_uri=redirect_uri) | [
"def",
"authorization_code",
"(",
"self",
",",
"code",
",",
"redirect_uri",
")",
":",
"return",
"self",
".",
"_token_request",
"(",
"grant_type",
"=",
"'authorization_code'",
",",
"code",
"=",
"code",
",",
"redirect_uri",
"=",
"redirect_uri",
")"
] | Retrieve access token by `authorization_code` grant.
https://tools.ietf.org/html/rfc6749#section-4.1.3
:param str code: The authorization code received from the authorization
server.
:param str redirect_uri: the identical value of the "redirect_uri"
parameter in the authorization request.
:rtype: dict
:return: Access token response | [
"Retrieve",
"access",
"token",
"by",
"authorization_code",
"grant",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/openid_connect.py#L171-L185 | train | 212,848 |
Peter-Slump/python-keycloak-client | src/keycloak/openid_connect.py | KeycloakOpenidConnect.password_credentials | def password_credentials(self, username, password, **kwargs):
"""
Retrieve access token by 'password credentials' grant.
https://tools.ietf.org/html/rfc6749#section-4.3
:param str username: The user name to obtain an access token for
:param str password: The user's password
:rtype: dict
:return: Access token response
"""
return self._token_request(grant_type='password',
username=username, password=password,
**kwargs) | python | def password_credentials(self, username, password, **kwargs):
"""
Retrieve access token by 'password credentials' grant.
https://tools.ietf.org/html/rfc6749#section-4.3
:param str username: The user name to obtain an access token for
:param str password: The user's password
:rtype: dict
:return: Access token response
"""
return self._token_request(grant_type='password',
username=username, password=password,
**kwargs) | [
"def",
"password_credentials",
"(",
"self",
",",
"username",
",",
"password",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_token_request",
"(",
"grant_type",
"=",
"'password'",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password"... | Retrieve access token by 'password credentials' grant.
https://tools.ietf.org/html/rfc6749#section-4.3
:param str username: The user name to obtain an access token for
:param str password: The user's password
:rtype: dict
:return: Access token response | [
"Retrieve",
"access",
"token",
"by",
"password",
"credentials",
"grant",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/openid_connect.py#L187-L200 | train | 212,849 |
Peter-Slump/python-keycloak-client | src/keycloak/openid_connect.py | KeycloakOpenidConnect.refresh_token | def refresh_token(self, refresh_token, **kwargs):
"""
Refresh an access token
https://tools.ietf.org/html/rfc6749#section-6
:param str refresh_token:
:param str scope: (optional) Space delimited list of strings.
:rtype: dict
:return: Access token response
"""
return self._token_request(grant_type='refresh_token',
refresh_token=refresh_token, **kwargs) | python | def refresh_token(self, refresh_token, **kwargs):
"""
Refresh an access token
https://tools.ietf.org/html/rfc6749#section-6
:param str refresh_token:
:param str scope: (optional) Space delimited list of strings.
:rtype: dict
:return: Access token response
"""
return self._token_request(grant_type='refresh_token',
refresh_token=refresh_token, **kwargs) | [
"def",
"refresh_token",
"(",
"self",
",",
"refresh_token",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_token_request",
"(",
"grant_type",
"=",
"'refresh_token'",
",",
"refresh_token",
"=",
"refresh_token",
",",
"*",
"*",
"kwargs",
")"
] | Refresh an access token
https://tools.ietf.org/html/rfc6749#section-6
:param str refresh_token:
:param str scope: (optional) Space delimited list of strings.
:rtype: dict
:return: Access token response | [
"Refresh",
"an",
"access",
"token"
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/openid_connect.py#L214-L226 | train | 212,850 |
Peter-Slump/python-keycloak-client | src/keycloak/openid_connect.py | KeycloakOpenidConnect._token_request | def _token_request(self, grant_type, **kwargs):
"""
Do the actual call to the token end-point.
:param grant_type:
:param kwargs: See invoking methods.
:return:
"""
payload = {
'grant_type': grant_type,
'client_id': self._client_id,
'client_secret': self._client_secret
}
payload.update(**kwargs)
return self._realm.client.post(self.get_url('token_endpoint'),
data=payload) | python | def _token_request(self, grant_type, **kwargs):
"""
Do the actual call to the token end-point.
:param grant_type:
:param kwargs: See invoking methods.
:return:
"""
payload = {
'grant_type': grant_type,
'client_id': self._client_id,
'client_secret': self._client_secret
}
payload.update(**kwargs)
return self._realm.client.post(self.get_url('token_endpoint'),
data=payload) | [
"def",
"_token_request",
"(",
"self",
",",
"grant_type",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"'grant_type'",
":",
"grant_type",
",",
"'client_id'",
":",
"self",
".",
"_client_id",
",",
"'client_secret'",
":",
"self",
".",
"_client_secret"... | Do the actual call to the token end-point.
:param grant_type:
:param kwargs: See invoking methods.
:return: | [
"Do",
"the",
"actual",
"call",
"to",
"the",
"token",
"end",
"-",
"point",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/openid_connect.py#L276-L293 | train | 212,851 |
Peter-Slump/python-keycloak-client | src/keycloak/admin/clientroles.py | ClientRoles.create | def create(self, name, **kwargs):
"""
Create new role
http://www.keycloak.org/docs-api/3.4/rest-api/index.html
#_roles_resource
:param str name: Name for the role
:param str description: (optional)
:param str id: (optional)
:param bool client_role: (optional)
:param bool composite: (optional)
:param object composites: (optional)
:param str container_id: (optional)
:param bool scope_param_required: (optional)
"""
payload = OrderedDict(name=name)
for key in ROLE_KWARGS:
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
return self._client.post(
url=self._client.get_full_url(
self.get_path('collection',
realm=self._realm_name,
id=self._client_id)
),
data=json.dumps(payload, sort_keys=True)
) | python | def create(self, name, **kwargs):
"""
Create new role
http://www.keycloak.org/docs-api/3.4/rest-api/index.html
#_roles_resource
:param str name: Name for the role
:param str description: (optional)
:param str id: (optional)
:param bool client_role: (optional)
:param bool composite: (optional)
:param object composites: (optional)
:param str container_id: (optional)
:param bool scope_param_required: (optional)
"""
payload = OrderedDict(name=name)
for key in ROLE_KWARGS:
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
return self._client.post(
url=self._client.get_full_url(
self.get_path('collection',
realm=self._realm_name,
id=self._client_id)
),
data=json.dumps(payload, sort_keys=True)
) | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"OrderedDict",
"(",
"name",
"=",
"name",
")",
"for",
"key",
"in",
"ROLE_KWARGS",
":",
"if",
"key",
"in",
"kwargs",
":",
"payload",
"[",
"to_camel_case",
"("... | Create new role
http://www.keycloak.org/docs-api/3.4/rest-api/index.html
#_roles_resource
:param str name: Name for the role
:param str description: (optional)
:param str id: (optional)
:param bool client_role: (optional)
:param bool composite: (optional)
:param object composites: (optional)
:param str container_id: (optional)
:param bool scope_param_required: (optional) | [
"Create",
"new",
"role"
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/admin/clientroles.py#L43-L72 | train | 212,852 |
Peter-Slump/python-keycloak-client | src/keycloak/admin/clientroles.py | ClientRole.update | def update(self, name, **kwargs):
"""
Update existing role.
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_roles_resource
:param str name: Name for the role
:param str description: (optional)
:param str id: (optional)
:param bool client_role: (optional)
:param bool composite: (optional)
:param object composites: (optional)
:param str container_id: (optional)
:param bool scope_param_required: (optional)
"""
payload = OrderedDict(name=name)
for key in ROLE_KWARGS:
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
return self._client.put(
url=self._client.get_full_url(
self.get_path('single',
realm=self._realm_name,
id=self._client_id,
role_name=self._role_name)
),
data=json.dumps(payload, sort_keys=True)
) | python | def update(self, name, **kwargs):
"""
Update existing role.
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_roles_resource
:param str name: Name for the role
:param str description: (optional)
:param str id: (optional)
:param bool client_role: (optional)
:param bool composite: (optional)
:param object composites: (optional)
:param str container_id: (optional)
:param bool scope_param_required: (optional)
"""
payload = OrderedDict(name=name)
for key in ROLE_KWARGS:
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
return self._client.put(
url=self._client.get_full_url(
self.get_path('single',
realm=self._realm_name,
id=self._client_id,
role_name=self._role_name)
),
data=json.dumps(payload, sort_keys=True)
) | [
"def",
"update",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"OrderedDict",
"(",
"name",
"=",
"name",
")",
"for",
"key",
"in",
"ROLE_KWARGS",
":",
"if",
"key",
"in",
"kwargs",
":",
"payload",
"[",
"to_camel_case",
"("... | Update existing role.
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_roles_resource
:param str name: Name for the role
:param str description: (optional)
:param str id: (optional)
:param bool client_role: (optional)
:param bool composite: (optional)
:param object composites: (optional)
:param str container_id: (optional)
:param bool scope_param_required: (optional) | [
"Update",
"existing",
"role",
"."
] | 379ae58f3c65892327b0c98c06d4982aa83f357e | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/admin/clientroles.py#L87-L116 | train | 212,853 |
wummel/patool | patoolib/programs/rpm2cpio.py | extract_rpm | def extract_rpm (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a RPM archive."""
# also check cpio
cpio = util.find_program("cpio")
if not cpio:
raise util.PatoolError("cpio(1) is required for rpm2cpio extraction; please install it")
path = util.shell_quote(os.path.abspath(archive))
cmdlist = [util.shell_quote(cmd), path, "|", util.shell_quote(cpio),
'--extract', '--make-directories', '--preserve-modification-time',
'--no-absolute-filenames', '--force-local', '--nonmatching',
r'"*\.\.*"']
if verbosity > 1:
cmdlist.append('-v')
return (cmdlist, {'cwd': outdir, 'shell': True}) | python | def extract_rpm (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a RPM archive."""
# also check cpio
cpio = util.find_program("cpio")
if not cpio:
raise util.PatoolError("cpio(1) is required for rpm2cpio extraction; please install it")
path = util.shell_quote(os.path.abspath(archive))
cmdlist = [util.shell_quote(cmd), path, "|", util.shell_quote(cpio),
'--extract', '--make-directories', '--preserve-modification-time',
'--no-absolute-filenames', '--force-local', '--nonmatching',
r'"*\.\.*"']
if verbosity > 1:
cmdlist.append('-v')
return (cmdlist, {'cwd': outdir, 'shell': True}) | [
"def",
"extract_rpm",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"# also check cpio",
"cpio",
"=",
"util",
".",
"find_program",
"(",
"\"cpio\"",
")",
"if",
"not",
"cpio",
":",
"raise",
"ut... | Extract a RPM archive. | [
"Extract",
"a",
"RPM",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/rpm2cpio.py#L20-L33 | train | 212,854 |
wummel/patool | patoolib/programs/py_tarfile.py | list_tar | def list_tar (archive, compression, cmd, verbosity, interactive):
"""List a TAR archive with the tarfile Python module."""
try:
with tarfile.open(archive) as tfile:
tfile.list(verbose=verbosity>1)
except Exception as err:
msg = "error listing %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | python | def list_tar (archive, compression, cmd, verbosity, interactive):
"""List a TAR archive with the tarfile Python module."""
try:
with tarfile.open(archive) as tfile:
tfile.list(verbose=verbosity>1)
except Exception as err:
msg = "error listing %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | [
"def",
"list_tar",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"try",
":",
"with",
"tarfile",
".",
"open",
"(",
"archive",
")",
"as",
"tfile",
":",
"tfile",
".",
"list",
"(",
"verbose",
"=",
"verbosit... | List a TAR archive with the tarfile Python module. | [
"List",
"a",
"TAR",
"archive",
"with",
"the",
"tarfile",
"Python",
"module",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_tarfile.py#L23-L31 | train | 212,855 |
wummel/patool | patoolib/programs/py_tarfile.py | extract_tar | def extract_tar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a TAR archive with the tarfile Python module."""
try:
with tarfile.open(archive) as tfile:
tfile.extractall(path=outdir)
except Exception as err:
msg = "error extracting %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | python | def extract_tar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a TAR archive with the tarfile Python module."""
try:
with tarfile.open(archive) as tfile:
tfile.extractall(path=outdir)
except Exception as err:
msg = "error extracting %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | [
"def",
"extract_tar",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"try",
":",
"with",
"tarfile",
".",
"open",
"(",
"archive",
")",
"as",
"tfile",
":",
"tfile",
".",
"extractall",
"(",
"... | Extract a TAR archive with the tarfile Python module. | [
"Extract",
"a",
"TAR",
"archive",
"with",
"the",
"tarfile",
"Python",
"module",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_tarfile.py#L35-L43 | train | 212,856 |
wummel/patool | patoolib/programs/py_tarfile.py | create_tar | def create_tar (archive, compression, cmd, verbosity, interactive, filenames):
"""Create a TAR archive with the tarfile Python module."""
mode = get_tar_mode(compression)
try:
with tarfile.open(archive, mode) as tfile:
for filename in filenames:
tfile.add(filename)
except Exception as err:
msg = "error creating %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | python | def create_tar (archive, compression, cmd, verbosity, interactive, filenames):
"""Create a TAR archive with the tarfile Python module."""
mode = get_tar_mode(compression)
try:
with tarfile.open(archive, mode) as tfile:
for filename in filenames:
tfile.add(filename)
except Exception as err:
msg = "error creating %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | [
"def",
"create_tar",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"filenames",
")",
":",
"mode",
"=",
"get_tar_mode",
"(",
"compression",
")",
"try",
":",
"with",
"tarfile",
".",
"open",
"(",
"archive",
",",
... | Create a TAR archive with the tarfile Python module. | [
"Create",
"a",
"TAR",
"archive",
"with",
"the",
"tarfile",
"Python",
"module",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_tarfile.py#L46-L56 | train | 212,857 |
wummel/patool | patoolib/programs/py_tarfile.py | get_tar_mode | def get_tar_mode (compression):
"""Determine tarfile open mode according to the given compression."""
if compression == 'gzip':
return 'w:gz'
if compression == 'bzip2':
return 'w:bz2'
if compression == 'lzma' and py_lzma:
return 'w:xz'
if compression:
msg = 'pytarfile does not support %s for tar compression'
raise util.PatoolError(msg % compression)
# no compression
return 'w' | python | def get_tar_mode (compression):
"""Determine tarfile open mode according to the given compression."""
if compression == 'gzip':
return 'w:gz'
if compression == 'bzip2':
return 'w:bz2'
if compression == 'lzma' and py_lzma:
return 'w:xz'
if compression:
msg = 'pytarfile does not support %s for tar compression'
raise util.PatoolError(msg % compression)
# no compression
return 'w' | [
"def",
"get_tar_mode",
"(",
"compression",
")",
":",
"if",
"compression",
"==",
"'gzip'",
":",
"return",
"'w:gz'",
"if",
"compression",
"==",
"'bzip2'",
":",
"return",
"'w:bz2'",
"if",
"compression",
"==",
"'lzma'",
"and",
"py_lzma",
":",
"return",
"'w:xz'",
... | Determine tarfile open mode according to the given compression. | [
"Determine",
"tarfile",
"open",
"mode",
"according",
"to",
"the",
"given",
"compression",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_tarfile.py#L59-L71 | train | 212,858 |
wummel/patool | patoolib/programs/arj.py | extract_arj | def extract_arj (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an ARJ archive."""
cmdlist = [cmd, 'x', '-r']
if not interactive:
cmdlist.append('-y')
cmdlist.extend([archive, outdir])
return cmdlist | python | def extract_arj (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an ARJ archive."""
cmdlist = [cmd, 'x', '-r']
if not interactive:
cmdlist.append('-y')
cmdlist.extend([archive, outdir])
return cmdlist | [
"def",
"extract_arj",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
",",
"'x'",
",",
"'-r'",
"]",
"if",
"not",
"interactive",
":",
"cmdlist",
".",
"append",
"(... | Extract an ARJ archive. | [
"Extract",
"an",
"ARJ",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/arj.py#L18-L24 | train | 212,859 |
wummel/patool | patoolib/programs/arj.py | list_arj | def list_arj (archive, compression, cmd, verbosity, interactive):
"""List an ARJ archive."""
cmdlist = [cmd]
if verbosity > 1:
cmdlist.append('v')
else:
cmdlist.append('l')
if not interactive:
cmdlist.append('-y')
cmdlist.extend(['-r', archive])
return cmdlist | python | def list_arj (archive, compression, cmd, verbosity, interactive):
"""List an ARJ archive."""
cmdlist = [cmd]
if verbosity > 1:
cmdlist.append('v')
else:
cmdlist.append('l')
if not interactive:
cmdlist.append('-y')
cmdlist.extend(['-r', archive])
return cmdlist | [
"def",
"list_arj",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
"]",
"if",
"verbosity",
">",
"1",
":",
"cmdlist",
".",
"append",
"(",
"'v'",
")",
"else",
":",
"cmdlist",
"... | List an ARJ archive. | [
"List",
"an",
"ARJ",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/arj.py#L27-L37 | train | 212,860 |
wummel/patool | patoolib/programs/arj.py | create_arj | def create_arj (archive, compression, cmd, verbosity, interactive, filenames):
"""Create an ARJ archive."""
cmdlist = [cmd, 'a', '-r']
if not interactive:
cmdlist.append('-y')
cmdlist.append(archive)
cmdlist.extend(filenames)
return cmdlist | python | def create_arj (archive, compression, cmd, verbosity, interactive, filenames):
"""Create an ARJ archive."""
cmdlist = [cmd, 'a', '-r']
if not interactive:
cmdlist.append('-y')
cmdlist.append(archive)
cmdlist.extend(filenames)
return cmdlist | [
"def",
"create_arj",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"filenames",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
",",
"'a'",
",",
"'-r'",
"]",
"if",
"not",
"interactive",
":",
"cmdlist",
".",
"append",
... | Create an ARJ archive. | [
"Create",
"an",
"ARJ",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/arj.py#L49-L56 | train | 212,861 |
wummel/patool | patoolib/programs/zpaq.py | create_zpaq | def create_zpaq(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a ZPAQ archive."""
cmdlist = [cmd, 'a', archive]
cmdlist.extend(filenames)
cmdlist.extend(['-method', '4'])
return cmdlist | python | def create_zpaq(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a ZPAQ archive."""
cmdlist = [cmd, 'a', archive]
cmdlist.extend(filenames)
cmdlist.extend(['-method', '4'])
return cmdlist | [
"def",
"create_zpaq",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"filenames",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
",",
"'a'",
",",
"archive",
"]",
"cmdlist",
".",
"extend",
"(",
"filenames",
")",
"cmdlist... | Create a ZPAQ archive. | [
"Create",
"a",
"ZPAQ",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/zpaq.py#L30-L35 | train | 212,862 |
wummel/patool | patoolib/programs/unalz.py | extract_alzip | def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a ALZIP archive."""
return [cmd, '-d', outdir, archive] | python | def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a ALZIP archive."""
return [cmd, '-d', outdir, archive] | [
"def",
"extract_alzip",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"return",
"[",
"cmd",
",",
"'-d'",
",",
"outdir",
",",
"archive",
"]"
] | Extract a ALZIP archive. | [
"Extract",
"a",
"ALZIP",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/unalz.py#L18-L20 | train | 212,863 |
wummel/patool | patoolib/programs/tar.py | extract_tar | def extract_tar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a TAR archive."""
cmdlist = [cmd, '--extract']
add_tar_opts(cmdlist, compression, verbosity)
cmdlist.extend(["--file", archive, '--directory', outdir])
return cmdlist | python | def extract_tar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a TAR archive."""
cmdlist = [cmd, '--extract']
add_tar_opts(cmdlist, compression, verbosity)
cmdlist.extend(["--file", archive, '--directory', outdir])
return cmdlist | [
"def",
"extract_tar",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
",",
"'--extract'",
"]",
"add_tar_opts",
"(",
"cmdlist",
",",
"compression",
",",
"verbosity",
... | Extract a TAR archive. | [
"Extract",
"a",
"TAR",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/tar.py#L20-L25 | train | 212,864 |
wummel/patool | patoolib/programs/tar.py | add_tar_opts | def add_tar_opts (cmdlist, compression, verbosity):
"""Add tar options to cmdlist."""
progname = os.path.basename(cmdlist[0])
if compression == 'gzip':
cmdlist.append('-z')
elif compression == 'compress':
cmdlist.append('-Z')
elif compression == 'bzip2':
cmdlist.append('-j')
elif compression in ('lzma', 'xz') and progname == 'bsdtar':
cmdlist.append('--%s' % compression)
elif compression in ('lzma', 'xz', 'lzip'):
# use the compression name as program name since
# tar is picky which programs it can use
program = compression
# set compression program
cmdlist.extend(['--use-compress-program', program])
if verbosity > 1:
cmdlist.append('--verbose')
if progname == 'tar':
cmdlist.append('--force-local') | python | def add_tar_opts (cmdlist, compression, verbosity):
"""Add tar options to cmdlist."""
progname = os.path.basename(cmdlist[0])
if compression == 'gzip':
cmdlist.append('-z')
elif compression == 'compress':
cmdlist.append('-Z')
elif compression == 'bzip2':
cmdlist.append('-j')
elif compression in ('lzma', 'xz') and progname == 'bsdtar':
cmdlist.append('--%s' % compression)
elif compression in ('lzma', 'xz', 'lzip'):
# use the compression name as program name since
# tar is picky which programs it can use
program = compression
# set compression program
cmdlist.extend(['--use-compress-program', program])
if verbosity > 1:
cmdlist.append('--verbose')
if progname == 'tar':
cmdlist.append('--force-local') | [
"def",
"add_tar_opts",
"(",
"cmdlist",
",",
"compression",
",",
"verbosity",
")",
":",
"progname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"cmdlist",
"[",
"0",
"]",
")",
"if",
"compression",
"==",
"'gzip'",
":",
"cmdlist",
".",
"append",
"(",
"'-... | Add tar options to cmdlist. | [
"Add",
"tar",
"options",
"to",
"cmdlist",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/tar.py#L44-L64 | train | 212,865 |
wummel/patool | patoolib/programs/py_zipfile.py | list_zip | def list_zip(archive, compression, cmd, verbosity, interactive):
"""List member of a ZIP archive with the zipfile Python module."""
try:
with zipfile.ZipFile(archive, "r") as zfile:
for name in zfile.namelist():
if verbosity >= 0:
print(name)
except Exception as err:
msg = "error listing %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | python | def list_zip(archive, compression, cmd, verbosity, interactive):
"""List member of a ZIP archive with the zipfile Python module."""
try:
with zipfile.ZipFile(archive, "r") as zfile:
for name in zfile.namelist():
if verbosity >= 0:
print(name)
except Exception as err:
msg = "error listing %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | [
"def",
"list_zip",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"try",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"archive",
",",
"\"r\"",
")",
"as",
"zfile",
":",
"for",
"name",
"in",
"zfile",
".",
... | List member of a ZIP archive with the zipfile Python module. | [
"List",
"member",
"of",
"a",
"ZIP",
"archive",
"with",
"the",
"zipfile",
"Python",
"module",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_zipfile.py#L25-L35 | train | 212,866 |
wummel/patool | patoolib/programs/py_zipfile.py | extract_zip | def extract_zip(archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a ZIP archive with the zipfile Python module."""
try:
with zipfile.ZipFile(archive) as zfile:
zfile.extractall(outdir)
except Exception as err:
msg = "error extracting %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | python | def extract_zip(archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a ZIP archive with the zipfile Python module."""
try:
with zipfile.ZipFile(archive) as zfile:
zfile.extractall(outdir)
except Exception as err:
msg = "error extracting %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | [
"def",
"extract_zip",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"try",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"archive",
")",
"as",
"zfile",
":",
"zfile",
".",
"extractall",
"(",
... | Extract a ZIP archive with the zipfile Python module. | [
"Extract",
"a",
"ZIP",
"archive",
"with",
"the",
"zipfile",
"Python",
"module",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_zipfile.py#L39-L47 | train | 212,867 |
wummel/patool | patoolib/programs/py_zipfile.py | create_zip | def create_zip(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a ZIP archive with the zipfile Python module."""
try:
with zipfile.ZipFile(archive, 'w') as zfile:
for filename in filenames:
if os.path.isdir(filename):
write_directory(zfile, filename)
else:
zfile.write(filename)
except Exception as err:
msg = "error creating %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | python | def create_zip(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a ZIP archive with the zipfile Python module."""
try:
with zipfile.ZipFile(archive, 'w') as zfile:
for filename in filenames:
if os.path.isdir(filename):
write_directory(zfile, filename)
else:
zfile.write(filename)
except Exception as err:
msg = "error creating %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | [
"def",
"create_zip",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"filenames",
")",
":",
"try",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"archive",
",",
"'w'",
")",
"as",
"zfile",
":",
"for",
"filename",
... | Create a ZIP archive with the zipfile Python module. | [
"Create",
"a",
"ZIP",
"archive",
"with",
"the",
"zipfile",
"Python",
"module",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_zipfile.py#L50-L62 | train | 212,868 |
wummel/patool | patoolib/programs/py_zipfile.py | write_directory | def write_directory (zfile, directory):
"""Write recursively all directories and filenames to zipfile instance."""
for dirpath, dirnames, filenames in os.walk(directory):
zfile.write(dirpath)
for filename in filenames:
zfile.write(os.path.join(dirpath, filename)) | python | def write_directory (zfile, directory):
"""Write recursively all directories and filenames to zipfile instance."""
for dirpath, dirnames, filenames in os.walk(directory):
zfile.write(dirpath)
for filename in filenames:
zfile.write(os.path.join(dirpath, filename)) | [
"def",
"write_directory",
"(",
"zfile",
",",
"directory",
")",
":",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"zfile",
".",
"write",
"(",
"dirpath",
")",
"for",
"filename",
"in",
"filenames"... | Write recursively all directories and filenames to zipfile instance. | [
"Write",
"recursively",
"all",
"directories",
"and",
"filenames",
"to",
"zipfile",
"instance",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_zipfile.py#L65-L70 | train | 212,869 |
wummel/patool | patoolib/programs/shorten.py | extract_shn | def extract_shn (archive, compression, cmd, verbosity, interactive, outdir):
"""Decompress a SHN archive to a WAV file."""
cmdlist = [util.shell_quote(cmd)]
outfile = util.get_single_outfile(outdir, archive, extension=".wav")
cmdlist.extend(['-x', '-', util.shell_quote(outfile), '<',
util.shell_quote(archive)])
return (cmdlist, {'shell': True}) | python | def extract_shn (archive, compression, cmd, verbosity, interactive, outdir):
"""Decompress a SHN archive to a WAV file."""
cmdlist = [util.shell_quote(cmd)]
outfile = util.get_single_outfile(outdir, archive, extension=".wav")
cmdlist.extend(['-x', '-', util.shell_quote(outfile), '<',
util.shell_quote(archive)])
return (cmdlist, {'shell': True}) | [
"def",
"extract_shn",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"cmdlist",
"=",
"[",
"util",
".",
"shell_quote",
"(",
"cmd",
")",
"]",
"outfile",
"=",
"util",
".",
"get_single_outfile",
... | Decompress a SHN archive to a WAV file. | [
"Decompress",
"a",
"SHN",
"archive",
"to",
"a",
"WAV",
"file",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/shorten.py#L19-L25 | train | 212,870 |
wummel/patool | patoolib/programs/shorten.py | create_shn | def create_shn (archive, compression, cmd, verbosity, interactive, filenames):
"""Compress a WAV file to a SHN archive."""
if len(filenames) > 1:
raise util.PatoolError("multiple filenames for shorten not supported")
cmdlist = [util.shell_quote(cmd)]
cmdlist.extend(['-', util.shell_quote(archive), '<',
util.shell_quote(filenames[0])])
return (cmdlist, {'shell': True}) | python | def create_shn (archive, compression, cmd, verbosity, interactive, filenames):
"""Compress a WAV file to a SHN archive."""
if len(filenames) > 1:
raise util.PatoolError("multiple filenames for shorten not supported")
cmdlist = [util.shell_quote(cmd)]
cmdlist.extend(['-', util.shell_quote(archive), '<',
util.shell_quote(filenames[0])])
return (cmdlist, {'shell': True}) | [
"def",
"create_shn",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"filenames",
")",
":",
"if",
"len",
"(",
"filenames",
")",
">",
"1",
":",
"raise",
"util",
".",
"PatoolError",
"(",
"\"multiple filenames for shor... | Compress a WAV file to a SHN archive. | [
"Compress",
"a",
"WAV",
"file",
"to",
"a",
"SHN",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/shorten.py#L28-L35 | train | 212,871 |
wummel/patool | patoolib/programs/xdms.py | extract_dms | def extract_dms (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a DMS archive."""
check_archive_ext(archive)
cmdlist = [cmd, '-d', outdir]
if verbosity > 1:
cmdlist.append('-v')
cmdlist.extend(['u', archive])
return cmdlist | python | def extract_dms (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a DMS archive."""
check_archive_ext(archive)
cmdlist = [cmd, '-d', outdir]
if verbosity > 1:
cmdlist.append('-v')
cmdlist.extend(['u', archive])
return cmdlist | [
"def",
"extract_dms",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"check_archive_ext",
"(",
"archive",
")",
"cmdlist",
"=",
"[",
"cmd",
",",
"'-d'",
",",
"outdir",
"]",
"if",
"verbosity",
... | Extract a DMS archive. | [
"Extract",
"a",
"DMS",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/xdms.py#L20-L27 | train | 212,872 |
wummel/patool | patoolib/programs/xdms.py | list_dms | def list_dms (archive, compression, cmd, verbosity, interactive):
"""List a DMS archive."""
check_archive_ext(archive)
return [cmd, 'v', archive] | python | def list_dms (archive, compression, cmd, verbosity, interactive):
"""List a DMS archive."""
check_archive_ext(archive)
return [cmd, 'v', archive] | [
"def",
"list_dms",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"check_archive_ext",
"(",
"archive",
")",
"return",
"[",
"cmd",
",",
"'v'",
",",
"archive",
"]"
] | List a DMS archive. | [
"List",
"a",
"DMS",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/xdms.py#L30-L33 | train | 212,873 |
wummel/patool | patoolib/programs/xz.py | list_xz | def list_xz (archive, compression, cmd, verbosity, interactive):
"""List a XZ archive."""
cmdlist = [cmd]
cmdlist.append('-l')
if verbosity > 1:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist | python | def list_xz (archive, compression, cmd, verbosity, interactive):
"""List a XZ archive."""
cmdlist = [cmd]
cmdlist.append('-l')
if verbosity > 1:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist | [
"def",
"list_xz",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
"]",
"cmdlist",
".",
"append",
"(",
"'-l'",
")",
"if",
"verbosity",
">",
"1",
":",
"cmdlist",
".",
"append",
... | List a XZ archive. | [
"List",
"a",
"XZ",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/xz.py#L24-L31 | train | 212,874 |
wummel/patool | patoolib/programs/xz.py | extract_lzma | def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an LZMA archive."""
cmdlist = [util.shell_quote(cmd), '--format=lzma']
if verbosity > 1:
cmdlist.append('-v')
outfile = util.get_single_outfile(outdir, archive)
cmdlist.extend(['-c', '-d', '--', util.shell_quote(archive), '>',
util.shell_quote(outfile)])
return (cmdlist, {'shell': True}) | python | def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an LZMA archive."""
cmdlist = [util.shell_quote(cmd), '--format=lzma']
if verbosity > 1:
cmdlist.append('-v')
outfile = util.get_single_outfile(outdir, archive)
cmdlist.extend(['-c', '-d', '--', util.shell_quote(archive), '>',
util.shell_quote(outfile)])
return (cmdlist, {'shell': True}) | [
"def",
"extract_lzma",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"cmdlist",
"=",
"[",
"util",
".",
"shell_quote",
"(",
"cmd",
")",
",",
"'--format=lzma'",
"]",
"if",
"verbosity",
">",
"... | Extract an LZMA archive. | [
"Extract",
"an",
"LZMA",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/xz.py#L45-L53 | train | 212,875 |
wummel/patool | patoolib/programs/unace.py | extract_ace | def extract_ace (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an ACE archive."""
cmdlist = [cmd, 'x']
if not outdir.endswith('/'):
outdir += '/'
cmdlist.extend([archive, outdir])
return cmdlist | python | def extract_ace (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an ACE archive."""
cmdlist = [cmd, 'x']
if not outdir.endswith('/'):
outdir += '/'
cmdlist.extend([archive, outdir])
return cmdlist | [
"def",
"extract_ace",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
",",
"'x'",
"]",
"if",
"not",
"outdir",
".",
"endswith",
"(",
"'/'",
")",
":",
"outdir",
... | Extract an ACE archive. | [
"Extract",
"an",
"ACE",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/unace.py#L18-L24 | train | 212,876 |
wummel/patool | patoolib/programs/unace.py | list_ace | def list_ace (archive, compression, cmd, verbosity, interactive):
"""List an ACE archive."""
cmdlist = [cmd]
if verbosity > 1:
cmdlist.append('v')
else:
cmdlist.append('l')
cmdlist.append(archive)
return cmdlist | python | def list_ace (archive, compression, cmd, verbosity, interactive):
"""List an ACE archive."""
cmdlist = [cmd]
if verbosity > 1:
cmdlist.append('v')
else:
cmdlist.append('l')
cmdlist.append(archive)
return cmdlist | [
"def",
"list_ace",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
"]",
"if",
"verbosity",
">",
"1",
":",
"cmdlist",
".",
"append",
"(",
"'v'",
")",
"else",
":",
"cmdlist",
"... | List an ACE archive. | [
"List",
"an",
"ACE",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/unace.py#L26-L34 | train | 212,877 |
wummel/patool | patoolib/programs/py_bz2.py | extract_bzip2 | def extract_bzip2 (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a BZIP2 archive with the bz2 Python module."""
targetname = util.get_single_outfile(outdir, archive)
try:
with bz2.BZ2File(archive) as bz2file:
with open(targetname, 'wb') as targetfile:
data = bz2file.read(READ_SIZE_BYTES)
while data:
targetfile.write(data)
data = bz2file.read(READ_SIZE_BYTES)
except Exception as err:
msg = "error extracting %s to %s: %s" % (archive, targetname, err)
raise util.PatoolError(msg)
return None | python | def extract_bzip2 (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a BZIP2 archive with the bz2 Python module."""
targetname = util.get_single_outfile(outdir, archive)
try:
with bz2.BZ2File(archive) as bz2file:
with open(targetname, 'wb') as targetfile:
data = bz2file.read(READ_SIZE_BYTES)
while data:
targetfile.write(data)
data = bz2file.read(READ_SIZE_BYTES)
except Exception as err:
msg = "error extracting %s to %s: %s" % (archive, targetname, err)
raise util.PatoolError(msg)
return None | [
"def",
"extract_bzip2",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"targetname",
"=",
"util",
".",
"get_single_outfile",
"(",
"outdir",
",",
"archive",
")",
"try",
":",
"with",
"bz2",
".",... | Extract a BZIP2 archive with the bz2 Python module. | [
"Extract",
"a",
"BZIP2",
"archive",
"with",
"the",
"bz2",
"Python",
"module",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_bz2.py#L27-L40 | train | 212,878 |
wummel/patool | patoolib/programs/py_bz2.py | create_bzip2 | def create_bzip2 (archive, compression, cmd, verbosity, interactive, filenames):
"""Create a BZIP2 archive with the bz2 Python module."""
if len(filenames) > 1:
raise util.PatoolError('multi-file compression not supported in Python bz2')
try:
with bz2.BZ2File(archive, 'wb') as bz2file:
filename = filenames[0]
with open(filename, 'rb') as srcfile:
data = srcfile.read(READ_SIZE_BYTES)
while data:
bz2file.write(data)
data = srcfile.read(READ_SIZE_BYTES)
except Exception as err:
msg = "error creating %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | python | def create_bzip2 (archive, compression, cmd, verbosity, interactive, filenames):
"""Create a BZIP2 archive with the bz2 Python module."""
if len(filenames) > 1:
raise util.PatoolError('multi-file compression not supported in Python bz2')
try:
with bz2.BZ2File(archive, 'wb') as bz2file:
filename = filenames[0]
with open(filename, 'rb') as srcfile:
data = srcfile.read(READ_SIZE_BYTES)
while data:
bz2file.write(data)
data = srcfile.read(READ_SIZE_BYTES)
except Exception as err:
msg = "error creating %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | [
"def",
"create_bzip2",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"filenames",
")",
":",
"if",
"len",
"(",
"filenames",
")",
">",
"1",
":",
"raise",
"util",
".",
"PatoolError",
"(",
"'multi-file compression not... | Create a BZIP2 archive with the bz2 Python module. | [
"Create",
"a",
"BZIP2",
"archive",
"with",
"the",
"bz2",
"Python",
"module",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_bz2.py#L43-L58 | train | 212,879 |
wummel/patool | patoolib/programs/lha.py | extract_lzh | def extract_lzh (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a LZH archive."""
opts = 'x'
if verbosity > 1:
opts += 'v'
opts += "w=%s" % outdir
return [cmd, opts, archive] | python | def extract_lzh (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a LZH archive."""
opts = 'x'
if verbosity > 1:
opts += 'v'
opts += "w=%s" % outdir
return [cmd, opts, archive] | [
"def",
"extract_lzh",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"opts",
"=",
"'x'",
"if",
"verbosity",
">",
"1",
":",
"opts",
"+=",
"'v'",
"opts",
"+=",
"\"w=%s\"",
"%",
"outdir",
"re... | Extract a LZH archive. | [
"Extract",
"a",
"LZH",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/lha.py#L18-L24 | train | 212,880 |
wummel/patool | patoolib/programs/lha.py | list_lzh | def list_lzh (archive, compression, cmd, verbosity, interactive):
"""List a LZH archive."""
cmdlist = [cmd]
if verbosity > 1:
cmdlist.append('v')
else:
cmdlist.append('l')
cmdlist.append(archive)
return cmdlist | python | def list_lzh (archive, compression, cmd, verbosity, interactive):
"""List a LZH archive."""
cmdlist = [cmd]
if verbosity > 1:
cmdlist.append('v')
else:
cmdlist.append('l')
cmdlist.append(archive)
return cmdlist | [
"def",
"list_lzh",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
"]",
"if",
"verbosity",
">",
"1",
":",
"cmdlist",
".",
"append",
"(",
"'v'",
")",
"else",
":",
"cmdlist",
"... | List a LZH archive. | [
"List",
"a",
"LZH",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/lha.py#L26-L34 | train | 212,881 |
wummel/patool | patoolib/programs/mac.py | extract_ape | def extract_ape (archive, compression, cmd, verbosity, interactive, outdir):
"""Decompress an APE archive to a WAV file."""
outfile = util.get_single_outfile(outdir, archive, extension=".wav")
return [cmd, archive, outfile, '-d'] | python | def extract_ape (archive, compression, cmd, verbosity, interactive, outdir):
"""Decompress an APE archive to a WAV file."""
outfile = util.get_single_outfile(outdir, archive, extension=".wav")
return [cmd, archive, outfile, '-d'] | [
"def",
"extract_ape",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"outfile",
"=",
"util",
".",
"get_single_outfile",
"(",
"outdir",
",",
"archive",
",",
"extension",
"=",
"\".wav\"",
")",
"... | Decompress an APE archive to a WAV file. | [
"Decompress",
"an",
"APE",
"archive",
"to",
"a",
"WAV",
"file",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/mac.py#L19-L22 | train | 212,882 |
wummel/patool | patoolib/programs/unadf.py | extract_adf | def extract_adf (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an ADF archive."""
return [cmd, archive, '-d', outdir] | python | def extract_adf (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an ADF archive."""
return [cmd, archive, '-d', outdir] | [
"def",
"extract_adf",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"return",
"[",
"cmd",
",",
"archive",
",",
"'-d'",
",",
"outdir",
"]"
] | Extract an ADF archive. | [
"Extract",
"an",
"ADF",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/unadf.py#L19-L21 | train | 212,883 |
wummel/patool | patoolib/programs/lrzip.py | extract_lrzip | def extract_lrzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a LRZIP archive."""
cmdlist = [cmd, '-d']
if verbosity > 1:
cmdlist.append('-v')
outfile = util.get_single_outfile(outdir, archive)
cmdlist.extend(["-o", outfile, os.path.abspath(archive)])
return cmdlist | python | def extract_lrzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a LRZIP archive."""
cmdlist = [cmd, '-d']
if verbosity > 1:
cmdlist.append('-v')
outfile = util.get_single_outfile(outdir, archive)
cmdlist.extend(["-o", outfile, os.path.abspath(archive)])
return cmdlist | [
"def",
"extract_lrzip",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
",",
"'-d'",
"]",
"if",
"verbosity",
">",
"1",
":",
"cmdlist",
".",
"append",
"(",
"'-v'"... | Extract a LRZIP archive. | [
"Extract",
"a",
"LRZIP",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/lrzip.py#L20-L27 | train | 212,884 |
wummel/patool | patoolib/programs/py_echo.py | list_bzip2 | def list_bzip2 (archive, compression, cmd, verbosity, interactive):
"""List a BZIP2 archive."""
return stripext(cmd, archive, verbosity) | python | def list_bzip2 (archive, compression, cmd, verbosity, interactive):
"""List a BZIP2 archive."""
return stripext(cmd, archive, verbosity) | [
"def",
"list_bzip2",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"return",
"stripext",
"(",
"cmd",
",",
"archive",
",",
"verbosity",
")"
] | List a BZIP2 archive. | [
"List",
"a",
"BZIP2",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_echo.py#L22-L24 | train | 212,885 |
wummel/patool | patoolib/programs/py_echo.py | list_ape | def list_ape (archive, compression, cmd, verbosity, interactive):
"""List an APE archive."""
return stripext(cmd, archive, verbosity, extension=".wav") | python | def list_ape (archive, compression, cmd, verbosity, interactive):
"""List an APE archive."""
return stripext(cmd, archive, verbosity, extension=".wav") | [
"def",
"list_ape",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"return",
"stripext",
"(",
"cmd",
",",
"archive",
",",
"verbosity",
",",
"extension",
"=",
"\".wav\"",
")"
] | List an APE archive. | [
"List",
"an",
"APE",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_echo.py#L34-L36 | train | 212,886 |
wummel/patool | patoolib/programs/py_echo.py | stripext | def stripext (cmd, archive, verbosity, extension=""):
"""Print the name without suffix."""
if verbosity >= 0:
print(util.stripext(archive)+extension)
return None | python | def stripext (cmd, archive, verbosity, extension=""):
"""Print the name without suffix."""
if verbosity >= 0:
print(util.stripext(archive)+extension)
return None | [
"def",
"stripext",
"(",
"cmd",
",",
"archive",
",",
"verbosity",
",",
"extension",
"=",
"\"\"",
")",
":",
"if",
"verbosity",
">=",
"0",
":",
"print",
"(",
"util",
".",
"stripext",
"(",
"archive",
")",
"+",
"extension",
")",
"return",
"None"
] | Print the name without suffix. | [
"Print",
"the",
"name",
"without",
"suffix",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_echo.py#L42-L46 | train | 212,887 |
wummel/patool | patoolib/programs/ar.py | extract_ar | def extract_ar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a AR archive."""
opts = 'x'
if verbosity > 1:
opts += 'v'
cmdlist = [cmd, opts, os.path.abspath(archive)]
return (cmdlist, {'cwd': outdir}) | python | def extract_ar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a AR archive."""
opts = 'x'
if verbosity > 1:
opts += 'v'
cmdlist = [cmd, opts, os.path.abspath(archive)]
return (cmdlist, {'cwd': outdir}) | [
"def",
"extract_ar",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"opts",
"=",
"'x'",
"if",
"verbosity",
">",
"1",
":",
"opts",
"+=",
"'v'",
"cmdlist",
"=",
"[",
"cmd",
",",
"opts",
",... | Extract a AR archive. | [
"Extract",
"a",
"AR",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/ar.py#L19-L25 | train | 212,888 |
wummel/patool | patoolib/programs/ar.py | list_ar | def list_ar (archive, compression, cmd, verbosity, interactive):
"""List a AR archive."""
opts = 't'
if verbosity > 1:
opts += 'v'
return [cmd, opts, archive] | python | def list_ar (archive, compression, cmd, verbosity, interactive):
"""List a AR archive."""
opts = 't'
if verbosity > 1:
opts += 'v'
return [cmd, opts, archive] | [
"def",
"list_ar",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"opts",
"=",
"'t'",
"if",
"verbosity",
">",
"1",
":",
"opts",
"+=",
"'v'",
"return",
"[",
"cmd",
",",
"opts",
",",
"archive",
"]"
] | List a AR archive. | [
"List",
"a",
"AR",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/ar.py#L27-L32 | train | 212,889 |
wummel/patool | patoolib/programs/ar.py | create_ar | def create_ar (archive, compression, cmd, verbosity, interactive, filenames):
"""Create a AR archive."""
opts = 'rc'
if verbosity > 1:
opts += 'v'
cmdlist = [cmd, opts, archive]
cmdlist.extend(filenames)
return cmdlist | python | def create_ar (archive, compression, cmd, verbosity, interactive, filenames):
"""Create a AR archive."""
opts = 'rc'
if verbosity > 1:
opts += 'v'
cmdlist = [cmd, opts, archive]
cmdlist.extend(filenames)
return cmdlist | [
"def",
"create_ar",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"filenames",
")",
":",
"opts",
"=",
"'rc'",
"if",
"verbosity",
">",
"1",
":",
"opts",
"+=",
"'v'",
"cmdlist",
"=",
"[",
"cmd",
",",
"opts",
... | Create a AR archive. | [
"Create",
"a",
"AR",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/ar.py#L36-L43 | train | 212,890 |
wummel/patool | patoolib/programs/cabextract.py | extract_cab | def extract_cab (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a CAB archive."""
cmdlist = [cmd, '-d', outdir]
if verbosity > 0:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist | python | def extract_cab (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a CAB archive."""
cmdlist = [cmd, '-d', outdir]
if verbosity > 0:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist | [
"def",
"extract_cab",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
",",
"'-d'",
",",
"outdir",
"]",
"if",
"verbosity",
">",
"0",
":",
"cmdlist",
".",
"append"... | Extract a CAB archive. | [
"Extract",
"a",
"CAB",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/cabextract.py#L18-L24 | train | 212,891 |
wummel/patool | patoolib/programs/cabextract.py | list_cab | def list_cab (archive, compression, cmd, verbosity, interactive):
"""List a CAB archive."""
cmdlist = [cmd, '-l']
if verbosity > 0:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist | python | def list_cab (archive, compression, cmd, verbosity, interactive):
"""List a CAB archive."""
cmdlist = [cmd, '-l']
if verbosity > 0:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist | [
"def",
"list_cab",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
",",
"'-l'",
"]",
"if",
"verbosity",
">",
"0",
":",
"cmdlist",
".",
"append",
"(",
"'-v'",
")",
"cmdlist",
... | List a CAB archive. | [
"List",
"a",
"CAB",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/cabextract.py#L26-L32 | train | 212,892 |
wummel/patool | patoolib/programs/rzip.py | extract_rzip | def extract_rzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an RZIP archive."""
cmdlist = [cmd, '-d', '-k']
if verbosity > 1:
cmdlist.append('-v')
outfile = util.get_single_outfile(outdir, archive)
cmdlist.extend(["-o", outfile, archive])
return cmdlist | python | def extract_rzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an RZIP archive."""
cmdlist = [cmd, '-d', '-k']
if verbosity > 1:
cmdlist.append('-v')
outfile = util.get_single_outfile(outdir, archive)
cmdlist.extend(["-o", outfile, archive])
return cmdlist | [
"def",
"extract_rzip",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
",",
"'-d'",
",",
"'-k'",
"]",
"if",
"verbosity",
">",
"1",
":",
"cmdlist",
".",
"append",... | Extract an RZIP archive. | [
"Extract",
"an",
"RZIP",
"archive",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/rzip.py#L19-L26 | train | 212,893 |
wummel/patool | patoolib/__init__.py | program_supports_compression | def program_supports_compression (program, compression):
"""Decide if the given program supports the compression natively.
@return: True iff the program supports the given compression format
natively, else False.
"""
if program in ('tar', ):
return compression in ('gzip', 'bzip2', 'xz', 'lzip', 'compress', 'lzma') + py_lzma
elif program in ('star', 'bsdtar', 'py_tarfile'):
return compression in ('gzip', 'bzip2') + py_lzma
return False | python | def program_supports_compression (program, compression):
"""Decide if the given program supports the compression natively.
@return: True iff the program supports the given compression format
natively, else False.
"""
if program in ('tar', ):
return compression in ('gzip', 'bzip2', 'xz', 'lzip', 'compress', 'lzma') + py_lzma
elif program in ('star', 'bsdtar', 'py_tarfile'):
return compression in ('gzip', 'bzip2') + py_lzma
return False | [
"def",
"program_supports_compression",
"(",
"program",
",",
"compression",
")",
":",
"if",
"program",
"in",
"(",
"'tar'",
",",
")",
":",
"return",
"compression",
"in",
"(",
"'gzip'",
",",
"'bzip2'",
",",
"'xz'",
",",
"'lzip'",
",",
"'compress'",
",",
"'lzm... | Decide if the given program supports the compression natively.
@return: True iff the program supports the given compression format
natively, else False. | [
"Decide",
"if",
"the",
"given",
"program",
"supports",
"the",
"compression",
"natively",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L288-L297 | train | 212,894 |
wummel/patool | patoolib/__init__.py | get_archive_format | def get_archive_format (filename):
"""Detect filename archive format and optional compression."""
mime, compression = util.guess_mime(filename)
if not (mime or compression):
raise util.PatoolError("unknown archive format for file `%s'" % filename)
if mime in ArchiveMimetypes:
format = ArchiveMimetypes[mime]
else:
raise util.PatoolError("unknown archive format for file `%s' (mime-type is `%s')" % (filename, mime))
if format == compression:
# file cannot be in same format compressed
compression = None
return format, compression | python | def get_archive_format (filename):
"""Detect filename archive format and optional compression."""
mime, compression = util.guess_mime(filename)
if not (mime or compression):
raise util.PatoolError("unknown archive format for file `%s'" % filename)
if mime in ArchiveMimetypes:
format = ArchiveMimetypes[mime]
else:
raise util.PatoolError("unknown archive format for file `%s' (mime-type is `%s')" % (filename, mime))
if format == compression:
# file cannot be in same format compressed
compression = None
return format, compression | [
"def",
"get_archive_format",
"(",
"filename",
")",
":",
"mime",
",",
"compression",
"=",
"util",
".",
"guess_mime",
"(",
"filename",
")",
"if",
"not",
"(",
"mime",
"or",
"compression",
")",
":",
"raise",
"util",
".",
"PatoolError",
"(",
"\"unknown archive fo... | Detect filename archive format and optional compression. | [
"Detect",
"filename",
"archive",
"format",
"and",
"optional",
"compression",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L302-L314 | train | 212,895 |
wummel/patool | patoolib/__init__.py | check_archive_format | def check_archive_format (format, compression):
"""Make sure format and compression is known."""
if format not in ArchiveFormats:
raise util.PatoolError("unknown archive format `%s'" % format)
if compression is not None and compression not in ArchiveCompressions:
raise util.PatoolError("unkonwn archive compression `%s'" % compression) | python | def check_archive_format (format, compression):
"""Make sure format and compression is known."""
if format not in ArchiveFormats:
raise util.PatoolError("unknown archive format `%s'" % format)
if compression is not None and compression not in ArchiveCompressions:
raise util.PatoolError("unkonwn archive compression `%s'" % compression) | [
"def",
"check_archive_format",
"(",
"format",
",",
"compression",
")",
":",
"if",
"format",
"not",
"in",
"ArchiveFormats",
":",
"raise",
"util",
".",
"PatoolError",
"(",
"\"unknown archive format `%s'\"",
"%",
"format",
")",
"if",
"compression",
"is",
"not",
"No... | Make sure format and compression is known. | [
"Make",
"sure",
"format",
"and",
"compression",
"is",
"known",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L317-L322 | train | 212,896 |
wummel/patool | patoolib/__init__.py | find_archive_program | def find_archive_program (format, command, program=None):
"""Find suitable archive program for given format and mode."""
commands = ArchivePrograms[format]
programs = []
if program is not None:
# try a specific program first
programs.append(program)
# first try the universal programs with key None
for key in (None, command):
if key in commands:
programs.extend(commands[key])
if not programs:
raise util.PatoolError("%s archive format `%s' is not supported" % (command, format))
# return the first existing program
for program in programs:
if program.startswith('py_'):
# it's a Python module and therefore always supported
return program
exe = util.find_program(program)
if exe:
if program == '7z' and format == 'rar' and not util.p7zip_supports_rar():
continue
return exe
# no programs found
raise util.PatoolError("could not find an executable program to %s format %s; candidates are (%s)," % (command, format, ",".join(programs))) | python | def find_archive_program (format, command, program=None):
"""Find suitable archive program for given format and mode."""
commands = ArchivePrograms[format]
programs = []
if program is not None:
# try a specific program first
programs.append(program)
# first try the universal programs with key None
for key in (None, command):
if key in commands:
programs.extend(commands[key])
if not programs:
raise util.PatoolError("%s archive format `%s' is not supported" % (command, format))
# return the first existing program
for program in programs:
if program.startswith('py_'):
# it's a Python module and therefore always supported
return program
exe = util.find_program(program)
if exe:
if program == '7z' and format == 'rar' and not util.p7zip_supports_rar():
continue
return exe
# no programs found
raise util.PatoolError("could not find an executable program to %s format %s; candidates are (%s)," % (command, format, ",".join(programs))) | [
"def",
"find_archive_program",
"(",
"format",
",",
"command",
",",
"program",
"=",
"None",
")",
":",
"commands",
"=",
"ArchivePrograms",
"[",
"format",
"]",
"programs",
"=",
"[",
"]",
"if",
"program",
"is",
"not",
"None",
":",
"# try a specific program first",... | Find suitable archive program for given format and mode. | [
"Find",
"suitable",
"archive",
"program",
"for",
"given",
"format",
"and",
"mode",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L325-L349 | train | 212,897 |
wummel/patool | patoolib/__init__.py | list_formats | def list_formats ():
"""Print information about available archive formats to stdout."""
print("Archive programs of", App)
print("Archive programs are searched in the following directories:")
print(util.system_search_path())
print()
for format in ArchiveFormats:
print(format, "files:")
for command in ArchiveCommands:
programs = ArchivePrograms[format]
if command not in programs and None not in programs:
print(" %8s: - (not supported)" % command)
continue
try:
program = find_archive_program(format, command)
print(" %8s: %s" % (command, program), end=' ')
if format == 'tar':
encs = [x for x in ArchiveCompressions if util.find_program(x)]
if encs:
print("(supported compressions: %s)" % ", ".join(encs), end=' ')
elif format == '7z':
if util.p7zip_supports_rar():
print("(rar archives supported)", end=' ')
else:
print("(rar archives not supported)", end=' ')
print()
except util.PatoolError:
# display information what programs can handle this archive format
handlers = programs.get(None, programs.get(command))
print(" %8s: - (no program found; install %s)" %
(command, util.strlist_with_or(handlers))) | python | def list_formats ():
"""Print information about available archive formats to stdout."""
print("Archive programs of", App)
print("Archive programs are searched in the following directories:")
print(util.system_search_path())
print()
for format in ArchiveFormats:
print(format, "files:")
for command in ArchiveCommands:
programs = ArchivePrograms[format]
if command not in programs and None not in programs:
print(" %8s: - (not supported)" % command)
continue
try:
program = find_archive_program(format, command)
print(" %8s: %s" % (command, program), end=' ')
if format == 'tar':
encs = [x for x in ArchiveCompressions if util.find_program(x)]
if encs:
print("(supported compressions: %s)" % ", ".join(encs), end=' ')
elif format == '7z':
if util.p7zip_supports_rar():
print("(rar archives supported)", end=' ')
else:
print("(rar archives not supported)", end=' ')
print()
except util.PatoolError:
# display information what programs can handle this archive format
handlers = programs.get(None, programs.get(command))
print(" %8s: - (no program found; install %s)" %
(command, util.strlist_with_or(handlers))) | [
"def",
"list_formats",
"(",
")",
":",
"print",
"(",
"\"Archive programs of\"",
",",
"App",
")",
"print",
"(",
"\"Archive programs are searched in the following directories:\"",
")",
"print",
"(",
"util",
".",
"system_search_path",
"(",
")",
")",
"print",
"(",
")",
... | Print information about available archive formats to stdout. | [
"Print",
"information",
"about",
"available",
"archive",
"formats",
"to",
"stdout",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L352-L382 | train | 212,898 |
wummel/patool | patoolib/__init__.py | check_program_compression | def check_program_compression(archive, command, program, compression):
"""Check if a program supports the given compression."""
program = os.path.basename(program)
if compression:
# check if compression is supported
if not program_supports_compression(program, compression):
if command == 'create':
comp_command = command
else:
comp_command = 'extract'
comp_prog = find_archive_program(compression, comp_command)
if not comp_prog:
msg = "cannot %s archive `%s': compression `%s' not supported"
raise util.PatoolError(msg % (command, archive, compression)) | python | def check_program_compression(archive, command, program, compression):
"""Check if a program supports the given compression."""
program = os.path.basename(program)
if compression:
# check if compression is supported
if not program_supports_compression(program, compression):
if command == 'create':
comp_command = command
else:
comp_command = 'extract'
comp_prog = find_archive_program(compression, comp_command)
if not comp_prog:
msg = "cannot %s archive `%s': compression `%s' not supported"
raise util.PatoolError(msg % (command, archive, compression)) | [
"def",
"check_program_compression",
"(",
"archive",
",",
"command",
",",
"program",
",",
"compression",
")",
":",
"program",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"program",
")",
"if",
"compression",
":",
"# check if compression is supported",
"if",
"not... | Check if a program supports the given compression. | [
"Check",
"if",
"a",
"program",
"supports",
"the",
"given",
"compression",
"."
] | d7e64d9fd60faaa4b3f824bd97c43ce59b185c40 | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L385-L398 | train | 212,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.