code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
for var in self.variables.values(): for n, dim in enumerate(var.dimensions): if dim == name: var._h5ds.dims[n].detach_scale(self._all_h5groups[dim]) for subgroup in self.groups.values(): if dim not in subgroup._h5group: subgroup._detach_dim_scale(name)
def _detach_dim_scale(self, name)
Detach the dimension scale corresponding to a dimension name.
4.773755
4.551906
1.048737
if self.dimensions[dimension] is not None: raise ValueError("Dimension '%s' is not unlimited and thus " "cannot be resized." % dimension) # Resize the dimension. self._current_dim_sizes[dimension] = size for var in self.variables.values(): new_shape = list(var.shape) for i, d in enumerate(var.dimensions): if d == dimension: new_shape[i] = size new_shape = tuple(new_shape) if new_shape != var.shape: var._h5ds.resize(new_shape) # Recurse as dimensions are visible to this group and all child groups. for i in self.groups.values(): i.resize_dimension(dimension, size)
def resize_dimension(self, dimension, size)
Resize a dimension to a certain size. It will pad with the underlying HDF5 data sets' fill values (usually zero) where necessary.
3.789677
3.432199
1.104154
return np.array([ q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3], q1[2]*q2[3] - q2[2]*q1[3] + q1[0]*q2[1] + q2[0]*q1[1], q1[3]*q2[1] - q2[3]*q1[1] + q1[0]*q2[2] + q2[0]*q1[2], q1[1]*q2[2] - q2[1]*q1[2] + q1[0]*q2[3] + q2[0]*q1[3]])
def multiplyQuats(q1, q2)
q1, q2 must be [scalar, x, y, z] but those may be arrays or scalars
1.308399
1.307145
1.000959
qConj = -q qConj[0] = -qConj[0] normSqr = multiplyQuats(q, qConj)[0] return qConj/normSqr
def quatInv(q)
Returns QBar such that Q*QBar = 1
4.708818
5.046292
0.933124
alpha = np.arctan2(vec[1], vec[0]) beta = np.arccos(vec[2]) gamma = -alpha*vec[2] cb = np.cos(0.5*beta) sb = np.sin(0.5*beta) return np.array([cb*np.cos(0.5*(alpha + gamma)), sb*np.sin(0.5*(gamma - alpha)), sb*np.cos(0.5*(gamma - alpha)), cb*np.sin(0.5*(alpha + gamma))])
def alignVec_quat(vec)
Returns a unit quaternion that will align vec with the z-axis
2.319339
2.320387
0.999548
qInv = quatInv(quat) if inverse: return transformTimeDependentVector(qInv, vec, inverse=0) return multiplyQuats(quat, multiplyQuats(np.append(np.array([ np.zeros(len(vec[0]))]), vec, 0), qInv))[1:]
def transformTimeDependentVector(quat, vec, inverse=0)
Given (for example) a minimal rotation frame quat, transforms vec from the minimal rotation frame to the inertial frame. With inverse=1, transforms from the inertial frame to the minimal rotation frame.
5.230852
5.767856
0.906897
v = chi.T sp = np.sin(phase) cp = np.cos(phase) res = 1.*v res[0] = v[0]*cp + v[1]*sp res[1] = v[1]*cp - v[0]*sp return res.T
def rotate_in_plane(chi, phase)
For transforming spins between the coprecessing and coorbital frames
2.749116
2.803828
0.980487
# Transform to coprecessing frame vec_copr = rotate_in_plane(vec_coorb, -orbPhase) # Transform to inertial frame vec = transformTimeDependentVector(np.array([quat_copr]).T, np.array([vec_copr]).T).T[0] return np.array(vec)
def transform_vector_coorb_to_inertial(vec_coorb, orbPhase, quat_copr)
Given a vector (of size 3) in coorbital frame, orbital phase in coprecessing frame and a minimal rotation frame quat, transforms the vector from the coorbital to the inertial frame.
4.790807
4.328659
1.106765
# for reproducibility np.random.seed(0) # Get distribution in coorbital frame dist_coorb = np.array([np.random.normal(m, s, 1000) for m,s in zip(vec_coorb, vec_err_coorb)]).T # Transform distribution to coprecessing frame dist_copr = rotate_in_plane(dist_coorb, -orbPhase) # Transform distribution to inertial frame dist_inertial = transformTimeDependentVector( np.array([quat_copr for _ in dist_copr]).T, dist_copr.T).T # Get 1sigma width in inertial frame vec_err_inertial = np.std(dist_inertial, axis=0) return vec_err_inertial
def transform_error_coorb_to_inertial(vec_coorb, vec_err_coorb, orbPhase, quat_copr)
Transform error in a vector from the coorbital frame to the inertial frame. Generates distributions in the coorbital frame, transforms them to inertial frame and returns 1-simga widths in the inertial frame.
3.456278
2.963145
1.166422
fits = {} for key in ['mf']: fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file) for key in ['chif', 'vf']: fits[key] = self._load_vector_fit(key, h5file) return fits
def _load_fits(self, h5file)
Loads fits from h5file and returns a dictionary of fits.
4.691084
4.427013
1.05965
# larger than default sometimes needed when extrapolating omega_switch_test = 0.019 extra_args = [] extra_args.append({ 'omega0': 5e-3, 'PN_approximant': 'SpinTaylorT4', 'PN_dt': 0.1, 'PN_spin_order': 7, 'PN_phase_order': 7, 'omega_switch': omega_switch_test, }) extra_args.append({ 'omega0': 6e-3, 'PN_approximant': 'SpinTaylorT1', 'PN_dt': 0.5, 'PN_spin_order': 5, 'PN_phase_order': 7, 'omega_switch': omega_switch_test, }) extra_args.append({ 'omega0': 7e-3, 'PN_approximant': 'SpinTaylorT2', 'PN_dt': 1, 'PN_spin_order': 7, 'PN_phase_order': 5, 'omega_switch': omega_switch_test, }) # These should be pure NRSur7dq2 extra_args.append({'omega0': 3e-2}) extra_args.append({'omega0': 5e-2}) return extra_args
def _extra_regression_kwargs(self)
List of additional kwargs to use in regression tests.
2.930598
2.887976
1.014758
q, chiAz, chiBz = x[0], x[3], x[6] eta = q/(1.+q)**2 chi_wtAvg = (q*chiAz+chiBz)/(1.+q) chiHat = (chi_wtAvg - 38.*eta/113.*(chiAz + chiBz))/(1. - 76.*eta/113.) chi_a = (chiAz - chiBz)/2. fit_params = x fit_params[0] = np.log(q) fit_params[3] = chiHat fit_params[6] = chi_a return fit_params
def _get_fit_params(self, x, fit_key)
Transforms the input parameter to fit parameters for the 7dq2 model. That is, maps from x = [q, chiAx, chiAy, chiAz, chiBx, chiBy, chiBz] fit_params = [np.log(q), chiAx, chiAy, chiHat, chiBx, chiBy, chi_a] chiHat is defined in Eq.(3) of 1508.07253, but with chiAz and chiBz instead of chiA and chiB. chi_a = (chiAz - chiBz)/2.
5.261687
3.632421
1.448535
if omega0 < omega0_nrsur: # If omega0 is below the NRSur7dq2 start frequency, we use PN # to evolve the spins until orbital frequency = omega0_nrsur. # Note that we update omega0_nrsur here with the PN # frequency that was closest to the input omega0_nrsur. chiA0_nrsur_copr, chiB0_nrsur_copr, quat0_nrsur_copr, \ phi0_nrsur, omega0_nrsur \ = evolve_pn_spins(q, chiA0, chiB0, omega0, omega0_nrsur, approximant=PN_approximant, dt=PN_dt, spinO=PN_spin0, phaseO=PN_phase0) else: # If omega0>= omega0_nrsur, we evolve spins directly with NRSur7dq2 # waveform model. We set the coprecessing frame quaternion to # identity and orbital phase to 0 at omega=omega0, hence the # coprecessing frame is the same as the inertial frame here. # Note that we update omega0_nrsur here and set it to omega0 chiA0_nrsur_copr, chiB0_nrsur_copr, quat0_nrsur_copr, \ phi0_nrsur, omega0_nrsur \ = chiA0, chiB0, [1,0,0,0], 0, omega0 # Load NRSur7dq2 if needed if self.nrsur is None: self._load_NRSur7dq2() # evaluate NRSur7dq2 dynamics # We set allow_extrapolation=True always since we test param limits # independently quat, orbphase, chiA_copr, chiB_copr = self.nrsur.get_dynamics(q, chiA0_nrsur_copr, chiB0_nrsur_copr, init_quat=quat0_nrsur_copr, init_phase=phi0_nrsur, omega_ref=omega0_nrsur, allow_extrapolation=True) # get data at time node where remnant fits are done fitnode_time = -100 nodeIdx = np.argmin(np.abs(self.nrsur.tds - fitnode_time)) quat_fitnode = quat.T[nodeIdx] orbphase_fitnode = orbphase[nodeIdx] # get coorbital frame spins at the time node chiA_coorb_fitnode = utils.rotate_in_plane(chiA_copr[nodeIdx], orbphase_fitnode) chiB_coorb_fitnode = utils.rotate_in_plane(chiB_copr[nodeIdx], orbphase_fitnode) return chiA_coorb_fitnode, chiB_coorb_fitnode, quat_fitnode, \ orbphase_fitnode
def _evolve_spins(self, q, chiA0, chiB0, omega0, PN_approximant, PN_dt, PN_spin0, PN_phase0, omega0_nrsur)
Evolves spins of the component BHs from an initial orbital frequency = omega0 until t=-100 M from the peak of the waveform. If omega0 < omega0_nrsur, use PN to evolve the spins until orbital frequency = omega0. Then evolves further with the NRSur7dq2 waveform model until t=-100M from the peak. Assumes chiA0 and chiB0 are defined in the inertial frame defined at orbital frequency = omega0 as: The z-axis is along the Newtonian orbital angular momentum when the PN orbital frequency = omega0. The x-axis is along the line of separation from the smaller BH to the larger BH at this frequency. The y-axis completes the triad. Returns spins in the coorbital frame at t=-100M, as well as the coprecessing frame quaternion and orbital phase in the coprecessing frame at this time.
3.340267
2.857323
1.16902
chiA = np.array(chiA) chiB = np.array(chiB) # Warn/Exit if extrapolating allow_extrap = kwargs.pop('allow_extrap', False) self._check_param_limits(q, chiA, chiB, allow_extrap) omega0 = kwargs.pop('omega0', None) PN_approximant = kwargs.pop('PN_approximant', 'SpinTaylorT4') PN_dt = kwargs.pop('PN_dt', 0.1) PN_spin_order = kwargs.pop('PN_spin_order', 7) PN_phase_order = kwargs.pop('PN_phase_order', 7) omega_switch = kwargs.pop('omega_switch', 0.018) self._check_unused_kwargs(kwargs) if omega0 is None: # If omega0 is given, assume chiA, chiB are the coorbital frame # spins at t=-100 M. x = np.concatenate(([q], chiA, chiB)) else: # If omega0 is given, evolve the spins from omega0 # to t = -100 M from the peak. chiA_coorb_fitnode, chiB_coorb_fitnode, quat_fitnode, \ orbphase_fitnode \ = self._evolve_spins(q, chiA, chiB, omega0, PN_approximant, PN_dt, PN_spin_order, PN_phase_order, omega_switch) # x should contain coorbital frame spins at t=-100M x = np.concatenate(([q], chiA_coorb_fitnode, chiB_coorb_fitnode)) def eval_vector_fit(x, fit_key): res = self._evaluate_fits(x, fit_key) fit_val = res.T[0] fit_err = res.T[1] if omega0 is not None: # If spins were given in inertial frame at omega0, # transform vectors and errors back to the same frame. fit_val = utils.transform_vector_coorb_to_inertial(fit_val, orbphase_fitnode, quat_fitnode) fit_err = utils.transform_error_coorb_to_inertial(fit_val, fit_err, orbphase_fitnode, quat_fitnode) return fit_val, fit_err if fit_key == 'mf' or fit_key == 'all': mf, mf_err = self._evaluate_fits(x, 'mf') if fit_key == 'mf': return mf, mf_err if fit_key == 'chif' or fit_key == 'all': chif, chif_err = eval_vector_fit(x, 'chif') if fit_key == 'chif': return chif, chif_err if fit_key == 'vf' or fit_key == 'all': vf, vf_err = eval_vector_fit(x, 'vf') if fit_key == 'vf': return vf, vf_err if fit_key == 'all': return mf, chif, vf, mf_err, chif_err, vf_err
def _eval_wrapper(self, fit_key, q, chiA, chiB, **kwargs)
Evaluates the surfinBH7dq2 model.
2.779106
2.774267
1.001744
if name not in fits_collection.keys(): raise Exception('Invalid fit name : %s'%name) else: testPath = DataPath() + '/' + fits_collection[name].data_url.split('/')[-1] if (not os.path.isfile(testPath)): DownloadData(name) fit = fits_collection[name].fit_class(name.split('surfinBH')[-1]) print('Loaded %s fit.'%name) return fit
def LoadFits(name)
Loads data for a fit. If data is not available, downloads it before loading.
5.930563
5.571562
1.064435
if name == 'all': for tmp_name in fits_collection.keys(): DownloadData(name=tmp_name, data_dir=data_dir) return if name not in fits_collection.keys(): raise Exception('Invalid fit name : %s'%name) print('Downloading %s data'%name) data_url = fits_collection[name].data_url filename = data_url.split('/')[-1] try: os.makedirs(data_dir) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(data_dir): pass else: raise urlretrieve(data_url, data_dir + '/' + filename)
def DownloadData(name='all', data_dir=DataPath())
Downloads fit data to DataPath() diretory. If name='all', gets all fit data.
2.247849
2.302146
0.976415
fits = {} for key in ['mf', 'chifz', 'vfx', 'vfy']: fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file) return fits
def _load_fits(self, h5file)
Loads fits from h5file and returns a dictionary of fits.
8.751637
8.075635
1.083709
chiA = np.array(chiA) chiB = np.array(chiB) # Warn/Exit if extrapolating allow_extrap = kwargs.pop('allow_extrap', False) self._check_param_limits(q, chiA, chiB, allow_extrap) self._check_unused_kwargs(kwargs) x = [q, chiA[2], chiB[2]] if fit_key == 'mf' or fit_key == 'all': mf, mf_err = self._evaluate_fits(x, 'mf') if fit_key == 'mf': return mf, mf_err if fit_key == 'chif' or fit_key == 'all': chifz, chifz_err = self._evaluate_fits(x, 'chifz') chif = np.array([0,0,chifz]) chif_err = np.array([0,0,chifz_err]) if fit_key == 'chif': return chif, chif_err if fit_key == 'vf' or fit_key == 'all': vfx, vfx_err = self._evaluate_fits(x, 'vfx') vfy, vfy_err = self._evaluate_fits(x, 'vfy') vf = np.array([vfx, vfy, 0]) vf_err = np.array([vfx_err, vfy_err, 0]) if fit_key == 'vf': return vf, vf_err if fit_key == 'all': return mf, chif, vf, mf_err, chif_err, vf_err
def _eval_wrapper(self, fit_key, q, chiA, chiB, **kwargs)
Evaluates the surfinBH3dq8 model.
2.132817
2.149694
0.992149
omega, phi, chiA, chiB, lNhat, e1 = lal_spin_evloution_wrapper(approximant, q, omega0, chiA0, chiB0, dt, spinO, phaseO) # Compute omega, inertial spins, angular momentum direction and orbital # phase when omega = omegaTimesM_final end_idx = np.argmin(np.abs(omega - omegaTimesM_final)) omegaTimesM_end = omega[end_idx] chiA_end = chiA[end_idx] chiB_end = chiB[end_idx] lNhat_end = lNhat[end_idx] phi_end = phi[end_idx] # Align the z-direction along orbital angular momentum direction # at end_idx. This moves us in to the coprecessing frame. q_copr_end = _utils.alignVec_quat(lNhat_end) chiA_end_copr = _utils.transformTimeDependentVector( np.array([q_copr_end]).T, np.array([chiA_end]).T, inverse=1).T[0] chiB_end_copr = _utils.transformTimeDependentVector( np.array([q_copr_end]).T, np.array([chiB_end]).T, inverse=1).T[0] return chiA_end_copr, chiB_end_copr, q_copr_end, phi_end, omegaTimesM_end
def evolve_pn_spins(q, chiA0, chiB0, omega0, omegaTimesM_final, approximant='SpinTaylorT4', dt=0.1, spinO=7, phaseO=7)
Evolves PN spins from a starting orbital frequency and spins to a final frequency. Inputs: q: Mass ratio (q>=1) chiA0: Dimless spin of BhA at initial freq. chiB0: Dimless spin of BhB at initial freq. omega0: Initial orbital frequency in dimless units. omegaTimesM_final: Final orbital frequency in dimless units. approximant: 'SpinTaylorT1/T2/T4'. Default: 'SpinTaylorT4'. dt: Dimless step time for evolution. Default: 0.1 . spinO: Twice PN order of spin effects. Default: 5 . phaseO: Twice PN order in phase. Default: 8 . Outputs (all are time series): chiA_end_copr: Spin of BhA at final frequency, in coprecessing frame. chiB_end_copr: Spin of BhB at final frequency, in coprecessing frame. q_copr_end: Coprecessing frame quaternion at final frequency. phi_end: Orbital phase in the coprecessing frame at final frequency. omegaTimesM_end Dimensionless final frequency. Should agree with omegaTimesM_final. The inertial frame is assumed to be aligned to the coorbital frame at orbital frequency = omega0. chiA0 and chiB0 are the inertial/coorbital frame spins at omega0.
3.783738
3.16295
1.196269
if type(value) in (tuple, list): for v in value: if v is None: return True return False else: return value is None
def is_null(value)
Check if the scalar value or tuple/list value is NULL. :param value: Value to check. :type value: a scalar or tuple or list :return: Returns ``True`` if and only if the value is NULL (scalar value is None or _any_ tuple/list elements are None). :rtype: bool
2.518008
2.712021
0.928462
return u'{}.{}'.format(obj.__class__.__module__, obj.__class__.__name__)
def qual(obj)
Return fully qualified name of a class.
5.015184
3.926693
1.277203
assert type(return_keys) == bool assert type(return_values) == bool assert type(reverse) == bool assert limit is None or (type(limit) == int and limit > 0 and limit < 10000000) return PersistentMapIterator(txn, self, from_key=from_key, to_key=to_key, return_keys=return_keys, return_values=return_values, reverse=reverse, limit=limit)
def select(self, txn, from_key=None, to_key=None, return_keys=True, return_values=True, reverse=False, limit=None)
Select all records (key-value pairs) in table, optionally within a given key range. :param txn: The transaction in which to run. :type txn: :class:`zlmdb.Transaction` :param from_key: Return records starting from (and including) this key. :type from_key: object :param to_key: Return records up to (but not including) this key. :type to_key: object :param return_keys: If ``True`` (default), return keys of records. :type return_keys: bool :param return_values: If ``True`` (default), return values of records. :type return_values: bool :param limit: Limit number of records returned. :type limit: int :return:
1.952073
2.286962
0.853566
key_from = struct.pack('>H', self._slot) if prefix: key_from += self._serialize_key(prefix) kfl = len(key_from) cnt = 0 cursor = txn._txn.cursor() has_more = cursor.set_range(key_from) while has_more: _key = cursor.key() _prefix = _key[:kfl] if _prefix != key_from: break cnt += 1 has_more = cursor.next() return cnt
def count(self, txn, prefix=None)
Count number of records in the persistent map. When no prefix is given, the total number of records is returned. When a prefix is given, only the number of records with keys that have this prefix are counted. :param txn: The transaction in which to run. :type txn: :class:`zlmdb.Transaction` :param prefix: The key prefix of records to count. :type prefix: object :returns: The number of records. :rtype: int
3.633453
3.998526
0.908698
key_from = struct.pack('>H', self._slot) + self._serialize_key(from_key) to_key = struct.pack('>H', self._slot) + self._serialize_key(to_key) cnt = 0 cursor = txn._txn.cursor() has_more = cursor.set_range(key_from) while has_more: if cursor.key() >= to_key: break cnt += 1 has_more = cursor.next() return cnt
def count_range(self, txn, from_key, to_key)
Counter number of records in the perstistent map with keys within the given range. :param txn: The transaction in which to run. :type txn: :class:`zlmdb.Transaction` :param from_key: Count records starting and including from this key. :type from_key: object :param to_key: End counting records before this key. :type to_key: object :returns: The number of records. :rtype: int
2.853572
3.047471
0.936374
rng = random.SystemRandom() token_value = u''.join(rng.choice(CHARSET) for _ in range(CHAR_GROUPS * CHARS_PER_GROUP)) if CHARS_PER_GROUP > 1: return GROUP_SEP.join(map(u''.join, zip(*[iter(token_value)] * CHARS_PER_GROUP))) else: return token_value
def _random_string()
Generate a globally unique serial / product code of the form ``u'YRAC-EL4X-FQQE-AW4T-WNUV-VN6T'``. The generated value is cryptographically strong and has (at least) 114 bits of entropy. :return: new random string key
3.780056
3.962365
0.95399
d = {} for k, item in f.items(): if type(item) == h5py._hl.dataset.Dataset: v = item.value if type(v) == np.string_: v = str(v) if type(v) == str and v == "NONE": d[k] = None elif type(v) == str and v == "EMPTYARR": d[k] = np.array([]) elif isinstance(v, bytes): d[k] = v.decode('utf-8') else: d[k] = v elif k[:5] == "DICT_": d[k[5:]] = self._read_dict(item) elif k[:5] == "LIST_": tmpD = self._read_dict(item) d[k[5:]] = [tmpD[str(i)] for i in range(len(tmpD))] return d
def _read_dict(self, f)
Converts h5 groups to dictionaries
2.427604
2.282336
1.063649
if (fit_key is None) ^ (h5file is None): raise ValueError("Either specify both fit_key and h5file, or" " neither") if not ((fit_key is None) ^ (fit_data is None)): raise ValueError("Specify exactly one of fit_key and fit_data.") if fit_data is None: fit_data = self._read_dict(h5file[fit_key]) if 'fitType' in fit_data.keys() and fit_data['fitType'] == 'GPR': fit = _eval_pysur.evaluate_fit.getGPRFitAndErrorEvaluator(fit_data) else: fit = _eval_pysur.evaluate_fit.getFitEvaluator(fit_data) return fit
def _load_scalar_fit(self, fit_key=None, h5file=None, fit_data=None)
Loads a single fit
3.219804
3.221387
0.999509
vector_fit = [] for i in range(len(h5file[fit_key].keys())): fit_data = self._read_dict(h5file[fit_key]['comp_%d'%i]) vector_fit.append(self._load_scalar_fit(fit_data=fit_data)) return vector_fit
def _load_vector_fit(self, fit_key, h5file)
Loads a vector of fits
3.239037
3.128265
1.03541
fit = self.fits[fit_key] fit_params = self._get_fit_params(np.copy(x), fit_key) if type(fit) == list: res = [] for i in range(len(fit)): res.append(fit[i](fit_params)) return np.array(res) else: return fit(fit_params)
def _evaluate_fits(self, x, fit_key)
Evaluates a particular fit by passing fit_key to self.fits. Assumes self._get_fit_params() has been overriden.
2.328681
2.113578
1.101772
if len(kwargs.keys()) != 0: unused = "" for k in kwargs.keys(): unused += "'%s', "%k if unused[-2:] == ", ": # get rid of trailing comma unused = unused[:-2] raise Exception('Unused keys in kwargs: %s'%unused)
def _check_unused_kwargs(self, kwargs)
Call this at the end of call module to check if all the kwargs have been used. Assumes kwargs were extracted using pop.
3.977343
3.796614
1.047603
if q < 1: raise ValueError('Mass ratio should be >= 1.') chiAmag = np.sqrt(np.sum(chiA**2)) chiBmag = np.sqrt(np.sum(chiB**2)) if chiAmag > 1 + 1e-14: raise ValueError('Spin magnitude of BhA > 1.') if chiBmag > 1 + 1e-14: raise ValueError('Spin magnitude of BhB > 1.') if self.aligned_spin_only: if np.sqrt(np.sum(chiA[:2]**2)) > 1e-14: raise ValueError('The x & y components of chiA should be zero.') if np.sqrt(np.sum(chiB[:2]**2)) > 1e-14: raise ValueError('The x & y components of chiB should be zero.') # Do not check param limits if allow_extrap=True if allow_extrap: return if q > self.hard_param_lims['q']+ 1e-14: raise ValueError('Mass ratio outside allowed range.') elif q > self.soft_param_lims['q']: warnings.warn('Mass ratio outside training range.') if chiAmag > self.hard_param_lims['chiAmag']+ 1e-14: raise ValueError('Spin magnitude of BhA outside allowed range.') elif chiAmag > self.soft_param_lims['chiAmag']: warnings.warn('Spin magnitude of BhA outside training range.') if chiBmag > self.hard_param_lims['chiBmag']+ 1e-14: raise ValueError('Spin magnitude of BhB outside allowed range.') elif chiBmag > self.soft_param_lims['chiBmag']: warnings.warn('Spin magnitude of BhB outside training range.')
def _check_param_limits(self, q, chiA, chiB, allow_extrap)
Checks that params are within allowed range of paramters. Raises a warning if outside self.soft_param_lims limits and raises an error if outside self.hard_param_lims. If allow_extrap=True, skips these checks.
2.048388
1.94329
1.054082
def decorate(o): assert isinstance(o, PersistentMap) name = o.__class__.__name__ assert slot_index not in self._index_to_slot assert name not in self._name_to_slot o._zlmdb_slot = slot_index o._zlmdb_marshal = marshal o._zlmdb_unmarshal = unmarshal o._zlmdb_build = build o._zlmdb_cast = cast o._zlmdb_compress = compress _slot = Slot(slot_index, name, o) self._index_to_slot[slot_index] = _slot self._name_to_slot[name] = _slot return o return decorate
def slot(self, slot_index, marshal=None, unmarshal=None, build=None, cast=None, compress=False)
Decorator for use on classes derived from zlmdb.PersistentMap. The decorator define slots in a LMDB database schema based on persistent maps, and slot configuration. :param slot_index: :param marshal: :param unmarshal: :param build: :param cast: :param compress: :return:
2.53001
2.221075
1.139092
return os.path.abspath('%s/data'%(os.path.dirname( \ os.path.realpath(__file__))))
def DataPath()
Return the default path for fit data h5 files
4.061231
4.276274
0.949713
try: encalg = kwargs["request_object_encryption_alg"] except KeyError: try: encalg = service_context.behaviour["request_object_encryption_alg"] except KeyError: return msg if not encalg: return msg try: encenc = kwargs["request_object_encryption_enc"] except KeyError: try: encenc = service_context.behaviour["request_object_encryption_enc"] except KeyError: raise MissingRequiredAttribute( "No request_object_encryption_enc specified") if not encenc: raise MissingRequiredAttribute( "No request_object_encryption_enc specified") _jwe = JWE(msg, alg=encalg, enc=encenc) _kty = alg2keytype(encalg) try: _kid = kwargs["enc_kid"] except KeyError: _kid = "" if "target" not in kwargs: raise MissingRequiredAttribute("No target specified") if _kid: _keys = service_context.keyjar.get_encrypt_key(_kty, owner=kwargs["target"], kid=_kid) _jwe["kid"] = _kid else: _keys = service_context.keyjar.get_encrypt_key(_kty, owner=kwargs["target"]) return _jwe.encrypt(_keys)
def request_object_encryption(msg, service_context, **kwargs)
Created an encrypted JSON Web token with *msg* as body. :param msg: The mesaqg :param service_context: :param kwargs: :return:
2.26869
2.340202
0.969442
_filedir = local_dir if not os.path.isdir(_filedir): os.makedirs(_filedir) _webpath = base_path _name = rndstr(10) + ".jwt" filename = os.path.join(_filedir, _name) while os.path.exists(filename): _name = rndstr(10) filename = os.path.join(_filedir, _name) _webname = "%s%s" % (_webpath, _name) return filename, _webname
def construct_request_uri(local_dir, base_path, **kwargs)
Constructs a special redirect_uri to be used when communicating with one OP. Each OP should get their own redirect_uris. :param local_dir: Local directory in which to place the file :param base_path: Base URL to start with :param kwargs: :return: 2-tuple with (filename, url)
2.907377
2.687207
1.081933
service = {} for service_name, service_configuration in service_definitions.items(): try: kwargs = service_configuration['kwargs'] except KeyError: kwargs = {} kwargs.update({'service_context': service_context, 'state_db': state_db, 'client_authn_factory': client_authn_factory}) if isinstance(service_configuration['class'], str): _srv = util.importer(service_configuration['class'])(**kwargs) else: _srv = service_configuration['class'](**kwargs) try: service[_srv.service_name] = _srv except AttributeError: raise ValueError("Could not load '{}'".format(service_name)) return service
def init_services(service_definitions, service_context, state_db, client_authn_factory=None)
Initiates a set of services :param service_definitions: A dictionary cotaining service definitions :param service_context: A reference to the service context, this is the same for all service instances. :param state_db: A reference to the state database. Shared by all the services. :param client_authn_factory: A list of methods the services can use to authenticate the client to a service. :return: A dictionary, with service name as key and the service instance as value.
2.263986
2.355318
0.961223
ar_args = kwargs.copy() # Go through the list of claims defined for the message class # there are a couple of places where informtation can be found # access them in the order of priority # 1. A keyword argument # 2. configured set of default attribute values # 3. default attribute values defined in the OIDC standard document for prop in self.msg_type.c_param.keys(): if prop in ar_args: continue else: try: ar_args[prop] = getattr(self.service_context, prop) except AttributeError: try: ar_args[prop] = self.conf['request_args'][prop] except KeyError: try: ar_args[prop] = self.service_context.register_args[ prop] except KeyError: try: ar_args[prop] = self.default_request_args[prop] except KeyError: pass return ar_args
def gather_request_args(self, **kwargs)
Go through the attributes that the message class can contain and add values if they are missing but exists in the client info or when there are default values. :param kwargs: Initial set of attributes. :return: Possibly augmented set of attributes
5.078773
4.81261
1.055305
try: _args = self.conf[context].copy() except KeyError: _args = kwargs else: _args.update(kwargs) return _args
def method_args(self, context, **kwargs)
Collect the set of arguments that should be used by a set of methods :param context: Which service we're working for :param kwargs: A set of keyword arguments that are added at run-time. :return: A set of keyword arguments
4.528187
5.058547
0.895156
_args = self.method_args('pre_construct', **kwargs) post_args = {} for meth in self.pre_construct: request_args, _post_args = meth(request_args, service=self, **_args) post_args.update(_post_args) return request_args, post_args
def do_pre_construct(self, request_args, **kwargs)
Will run the pre_construct methods one by one in the order given. :param request_args: Request arguments :param kwargs: Extra key word arguments :return: A tuple of request_args and post_args. post_args are to be used by the post_construct methods.
3.884093
3.311571
1.172885
_args = self.method_args('post_construct', **kwargs) for meth in self.post_construct: request_args = meth(request_args, service=self, **_args) return request_args
def do_post_construct(self, request_args, **kwargs)
Will run the post_construct methods one at the time in order. :param request_args: Request arguments :param kwargs: Arguments used by the post_construct method :return: Possible modified set of request arguments.
5.082613
5.419499
0.937838
if request_args is None: request_args = {} # run the pre_construct methods. Will return a possibly new # set of request arguments but also a set of arguments to # be used by the post_construct methods. request_args, post_args = self.do_pre_construct(request_args, **kwargs) # If 'state' appears among the keyword argument and is not # expected to appear in the request, remove it. if 'state' in self.msg_type.c_param and 'state' in kwargs: # Don't overwrite something put there by the constructor if 'state' not in request_args: request_args['state'] = kwargs['state'] # logger.debug("request_args: %s" % sanitize(request_args)) _args = self.gather_request_args(**request_args) # logger.debug("kwargs: %s" % sanitize(kwargs)) # initiate the request as in an instance of the self.msg_type # message type request = self.msg_type(**_args) return self.do_post_construct(request, **post_args)
def construct(self, request_args=None, **kwargs)
Instantiate the request as a message class instance with attribute values gathered in a pre_construct method or in the gather_request_args method. :param request_args: :param kwargs: extra keyword arguments :return: message class instance
4.891737
4.758821
1.027931
if http_args is None: http_args = {} if authn_method: logger.debug('Client authn method: {}'.format(authn_method)) return self.client_authn_factory(authn_method).construct( request, self, http_args=http_args, **kwargs) else: return http_args
def init_authentication_method(self, request, authn_method, http_args=None, **kwargs)
Will run the proper client authentication method. Each such method will place the necessary information in the necessary place. A method may modify the request. :param request: The request, a Message class instance :param authn_method: Client authentication method :param http_args: HTTP header arguments :param kwargs: Extra keyword arguments :return: Extended set of HTTP header arguments
3.114008
3.134629
0.993422
if request_args is None: request_args = {} # remove arguments that should not be included in the request # _args = dict( # [(k, v) for k, v in kwargs.items() if v and k not in SPECIAL_ARGS]) return self.construct(request_args, **kwargs)
def construct_request(self, request_args=None, **kwargs)
The method where everything is setup for sending the request. The request information is gathered and the where and how of sending the request is decided. :param request_args: Initial request arguments :param kwargs: Extra keyword arguments :return: A dictionary with the keys 'url' and possibly 'body', 'kwargs', 'request' and 'ht_args'.
4.114796
4.56827
0.900734
if self.endpoint: return self.endpoint else: return self.service_context.provider_info[self.endpoint_name]
def get_endpoint(self)
Find the service endpoint :return: The service endpoint (a URL)
5.725232
6.388963
0.896113
headers = {} # If I should deal with client authentication if authn_method: h_arg = self.init_authentication_method(request, authn_method, **kwargs) try: headers = h_arg['headers'] except KeyError: pass return headers
def get_authn_header(self, request, authn_method, **kwargs)
Construct an authorization specification to be sent in the HTTP header. :param request: The service request :param authn_method: Which authentication/authorization method to use :param kwargs: Extra keyword arguments :return: A set of keyword arguments to be sent in the HTTP header.
6.101291
6.884531
0.886232
if not method: method = self.http_method if not authn_method: authn_method = self.get_authn_method() if not request_body_type: request_body_type = self.request_body_type request = self.construct_request(request_args=request_args, **kwargs) _info = {'method': method} _args = kwargs.copy() if self.service_context.issuer: _args['iss'] = self.service_context.issuer # Client authentication by usage of the Authorization HTTP header # or by modifying the request object _headers = self.get_authn_header(request, authn_method, authn_endpoint=self.endpoint_name, **_args) # Find out where to send this request try: endpoint_url = kwargs['endpoint'] except KeyError: endpoint_url = self.get_endpoint() _info['url'] = get_http_url(endpoint_url, request, method=method) # If there is to be a body part if method == 'POST': # How should it be serialized if request_body_type == 'urlencoded': content_type = URL_ENCODED elif request_body_type in ['jws', 'jwe', 'jose']: content_type = JOSE_ENCODED else: # request_body_type == 'json' content_type = JSON_ENCODED _info['body'] = get_http_body(request, content_type) _headers.update({'Content-Type': content_type}) if _headers: _info['headers'] = _headers return _info
def get_request_parameters(self, request_body_type="", method="", authn_method='', request_args=None, http_args=None, **kwargs)
Builds the request message and constructs the HTTP headers. This is the starting point for a pipeline that will: - construct the request message - add/remove information to/from the request message in the way a specific client authentication method requires. - gather a set of HTTP headers like Content-type and Authorization. - serialize the request message into the necessary format (JSON, urlencoded, signed JWT) :param request_body_type: Which serialization to use for the HTTP body :param method: HTTP method used. :param authn_method: Client authentication method :param request_args: Message arguments :param http_args: Initial HTTP header arguments :param kwargs: extra keyword arguments :return: Dictionary with the necessary information for the HTTP request
3.081563
3.074028
1.002451
# If info is a whole URL pick out the query or fragment part if '?' in info or '#' in info: parts = urlparse(info) scheme, netloc, path, params, query, fragment = parts[:6] # either query of fragment if query: info = query else: info = fragment return info
def get_urlinfo(info)
Pick out the fragment or query part from a URL. :param info: A URL possibly containing a query or a fragment part :return: the query/fragment part
4.851365
4.176294
1.161643
kwargs = {'client_id': self.service_context.client_id, 'iss': self.service_context.issuer, 'keyjar': self.service_context.keyjar, 'verify': True} return kwargs
def gather_verify_arguments(self)
Need to add some information before running verify() :return: dictionary with arguments to the verify call
4.151449
3.857609
1.076172
if not sformat: sformat = self.response_body_type logger.debug('response format: {}'.format(sformat)) if sformat in ['jose', 'jws', 'jwe']: resp = self.post_parse_response(info, state=state) if not resp: logger.error('Missing or faulty response') raise ResponseError("Missing or faulty response") return resp # If format is urlencoded 'info' may be a URL # in which case I have to get at the query/fragment part if sformat == "urlencoded": info = self.get_urlinfo(info) if sformat == 'jwt': args = {'allowed_sign_algs': self.service_context.get_sign_alg(self.service_name)} enc_algs = self.service_context.get_enc_alg_enc(self.service_name) args['allowed_enc_algs'] = enc_algs['alg'] args['allowed_enc_encs'] = enc_algs['enc'] _jwt = JWT(key_jar=self.service_context.keyjar, **args) _jwt.iss = self.service_context.client_id info = _jwt.unpack(info) sformat = "dict" logger.debug('response_cls: {}'.format(self.response_cls.__name__)) try: resp = self.response_cls().deserialize( info, sformat, iss=self.service_context.issuer, **kwargs) except Exception as err: resp = None if sformat == 'json': # Could be JWS or JWE but wrongly tagged # Adding issuer is just a fail-safe. If one things was wrong # then two can be. try: resp = self.response_cls().deserialize( info, 'jwt', iss=self.service_context.issuer, **kwargs) except Exception as err2: pass if resp is None: logger.error('Error while deserializing: {}'.format(err)) raise msg = 'Initial response parsing => "{}"' logger.debug(msg.format(resp.to_dict())) # is this an error message if is_error_message(resp): logger.debug('Error response: {}'.format(resp)) else: vargs = self.gather_verify_arguments() logger.debug("Verify response with {}".format(vargs)) try: # verify the message. If something is wrong an exception is # thrown resp.verify(**vargs) except Exception as err: logger.error( 'Got exception while verifying response: {}'.format(err)) raise resp = self.post_parse_response(resp, state=state) if not resp: logger.error('Missing or faulty response') raise ResponseError("Missing or faulty response") return resp
def parse_response(self, info, sformat="", state="", **kwargs)
This the start of a pipeline that will: 1 Deserializes a response into it's response message class. Or :py:class:`oidcmsg.oauth2.ErrorResponse` if it's an error message 2 verifies the correctness of the response by running the verify method belonging to the message class used. 3 runs the do_post_parse_response method iff the response was not an error response. :param info: The response, can be either in a JSON or an urlencoded format :param sformat: Which serialization that was used :param state: The state :param kwargs: Extra key word arguments :return: The parsed and to some extend verified response
3.672009
3.476795
1.056148
if attr in self.conf: return self.conf[attr] else: return default
def get_conf_attr(self, attr, default=None)
Get the value of a attribute in the configuration :param attr: The attribute :param default: If the attribute doesn't appear in the configuration return this value :return: The value of attribute in the configuration or the default value
2.791916
4.290189
0.650768
try: cv_len = service.service_context.config['code_challenge']['length'] except KeyError: cv_len = 64 # Use default # code_verifier: string of length cv_len code_verifier = unreserved(cv_len) _cv = code_verifier.encode() try: _method = service.service_context.config['code_challenge']['method'] except KeyError: _method = 'S256' try: # Pick hash method _hash_method = CC_METHOD[_method] # Use it on the code_verifier _hv = _hash_method(_cv).digest() # base64 encode the hash value code_challenge = b64e(_hv).decode('ascii') except KeyError: raise Unsupported( 'PKCE Transformation method:{}'.format(_method)) _item = Message(code_verifier=code_verifier,code_challenge_method=_method) service.store_item(_item, 'pkce', request_args['state']) request_args.update({"code_challenge": code_challenge, "code_challenge_method": _method}) return request_args
def add_code_challenge(request_args, service, **kwargs)
PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.Authorization` instance :param service: The service that uses this function :param request_args: Set of request arguments :param kwargs: Extra set of keyword arguments :return: Updated set of request arguments
4.336512
4.291357
1.010522
_item = service.get_item(Message, 'pkce', kwargs['state']) request_args.update({'code_verifier': _item['code_verifier']}) return request_args
def add_code_verifier(request_args, service, **kwargs)
PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.AccessToken` instance :param service: The service that uses this function :param request_args: Set of request arguments :return: updated set of request arguments
9.302922
8.08823
1.15018
_ctx = self.service_context kwargs = { 'client_id': _ctx.client_id, 'iss': _ctx.issuer, 'keyjar': _ctx.keyjar, 'verify': True, 'skew': _ctx.clock_skew } for attr, param in IDT2REG.items(): try: kwargs[attr] = _ctx.registration_response[param] except KeyError: pass try: kwargs['allow_missing_kid'] = self.service_context.allow[ 'missing_kid'] except KeyError: pass return kwargs
def gather_verify_arguments(self)
Need to add some information before running verify() :return: dictionary with arguments to the verify call
4.273291
4.372301
0.977355
if "scope" not in response: try: _key = kwargs['state'] except KeyError: pass else: if _key: item = self.get_item(oauth2.AuthorizationRequest, 'auth_request', _key) try: response["scope"] = item["scope"] except KeyError: pass return response
def post_parse_response(self, response, **kwargs)
Add scope claim to response, from the request, if not present in the response :param response: The response :param kwargs: Extra Keyword arguments :return: A possibly augmented response
5.375845
4.793016
1.1216
request_args = self.multiple_extend_request_args( request_args, kwargs['state'], ['id_token'], ['auth_response', 'token_response', 'refresh_token_response'], orig=True ) try: request_args['id_token_hint'] = request_args['id_token'] except KeyError: pass else: del request_args['id_token'] return request_args, {}
def get_id_token_hint(self, request_args=None, **kwargs)
Add id_token_hint to request :param request_args: :param kwargs: :return:
4.125981
4.226713
0.976168
_data = self.state_db.get(key) if not _data: raise KeyError(key) else: return State().from_json(_data)
def get_state(self, key)
Get the state connected to a given key. :param key: Key into the state database :return: A :py:class:´oidcservice.state_interface.State` instance
4.555143
4.306129
1.057828
try: _state = self.get_state(key) except KeyError: _state = State() try: _state[item_type] = item.to_json() except AttributeError: _state[item_type] = item self.state_db.set(key, _state.to_json())
def store_item(self, item, item_type, key)
Store a service response. :param item: The item as a :py:class:`oidcmsg.message.Message` subclass instance or a JSON document. :param item_type: The type of request or response :param key: The key under which the information should be stored in the state database
2.758956
2.558462
1.078365
_state = self.get_state(key) if not _state: raise KeyError(key) return _state['iss']
def get_iss(self, key)
Get the Issuer ID :param key: Key to the information in the state database :return: The issuer ID
4.233634
4.998006
0.847065
_state = self.get_state(key) try: return item_cls(**_state[item_type]) except TypeError: return item_cls().from_json(_state[item_type])
def get_item(self, item_cls, item_type, key)
Get a piece of information (a request or a response) from the state database. :param item_cls: The :py:class:`oidcmsg.message.Message` subclass that described the item. :param item_type: Which request/response that is wanted :param key: The key to the information in the state database :return: A :py:class:`oidcmsg.message.Message` instance
3.679937
4.323036
0.851239
try: item = self.get_item(item_cls, item_type, key) except KeyError: pass else: for parameter in parameters: if orig: try: args[parameter] = item[parameter] except KeyError: pass else: try: args[parameter] = item[verified_claim_name(parameter)] except KeyError: try: args[parameter] = item[parameter] except KeyError: pass return args
def extend_request_args(self, args, item_cls, item_type, key, parameters, orig=False)
Add a set of parameters and their value to a set of request arguments. :param args: A dictionary :param item_cls: The :py:class:`oidcmsg.message.Message` subclass that describes the item :param item_type: The type of item, this is one of the parameter names in the :py:class:`oidcservice.state_interface.State` class. :param key: The key to the information in the database :param parameters: A list of parameters who's values this method will return. :param orig: Where the value of a claim is a signed JWT return that. :return: A dictionary with keys from the list of parameters and values being the values of those parameters in the item. If the parameter does not a appear in the item it will not appear in the returned dictionary.
2.444379
2.191537
1.115372
_state = self.get_state(key) for typ in item_types: try: _item = Message(**_state[typ]) except KeyError: continue for parameter in parameters: if orig: try: args[parameter] = _item[parameter] except KeyError: pass else: try: args[parameter] = _item[verified_claim_name(parameter)] except KeyError: try: args[parameter] = _item[parameter] except KeyError: pass return args
def multiple_extend_request_args(self, args, key, parameters, item_types, orig=False)
Go through a set of items (by their type) and add the attribute-value that match the list of parameters to the arguments If the same parameter occurs in 2 different items then the value in the later one will be the one used. :param args: Initial set of arguments :param key: Key to the State information in the state database :param parameters: A list of parameters that we're looking for :param item_types: A list of item_type specifying which items we are interested in. :param orig: Where the value of a claim is a signed JWT return that. :return: A possibly augmented set of arguments.
3.195659
2.785017
1.147447
self.state_db.set(KEY_PATTERN[xtyp].format(x), state) try: _val = self.state_db.get("ref{}ref".format(state)) except KeyError: _val = None if _val is None: refs = {xtyp:x} else: refs = json.loads(_val) refs[xtyp] = x self.state_db.set("ref{}ref".format(state), json.dumps(refs))
def store_X2state(self, x, state, xtyp)
Store the connection between some value (x) and a state value. This allows us later in the game to find the state if we have x. :param x: The value of x :param state: The state value :param xtyp: The type of value x is (e.g. nonce, ...)
3.571324
3.531453
1.01129
_state = self.state_db.get(KEY_PATTERN[xtyp].format(x)) if _state: return _state else: raise KeyError('Unknown {}: "{}"'.format(xtyp, x))
def get_state_by_X(self, x, xtyp)
Find the state value by providing the x value. Will raise an exception if the x value is absent from the state data base. :param x: The x value :return: The state value
4.764398
4.874802
0.977352
if not webname.startswith(self.base_url): raise ValueError("Webname doesn't match base_url") _name = webname[len(self.base_url):] if _name.startswith('/'): return _name[1:] else: return _name
def filename_from_webname(self, webname)
A 1<->1 map is maintained between a URL pointing to a file and the name of the file in the file system. As an example if the base_url is 'https://example.com' and a jwks_uri is 'https://example.com/jwks_uri.json' then the filename of the corresponding file on the local filesystem would be 'jwks_uri'. Relative to the directory from which the RP instance is run. :param webname: The published URL :return: local filename
2.724868
2.862839
0.951806
m = hashlib.sha256() try: m.update(as_bytes(self.provider_info['issuer'])) except KeyError: m.update(as_bytes(self.issuer)) m.update(as_bytes(self.base_url)) if not path.startswith('/'): return ['{}/{}/{}'.format(self.base_url, path, m.hexdigest())] else: return ['{}{}/{}'.format(self.base_url, path, m.hexdigest())]
def generate_request_uris(self, path)
Need to generate a redirect_uri path that is unique for a OP/RP combo This is to counter the mix-up attack. :param path: Leading path :return: A list of one unique URL
2.599536
2.53088
1.027127
for where, spec in keyspec.items(): if where == 'file': for typ, files in spec.items(): if typ == 'rsa': for fil in files: _key = RSAKey( key=import_private_rsa_key_from_file(fil), use='sig') _kb = KeyBundle() _kb.append(_key) self.keyjar.add_kb('', _kb) elif where == 'url': for iss, url in spec.items(): kb = KeyBundle(source=url) self.keyjar.add_kb(iss, kb)
def import_keys(self, keyspec)
The client needs it's own set of keys. It can either dynamically create them or load them from local storage. This method can also fetch other entities keys provided the URL points to a JWKS. :param keyspec:
3.856556
4.060597
0.949751
_now = utc_time_sans_frac() at = AuthnToken(iss=client_id, sub=client_id, aud=audience, jti=rndstr(32), exp=_now + lifetime, iat=_now) logger.debug('AuthnToken: {}'.format(at.to_dict())) return at.to_jwt(key=keys, algorithm=algorithm)
def assertion_jwt(client_id, keys, audience, algorithm, lifetime=600)
Create a signed Json Web Token containing some information. :param client_id: The Client ID :param keys: Signing keys :param audience: Who is the receivers for this assertion :param algorithm: Signing algorithm :param lifetime: The lifetime of the signed Json Web Token :return: A Signed Json Web Token
3.682144
4.214959
0.87359
if request is not None: try: _token = request[token_type] except KeyError: pass else: del request[token_type] # Required under certain circumstances :-) not under other request.c_param[token_type] = SINGLE_OPTIONAL_STRING return _token try: return kwargs["access_token"] except KeyError: # I should pick the latest acquired token, this should be the right # order for that. _arg = service.multiple_extend_request_args( {}, kwargs['state'], ['access_token'], ['auth_response', 'token_response', 'refresh_token_response']) return _arg['access_token']
def find_token(request, token_type, service, **kwargs)
The access token can be in a number of places. There are priority rules as to which one to use, abide by those: 1 If it's among the request parameters use that 2 If among the extra keyword arguments 3 Acquired by a previous run service. :param request: :param token_type: :param service: :param kwargs: :return:
10.025249
9.721509
1.031244
eta = getattr(service_context, 'client_secret_expires_at', 0) now = when or utc_time_sans_frac() if eta != 0 and eta < now: return False return True
def valid_service_context(service_context, when=0)
Check if the client_secret has expired :param service_context: A :py:class:`oidcservice.service_context.ServiceContext` instance :param when: A time stamp against which the expiration time is to be checked :return: True if the client_secret is still valid
4.978267
4.168716
1.194197
if http_args is None: http_args = {} if "headers" not in http_args: http_args["headers"] = {} # get the username (client_id) and the password (client_secret) try: passwd = kwargs["password"] except KeyError: try: passwd = request["client_secret"] except KeyError: passwd = service.service_context.client_secret try: user = kwargs["user"] except KeyError: user = service.service_context.client_id # The credential is username and password concatenated with a ':' # in between and then base 64 encoded becomes the authentication # token. credentials = "{}:{}".format(quote_plus(user), quote_plus(passwd)) authz = base64.urlsafe_b64encode(credentials.encode("utf-8")).decode( "utf-8") http_args["headers"]["Authorization"] = "Basic {}".format(authz) # If client_secret was part of the request message instance remove it try: del request["client_secret"] except (KeyError, TypeError): pass # If we're doing an access token request with an authorization code # then we should add client_id to the request if it's not already # there if isinstance(request, AccessTokenRequest) and request[ 'grant_type'] == 'authorization_code': if 'client_id' not in request: try: request['client_id'] = service.service_context.client_id except AttributeError: pass else: # remove client_id if not required by the request definition try: _req = request.c_param["client_id"][VREQUIRED] except (KeyError, AttributeError): _req = False # if it's not required remove it if not _req: try: del request["client_id"] except KeyError: pass return http_args
def construct(self, request, service=None, http_args=None, **kwargs)
Construct a dictionary to be added to the HTTP request headers :param request: The request :param service: A :py:class:`oidcservice.service.Service` instance :param http_args: HTTP arguments :return: dictionary of HTTP arguments
3.236281
3.19641
1.012474
if service.service_name == 'refresh_token': _acc_token = find_token(request, 'refresh_token', service, **kwargs) else: _acc_token = find_token(request, 'access_token', service, **kwargs) if not _acc_token: raise KeyError('No access or refresh token available') # The authorization value starts with 'Bearer' when bearer tokens # are used _bearer = "Bearer {}".format(_acc_token) # Add 'Authorization' to the headers if http_args is None: http_args = {"headers": {}} http_args["headers"]["Authorization"] = _bearer else: try: http_args["headers"]["Authorization"] = _bearer except KeyError: http_args["headers"] = {"Authorization": _bearer} return http_args
def construct(self, request=None, service=None, http_args=None, **kwargs)
Constructing the Authorization header. The value of the Authorization header is "Bearer <access_token>". :param request: Request class instance :param service: Service :param http_args: HTTP header arguments :param kwargs: extra keyword arguments :return:
3.119604
3.011832
1.035783
_acc_token = '' for _token_type in ['access_token', 'refresh_token']: _acc_token = find_token(request, _token_type, service, **kwargs) if _acc_token: break if not _acc_token: raise KeyError('No access or refresh token available') else: request["access_token"] = _acc_token return http_args
def construct(self, request, service=None, http_args=None, **kwargs)
Will add a token to the request if not present :param request: The request :param service_context: A :py:class:`oidcservice.service.Service` instance :param http_args: HTTP arguments :param kwargs: extra keyword arguments :return: A possibly modified dictionary with HTTP arguments.
3.818583
3.69623
1.033102
try: algorithm = kwargs["algorithm"] except KeyError: # different contexts uses different signing algorithms algorithm = DEF_SIGN_ALG[context] if not algorithm: raise AuthnFailure("Missing algorithm specification") return algorithm
def choose_algorithm(self, context, **kwargs)
Pick signing algorithm :param context: Signing context :param kwargs: extra keyword arguments :return: Name of a signing algorithm
9.300856
8.635293
1.077075
return service_context.keyjar.get_signing_key( alg2keytype(algorithm), alg=algorithm)
def get_signing_key(self, algorithm, service_context)
Pick signing key based on signing algorithm to be used :param algorithm: Signing algorithm :param service_context: A :py:class:`oidcservice.service_context.ServiceContext` instance :return: A key
6.858477
8.263348
0.829988
_key = service_context.keyjar.get_key_by_kid(kid) if _key: ktype = alg2keytype(algorithm) if _key.kty != ktype: raise NoMatchingKey("Wrong key type") else: return _key else: raise NoMatchingKey("No key with kid:%s" % kid)
def get_key_by_kid(self, kid, algorithm, service_context)
Pick a key that matches a given key ID and signing algorithm. :param kid: Key ID :param algorithm: Signing algorithm :param service_context: A :py:class:`oidcservice.service_context.ServiceContext` instance :return: A matching key
3.148735
3.304528
0.952855
if 'client_assertion' in kwargs: request["client_assertion"] = kwargs['client_assertion'] if 'client_assertion_type' in kwargs: request[ 'client_assertion_type'] = kwargs['client_assertion_type'] else: request["client_assertion_type"] = JWT_BEARER elif 'client_assertion' in request: if 'client_assertion_type' not in request: request["client_assertion_type"] = JWT_BEARER else: algorithm = None _context = service.service_context # audience for the signed JWT depends on which endpoint # we're talking to. if kwargs['authn_endpoint'] in ['token_endpoint']: try: algorithm = _context.behaviour[ 'token_endpoint_auth_signing_alg'] except (KeyError, AttributeError): pass audience = _context.provider_info['token_endpoint'] else: audience = _context.provider_info['issuer'] if not algorithm: algorithm = self.choose_algorithm(**kwargs) ktype = alg2keytype(algorithm) try: if 'kid' in kwargs: signing_key = [self.get_key_by_kid(kwargs["kid"], algorithm, _context)] elif ktype in _context.kid["sig"]: try: signing_key = [self.get_key_by_kid( _context.kid["sig"][ktype], algorithm, _context)] except KeyError: signing_key = self.get_signing_key(algorithm, _context) else: signing_key = self.get_signing_key(algorithm, _context) except NoMatchingKey as err: logger.error("%s" % sanitize(err)) raise try: _args = {'lifetime': kwargs['lifetime']} except KeyError: _args = {} # construct the signed JWT with the assertions and add # it as value to the 'client_assertion' claim of the request request["client_assertion"] = assertion_jwt( _context.client_id, signing_key, audience, algorithm, **_args) request["client_assertion_type"] = JWT_BEARER try: del request["client_secret"] except KeyError: pass # If client_id is not required to be present, remove it. if not request.c_param["client_id"][VREQUIRED]: try: del request["client_id"] except KeyError: pass return {}
def construct(self, request, service=None, http_args=None, **kwargs)
Constructs a client assertion and signs it with a key. The request is modified as a side effect. :param request: The request :param service: A :py:class:`oidcservice.service.Service` instance :param http_args: HTTP arguments :param kwargs: Extra arguments :return: Constructed HTTP arguments, in this case none
3.20893
3.101934
1.034493
try: _iss = self.service_context.issuer except AttributeError: _iss = self.endpoint if _iss.endswith('/'): return OIDCONF_PATTERN.format(_iss[:-1]) else: return OIDCONF_PATTERN.format(_iss)
def get_endpoint(self)
Find the issuer ID and from it construct the service endpoint :return: Service endpoint
4.993871
5.06818
0.985338
issuer = self.service_context.issuer # Verify that the issuer value received is the same as the # url that was used as service endpoint (without the .well-known part) if "issuer" in resp: _pcr_issuer = resp["issuer"] if resp["issuer"].endswith("/"): if issuer.endswith("/"): _issuer = issuer else: _issuer = issuer + "/" else: if issuer.endswith("/"): _issuer = issuer[:-1] else: _issuer = issuer # In some cases we can live with the two URLs not being # the same. But this is an excepted that has to be explicit try: self.service_context.allow['issuer_mismatch'] except KeyError: if _issuer != _pcr_issuer: raise OidcServiceError( "provider info issuer mismatch '%s' != '%s'" % ( _issuer, _pcr_issuer)) else: # No prior knowledge _pcr_issuer = issuer self.service_context.issuer = _pcr_issuer self.service_context.provider_info = resp # If there are services defined set the service endpoint to be # the URLs specified in the provider information. try: _srvs = self.service_context.service except AttributeError: pass else: if self.service_context.service: for key, val in resp.items(): # All service endpoint parameters in the provider info has # a name ending in '_endpoint' so I can look specifically # for those if key.endswith("_endpoint"): for _srv in self.service_context.service.values(): # Every service has an endpoint_name assigned # when initiated. This name *MUST* match the # endpoint names used in the provider info if _srv.endpoint_name == key: _srv.endpoint = val # If I already have a Key Jar then I'll add then provider keys to # that. Otherwise a new Key Jar is minted try: kj = self.service_context.keyjar except KeyError: kj = KeyJar() # Load the keys. Note that this only means that the key specification # is loaded not necessarily that any keys are fetched. if 'jwks_uri' in resp: kj.load_keys(_pcr_issuer, jwks_uri=resp['jwks_uri']) elif 'jwks' in resp: kj.load_keys(_pcr_issuer, jwks=resp['jwks']) self.service_context.keyjar = kj
def _update_service_context(self, resp, **kwargs)
Deal with Provider Config Response. Based on the provider info response a set of parameters in different places needs to be set. :param resp: The provider info response :param service_context: Information collected/used by services
4.571503
4.547676
1.005239
if resource[0] in ['=', '@', '!']: # Have no process for handling these raise ValueError('Not allowed resource identifier') try: part = urlsplit(resource) except Exception: raise ValueError('Unparsable resource') else: if not part[SCHEME]: if not part[NETLOC]: _path = part[PATH] if not part[QUERY] and not part[FRAGMENT]: if '/' in _path or ':' in _path: resource = "https://{}".format(resource) part = urlsplit(resource) authority = part[NETLOC] else: if '@' in _path: authority = _path.split('@')[1] else: authority = _path resource = 'acct:{}'.format(_path) elif part[QUERY]: resource = "https://{}?{}".format(_path, part[QUERY]) parts = urlsplit(resource) authority = parts[NETLOC] else: resource = "https://{}".format(_path) part = urlsplit(resource) authority = part[NETLOC] else: raise ValueError('Missing netloc') else: _scheme = part[SCHEME] if _scheme not in ['http', 'https', 'acct']: # assume it to be a hostname port combo, # eg. example.com:8080 resource = 'https://{}'.format(resource) part = urlsplit(resource) authority = part[NETLOC] resource = self.create_url(part, [FRAGMENT]) elif _scheme in ['http', 'https'] and not part[NETLOC]: raise ValueError( 'No authority part in the resource specification') elif _scheme == 'acct': _path = part[PATH] for c in ['/', '?']: _path = _path.split(c)[0] if '@' in _path: authority = _path.split('@')[1] else: raise ValueError( 'No authority part in the resource specification') authority = authority.split('#')[0] resource = self.create_url(part, [FRAGMENT]) else: authority = part[NETLOC] resource = self.create_url(part, [FRAGMENT]) location = WF_URL.format(authority) return oidc.WebFingerRequest( resource=resource, rel=OIC_ISSUER).request(location)
def query(self, resource)
Given a resource identifier find the domain specifier and then construct the webfinger request. Implements http://openid.net/specs/openid-connect-discovery-1_0.html#NormalizationSteps :param resource:
3.276919
3.148183
1.040892
if method in ["GET", "DELETE"]: if req.keys(): _req = req.copy() comp = urlsplit(str(url)) if comp.query: _req.update(parse_qs(comp.query)) _query = str(_req.to_urlencoded()) return urlunsplit((comp.scheme, comp.netloc, comp.path, _query, comp.fragment)) else: return url else: return url
def get_http_url(url, req, method='GET')
Add a query part representing the request to a url that may already contain a query part. Only done if the HTTP method used is 'GET' or 'DELETE'. :param url: The URL :param req: The request as a :py:class:`oidcmsg.message.Message` instance :param method: The HTTP method :return: A possibly modified URL
3.202357
3.098773
1.033428
if URL_ENCODED in content_type: return req.to_urlencoded() elif JSON_ENCODED in content_type: return req.to_json() elif JOSE_ENCODED in content_type: return req # already packaged else: raise UnSupported( "Unsupported content type: '%s'" % content_type)
def get_http_body(req, content_type=URL_ENCODED)
Get the message into the format that should be places in the body part of a HTTP request. :param req: The service request as a :py:class:`oidcmsg.message.Message` instance :param content_type: The format of the body part. :return: The correctly formatet service request.
3.913191
3.79304
1.031677
if ':' in s: c = s.split(':') if len(c) != 2: raise ValueError("Syntax error: {s}") return c[0], c[1] else: c = s.split('.') if len(c) < 2: raise ValueError("Syntax error: {s}") return '.'.join(c[:-1]), c[-1]
def modsplit(s)
Split importable
2.297835
2.292334
1.0024
c1, c2 = modsplit(name) module = importlib.import_module(c1) return getattr(module, c2)
def importer(name)
Import by name
4.874366
4.673959
1.042877
_basech = string.ascii_letters + string.digits return "".join([rnd.choice(_basech) for _ in range(size)])
def rndstr(size=16)
Returns a string of random ascii characters or digits :param size: The length of the string :return: string
4.645634
4.926266
0.943033
_context = service.service_context if "redirect_uris" not in request_args: # Callbacks is a dictionary with callback type 'code', 'implicit', # 'form_post' as keys. try: _cbs = _context.callbacks except AttributeError: request_args['redirect_uris'] = _context.redirect_uris else: # Filter out local additions. _uris = [v for k, v in _cbs.items() if not k.startswith('__')] request_args['redirect_uris'] = _uris return request_args, {}
def add_redirect_uris(request_args, service=None, **kwargs)
Add redirect_uris to the request arguments. :param request_args: Incomming request arguments :param service: A link to the service :param kwargs: Possible extra keyword arguments :return: A possibly augmented set of request arguments.
5.03683
5.326821
0.94556
if not pcr: pcr = self.service_context.provider_info regreq = oidc.RegistrationRequest for _pref, _prov in PREFERENCE2PROVIDER.items(): try: vals = self.service_context.client_preferences[_pref] except KeyError: continue try: _pvals = pcr[_prov] except KeyError: try: # If the provider have not specified use what the # standard says is mandatory if at all. _pvals = PROVIDER_DEFAULT[_pref] except KeyError: logger.info( 'No info from provider on {} and no default'.format( _pref)) _pvals = vals if isinstance(vals, str): if vals in _pvals: self.service_context.behaviour[_pref] = vals else: try: vtyp = regreq.c_param[_pref] except KeyError: # Allow non standard claims if isinstance(vals, list): self.service_context.behaviour[_pref] = [ v for v in vals if v in _pvals] elif vals in _pvals: self.service_context.behaviour[_pref] = vals else: if isinstance(vtyp[0], list): self.service_context.behaviour[_pref] = [] for val in vals: if val in _pvals: self.service_context.behaviour[_pref].append( val) else: for val in vals: if val in _pvals: self.service_context.behaviour[_pref] = val break if _pref not in self.service_context.behaviour: raise ConfigurationError( "OP couldn't match preference:%s" % _pref, pcr) for key, val in self.service_context.client_preferences.items(): if key in self.service_context.behaviour: continue try: vtyp = regreq.c_param[key] if isinstance(vtyp[0], list): pass elif isinstance(val, list) and not isinstance(val, str): val = val[0] except KeyError: pass if key not in PREFERENCE2PROVIDER: self.service_context.behaviour[key] = val logger.debug( 'service_context behaviour: {}'.format( self.service_context.behaviour))
def match_preferences(self, pcr=None, issuer=None)
Match the clients preferences against what the provider can do. This is to prepare for later client registration and or what functionality the client actually will use. In the client configuration the client preferences are expressed. These are then compared with the Provider Configuration information. If the Provider has left some claims out, defaults specified in the standard will be used. :param pcr: Provider configuration response if available :param issuer: The issuer identifier
3.034323
2.89505
1.048107
'''Return the soundex code for given character :param char: Character whose soundex code is needed :return: Returns soundex code if character is found in charmap else returns 0 ''' lang = get_language(char) try: if lang == "en_US": return _soundex_map["soundex_en"][charmap[lang].index(char)] else: return _soundex_map["soundex"][charmap[lang].index(char)] except: # Case of exception KeyError because we don't have soundex # mapping for the character pass return 0
def soundexCode(self, char)
Return the soundex code for given character :param char: Character whose soundex code is needed :return: Returns soundex code if character is found in charmap else returns 0
4.733743
3.100207
1.526912
'''Calculate soundex of given string This function calculates soundex for Indian language string as well as English string. This function is exposed as service method for JSONRPC in SILPA framework. :param name: String whose Soundex value to be calculated :param length: Length of final Soundex string, if soundex caculated is more than this it will be truncated to length. :return: Soundex string of `name' ''' sndx = [] fc = name[0] # translate alpha chars in name to soundex digits for c in name[1:].lower(): d = str(self.soundexCode(c)) # remove all 0s from the soundex code if d == '0': continue # duplicate consecutive soundex digits are skipped if len(sndx) == 0: sndx.append(d) elif d != sndx[-1]: sndx.append(d) # append first character to result sndx.insert(0, fc) if get_language(name[0]) == 'en_US': # Don't padd return ''.join(sndx) if len(sndx) < length: sndx.extend(repeat('0', length)) return ''.join(sndx[:length]) return ''.join(sndx[:length])
def soundex(self, name, length=8)
Calculate soundex of given string This function calculates soundex for Indian language string as well as English string. This function is exposed as service method for JSONRPC in SILPA framework. :param name: String whose Soundex value to be calculated :param length: Length of final Soundex string, if soundex caculated is more than this it will be truncated to length. :return: Soundex string of `name'
5.577073
2.759491
2.021051
'''Compare soundex of given strings This function checks if 2 given strings are phonetically sounds same by doing soundex code comparison :param string1: First string for comparison :param string2: Second string for comparison :return: Returns 0 if both strings are same, 1 if strings sound phonetically same and from same language, 2 if strings are phonetically same and from different languages. Returns -1 if strings are not equal. We can't perform English cross language comparision if English string is passed as one function will return -1. ''' # do a quick check if string1 == string2: return 0 string1_lang = get_language(string1[0]) string2_lang = get_language(string2[0]) if (string1_lang == 'en_US' and string2_lang != 'en_US') or \ (string1_lang != 'en_US' and string2_lang == 'en_US'): # Can't Soundex compare English and Indic string return -1 soundex1 = self.soundex(string1) soundex2 = self.soundex(string2) if soundex1[1:] == soundex2[1:]: # Strings sound phonetically same if string1_lang == string2_lang: # They are from same language return 1 else: # Different language return 2 # Strings are not same return -1
def compare(self, string1, string2)
Compare soundex of given strings This function checks if 2 given strings are phonetically sounds same by doing soundex code comparison :param string1: First string for comparison :param string2: Second string for comparison :return: Returns 0 if both strings are same, 1 if strings sound phonetically same and from same language, 2 if strings are phonetically same and from different languages. Returns -1 if strings are not equal. We can't perform English cross language comparision if English string is passed as one function will return -1.
4.220844
1.909323
2.21065
if not url or "//" not in url: raise ValueError("Missing or invalid url: %s" % url) render_url = self.BASE_URL + url headers = { 'X-Prerender-Token': self.token, } r = self.session.get(render_url, headers=headers, allow_redirects=False) assert r.status_code < 500 return self.build_django_response_from_requests_response(r)
def get_response_for_url(self, url)
Accepts a fully-qualified url. Returns an HttpResponse, passing through all headers and the status code.
3.942206
3.860346
1.021205
if not url and not regex: raise ValueError("Neither a url or regex was provided to update_url.") headers = { 'X-Prerender-Token': self.token, 'Content-Type': 'application/json', } data = { 'prerenderToken': settings.PRERENDER_TOKEN, } if url: data["url"] = url if regex: data["regex"] = regex r = self.session.post(self.RECACHE_URL, headers=headers, data=data) return r.status_code < 500
def update_url(self, url=None, regex=None)
Accepts a fully-qualified url, or regex. Returns True if successful, False if not successful.
2.826424
2.701713
1.04616
if not url: raise ValueError("Neither a url or regex was provided to update_url.") post_url = "%s%s" % (self.BASE_URL, url) r = self.session.post(post_url) return int(r.status_code) < 500
def update_url(self, url=None)
Accepts a fully-qualified url. Returns True if successful, False if not successful.
4.27196
3.995692
1.069141
if 'user' not in validated_data: validated_data['user'] = self.context['request'].user return super(RefreshTokenSerializer, self).create(validated_data)
def create(self, validated_data)
Override ``create`` to provide a user via request.user by default. This is required since the read_only ``user`` field is not included by default anymore since https://github.com/encode/django-rest-framework/pull/5886.
2.641312
2.343156
1.127246
user = request.user if not user.is_authenticated: return False elif user.is_staff or user.is_superuser: return True return user == obj.user
def has_object_permission(self, request, view, obj)
Allow staff or superusers, and the owner of the object itself.
2.748476
2.198565
1.250122
with self._cond: to_notify = self._initial - self._value self._value = self._initial self._cond.notify(to_notify)
def clear(self)
Release the semaphore of all of its bounds, setting the internal counter back to its original bind limit. Notify an equivalent amount of threads that they can run.
6.684828
5.475365
1.220892
def _convert(value): if isinstance(value, _datetime.date): return value.strftime('%s') return value @_six.wraps(fn) def _fn(self, command, **params): # sanitize the params by removing the None values with self.startup_lock: if self.timer.ident is None: self.timer.setDaemon(True) self.timer.start() params = dict((key, _convert(value)) for key, value in _six.iteritems(params) if value is not None) self.semaphore.acquire() resp = fn(self, command, **params) try: respdata = resp.json(object_hook=_AutoCastDict) except: # use more specific error if available or fallback to ValueError resp.raise_for_status() raise Exception('No JSON object could be decoded') # check for 'error' then check for status due to Poloniex inconsistency if 'error' in respdata: raise PoloniexCommandException(respdata['error']) resp.raise_for_status() return respdata return _fn
def _api_wrapper(fn)
API function decorator that performs rate limiting and error checking.
4.923499
4.867276
1.011551
params['command'] = command response = self.session.get(self._public_url, params=params) return response
def _public(self, command, **params)
Invoke the 'command' public API with optional params.
3.974399
3.855561
1.030823
return self._public('returnOrderBook', currencyPair=currencyPair, depth=depth)
def returnOrderBook(self, currencyPair='all', depth='50')
Returns the order book for a given market, as well as a sequence number for use with the Push API and an indicator specifying whether the market is frozen. You may set currencyPair to "all" to get the order books of all markets.
4.822388
4.995569
0.965333
return self._public('returnTradeHistory', currencyPair=currencyPair, start=start, end=end)
def returnTradeHistory(self, currencyPair, start=None, end=None)
Returns the past 200 trades for a given market, or up to 50,000 trades between a range specified in UNIX timestamps by the "start" and "end" GET parameters.
3.964014
4.588697
0.863865
return self._public('returnChartData', currencyPair=currencyPair, period=period, start=start, end=end)
def returnChartData(self, currencyPair, period, start=0, end=2**32-1)
Returns candlestick chart data. Required GET parameters are "currencyPair", "period" (candlestick period in seconds; valid values are 300, 900, 1800, 7200, 14400, and 86400), "start", and "end". "Start" and "end" are given in UNIX timestamp format and used to specify the date range for the data returned.
3.571379
3.601826
0.991547