code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
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) | Helper function to plot the Muller potential | 3.56454 | 3.493285 | 1.020398 |
value = True
for i, X in enumerate(sequences):
if not isinstance(X, np.ndarray):
if (not allow_trajectory) and isinstance(X, md.Trajectory):
value = False
break
if not isinstance(X, md.Trajectory) and X.ndim != ndim:
value = False
break
if max_iter is not None and i >= max_iter:
break
if not value:
raise ValueError('sequences must be a list of sequences') | def check_iter_of_sequences(sequences, allow_trajectory=False, ndim=2,
max_iter=None) | Check that ``sequences`` is a iterable of trajectory-like sequences,
suitable as input to ``fit()`` for estimators following the MSMBuilder
API.
Parameters
----------
sequences : object
The object to check
allow_trajectory : bool
Are ``md.Trajectory``s allowed?
ndim : int
The expected dimensionality of the sequences
max_iter : int, optional
Only check at maximum the first ``max_iter`` entries in ``sequences``. | 2.696543 | 2.850149 | 0.946106 |
X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
if force_all_finite:
_assert_all_finite(X_2d)
if X is X_2d and copy:
X_2d = _safe_copy(X_2d)
return X_2d | def array2d(X, dtype=None, order=None, copy=False, force_all_finite=True) | Returns at least 2-d array with data from X | 2.07291 | 2.155992 | 0.961465 |
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) | 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. | 3.746758 | 5.00804 | 0.748149 |
self._build_counts(sequences)
# use a dict like a switch statement: dispatch to different
# transition matrix estimators depending on the value of
# self.reversible_type
fit_method_map = {
'mle': self._fit_mle,
'transpose': self._fit_transpose,
'none': self._fit_asymetric}
try:
# pull out the appropriate method
fit_method = fit_method_map[str(self.reversible_type).lower()]
# step 3. estimate transition matrix
self.transmat_, self.populations_ = fit_method(self.countsmat_)
except KeyError:
raise ValueError('reversible_type must be one of %s: %s' % (
', '.join(fit_method_map.keys()), self.reversible_type))
self._is_dirty = True
return self | def fit(self, sequences, y=None) | Estimate model parameters.
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
-------
self
Notes
-----
`None` and `NaN` are recognized immediately as invalid labels.
Therefore, transition counts from or to a sequence item which is NaN or
None will not be counted. The mapping_ attribute will not include the
NaN or None. | 5.310899 | 5.772287 | 0.920068 |
r
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') | 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. | 2.809679 | 2.859441 | 0.982597 |
r
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) | 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. | 5.177042 | 6.042725 | 0.85674 |
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) | Return some diagnostic summary statistics about this Markov model | 2.533422 | 2.497684 | 1.014309 |
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) | 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. | 11.569642 | 12.683118 | 0.912208 |
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) | 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. | 4.292411 | 4.104525 | 1.045775 |
# 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) | 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. | 7.616336 | 8.300938 | 0.917527 |
return np.concatenate([self.features[feat].partial_transform(traj)
for feat in self.which_feat], axis=1) | def partial_transform(self, traj) | Featurize an MD trajectory into a vector space.
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory. | 5.954515 | 11.51773 | 0.516987 |
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) | 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 | 4.261335 | 3.566614 | 1.194785 |
features_list = self.feat.describe_features(traj)
return [features_list[i] for i in self.indices] | def describe_features(self, traj) | Returns a sliced version of the feature descriptor
Parameters
----------
traj : MDtraj trajectory object
Returns
-------
list of sliced dictionaries describing each feature. | 4.580416 | 5.347209 | 0.856599 |
check_iter_of_sequences(sequences)
s = super(MultiSequencePreprocessingMixin, self)
s.fit(self._concat(sequences))
return self | def fit(self, sequences, y=None) | Fit Preprocessing to X.
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.
y : None
Ignored
Returns
-------
self | 15.502545 | 21.251339 | 0.729486 |
s = super(MultiSequencePreprocessingMixin, self)
return s.transform(sequence) | 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) | 12.956225 | 17.694736 | 0.732208 |
s = super(MultiSequencePreprocessingMixin, self)
if hasattr(s, 'fit'):
return s.fit(sequence)
return self | def partial_fit(self, sequence, y=None) | Fit Preprocessing to X.
Parameters
----------
sequence : array-like, [sequence_length, n_features]
A multivariate timeseries.
y : None
Ignored
Returns
-------
self | 7.573755 | 8.963161 | 0.844987 |
return self.partial_fit(np.concatenate(X, axis=0)) | def fit(self, X, y=None) | Fit Preprocessing to X.
Parameters
----------
sequence : array-like, [sequence_length, n_features]
A multivariate timeseries.
y : None
Ignored
Returns
-------
self | 8.166861 | 16.840052 | 0.484966 |
check_iter_of_sequences(sequences)
for sequence in sequences:
s = super(MultiSequencePreprocessingMixin, self)
s.partial_fit(sequence)
return self | def fit(self, sequences, y=None) | Fit Preprocessing to X.
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.
y : None
Ignored
Returns
-------
self | 11.977576 | 16.829081 | 0.711719 |
# check to make sure topologies are consistent with the reference frame
try:
assert traj.top == self.reference_frame.top
except:
warnings.warn("The topology of the trajectory is not" +
"the same as that of the reference frame," +
"which might give meaningless results.")
distances, _ = md.compute_contacts(traj, self.contacts,
self.scheme, ignore_nonprotein=False,
periodic = self.periodic)
return self._transform(distances) | def partial_transform(self, traj) | Featurize an MD trajectory into a vector space derived from
residue-residue distances
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories | 7.193724 | 7.658197 | 0.93935 |
feature_descs = []
# fill in the atom indices using just the first frame
distances, residue_indices = md.compute_contacts(traj[0],
self.contacts, self.scheme,
ignore_nonprotein=False,
periodic=self.periodic)
top = traj.topology
aind = []
resseqs = []
resnames = []
for resid_ids in residue_indices:
aind += ["N/A"]
resseqs += [[top.residue(ri).resSeq for ri in resid_ids]]
resnames += [[top.residue(ri).name for ri in resid_ids]]
zippy = itertools.product(["Ligand Contact"], [self.scheme],
["N/A"],
zip(aind, resseqs, residue_indices, resnames))
feature_descs.extend(dict_maker(zippy))
return feature_descs | def describe_features(self, traj) | Return a list of dictionaries describing the contacts features.
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 dihedral
- resnames: unique names of residues
- atominds: the four atom indicies
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: Contact
- featuregroup: ca, heavy etc. | 6.571094 | 6.014325 | 1.092574 |
# check to make sure topologies are consistent with the reference frame
try:
assert traj.top == self.reference_frame.top
except:
warnings.warn("The topology of the trajectory is not" +
"the same as that of the reference frame," +
"which might give meaningless results.")
X = np.zeros((traj.n_frames, self.n_features))
for f in range(self.n_features):
frame = self.reference_traj[f]
traj.superpose(frame, atom_indices=self.align_indices)
X[:,f] = self._naive_rmsd(traj, frame, self.calculate_indices)
return X | def partial_transform(self, traj) | Featurize an MD trajectory into a vector space via distance
after superposition
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, shape=(n_frames, n_ref_frames)
The RMSD value of each frame of the input trajectory to be
featurized versus each frame in the reference trajectory. The
number of features is the number of reference frames.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories | 5.132881 | 4.84587 | 1.059228 |
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) | Retry a function `max_retries` times. | 1.997395 | 1.933396 | 1.033102 |
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) | 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. | 3.782146 | 2.822734 | 1.339888 |
lines = [s.strip() for s in cls.__doc__.splitlines()]
note_i = lines.index("Notes")
return "\n".join(lines[note_i + 2:]) | def description(cls) | Get a description from the Notes section of the docstring. | 4.238931 | 2.977722 | 1.423548 |
generic_keys = set(properties.keys()) - set(exclude_list)
for generic_key in generic_keys:
self.__setattr__(
self._convert_to_snake_case(generic_key),
properties[generic_key],
) | def set_generic_keys(self, properties, exclude_list) | Sets all the key value pairs that were not set manually in __init__. | 2.853903 | 2.442372 | 1.168497 |
star_resources = []
for statement in self.statements:
if not statement.resource:
continue
if statement.resource == "*" or (isinstance(statement.resource, list) and "*" in statement.resource):
star_resources.append(statement)
return star_resources | def star_resource_statements(self) | Find statements with a resources that is a * or has a * in it. | 2.9098 | 2.524237 | 1.152744 |
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) | Find statements which allow wildcard actions.
A pattern can be specified for the wildcard action | 4.98648 | 4.755055 | 1.048669 |
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) | Find statements which allow wildcard principals.
A pattern can be specified for the wildcard principal | 4.94492 | 4.473185 | 1.105458 |
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) | Find non whitelisted allowed principals. | 3.953676 | 3.61427 | 1.093907 |
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) | Find allowed not-principals. | 4.091753 | 3.354367 | 1.219829 |
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) | Parses and sets parameters in the model. | 2.790042 | 2.688282 | 1.037853 |
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) | Parses and sets resources in the model using a factory. | 2.227008 | 1.971234 | 1.129753 |
if self._session is None:
self._session = requests.Session()
self._session.headers.update(self._headers)
return self._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 | 2.531342 | 2.57665 | 0.982416 |
if self._client is None:
self._client = KeycloakClient(server_url=self._server_url,
headers=self._headers)
return self._client | def client(self) | :rtype: keycloak.client.KeycloakClient | 3.896165 | 2.61988 | 1.487154 |
return KeycloakOpenidConnect(realm=self, client_id=client_id,
client_secret=client_secret) | 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 | 4.828731 | 4.15101 | 1.163267 |
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) | 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) | 4.427022 | 4.890455 | 0.905237 |
return self._client.get(
url=self._client.get_full_url(
self.get_path('collection', realm=self._realm_name)
)
) | def all(self) | Return all registered users
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource | 7.393078 | 4.95914 | 1.490798 |
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) | Return registered user with the given user id.
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource | 4.768811 | 3.967529 | 1.20196 |
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) | 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 | 3.964881 | 3.832154 | 1.034635 |
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) | 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 | 5.023178 | 5.402681 | 0.929756 |
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) | 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 | 4.894165 | 4.83914 | 1.011371 |
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) | 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 | 6.448932 | 7.113332 | 0.906598 |
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) | 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 | 5.454419 | 5.664816 | 0.962859 |
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) | 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 | 4.393842 | 5.240376 | 0.838459 |
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) | 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 | 5.88362 | 7.309687 | 0.804907 |
return self._realm.client.delete(
'{}/{}'.format(self.well_known['policy_endpoint'], id),
headers=self.get_headers(token)
) | 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 | 6.368392 | 8.749663 | 0.727844 |
return self._realm.client.get(
self.well_known['policy_endpoint'],
headers=self.get_headers(token),
**kwargs
) | def permission_list(self, token, **kwargs) | Querying permission
https://www.keycloak.org/docs/latest/authorization_services/index.html#querying-permission
:param str token: client access token
:param str resource: (optional)
:param str name: (optional)
:param str scope: (optional)
:rtype: dict | 6.850407 | 11.314564 | 0.60545 |
headers = {"Authorization": "Bearer %s" % token}
url = self._realm.client.get_full_url(
PATH_ENTITLEMENT.format(self._realm.realm_name, self._client_id)
)
return self._realm.client.get(url, headers=headers) | def entitlement(self, token) | Client applications can use a specific endpoint to obtain a special
security token called a requesting party token (RPT). This token
consists of all the entitlements (or permissions) for a user as a
result of the evaluation of the permissions and authorization policies
associated with the resources being requested. With an RPT, client
applications can gain access to protected resources at the resource
server.
http://www.keycloak.org/docs/latest/authorization_services/index
.html#_service_entitlement_api
:rtype: dict | 3.704324 | 3.992744 | 0.927764 |
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) | Permission information is encoded in an authorization token. | 2.282079 | 2.129614 | 1.071593 |
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) | 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 | 2.674719 | 2.807078 | 0.952848 |
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) | 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 | 4.602666 | 5.534023 | 0.831703 |
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) | 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 | 2.822711 | 3.010509 | 0.937619 |
return self._client.post(
url=self._client.get_full_url(
self.get_path(
'single', realm=self._realm_name, id=self._user_id
)
),
data=json.dumps(roles, sort_keys=True)
) | def add(self, roles) | :param roles: _rolerepresentation array keycloak api | 4.191003 | 3.695123 | 1.134198 |
return jwt.decode(
token, key,
audience=kwargs.pop('audience', None) or self._client_id,
algorithms=algorithms or ['RS256'], **kwargs
) | def decode_token(self, token, key, algorithms=None, **kwargs) | A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
structure that represents a cryptographic key. This specification
also defines a JWK Set JSON data structure that represents a set of
JWKs. Cryptographic algorithms and identifiers for use with this
specification are described in the separate JSON Web Algorithms (JWA)
specification and IANA registries established by that specification.
https://tools.ietf.org/html/rfc7517
:param str token: A signed JWS to be verified.
:param str key: A key to attempt to verify the payload with.
:param str,list algorithms: (optional) Valid algorithms that should be
used to verify the JWS. Defaults to `['RS256']`
:param str audience: (optional) The intended audience of the token. If
the "aud" claim is included in the claim set, then the audience
must be included and must equal the provided claim.
:param str,iterable issuer: (optional) Acceptable value(s) for the
issuer of the token. If the "iss" claim is included in the claim
set, then the issuer must be given and the claim in the token must
be among the acceptable values.
:param str subject: (optional) The subject of the token. If the "sub"
claim is included in the claim set, then the subject must be
included and must equal the provided claim.
:param str access_token: (optional) An access token returned alongside
the id_token during the authorization grant flow. If the "at_hash"
claim is included in the claim set, then the access_token must be
included, and it must match the "at_hash" claim.
:param dict options: (optional) A dictionary of options for skipping
validation steps.
defaults:
.. code-block:: python
{
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'leeway': 0,
}
:return: The dict representation of the claims set, assuming the
signature is valid and all requested data validation passes.
:rtype: dict
:raises jose.exceptions.JWTError: If the signature is invalid in any
way.
:raises jose.exceptions.ExpiredSignatureError: If the signature has
expired.
:raises jose.exceptions.JWTClaimsError: If any claim is invalid in any
way. | 3.88221 | 5.799247 | 0.669433 |
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) | The logout endpoint logs out the authenticated user.
:param str refresh_token: | 3.457398 | 4.344213 | 0.795863 |
url = self.well_known['userinfo_endpoint']
return self._realm.client.get(url, headers={
"Authorization": "Bearer {}".format(
token
)
}) | 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 | 7.999733 | 7.810247 | 1.024261 |
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) | 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 | 3.79753 | 3.925326 | 0.967443 |
return self._token_request(grant_type='authorization_code', code=code,
redirect_uri=redirect_uri) | 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 | 3.580948 | 5.307037 | 0.674755 |
return self._token_request(grant_type='password',
username=username, password=password,
**kwargs) | 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 | 5.249111 | 6.124967 | 0.857002 |
return self._token_request(grant_type='refresh_token',
refresh_token=refresh_token, **kwargs) | 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 | 3.897741 | 5.466653 | 0.713003 |
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) | Do the actual call to the token end-point.
:param grant_type:
:param kwargs: See invoking methods.
:return: | 2.838407 | 3.252654 | 0.872643 |
async with req_ctx as response:
try:
response.raise_for_status()
except aiohttp.client.ClientResponseError as cre:
text = await response.text(errors='replace')
self.logger.debug('{cre}; '
'Request info: {cre.request_info}; '
'Response headers: {cre.headers}; '
'Response status: {cre.status}; '
'Content: {text}'.format(cre=cre, text=text))
raise KeycloakClientError(original_exc=cre)
try:
result = await response.json(content_type=None)
except ValueError:
result = await response.read()
return result | async def _handle_response(self, req_ctx) -> Any | :param aiohttp.client._RequestContextManager req_ctx
:return: | 3.228522 | 3.09973 | 1.041549 |
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) | 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) | 4.401087 | 4.382604 | 1.004217 |
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) | 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) | 4.004014 | 4.022539 | 0.995395 |
# 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) | Extract a RPM archive. | 6.061433 | 6.224617 | 0.973784 |
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) | List a TAR archive with the tarfile Python module. | 4.091401 | 4.178373 | 0.979185 |
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) | Extract a TAR archive with the tarfile Python module. | 3.373628 | 3.417433 | 0.987182 |
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) | Create a TAR archive with the tarfile Python module. | 3.362991 | 3.29165 | 1.021673 |
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) | Determine tarfile open mode according to the given compression. | 3.336429 | 3.331508 | 1.001477 |
cmdlist = [util.shell_quote(cmd)]
if verbosity > 1:
cmdlist.append('-v')
cmdlist.extend(['-c', '--'])
cmdlist.extend([util.shell_quote(x) for x in filenames])
cmdlist.extend(['>', util.shell_quote(archive)])
return (cmdlist, {'shell': True}) | def create_singlefile_standard (archive, compression, cmd, verbosity, interactive, filenames) | Standard routine to create a singlefile archive (like gzip). | 3.390628 | 3.356664 | 1.010118 |
cmdlist = [cmd, '-n']
add_star_opts(cmdlist, compression, verbosity)
cmdlist.append("file=%s" % archive)
return cmdlist | def list_tar (archive, compression, cmd, verbosity, interactive) | List a TAR archive. | 8.692081 | 8.431235 | 1.030938 |
cmdlist = [cmd, '-c']
add_star_opts(cmdlist, compression, verbosity)
cmdlist.append("file=%s" % archive)
cmdlist.extend(filenames)
return cmdlist | def create_tar (archive, compression, cmd, verbosity, interactive, filenames) | Create a TAR archive. | 6.11434 | 6.03195 | 1.013659 |
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) | Extract an ARJ archive. | 4.437896 | 4.287957 | 1.034967 |
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) | List an ARJ archive. | 3.138335 | 3.121249 | 1.005474 |
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) | Create an ARJ archive. | 3.85667 | 3.935459 | 0.97998 |
cmdlist = [cmd, 'a', archive]
cmdlist.extend(filenames)
cmdlist.extend(['-method', '4'])
return cmdlist | def create_zpaq(archive, compression, cmd, verbosity, interactive, filenames) | Create a ZPAQ archive. | 7.211496 | 7.373081 | 0.978084 |
return [cmd, '-d', outdir, archive] | def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir) | Extract a ALZIP archive. | 16.532717 | 18.566353 | 0.890467 |
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) | Extract a TAR archive. | 4.830472 | 4.669214 | 1.034537 |
cmdlist = [cmd, '--list']
add_tar_opts(cmdlist, compression, verbosity)
cmdlist.extend(["--file", archive])
return cmdlist | def list_tar (archive, compression, cmd, verbosity, interactive) | List a TAR archive. | 5.636677 | 5.478647 | 1.028845 |
cmdlist = [cmd, '--create']
add_tar_opts(cmdlist, compression, verbosity)
cmdlist.extend(["--file", archive, '--'])
cmdlist.extend(filenames)
return cmdlist | def create_tar (archive, compression, cmd, verbosity, interactive, filenames) | Create a TAR archive. | 4.800838 | 4.531335 | 1.059475 |
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) | Add tar options to cmdlist. | 3.601314 | 3.44281 | 1.046039 |
# archmage can only extract in non-existing directories
# so a nice dirname is created
name = util.get_single_outfile("", archive)
outfile = os.path.join(outdir, name)
return [cmd, '-x', os.path.abspath(archive), outfile] | def extract_chm (archive, compression, cmd, verbosity, interactive, outdir) | Extract a CHM archive. | 13.252467 | 14.876823 | 0.890813 |
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) | List member of a ZIP archive with the zipfile Python module. | 3.137389 | 3.18537 | 0.984937 |
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) | Extract a ZIP archive with the zipfile Python module. | 3.085525 | 3.247449 | 0.950138 |
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) | Create a ZIP archive with the zipfile Python module. | 2.69245 | 2.791517 | 0.964511 |
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) | Write recursively all directories and filenames to zipfile instance. | 1.99054 | 1.702591 | 1.169124 |
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) | Decompress a SHN archive to a WAV file. | 7.698307 | 6.607451 | 1.165095 |
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) | Compress a WAV file to a SHN archive. | 6.710344 | 6.632543 | 1.01173 |
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) | Extract a DMS archive. | 5.136802 | 4.997931 | 1.027786 |
check_archive_ext(archive)
return [cmd, 'v', archive] | def list_dms (archive, compression, cmd, verbosity, interactive) | List a DMS archive. | 22.264875 | 23.31345 | 0.955023 |
if not archive.lower().endswith(".dms"):
rest = archive[-4:]
msg = "xdms(1) archive file must end with `.dms', not `%s'" % rest
raise util.PatoolError(msg) | def check_archive_ext (archive) | xdms(1) cannot handle files with extensions other than '.dms'. | 11.193983 | 6.451819 | 1.735012 |
cmdlist = [cmd]
cmdlist.append('-l')
if verbosity > 1:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist | def list_xz (archive, compression, cmd, verbosity, interactive) | List a XZ archive. | 3.191787 | 3.108344 | 1.026845 |
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) | Extract an LZMA archive. | 4.60701 | 4.716743 | 0.976736 |
cmdlist = [cmd, 'x']
if not outdir.endswith('/'):
outdir += '/'
cmdlist.extend([archive, outdir])
return cmdlist | def extract_ace (archive, compression, cmd, verbosity, interactive, outdir) | Extract an ACE archive. | 4.960293 | 4.787302 | 1.036135 |
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) | List an ACE archive. | 3.589509 | 3.430534 | 1.046341 |
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) | Extract a BZIP2 archive with the bz2 Python module. | 2.761298 | 2.761226 | 1.000026 |
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) | Create a BZIP2 archive with the bz2 Python module. | 2.73223 | 2.669788 | 1.023389 |
return [cmd, os.path.abspath(archive), outdir] | def extract_chm (archive, compression, cmd, verbosity, interactive, outdir) | Extract a CHM archive. | 12.110789 | 14.009627 | 0.864462 |
opts = 'x'
if verbosity > 1:
opts += 'v'
opts += "w=%s" % outdir
return [cmd, opts, archive] | def extract_lzh (archive, compression, cmd, verbosity, interactive, outdir) | Extract a LZH archive. | 6.695606 | 6.621155 | 1.011244 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.