code stringlengths 1 18.2k |
|---|
def _createDatabase( self ): """Private method to create the SQLite database file.""" # create experiment metadata table command = """ CREATE TABLE {tn} ( {k} INT PRIMARY KEY NOT NULL, START_TIME INT NOT NULL, END_TIME INT NOT NULL, ELAPSED_TIME INT NOT NULL, SETUP_TIME INT NOT NULL, EXPERIMENT_TIME INT NOT NULL, TEARD... |
def alchemyencoder(obj): """JSON encoder function for SQLAlchemy special classes.""" if isinstance(obj, datetime.date): return obj.isoformat() elif isinstance(obj, decimal.Decimal): return float(obj) |
def authenticate(self, request): """ Authenticate the request and return a two-tuple of (user, token). """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'token': return None if len(auth) == 1: msg = _('Invalid auth token header. No credentials provided.') raise AuthenticationFailed... |
def authenticate_credentials(self, token: bytes, request=None): """ Authenticate the token with optional request for context. """ user = AuthToken.get_user_for_token(token) if user is None: raise AuthenticationFailed(_('Invalid auth token.')) if not user.is_active: raise AuthenticationFailed(_('User inactive or deleted... |
def create(self, target, target_type=None, **kwds): """ Endpoint: /action/<target_id>/<target_type>/create.json Creates a new action and returns it. The target parameter can either be an id or a Trovebox object. If a Trovebox object is used, the target type is inferred automatically. """ # Extract the target type if ta... |
def delete(self, action, **kwds): """ Endpoint: /action/<id>/delete.json Deletes an action. Returns True if successful. Raises a TroveboxError if not. """ return self._client.post("/action/%s/delete.json" % self._extract_id(action), **kwds)["result"] |
def view(self, action, **kwds): """ Endpoint: /action/<id>/view.json Requests all properties of an action. Returns the requested action object. """ result = self._client.get("/action/%s/view.json" % self._extract_id(action), **kwds)["result"] return Action(self._client, result) |
def set(self, key, *args): """Hash the key and set it in the cache""" return self.cache.set(self._hashed(key), *args) |
def get_conv(bits, bin_point, signed=False, scaling=1.0): """ Creates a I{conversion structure} implented as a dictionary containing all parameters needed to switch between number representations. @param bits: the number of bits @param bin_point: binary point position @param signed: True if Fix, False if UFix @param sc... |
raise ConversionError("numer of bits not supported: " + str(bits)) if signed: _get_signed_params(conversion_t) else: _get_unsigned_params(conversion_t) return conversion_t |
def conv_from_name(name): """ Understand simulink syntax for fixed types and returns the proper conversion structure. @param name: the type name as in simulin (i.e. UFix_8_7 ... ) @raise ConversionError: When cannot decode the string """ _match = re.match(r"^(?P<signed>u?fix)_(?P<bits>\d+)_(?P<binary>\d+)", name, flags... |
def _get_unsigned_params(conv): """ Fill the sign-dependent params of the conv structure in case of unsigned conversion @param conv: the structure to be filled """ conv["sign_mask"] = 0 conv["int_min"] = 0 conv["int_mask"] = sum([2 ** i for i in range(conv["bin_point"], conv["bits"])]) conv["int_max"] = sum([2 ** i for... |
def _get_signed_params(conv): """ Fill the sign-dependent params of the conv structure in case of signed conversion @param conv: the structure to be filled """ conv["sign_mask"] = 2 ** (conv["bits"] - 1) conv["int_min"] = -1 * (2 ** (conv["bits"] - 1 - conv["bin_point"])) conv["int_mask"] = sum([2 ** i for i in range(c... |
def fix2real(uval, conv): """ Convert a 32 bit unsigned int register into the value it represents in its Fixed arithmetic form. @param uval: the numeric unsigned value in simulink representation @param conv: conv structure with conversion specs as generated by I{get_conv} @return: the real number represented by the Fix... |
def bin2real(binary_string, conv, endianness="@"): """ Converts a binary string representing a number to its Fixed arithmetic representation @param binary_string: binary number in simulink representation @param conv: conv structure containing conversion specs @param endianness: optionally specify bytes endianness for u... |
def stream2real(binary_stream, conv, endianness="@"): """ Converts a binary stream into a sequence of real numbers @param binary_stream: a binary string representing a sequence of numbers @param conv: conv structure containing conversion specs @param endianness: optionally specify bytes endianness for unpacking @return... |
def real2fix(real, conv): """ Convert a real number to its fixed representation so that it can be written into a 32 bit register. @param real: the real number to be converted into fixed representation @param conv: conv structre with conversion specs @return: the fixed representation of the real number @raise Converison... |
dec_val // conv["dec_step"] if dec > conv["dec_mask"]: dec = conv["dec_mask"] dec_val = dec * conv["dec_step"] val += dec_val if (val - real) > (real - val + conv["dec_step"]): dec -= 1 if sign == 1: return conv["sign_mask"] + ((int_val << conv["bin_point"]) & conv["int_mask"]) + dec else: return ((int_val << conv["bin... |
def _emulated(self, timeout=None): """Get the next message avaiable in the queue. :returns: The message and the name of the queue it came from as a tuple. :raises Empty: If there are no more items in any of the queues. """ # A set of queues we've already tried. tried = set() while True: # Get the next queue in the cycl... |
def fallback_render(template, context, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): """ Render from given template and context. This is a basic implementation actually does nothing and just returns the content of given template file `template`. :param template: Template file path :param context: A... |
def filter_kwargs(keys, kwargs): """ :param keys: A iterable key names to select items :param kwargs: A dict or dict-like object reprensents keyword args >>> list(filter_kwargs(("a", "b"), dict(a=1, b=2, c=3, d=4))) [('a', 1), ('b', 2)] """ for k in keys: if k in kwargs: yield (k, kwargs[k]) |
def filter_options(cls, kwargs, keys): """ Make optional kwargs valid and optimized for each template engines. :param kwargs: keyword arguements to process :param keys: optional argument names >>> Engine.filter_options(dict(aaa=1, bbb=2), ("aaa", )) {'aaa': 1} >>> Engine.filter_options(dict(bbb=2), ("aaa", )) {} """ re... |
def renders(self, template_content, context=None, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): """ :param template_content: Template content :param context: A dict or dict-like object to instantiate given template file or None :param at_paths: Template search paths :param at_encoding: Template enc... |
def render(self, template, context=None, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): """ :param template: Template file path :param context: A dict or dict-like object to instantiate given template file :param at_paths: Template search paths :param at_encoding: Template encoding :param kwargs: Ke... |
def PCA(Y, components): """ run PCA, retrieving the first (components) principle components return [s0, eig, w0] s0: factors w0: weights """ N,D = Y.shape sv = linalg.svd(Y, full_matrices=0); [s0, w0] = [sv[0][:, 0:components], np.dot(np.diag(sv[1]), sv[2]).T[:, 0:components]] v = s0.std(axis=0) s0 /= v; w0 *= v; retur... |
def PC_varExplained(Y,standardized=True): """ Run PCA and calculate the cumulative fraction of variance Args: Y: phenotype values standardize: if True, phenotypes are standardized Returns: var: cumulative distribution of variance explained """ # figuring out the number of latent factors if standardized: Y-=Y.mean(0) Y/... |
def main(tex_file, output, verbose): """ FLaP merges your LaTeX projects into a single LaTeX file that refers to images in the same directory. It reads the given root TEX_FILE and generates a flatten version in the given OUTPUT directory. It inlines the content of any TeX files refered by \\input or \\include but also ... |
def deploy(overwrite=False): """ deploy a versioned project on the host """ check_settings() if overwrite: rmvirtualenv() deploy_funcs = [deploy_project,deploy_templates, deploy_static, deploy_media, deploy_webconf, deploy_wsgi] if not patch_project() or overwrite: deploy_funcs = [deploy_db,mkvirtualenv,pip_install_req... |
def setupnode(overwrite=False): """ Install a baseline host. Can be run multiple times """ if not port_is_open(): if not skip_disable_root(): disable_root() port_changed = change_ssh_port() #avoid trying to take shortcuts if setupnode did not finish #on previous execution if server_state('setupnode-incomplete'): env.ov... |
def splitGeno(pos,method='slidingWindow',size=5e4,step=None,annotation_file=None,cis=1e4,funct=None,out_file=None): """ split geno into windows and store output in csv file Args: pos: genomic position in the format (chrom,pos) method: method used to slit the windows: 'slidingWindow': uses a sliding window 'geneWindow':... |
def splitGenoSlidingWindow(pos,out_file,size=5e4,step=None): """ split into windows using a slide criterion Args: size: window size step: moving step (default: 0.5*size) Returns: wnd_i: number of windows nSnps: vector of per-window number of SNPs """ if step is None: step = 0.5*size chroms = SP.unique(pos[:,0]) RV = []... |
def publish(self, daap_server, preferred_database=None): """ Publish a given `DAAPServer` instance. The given instances should be fully configured, including the provider. By default Zeroconf only advertises the first database, but the DAAP protocol has support for multiple databases. Therefore, the parameter `preferre... |
information for one database only. Since # the protocol supports multiple database, let the user decide which # database to advertise. If none is specified, take the first one. provider = daap_server.provider try: if preferred_database is not None: database = provider.server.databases[preferred_database] else: database... |
has no support for persistent IDs, generate a random # ID. if provider.supports_persistent_id: machine_id = hex(provider.server.persistent_id) database_id = hex(database.persistent_id) else: machine_id = hex(generate_persistent_id()) database_id = hex(generate_persistent_id()) # iTunes 11+ uses more properties, but thi... |
def unpublish(self, daap_server): """ Unpublish a given server. If the server was not published, this method will not do anything. :param DAAPServer daap_server: DAAP Server instance to publish. """ if daap_server not in self.daap_servers: return self.zeroconf.unregister_service(self.daap_servers[daap_server]) del self... |
def addRandomEffect(self, K=None, is_noise=False, normalize=False, Kcross=None, trait_covar_type='freeform', rank=1, fixed_trait_covar=None, jitter=1e-4): """ Add random effects term. Args: K: Sample Covariance Matrix [N, N] is_noise: Boolean indicator specifying if the matrix is homoscedastic noise (weighted identity ... |
diagonal matrix. The rank of the lowrank part is specified in the variable rank, 'block': multiple of a matrix of ones, 'block_id': sum of a multiple of a matrix of ones and a multiple of the idenity, 'block_diag': sum of a multiple of a matrix of ones and a diagonal matrix, rank: rank of a possible lowrank component (... |
shape for K' if Kcross is not None: assert self.Ntest is not None, 'VarianceDecomposition:: specify Ntest for predictions (method VarianceDecomposition::setTestSampleSize)' assert Kcross.shape[0]==self.N, 'VarianceDecomposition:: Incompatible shape for Kcross' assert Kcross.shape[1]==self.Ntest, 'VarianceDecomposition:... |
def addFixedEffect(self, F=None, A=None, Ftest=None): """ add fixed effect term to the model Args: F: sample design matrix for the fixed effect [N,K] A: trait design matrix for the fixed effect (e.g. sp.ones((1,P)) common effect; sp.eye(P) any effect) [L,P] Ftest: sample design matrix for test samples [Ntest,K] """ if ... |
def optimize(self, init_method='default', inference=None, n_times=10, perturb=False, pertSize=1e-3, verbose=None): """ Train the model using the specified initialization strategy Args: init_method: initialization strategy: 'default': variance is equally split across the different random effect terms. For mulit-trait mo... |
noise for each restart (default, False) perturbSize: std of the gassian noise used to perturb the initial point verbose: print if convergence is achieved and how many restarted were needed """ #verbose = dlimix.getVerbose(verbose) assert init_method in ['default', 'random', None], 'VarianceDecomposition: specified init... |
tested initialization points') else: print(('Local minimum found at iteration %d' % i)) return conv |
def getWeights(self, term_i=None): """ Return weights for fixed effect term term_i Args: term_i: fixed effect term index Returns: weights of the spefied fixed effect term. The output will be a KxL matrix of weights will be returned, where K is F.shape[1] and L is A.shape[1] of the correspoding fixed effect term (L will... |
def getTraitCovar(self, term_i=None): """ Return the estimated trait covariance matrix for term_i (or the total if term_i is None) To retrieve the matrix of correlation coefficient use \see getTraitCorrCoef Args: term_i: index of the random effect term we want to retrieve the covariance matrix Returns: estimated trait ... |
def getTraitCorrCoef(self,term_i=None): """ Return the estimated trait correlation coefficient matrix for term_i (or the total if term_i is None) To retrieve the trait covariance matrix use \see getTraitCovar Args: term_i: index of the random effect term we want to retrieve the correlation coefficients Returns: estimat... |
def getVarianceComps(self, univariance=False): """ Return the estimated variance components Args: univariance: Boolean indicator, if True variance components are normalized to sum up to 1 for each trait Returns: variance components of all random effects on all phenotypes [P, n_randEffs matrix] """ RV=sp.zeros((self.P,s... |
def _init_params_default(self): """ Internal method for default parameter initialization """ # if there are some nan -> mean impute Yimp = self.Y.copy() Inan = sp.isnan(Yimp) Yimp[Inan] = Yimp[~Inan].mean() if self.P==1: C = sp.array([[Yimp.var()]]) else: C = sp.cov(Yimp.T) C /= float(self.n_randEffs) for ti in range(s... |
def _det_inference(self): """ Internal method for determining the inference method """ # 2 random effects with complete design -> gp2KronSum # TODO: add check for low-rankness, use GP3KronSumLR and GP2KronSumLR when possible if (self.n_randEffs==2) and (~sp.isnan(self.Y).any()): rv = 'GP2KronSum' else: rv = 'GP' return... |
def _check_inference(self, inference): """ Internal method for checking that the selected inference scheme is compatible with the specified model """ if inference=='GP2KronSum': assert self.n_randEffs==2, 'VarianceDecomposition: for fast inference number of random effect terms must be == 2' assert not sp.isnan(self.Y).... |
def _initGP(self): """ Internal method for initialization of the GP inference objetct """ if self._inference=='GP2KronSum': signalPos = sp.where(sp.arange(self.n_randEffs)!=self.noisPos)[0][0] gp = GP2KronSum(Y=self.Y, F=self.sample_designs, A=self.trait_designs, Cg=self.trait_covars[signalPos], Cn=self.trait_covars[se... |
def _buildTraitCovar(self, trait_covar_type='freeform', rank=1, fixed_trait_covar=None, jitter=1e-4): """ Internal functions that builds the trait covariance matrix using the LIMIX framework Args: trait_covar_type: type of covaraince to use. Default 'freeform'. possible values are rank: rank of a possible lowrank compo... |
= LowRankCov(self.P, rank=rank) elif trait_covar_type=='lowrank_id': cov = SumCov(LowRankCov(self.P, rank=rank), FixedCov(sp.eye(self.P))) elif trait_covar_type=='lowrank_diag': cov = SumCov(LowRankCov(self.P, rank=rank), DiagonalCov(self.P)) elif trait_covar_type=='block': cov = FixedCov(sp.ones([self.P, self.P])) eli... |
def optimize_with_repeates(self,fast=None,verbose=None,n_times=10,lambd=None,lambd_g=None,lambd_n=None): """ Train the model repeadly up to a number specified by the users with random restarts and return a list of all relative minima that have been found. This list is sorted according to least likelihood. Each list ter... |
sp.zeros_like(self.gp.getParams()['dataTerm']) # minimize n_times for i in range(n_times): scales1 = self._getScalesRand() fixed1 = 1e-1*sp.randn(fixed0.shape[0],fixed0.shape[1]) conv = self.trainGP(fast=fast,scales0=scales1,fixed0=fixed1,lambd=lambd,lambd_g=lambd_g,lambd_n=lambd_n) if conv: # compare with previous min... |
def getTraitCovarStdErrors(self,term_i): """ Returns standard errors on trait covariances from term_i (for the covariance estimate \see getTraitCovar) Args: term_i: index of the term we are interested in """ assert self.init, 'GP not initialised' assert self.fast==False, 'Not supported for fast implementation' if self.... |
def getVarianceCompStdErrors(self,univariance=False): """ Return the standard errors on the estimated variance components (for variance component estimates \see getVarianceComps) Args: univariance: Boolean indicator, if True variance components are normalized to sum up to 1 for each trait Returns: standard errors on va... |
def predictPhenos(self,use_fixed=None,use_random=None): """ predict the conditional mean (BLUP) Args: use_fixed: list of fixed effect indeces to use for predictions use_random: list of random effect indeces to use for predictions Returns: predictions (BLUP) """ assert self.noisPos is not None, 'No noise element' assert... |
predicting from fixed effects weights = self.getWeights() w_i = 0 for term_i in use_fixed: Fstar = self.Fstar[term_i] if Fstar is None: warnings.warn('warning: fixed effect term %d not used for predictions as it has None test sample design'%term_i) continue if self.P==1: A = sp.eye(1) else: A = self.vd.getDesign(term_i... |
def crossValidation(self,seed=0,n_folds=10,fullVector=True,verbose=None,D=None,**keywords): """ Split the dataset in n folds, predict each fold after training the model on all the others Args: seed: seed n_folds: number of folds to train the model on fullVector: Bolean indicator, if true it stops if no convergence is o... |
print((".. predict fold %d"%fold_j)) Itrain = Icv!=fold_j Itest = Icv==fold_j Ytrain = self.Y[Itrain,:] Ytest = self.Y[Itest,:] vc = VarianceDecomposition(Ytrain) vc.setTestSampleSize(Itest.sum()) for term_i in range(self.n_fixedEffs): F = self.vd.getFixed(term_i) Ftest = F[Itest,:] Ftrain = F[Itrain,:] if self.P>1: A ... |
if conv: Ystar[Itest,:] = vc.predictPhenos() else: warnings.warn('not converged for fold %d' % fold_j) Ystar[Itest,:] = sp.nan return Ystar,RV |
def _getH2singleTrait(self, K, verbose=None): """ Internal function for parameter initialization estimate variance components and fixed effect using a linear mixed model with an intercept and 2 random effects (one is noise) Args: K: covariance matrix of the non-noise random effect term """ verbose = dlimix.getVerbose(v... |
return sth |
def _getScalesDiag(self,termx=0): """ Internal function for parameter initialization Uses 2 term single trait model to get covar params for initialization Args: termx: non-noise term terms that is used for initialization """ assert self.P>1, 'VarianceDecomposition:: diagonal init_method allowed only for multi trait mod... |
def _getScalesPairwise(self,verbose=False, initDiagonal=False): """ Internal function for parameter initialization Uses a single trait model for initializing variances and a pairwise model to initialize correlations """ var = sp.zeros((self.P,2)) if initDiagonal: #1. fit single trait model if verbose: print('.. fit sin... |
lmm = fastLMM(X=covariates, Y=self.Y[:,p:p+1], G=None, K=K) opt = lmm.findH2(nGridH2=100) h2 = opt['h2'] var[p,:] = h2 * varY var[p,self.noisPos] = (1.0-h2) * varY #import ipdb;ipdb.set_trace() else: if verbose: print('.. random initialization of diagonal') var = sp.random.randn(var.shape[0],var.shape[1]) var = var*var... |
offset_g = abs(sp.minimum(sp.linalg.eigh(Cg0)[0].min(),0))+1e-4 offset_n = abs(sp.minimum(sp.linalg.eigh(Cn0)[0].min(),0))+1e-4 Cg0+=offset_g*sp.eye(self.P) Cn0+=offset_n*sp.eye(self.P) Lg = sp.linalg.cholesky(Cg0) Ln = sp.linalg.cholesky(Cn0) Cg_params0 = sp.concatenate([Lg[:,p][:p+1] for p in range(self.P)]) Cn_param... |
def _getScalesRand(self): """ Internal function for parameter initialization Return a vector of random scales """ if self.P>1: scales = [] for term_i in range(self.n_randEffs): _scales = sp.randn(self.diag[term_i].shape[0]) if self.jitter[term_i]>0: _scales = sp.concatenate((_scales,sp.array([sp.sqrt(self.jitter[term_i... |
def _perturbation(self): """ Internal function for parameter initialization Returns Gaussian perturbation """ if self.P>1: scales = [] for term_i in range(self.n_randEffs): _scales = sp.randn(self.diag[term_i].shape[0]) if self.jitter[term_i]>0: _scales = sp.concatenate((_scales,sp.zeros(1))) scales.append(_scales) sca... |
def _getHessian(self): """ Internal function for estimating parameter uncertainty COMPUTES OF HESSIAN OF E(\theta) = - log L(\theta | X, y) """ assert self.init, 'GP not initialised' assert self.fast==False, 'Not supported for fast implementation' if self.cache['Hessian'] is None: ParamMask=self.gp.getParamMask()['cova... |
def _getLaplaceCovar(self): """ Internal function for estimating parameter uncertainty Returns: the """ assert self.init, 'GP not initialised' assert self.fast==False, 'Not supported for fast implementation' if self.cache['Sigma'] is None: self.cache['Sigma'] = sp.linalg.inv(self._getHessian()) return self.cache['Sigma... |
def _getModelPosterior(self,min): """ USES LAPLACE APPROXIMATION TO CALCULATE THE BAYESIAN MODEL POSTERIOR """ Sigma = self._getLaplaceCovar(min) n_params = self.vd.getNumberScales() ModCompl = 0.5*n_params*sp.log(2*sp.pi)+0.5*sp.log(sp.linalg.det(Sigma)) RV = min['LML']+ModCompl return RV |
def join_tokens_to_sentences(tokens): """ Correctly joins tokens to multiple sentences Instead of always placing white-space between the tokens, it will distinguish between the next symbol and *not* insert whitespace if it is a sentence symbol (e.g. '.', or '?') Args: tokens: array of string tokens Returns: Joint sente... |
def split(inp_str, sep_char, maxsplit=-1, escape_char='\\'): """Separates a string on a character, taking into account escapes. :param str inp_str: string to split. :param str sep_char: separator character. :param int maxsplit: maximum number of times to split from left. :param str escape_char: escape character. :rtype... |
def _full_sub_array(data_obj, xj_path, create_dict_path): """Retrieves all array or dictionary elements for '*' JSON path marker. :param dict|list data_obj: The current data object. :param str xj_path: A json path. :param bool create_dict_path create a dict path. :return: tuple with two values: first is a result and se... |
def _get_array_index(array_path): """Translates @first @last @1 @-1 expressions into an actual array index. :param str array_path: Array path in XJ notation. :rtype: int :return: Array index. """ if not array_path.startswith('@'): raise XJPathError('Array index must start from @ symbol.') array_path = array_path[1:] if... |
def _single_array_element(data_obj, xj_path, array_path, create_dict_path): """Retrieves a single array for a '@' JSON path marker. :param list data_obj: The current data object. :param str xj_path: A json path. :param str array_path: A lookup key. :param bool create_dict_path create a dict path. """ val_type, array_pa... |
def _split_path(xj_path): """Extract the last piece of XJPath. :param str xj_path: A XJPath expression. :rtype: tuple[str|None, str] :return: A tuple where first element is a root XJPath and the second is a last piece of key. """ res = xj_path.rsplit('.', 1) root_key = res[0] if len(res) > 1: return root_key, res[1] el... |
def validate_path(xj_path): """Validates XJ path. :param str xj_path: XJ Path :raise: XJPathError if validation fails. """ if not isinstance(xj_path, str): raise XJPathError('XJPath must be a string') for path in split(xj_path, '.'): if path == '*': continue if path.startswith('@'): if path == '@first' or path == '@las... |
def _clean_key_type(key_name, escape_char=ESCAPE_SEQ): """Removes type specifier returning detected type and a key name without type specifier. :param str key_name: A key name containing type postfix. :rtype: tuple[type|None, str] :returns: Type definition and cleaned key name. """ for i in (2, 1): if len(key_name) < i... |
def path_lookup(data_obj, xj_path, create_dict_path=False): """Looks up a xj path in the data_obj. :param dict|list data_obj: An object to look into. :param str xj_path: A path to extract data from. :param bool create_dict_path: Create an element if type is specified. :return: A tuple where 0 value is an extracted valu... |
isinstance(value, val_type): raise XJPathError( 'Key %s expects type "%s", but found value type is "%s"' % (top_key, val_type.__name__, type(value).__name__)) if leftover: return path_lookup(value, leftover, create_dict_path) else: return value, True else: if val_type is not None: if not isinstance(data_obj, dict): rai... |
def strict_path_lookup(data_obj, xj_path, force_type=None): """Looks up a xj path in the data_obj. :param dict|list data_obj: An object to look into. :param str xj_path: A path to extract data from. :param type force_type: A type that excepted to be. :return: Returns result or throws an exception if value is not found.... |
def map_logging_verbosity(verbosity): ''' Parameters ---------- verbosity: int logging verbosity level (0-4) Returns ------- A logging level as exported by `logging` module. By default returns logging.NOTSET Raises ------ TypeError when `verbosity` doesn't have type int ValueError when `verbosity` is negative ''' if no... |
def configure_logging(): '''Configures the root logger for command line applications. Two stream handlers will be added to the logger: * "out" that will direct INFO & DEBUG messages to the standard output stream * "err" that will direct WARN, WARNING, ERROR, & CRITICAL messages to the standard error stream Note ---- Th... |
= 'out' stdout_handler.setFormatter(formatter) stdout_handler.setLevel(0) stdout_handler.addFilter(InfoFilter()) logger.addHandler(stdout_handler) |
def sort_prefixes(orig, prefixes='@+'): """Returns a sorted list of prefixes. Args: orig (str): Unsorted list of prefixes. prefixes (str): List of prefixes, from highest-priv to lowest. """ new = '' for prefix in prefixes: if prefix in orig: new += prefix return new |
def parse_modes(params, mode_types=None, prefixes=''): """Return a modelist. Args: params (list of str): Parameters from MODE event. mode_types (list): CHANMODES-like mode types. prefixes (str): PREFIX-like mode types. """ # we don't accept bare strings because we don't want to try to do # intelligent parameter splitti... |
return assembled_modes |
def read_envfile(fpath): """Reads environment variables from .env key-value file. Rules: * Lines starting with # (hash) considered comments. Inline comments not supported; * Multiline values not supported. * Invalid lines are ignored; * Matching opening-closing quotes are stripped; * ${VAL} will be replaced with VAL va... |
drop_quotes('"', val.strip())) if not key: continue for match in RE_TPL_VAR.findall(val): var_tpl, var_name = match var_val = environ.get(var_name) if var_val is None: var_val = env_vars.get(var_name) if var_val is not None: val = val.replace(var_tpl, var_val, 1) env_vars[key] = val return env_vars |
def query(self, ip_address): """Query the Project Honeypot Http:BL API for the given IP address :param ip_address: IP address to query :type ip_address: str :rtype: dict """ try: return self._decode_response( socket.gethostbyname(self._build_query(ip_address))) except socket.gaierror: # Not listed return { 'days_since_... |
def _build_query(self, ip_address): """Returns the Http:BL query string to use :param ip_address: IP address to query :type ip_address: str :returns: str """ return '{}.{}.{}'.format( self.key, self._reverse_ip(ip_address), DNSBL_SUFFIX) |
def _decode_response(self, ip_address): """Decodes a HttpBL response IP and return data structure of response data. :param ip_address: IP address to query :type ip_address: str :rtype: dict :raises: ValueError """ # Reverse the IP, reassign the octets to integers vt, ts, days, rc = [int(o) for o in ip_address.split('.'... |
[SEARCH_ENGINE]} |
def verify_jwt(signed_request, expected_aud, secret, validators=[], required_keys=('request.pricePoint', 'request.name', 'request.description', 'response.transactionID'), algorithms=None): """ Verifies a postback/chargeback JWT. Returns the trusted JSON data from the original request. When there's an error, an exceptio... |
list of valid JWT algorithms to accept. By default this will only include HS256 because that's what the Firefox Marketplace uses. """ if not algorithms: algorithms = ['HS256'] issuer = _get_issuer(signed_request=signed_request) app_req = verify_sig(signed_request, secret, issuer=issuer, algorithms=algorithms, expected_... |
def verify_claims(app_req, issuer=None): """ Verify JWT claims. All times must be UTC unix timestamps. These claims will be verified: - iat: issued at time. If JWT was issued more than an hour ago it is rejected. - exp: expiration time. All exceptions are derived from :class:`mozpay.exc.InvalidJWT`. For expirations a :... |
def verify_keys(app_req, required_keys, issuer=None): """ Verify all JWT object keys listed in required_keys. Each required key is specified as a dot-separated path. The key values are returned as a list ordered by how you specified them. Take this JWT for example:: { "iss": "...", "aud": "...", "request": { "pricePoin... |
% (key_path, kp), issuer=issuer) val = parent.get(kp, None) if not val: raise InvalidJWT('JWT is missing %r: %s is not a valid key' % (key_path, kp), issuer=issuer) parent = val key_vals.append(parent) # last value of key_path return key_vals |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.