INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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 created. Parameters ------...
def plot_sampler_fingerprint( sampler, hyperprior, weights=None, cutoff_weight=None, nbins=None, labels=None, burn=0, chain_mask=None, temp_idx=0, points=None, plot_samples=False, sample_color='k', point_color=None, point_lw=3, title='', rot_x_labels=False, figsize=None ): """Mak...
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 sampler to plot the chains/ marginals of. Can also be an arr...
def plot_sampler_cov( sampler, method='corr', weights=None, cutoff_weight=None, labels=None, burn=0, chain_mask=None, temp_idx=0, cbar_label=None, title='', rot_x_labels=False, figsize=None, xlabel_on_top=True ): """Make a plot of the sampler's correlation or covariance matrix. ...
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 given a vector: math: q of num_params valu...
def sample_u(self, q): 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. Ba...
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 a vector: math: q of num_params values each of...
def elementwise_cdf(self, p): 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. Basic...
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 None.
def random_draw(self, size=None): """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 o...
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 given a vector: math: q of num_params valu...
def sample_u(self, q): 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. Ba...
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 a vector: math: q of num_params values each of...
def elementwise_cdf(self, p): 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. Basic...
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 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. """ ...
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 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. """ ...
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 given a vector: math: q of num_params valu...
def sample_u(self, q): 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. Ba...
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 a vector: math: q of num_params values each of...
def elementwise_cdf(self, p): 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. Basic...
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 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. """ ...
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% interval if this is used for setting bounds on optimizers/etc. where infinite bounds may not be useful. """ return [scipy.stats.norm.interval(self.i, loc=m, scale=s) for s, m in z...
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 given a vector: math: q of num_params valu...
def sample_u(self, q): 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. Ba...
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 a vector: math: q of num_params values each of...
def elementwise_cdf(self, p): 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. Basic...
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 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. """ ...
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% interval if this is used for setting bounds on optimizers/etc. where infinite bounds may not be useful. """ return [scipy.stats.lognorm.interval(self.i, s, loc=0, scale=em) for s,...
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 given a vector: math: q of num_params valu...
def sample_u(self, q): 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. Ba...
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 a vector: math: q of num_params values each of...
def elementwise_cdf(self, p): 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. Basic...
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 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. """ ...
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% interval if this is used for setting bounds on optimizers/etc. where infinite bounds may not be useful. """ return [scipy.stats.gamma.interval(self.i, a, loc=0, scale=1.0 / b) for...
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 given a vector: math: q of num_params valu...
def sample_u(self, q): 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. Ba...
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 a vector: math: q of num_params values each of...
def elementwise_cdf(self, p): 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. Basic...
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 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. """ ...
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 given a vector: math: q of num_params valu...
def sample_u(self, q): 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. Ba...
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 a vector: math: q of num_params values each of...
def elementwise_cdf(self, p): 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. Basic...
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 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. """ ...
Zapier can post something like this when tickets are cancelled { ticket_type: Individual ( Regular ) barcode: 12345678 email: demo
def zapier_cancel_hook(request): ''' Zapier can post something like this when tickets are cancelled { "ticket_type": "Individual (Regular)", "barcode": "12345678", "email": "demo@example.com" } ''' if request.META.get('HTTP_X_ZAPIER_SECRET', None) != settings.WAFER_TICKET...
Zapier can POST something like this when tickets are bought: {
def zapier_guest_hook(request): ''' Zapier can POST something like this when tickets are bought: { "ticket_type": "Individual (Regular)", "barcode": "12345678", "email": "demo@example.com" } ''' if request.META.get('HTTP_X_ZAPIER_SECRET', None) != settings.WAFER_TICKETS_...
Gains token from secure backend service.
def fetch_token(self): """Gains token from secure backend service. :return: Token formatted for Cocaine protocol header. """ grant_type = 'client_credentials' channel = yield self._tvm.ticket_full( self._client_id, self._client_secret, grant_type, {}) ticket...
: 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_update_sec=None): """ :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:...
Extracting information from an albacore summary file.
def process_summary(summaryfile, **kwargs): """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 sequencin...
Check if bam file is valid.
def check_bam(bam, samtype="bam"): """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 """ ut.check_existance(bam) samfile = pysam.AlignmentFile(bam, "rb") if not samfile.has_index...
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", check_sq=False) if not samfile.has_index(): pysam.index(...
Combines metrics from bam after extraction.
def process_bam(bam, **kwargs): """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 refe...
Extracts metrics from bam.
def extract_from_bam(params): """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 b...
Return the percent identity of a read.
def get_pID(read): """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 """ try: return 100 * (1 - read.get_tag("NM") / re...
Return handles from compressed files according to extension.
def handle_compressed_input(inputfq, file_type="fastq"): """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 compressio...
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.DataFrame( data=[len(rec) for rec in S...
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( data=[res for res in extract_from_fa...
Extract metrics from a fastq file.
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(rec)
Generator for returning metrics extracted from fastq.
def stream_fastq_full(fastq, threads): """Generator for returning metrics extracted from fastq. Extract from a fastq file: -readname -average and median quality -read_lenght """ logging.info("Nanoget: Starting to collect full metrics from plain fastq file.") inputfastq = handle_compress...
Extract metrics from a fastq file.
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), nanomath.ave_qual(rec.letter_annotations["phred_quality"]), nanomath.median_qual(rec.letter_annotat...
Extract metrics from a richer fastq file.
def process_fastq_rich(fastq, **kwargs): """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]...
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 record following a fastq for l in fp: # search for...
Minimal fastq metrics extractor.
def fq_minimal(fq): """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 """ try: while True: ti...
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 rec in fq_minimal(infastq) if rec], columns=["timestamp", "lengths"]...
Returns Piece subclass given index of piece.
def _get_piece(string, index): """ Returns Piece subclass given index of piece. :type: index: int :type: loc Location :raise: KeyError """ piece = string[index].strip() piece = piece.upper() piece_dict = {'R': Rook, 'P': Pawn, 'B': Bishop, ...
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 position. It is recommended...
def incomplete_alg(alg_str, input_color, position): """ 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...
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.
def make_legal(move, position): """ 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 :...
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.
def short_alg(algebraic_string, input_color, 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, ...
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.
def long_alg(alg_str, position): """ 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 ...
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 for j, bond in self._adj[i].items(): ...
remove explicit hydrogen if possible
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(): if atom.element == 'H': for m in self.neighbors(n): ...
add explicit hydrogens to 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 _ in range(atom.get_implicit_h([x.order for x in self._adj[n].values()])): ...
create substructure containing atoms from nbunch list
def substructure(self, atoms, meta=False, as_view=True): """ 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 pr...
check valences of all 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
def _matcher(self, other): """ return VF2 GraphMatcher MoleculeContainer < MoleculeContainer MoleculeContainer < CGRContainer """ if isinstance(other, (self._get_subclass('CGRContainer'), MoleculeContainer)): return GraphMatcher(other, self, lambda x, y: x ==...
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', itertools.chain.from_iterab...
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 change, if any try: status_changes = list(filter( l...
Return a list of issues with changelog metadata.
def find_issues(self, criteria={}, jql=None, order='KEY ASC', verbose=False, changelog=True): """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...
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()]) self.form_out(_form)
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 data form. """ catalog_data = fixture_bucket.get(self.input['form']['catalog']) # define add or edit based on 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_catalog': try: edited_object = dict() for i in self.input["form"]["Ca...
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 chars return re.sub(r'[^0-9a-zA-Z]+', '_', s.strip().replace(u'ğ', 'g').replace(u'ö', 'o').replace(...
Merge multiple dictionaries keeping the truthy values in case of key collisions.
def merge_truthy(*dicts): """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 ...
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.number): self.log( ...
Inner method for version upgrade.
def _perform_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: I...
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 field.
def logout(current): """ 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....
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) user_sess = UserSessi...
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_successful'] = False if self.current.is_auth: self._do_upgrade() e...
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).serialize()
: 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.update(matched_atoms) yield m
match each pattern to each molecule. if all patterns matches with all molecules return generator of all possible mapping.
def __get_mapping(self, structures): """ match each pattern to each molecule. if all patterns matches with all molecules return generator of all possible mapping. :param structures: disjoint molecules :return: mapping generator """ for c in permutations(s...
return the cached value or default if it can t be found
def get(self, default=None): """ return the cached value or default if it can't be found :param default: default value :return: cached value """ d = cache.get(self.key) return ((json.loads(d.decode('utf-8')) if self.serialize else d) if d is not N...
set cache value
def set(self, val, lifetime=None): """ set cache value :param val: any picklable object :param lifetime: exprition time in sec :return: val """ cache.set(self.key, (json.dumps(val) if self.serialize else val), lifetime or setti...
Add given value to item ( list )
def add(self, val): """ Add given value to item (list) Args: val: A JSON serializable object. Returns: Cache backend response. """ return cache.lpush(self.key, json.dumps(val) if self.serialize else val)
Get all list items.
def get_all(self): """ Get all list items. Returns: Cache backend response. """ result = cache.lrange(self.key, 0, -1) return (json.loads(item.decode('utf-8')) for item in result if item) if self.serialize else result
Removes given item from the list.
def remove_item(self, val): """ Removes given item from the list. Args: val: Item Returns: Cache backend response. """ return cache.lrem(self.key, json.dumps(val))
Removes all keys of this namespace Without args clears all keys starting with cls. PREFIX if called with args clears keys starting with given cls. PREFIX + args
def flush(cls, *args): """ Removes all keys of this namespace Without args, clears all keys starting with cls.PREFIX if called with args, clears keys starting with given cls.PREFIX + args Args: *args: Arbitrary number of arguments. Returns: List ...
Deletes session if keepalive request expired otherwise updates the keepalive timestamp value
def update_or_expire_session(self): """ Deletes session if keepalive request expired otherwise updates the keepalive timestamp value """ if not hasattr(self, 'key'): return now = time.time() timestamp = float(self.get() or 0) or now sess_id = s...
Sends a message to possible owners of the current workflows next lane.
def send_message_for_lane_change(sender, **kwargs): """ Sends a message to possible owners of the current workflows next lane. Args: **kwargs: ``current`` and ``possible_owners`` are required. sender (User): User object """ current = kwargs['current'] owners = kwargs['possi...
Encrypts password of the user.
def set_password(sender, **kwargs): """ Encrypts password of the user. """ if sender.model_class.__name__ == 'User': usr = kwargs['object'] if not usr.password.startswith('$pbkdf2'): usr.set_password(usr.password) usr.save()
Main screen for channel management. Channels listed and operations can be chosen on the screen. If there is an error message like non - choice it is shown here.
def channel_list(self): """ Main screen for channel management. Channels listed and operations can be chosen on the screen. If there is an error message like non-choice, it is shown here. """ if self.current.task_data.get('msg', False): if self.curre...
It controls errors. If there is an error returns channel list screen with error message.
def channel_choice_control(self): """ It controls errors. If there is an error, returns channel list screen with error message. """ self.current.task_data['control'], self.current.task_data['msg'] \ = self.selection_error_control(self.input['form']) if self.cu...
Features of new channel are specified like channel s name owner etc.
def create_new_channel(self): """ Features of new channel are specified like channel's name, owner etc. """ self.current.task_data['new_channel'] = True _form = NewChannelForm(Channel(), current=self.current) _form.title = _(u"Specify Features of New Channel to Create") ...
It saves new channel according to specified channel features.
def save_new_channel(self): """ It saves new channel according to specified channel features. """ form_info = self.input['form'] channel = Channel(typ=15, name=form_info['name'], description=form_info['description'], owner_id=f...
It is a channel choice list and chosen channels at previous step shouldn t be on the screen.
def choose_existing_channel(self): """ It is a channel choice list and chosen channels at previous step shouldn't be on the screen. """ if self.current.task_data.get('msg', False): self.show_warning_messages() _form = ChannelListForm() _form.title = ...
It controls errors. It generates an error message if zero or more than one channels are selected.
def existing_choice_control(self): """ It controls errors. It generates an error message if zero or more than one channels are selected. """ self.current.task_data['existing'] = False self.current.task_data['msg'] = _(u"You should choose just one channel to do operation."...
A channel can be splitted to new channel or other existing channel. It creates subscribers list as selectable to moved.
def split_channel(self): """ A channel can be splitted to new channel or other existing channel. It creates subscribers list as selectable to moved. """ if self.current.task_data.get('msg', False): self.show_warning_messages() self.current.task_data['split_o...
It controls subscribers choice and generates error message if there is a non - choice.
def subscriber_choice_control(self): """ It controls subscribers choice and generates error message if there is a non-choice. """ self.current.task_data['option'] = None self.current.task_data['chosen_subscribers'], names = self.return_selected_form_items( sel...
Channels and theirs subscribers are moved completely to new channel or existing channel.
def move_complete_channel(self): """ Channels and theirs subscribers are moved completely to new channel or existing channel. """ to_channel = Channel.objects.get(self.current.task_data['target_channel_key']) chosen_channels = self.current.task_data['chosen_channels'] ...
After splitting operation only chosen subscribers are moved to new channel or existing channel.
def move_chosen_subscribers(self): """ After splitting operation, only chosen subscribers are moved to new channel or existing channel. """ from_channel = Channel.objects.get(self.current.task_data['chosen_channels'][0]) to_channel = Channel.objects.get(self.current.task_...
While splitting channel and moving chosen subscribers to new channel old channel s messages are copied and moved to new channel.
def copy_and_move_messages(from_channel, to_channel): """ While splitting channel and moving chosen subscribers to new channel, old channel's messages are copied and moved to new channel. Args: from_channel (Channel object): move messages from channel to_chann...
It shows incorrect operations or successful operation messages.
def show_warning_messages(self, title=_(u"Incorrect Operation"), box_type='warning'): """ It shows incorrect operations or successful operation messages. Args: title (string): title of message box box_type (string): type of message box (warning, info) """ ...
It returns chosen keys list from a given form.
def return_selected_form_items(form_info): """ It returns chosen keys list from a given form. Args: form_info: serialized list of dict form data Returns: selected_keys(list): Chosen keys list selected_names(list): Chosen channels' or subscribers' name...
It controls the selection from the form according to the operations and returns an error message if it does not comply with the rules.
def selection_error_control(self, form_info): """ It controls the selection from the form according to the operations, and returns an error message if it does not comply with the rules. Args: form_info: Channel or subscriber form from the user Returns: True ...