text
stringlengths
81
112k
The default destination from logging in, redirect to the actual profile URL def redirect_profile(request): ''' The default destination from logging in, redirect to the actual profile URL ''' if request.user.is_authenticated: return HttpResponseRedirect(reverse('wafer_user_profile', ...
Returns a badge for the user's reviews of the talk def reviewed_badge(user, talk): """Returns a badge for the user's reviews of the talk""" context = { 'reviewed': False, } review = None if user and not user.is_anonymous(): review = talk.reviews.filter(reviewer=user).first() i...
r"""Warp inputs that are confined to the unit hypercube using the regularized incomplete beta function. Applies separately to each dimension, designed for use with :py:class:`WarpingFunction`. Assumes that your inputs `X` lie entirely within the unit hypercube [0, 1]. Note that you may ex...
r"""Warp inputs with a linear transformation. Applies the warping .. math:: w(x) = \frac{x-a}{b-a} to each dimension. If you set `a=min(X)` and `b=max(X)` then this is a convenient way to map your inputs to the unit hypercube. Parameters ---------- X : ar...
Evaluate the (possibly recursive) warping function and its derivatives. Parameters ---------- X : array, (`M`,) The points (from dimension `d`) to evaluate the warping function at. d : int The dimension to warp. n : int The derivative ...
Set `enforce_bounds` for both of the kernels to a new value. def enforce_bounds(self, v): """Set `enforce_bounds` for both of the kernels to a new value. """ self._enforce_bounds = v self.k.enforce_bounds = v self.w.enforce_bounds = v
Set the free parameters. Note that this bypasses enforce_bounds. def free_params(self, value): """Set the free parameters. Note that this bypasses enforce_bounds. """ value = scipy.asarray(value, dtype=float) self.K_up_to_date = False self.k.free_params = value[:self.k.num_free_...
Set the (free) hyperparameters. Parameters ---------- new_params : :py:class:`Array` or other Array-like New values of the free parameters. Raises ------ ValueError If the length of `new_params` is not consistent with :py:attr:`se...
Handles GET requests and instantiates blank versions of the form and its inline formsets. def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates blank versions of the form and its inline formsets. """ # Prepare base if 'pk' in kwargs: sel...
andles POST requests, instantiating a form instance and its inline formsets with the passed POST variables and then checking them for validity. def post(self, request, *args, **kwargs): """ andles POST requests, instantiating a form instance and its inline formsets with the passed POST variables and th...
Called if all forms are valid. Creates a Recipe instance along with associated Ingredients and Instructions and then redirects to a success page. def form_valid(self, form, forms): """ Called if all forms are valid. Creates a Recipe instance along with associated Ingredients and Instructions and then r...
Called if a form is invalid. Re-renders the context data with the data-filled forms and errors. def form_invalid(self, form, forms, open_tabs, position_form_default): """ Called if a form is invalid. Re-renders the context data with the data-filled forms and errors. """ # return self.re...
Wrapper for :py:func:`fmin_slsqp` to allow it to be called with :py:func:`minimize`-like syntax. This is included to enable the code to run with :py:mod:`scipy` versions older than 0.11.0. Accepts `opt_kwargs` in the same format as used by :py:func:`scipy.optimize.minimize`, with the additional precon...
Implementation of the Pochhammer symbol :math:`(a)_n` which handles negative integer arguments properly. Need conditional statement because scipy's impelementation of the Pochhammer symbol is wrong for negative integer arguments. This function uses the definition from http://functions.wolfram.com/G...
r"""Find the derivatives of :math:`K_\nu(y^{1/2})`. Parameters ---------- nu : float The order of the modified Bessel function of the second kind. y : array of float The values to evaluate at. n : nonnegative int, optional The order of derivative to take. def Kn2Der(nu,...
r"""Computes the function :math:`y^{\nu/2} K_{\nu}(y^{1/2})` and its derivatives. Care has been taken to handle the conditions at :math:`y=0`. For `n=0`, uses a direct evaluation of the expression, replacing points where `y=0` with the appropriate value. For `n>0`, uses a general sum expressio...
r"""Recursive evaluation of the incomplete Bell polynomial :math:`B_{n, k}(x)`. Evaluates the incomplete Bell polynomial :math:`B_{n, k}(x_1, x_2, \dots, x_{n-k+1})`, also known as the partial Bell polynomial or the Bell polynomial of the second kind. This polynomial is useful in the evaluation of (the...
Generate the restricted growth strings for all of the partitions of an `n`-member set. Uses Algorithm H from page 416 of volume 4A of Knuth's `The Art of Computer Programming`. Returns the partitions in lexicographical order. Parameters ---------- n : scalar int, non-negative Numbe...
Generate all of the partitions of a set. This is a helper function that utilizes the restricted growth strings from :py:func:`generate_set_partition_strings`. The partitions are returned in lexicographic order. Parameters ---------- set_ : :py:class:`Array` or other Array-like, (`m`,) ...
Returns a copy of arr with duplicate rows removed. From Stackoverflow "Find unique rows in numpy.array." Parameters ---------- arr : :py:class:`Array`, (`m`, `n`) The array to find the unique rows of. return_index : bool, optional If True, the indices of the unique rows in ...
Compute the average statistics (mean, std dev) for the given values. Parameters ---------- vals : array-like, (`M`, `D`) Values to compute the average statistics along the specified axis of. check_nan : bool, optional Whether or not to check for (and exclude) NaN's. Default is False...
Make a plot of a mean curve with uncertainty envelopes. def univariate_envelope_plot(x, mean, std, ax=None, base_alpha=0.375, envelopes=[1, 3], lb=None, ub=None, expansion=10, **kwargs): """Make a plot of a mean curve with uncertainty envelopes. """ if ax is None: f = plt.figure() ax = f.ad...
r"""Create summary statistics of the flattened chain of the sampler. The confidence regions are computed from the quantiles of the data. Parameters ---------- sampler : :py:class:`emcee.Sampler` instance or array, (`n_temps`, `n_chains`, `n_samp`, `n_dim`), (`n_chains`, `n_samp`, `n_dim`) or (...
Plot the results of MCMC sampler (posterior and chains). Loosely based on triangle.py. Provides extensive options to format the plot. Parameters ---------- sampler : :py:class:`emcee.Sampler` instance or array, (`n_temps`, `n_chains`, `n_samp`, `n_dim`), (`n_chains`, `n_samp`, `n_dim`) or (`n_...
Make a plot of the sampler's "fingerprint": univariate marginal histograms for all hyperparameters. The hyperparameters are mapped to [0, 1] using :py:meth:`hyperprior.elementwise_cdf`, so this can only be used with prior distributions which implement this function. Returns the figure and axis...
Make a plot of the sampler's correlation or covariance matrix. Returns the figure and axis created. Parameters ---------- sampler : :py:class:`emcee.Sampler` instance or array, (`n_temps`, `n_chains`, `n_samp`, `n_dim`), (`n_chains`, `n_samp`, `n_dim`) or (`n_samp`, `n_dim`) The sample...
r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, ...
r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given ...
Draw random samples of the hyperparameters. The outputs of the two priors are stacked vertically. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is...
r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, ...
r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given ...
Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. def random_draw(self, size=None): """Draw random sample...
Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. def random_draw(self, size=None): """Draw random sample...
r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, ...
r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given ...
Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. def random_draw(self, size=None): """Draw random sample...
The bounds of the random variable. Set `self.i=0.95` to return the 95% interval if this is used for setting bounds on optimizers/etc. where infinite bounds may not be useful. def bounds(self): """The bounds of the random variable. Set `self.i=0.95` to return the 95% in...
r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, ...
r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given ...
Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. def random_draw(self, size=None): """Draw random sample...
The bounds of the random variable. Set `self.i=0.95` to return the 95% interval if this is used for setting bounds on optimizers/etc. where infinite bounds may not be useful. def bounds(self): """The bounds of the random variable. Set `self.i=0.95` to return the 95% in...
r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, ...
r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given ...
Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. def random_draw(self, size=None): """Draw random sample...
The bounds of the random variable. Set `self.i=0.95` to return the 95% interval if this is used for setting bounds on optimizers/etc. where infinite bounds may not be useful. def bounds(self): """The bounds of the random variable. Set `self.i=0.95` to return the 95% in...
r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, ...
r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given ...
Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. def random_draw(self, size=None): """Draw random sample...
r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, ...
r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given ...
Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. def random_draw(self, size=None): """Draw random sample...
Zapier can post something like this when tickets are cancelled { "ticket_type": "Individual (Regular)", "barcode": "12345678", "email": "demo@example.com" } def zapier_cancel_hook(request): ''' Zapier can post something like this when tickets are cancelled { "ticket_...
Zapier can POST something like this when tickets are bought: { "ticket_type": "Individual (Regular)", "barcode": "12345678", "email": "demo@example.com" } def zapier_guest_hook(request): ''' Zapier can POST something like this when tickets are bought: { "ticket_typ...
Gains token from secure backend service. :return: Token formatted for Cocaine protocol header. def fetch_token(self): """Gains token from secure backend service. :return: Token formatted for Cocaine protocol header. """ grant_type = 'client_credentials' channel = yiel...
:param service: Service to wrap in. :param mod: Name (type) of token refresh backend. :param client_id: Client identifier. :param client_secret: Client secret. :param tok_update_sec: Token update interval in seconds. def make_secure_adaptor(service, mod, client_id, client_secret, tok_up...
Extracting information from an albacore summary file. Only reads which have a >0 length are returned. The fields below may or may not exist, depending on the type of sequencing performed. Fields 1-14 are for 1D sequencing. Fields 1-23 for 2D sequencing. Fields 24-27, 2-5, 22-23 for 1D^2 (1D2) sequ...
Check if bam file is valid. Bam file should: - exists - has an index (create if necessary) - is sorted by coordinate - has at least one mapped read def check_bam(bam, samtype="bam"): """Check if bam file is valid. Bam file should: - exists - has an index (create if necessary) ...
Extracting metrics from unaligned bam format Extracting lengths def process_ubam(bam, **kwargs): """Extracting metrics from unaligned bam format Extracting lengths """ logging.info("Nanoget: Starting to collect statistics from ubam file {}.".format(bam)) samfile = pysam.AlignmentFile(bam, "rb",...
Combines metrics from bam after extraction. Processing function: calls pool of worker functions to extract from a bam file the following metrics: -lengths -aligned lengths -qualities -aligned qualities -mapping qualities -edit distances to the reference genome scaled by read length ...
Extracts metrics from bam. Worker function per chromosome loop over a bam file and create list with tuples containing metrics: -qualities -aligned qualities -lengths -aligned lengths -mapping qualities -edit distances to the reference genome scaled by read length def extract_from_bam(p...
Return the percent identity of a read. based on the NM tag if present, if not calculate from MD tag and CIGAR string read.query_alignment_length can be zero in the case of ultra long reads aligned with minimap2 -L def get_pID(read): """Return the percent identity of a read. based on the NM tag i...
Return handles from compressed files according to extension. Check for which fastq input is presented and open a handle accordingly Can read from compressed files (gz, bz2, bgz) or uncompressed Relies on file extensions to recognize compression def handle_compressed_input(inputfq, file_type="fastq"): ...
Combine metrics extracted from a fasta file. def process_fasta(fasta, **kwargs): """Combine metrics extracted from a fasta file.""" logging.info("Nanoget: Starting to collect statistics from a fasta file.") inputfasta = handle_compressed_input(fasta, file_type="fasta") return ut.reduce_memory_usage(pd....
Combine metrics extracted from a fastq file. def process_fastq_plain(fastq, **kwargs): """Combine metrics extracted from a fastq file.""" logging.info("Nanoget: Starting to collect statistics from plain fastq file.") inputfastq = handle_compressed_input(fastq) return ut.reduce_memory_usage(pd.DataFrame...
Extract metrics from a fastq file. Return average quality and read length def extract_from_fastq(fq): """Extract metrics from a fastq file. Return average quality and read length """ for rec in SeqIO.parse(fq, "fastq"): yield nanomath.ave_qual(rec.letter_annotations["phred_quality"]), len...
Generator for returning metrics extracted from fastq. Extract from a fastq file: -readname -average and median quality -read_lenght def stream_fastq_full(fastq, threads): """Generator for returning metrics extracted from fastq. Extract from a fastq file: -readname -average and median ...
Extract metrics from a fastq file. Return identifier, read length, average quality and median quality def extract_all_from_fastq(rec): """Extract metrics from a fastq file. Return identifier, read length, average quality and median quality """ return (rec.id, len(rec), nan...
Extract metrics from a richer fastq file. Extract information from fastq files generated by albacore or MinKNOW, containing richer information in the header (key-value pairs) read=<int> [72] ch=<int> [159] start_time=<timestamp> [2016-07-15T14:23:22Z] # UTC ISO 8601 ISO 3339 timestamp Z indica...
Generator function adapted from https://github.com/lh3/readfq. def readfq(fp): """Generator function adapted from https://github.com/lh3/readfq.""" last = None # this is a buffer keeping the last unprocessed line while True: # mimic closure; is it a bad idea? if not last: # the first record or a...
Minimal fastq metrics extractor. Quickly parse a fasta/fastq file - but makes expectations on the file format There will be dragons if unexpected format is used Expects a fastq_rich format, but extracts only timestamp and length def fq_minimal(fq): """Minimal fastq metrics extractor. Quickly pars...
Swiftly extract minimal features (length and timestamp) from a rich fastq file def process_fastq_minimal(fastq, **kwargs): """Swiftly extract minimal features (length and timestamp) from a rich fastq file""" infastq = handle_compressed_input(fastq) try: df = pd.DataFrame( data=[rec for ...
Returns Piece subclass given index of piece. :type: index: int :type: loc Location :raise: KeyError def _get_piece(string, index): """ Returns Piece subclass given index of piece. :type: index: int :type: loc Location :raise: KeyError """ piece = string[index].strip() pi...
Converts a string written in short algebraic form into an incomplete move. These incomplete moves do not have the initial location specified and therefore cannot be used to update the board. IN order to fully utilize incomplete move, it must be run through ``make_legal()`` with the corresponding positio...
Converts an incomplete move (initial ``Location`` not specified) and the corresponding position into the a complete move with the most likely starting point specified. If no moves match, ``None`` is returned. :type: move: Move :type: position: Board :rtype: Move def make_legal(move, position):...
Converts a string written in short algebraic form, the color of the side whose turn it is, and the corresponding position into a complete move that can be played. If no moves match, None is returned. Examples: e4, Nf3, exd5, Qxf3, 00, 000, e8=Q :type: algebraic_string: str :type: input_color: ...
Converts a string written in long algebraic form and the corresponding position into a complete move (initial location specified). Used primarily for UCI, but can be used for other purposes. :type: alg_str: str :type: position: Board :rtype: Move def long_alg(alg_str, position): """ Co...
set or reset hyb and neighbors marks to atoms. def reset_query_marks(self): """ set or reset hyb and neighbors marks to atoms. """ for i, atom in self.atoms(): neighbors = 0 hybridization = 1 # hybridization 1- sp3; 2- sp2; 3- sp1; 4- aromatic ...
remove explicit hydrogen if possible :return: number of removed hydrogens def implicify_hydrogens(self): """ remove explicit hydrogen if possible :return: number of removed hydrogens """ explicit = defaultdict(list) c = 0 for n, atom in self.atoms(): ...
add explicit hydrogens to atoms :return: number of added atoms def explicify_hydrogens(self): """ add explicit hydrogens to atoms :return: number of added atoms """ tmp = [] for n, atom in self.atoms(): if atom.element != 'H': for _ ...
create substructure containing atoms from nbunch list :param atoms: list of atoms numbers of substructure :param meta: if True metadata will be copied to substructure :param as_view: If True, the returned graph-view provides a read-only view of the original structure scaffold withou...
check valences of all atoms :return: list of invalid atoms def check_valence(self): """ check valences of all atoms :return: list of invalid atoms """ return [x for x, atom in self.atoms() if not atom.check_valence(self.environment(x))]
return VF2 GraphMatcher MoleculeContainer < MoleculeContainer MoleculeContainer < CGRContainer def _matcher(self, other): """ return VF2 GraphMatcher MoleculeContainer < MoleculeContainer MoleculeContainer < CGRContainer """ if isinstance(other, (self._...
Turn a date into a datetime at midnight. def to_datetime(date): """Turn a date into a datetime at midnight. """ return datetime.datetime.combine(date, datetime.datetime.min.time())
Yield an IssueSnapshot for each time the issue size changed def iter_size_changes(self, issue): """Yield an IssueSnapshot for each time the issue size changed """ # Find the first size change, if any try: size_changes = list(filter(lambda h: h.field == 'Story Points', ...
Yield an IssueSnapshot for each time the issue changed status or resolution def iter_changes(self, issue, include_resolution_changes=True): """Yield an IssueSnapshot for each time the issue changed status or resolution """ is_resolved = False # Find the first status ch...
Return a list of issues with changelog metadata. Searches for the `issue_types`, `project`, `valid_resolutions` and 'jql_filter' set in the passed-in `criteria` object. Pass a JQL string to further qualify the query results. def find_issues(self, criteria={}, jql=None, order='KEY ASC', verbos...
Lists existing catalogs respect to ui view template format def list_catalogs(self): """ Lists existing catalogs respect to ui view template format """ _form = CatalogSelectForm(current=self.current) _form.set_choices_of('catalog', [(i, i) for i in fixture_bucket.get_keys()]) ...
Get existing catalog and fill the form with the model data. If given key not found as catalog, it generates an empty catalog data form. def get_catalog(self): """ Get existing catalog and fill the form with the model data. If given key not found as catalog, it generates an empty catalog...
Saves the catalog data to given key Cancels if the cmd is cancel Notifies user with the process. def save_catalog(self): """ Saves the catalog data to given key Cancels if the cmd is cancel Notifies user with the process. """ if self.input["cmd"] == 'save...
converts DD-MM-YYYY to YYYY-MM-DDT00:00:00Z def date_to_solr(d): """ converts DD-MM-YYYY to YYYY-MM-DDT00:00:00Z""" return "{y}-{m}-{day}T00:00:00Z".format(day=d[:2], m=d[3:5], y=d[6:]) if d else d
converts YYYY-MM-DDT00:00:00Z to DD-MM-YYYY def solr_to_date(d): """ converts YYYY-MM-DDT00:00:00Z to DD-MM-YYYY """ return "{day}:{m}:{y}".format(y=d[:4], m=d[5:7], day=d[8:10]) if d else d
converts some (tr) non-ascii chars to ascii counterparts, then return the result as lowercase def to_safe_str(s): """ converts some (tr) non-ascii chars to ascii counterparts, then return the result as lowercase """ # TODO: This is insufficient as it doesn't do anything for other non-ascii char...
Merge multiple dictionaries, keeping the truthy values in case of key collisions. Accepts any number of dictionaries, or any other object that returns a 2-tuple of key and value pairs when its `.items()` method is called. If a key exists in multiple dictionaries passed to this function, the values from th...
Perform the version upgrade on the database. def perform(self): """Perform the version upgrade on the database. """ db_versions = self.table.versions() version = self.version if (version.is_processed(db_versions) and not self.config.force_version == self.version...
Inner method for version upgrade. Not intended for standalone use. This method performs the actual version upgrade with all the pre, post operations and addons upgrades. :param version: The migration version to upgrade to :type version: Instance of Version class def _perform_version(s...
Log out view. Simply deletes the session object. For showing logout message: 'show_logout_message' field should be True in current.task_data, Message should be sent in current.task_data with 'logout_message' field. Message title should be sent in current.task_data with 'logout_title' fie...
open websocket connection def _do_upgrade(self): """ open websocket connection """ self.current.output['cmd'] = 'upgrade' self.current.output['user_id'] = self.current.user_id self.terminate_existing_login() self.current.user.bind_private_channel(self.current.session.sess_id) ...
Authenticate user with given credentials. Connects user's queue and exchange def do_view(self): """ Authenticate user with given credentials. Connects user's queue and exchange """ self.current.output['login_process'] = True self.current.task_data['login_successf...
Show :attr:`LoginForm` form. def show_view(self): """ Show :attr:`LoginForm` form. """ self.current.output['login_process'] = True if self.current.is_auth: self._do_upgrade() else: self.current.output['forms'] = LoginForm(current=self.current).ser...
:param mapping: generator :return: filtered generator def skip(mapping): """ :param mapping: generator :return: filtered generator """ found = set() for m in mapping: matched_atoms = set(m.values()) if found.intersection(matched_atoms): continue found.upd...