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 ...
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 ...
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 ...
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, ...
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 ...
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): ...
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...
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_mappi...
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 ord...
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...
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...
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_ei...
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, ...
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 ------...
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...
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 Dictiona...
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. ...
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 ...
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," + ...
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...
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, ...
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 informati...
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," + ...
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) ...
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...
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: ...
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) retur...
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...
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...
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 b...
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( ...
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 :para...
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)...
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: (optiona...
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 cla...
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 acc...
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 th...
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...
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 (...
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', [...
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: bool...
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 desc...
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, ...
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. Thes...
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...
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. ...
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 aut...
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=pa...
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 ...
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', ...
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) ...
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', re...
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) :...
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), '--extr...
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 ...
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.appe...
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 cre...
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) dat...
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) ...
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