text stringlengths 81 112k |
|---|
Run and return the results of the AttributeInitialization plugin.
def analyze(self, scratch, **kwargs):
"""Run and return the results of the AttributeInitialization plugin."""
changes = dict((x.name, self.sprite_changes(x)) for x in
scratch.sprites)
changes['stage'] = {
... |
Return the initialization state for each variable in variables.
The state is determined based on the scripts passed in via the scripts
parameter.
If there is more than one 'when green flag clicked' script and they
both modify the attribute, then the attribute is considered to not be
... |
Run and return the results of the VariableInitialization plugin.
def analyze(self, scratch, **kwargs):
"""Run and return the results of the VariableInitialization plugin."""
variables = dict((x, self.variable_state(x.scripts, x.variables))
for x in scratch.sprites)
vari... |
Output the default sprite names found in the project.
def finalize(self):
"""Output the default sprite names found in the project."""
print('{} default sprite names found:'.format(self.total_default))
for name in self.list_default:
print(name) |
Run and return the results from the SpriteNaming plugin.
def analyze(self, scratch, **kwargs):
"""Run and return the results from the SpriteNaming plugin."""
for sprite in self.iter_sprites(scratch):
for default in self.default_names:
if default in sprite.name:
... |
Allows all methods to be tunneled via GET for dev/debuging
purposes.
def get_tunneling(handler, registry):
""" Allows all methods to be tunneled via GET for dev/debuging
purposes.
"""
log.info('get_tunneling enabled')
def get_tunneling(request):
if request.method == 'GET':
... |
This allows replacing id_name with "self".
e.g. /users/joe/account == /users/self/account if joe is in the session
as an authorized user
def enable_selfalias(config, id_name):
"""
This allows replacing id_name with "self".
e.g. /users/joe/account == /users/self/account if joe is in the session
... |
Convert dotted keys in :params: dictset to a nested dictset.
E.g. {'settings.foo': 'bar'} -> {'settings': {'foo': 'bar'}}
def convert_dotted(params):
""" Convert dotted keys in :params: dictset to a nested dictset.
E.g. {'settings.foo': 'bar'} -> {'settings': {'foo': 'bar'}}
"""
... |
Prepare query and update params.
def prepare_request_params(self, _query_params, _json_params):
""" Prepare query and update params. """
self._query_params = dictset(
_query_params or self.request.params.mixed())
self._json_params = dictset(_json_params)
ctype = self.reques... |
Set self.request.override_renderer if needed.
def set_override_rendered(self):
""" Set self.request.override_renderer if needed. """
if '' in self.request.accept:
self.request.override_renderer = self._default_renderer
elif 'application/json' in self.request.accept:
self... |
Wrap `self.index` method with ESAggregator.
This makes `self.index` to first try to run aggregation and only
on fail original method is run. Method is wrapped only if it is
defined and `elasticsearch.enable_aggregations` setting is true.
def _setup_aggregation(self, aggregator=None):
"... |
Query ES collection and return results.
This is default implementation of querying ES collection with
`self._query_params`. It must return found ES collection
results for default response renderers to work properly.
def get_collection_es(self):
""" Query ES collection and return result... |
Fill missing model fields in JSON with {key: null value}.
Only run for PUT requests.
def fill_null_values(self):
""" Fill missing model fields in JSON with {key: null value}.
Only run for PUT requests.
"""
if not self.Model:
log.info("%s has no model defined" % sel... |
Set public limits if auth is enabled and user is not
authenticated.
Also sets default limit for GET, HEAD requests.
def set_public_limits(self):
""" Set public limits if auth is enabled and user is not
authenticated.
Also sets default limit for GET, HEAD requests.
"""
... |
Convert object IDs from `self._json_params` to objects if needed.
Only IDs that belong to relationship field of `self.Model`
are converted.
def convert_ids2objects(self):
""" Convert object IDs from `self._json_params` to objects if needed.
Only IDs that belong to relationship field o... |
Setup defaulf wrappers.
Wrappers are applied when view method does not return instance
of Response. In this case nefertari renderers call wrappers and
handle response generation.
def setup_default_wrappers(self):
""" Setup defaulf wrappers.
Wrappers are applied when view metho... |
Migrate data from mongodict <= 0.2.1 to 0.3.0
`config_old` and `config_new` should be dictionaries with the keys
regarding to MongoDB server:
- `host`
- `port`
- `database`
- `collection`
def migrate_codec(config_old, config_new):
'''Migrate data from mongodict <= 0.2.1 to 0... |
Generate map of `fieldName: clsInstance` from dict.
:param data: Dict where keys are field names and values are
new values of field.
:param model: Model class to which fields from :data: belong.
def from_dict(cls, data, model):
""" Generate map of `fieldName: clsInstance` from dict... |
Register new user by POSTing all required data.
def register(self):
""" Register new user by POSTing all required data. """
user, created = self.Model.create_account(
self._json_params)
if not created:
raise JHTTPConflict('Looks like you already have an account.')
... |
Register a new user by POSTing all required data.
User's `Authorization` header value is returned in `WWW-Authenticate`
header.
def register(self):
""" Register a new user by POSTing all required data.
User's `Authorization` header value is returned in `WWW-Authenticate`
heade... |
Claim current token by POSTing 'login' and 'password'.
User's `Authorization` header value is returned in `WWW-Authenticate`
header.
def claim_token(self, **params):
"""Claim current token by POSTing 'login' and 'password'.
User's `Authorization` header value is returned in `WWW-Authe... |
Reset current token by POSTing 'login' and 'password'.
User's `Authorization` header value is returned in `WWW-Authenticate`
header.
def reset_token(self, **params):
""" Reset current token by POSTing 'login' and 'password'.
User's `Authorization` header value is returned in `WWW-Auth... |
Apply privacy to nested documents.
:param data: Dict of data to which privacy is already applied.
def _apply_nested_privacy(self, data):
""" Apply privacy to nested documents.
:param data: Dict of data to which privacy is already applied.
"""
kw = {
'is_admin': sel... |
Add '_self' key value to :obj: dict.
def _set_object_self(self, obj):
""" Add '_self' key value to :obj: dict. """
from nefertari.elasticsearch import ES
location = self.request.path_url
route_kwargs = {}
""" Check for parents """
if self.request.matchdict:
... |
Returns the root resource.
def get_root_resource(config):
"""Returns the root resource."""
app_package_name = get_app_package_name(config)
return config.registry._root_resources.setdefault(
app_package_name, Resource(config)) |
``view`` is a dotted name of (or direct reference to) a
Python view class,
e.g. ``'my.package.views.MyView'``.
``member_name`` should be the appropriate singular version of the resource
given your locale and used with members of the collection.
``collection_name`` will be used to refer to the reso... |
Returns the dotted path to the default view class.
def get_default_view_path(resource):
"Returns the dotted path to the default view class."
parts = [a.member_name for a in resource.ancestors] +\
[resource.collection_name or resource.member_name]
if resource.prefix:
parts.insert(-1, r... |
Returns the list of ancestor resources.
def get_ancestors(self):
"Returns the list of ancestor resources."
if self._ancestors:
return self._ancestors
if not self.parent:
return []
obj = self.resource_map.get(self.parent.uid)
while obj and obj.member_n... |
:param member_name: singular name of the resource. It should be the
appropriate singular version of the resource given your locale
and used with members of the collection.
:param collection_name: plural name of the resource. It will be used
to refer to the resource collectio... |
Add a resource with its all children resources to the current
resource.
def add_from_child(self, resource, **kwargs):
""" Add a resource with its all children resources to the current
resource.
"""
new_resource = self.add(
resource.member_name, resource.collection_n... |
Add the path of a data set to the list of available sets
NOTE: a data set is assumed to be a pickled
and gzip compressed Pandas DataFrame
Parameters
----------
path : str
def add(self, path):
"""
Add the path of a data set to the list of available sets
... |
Unpacks a data set to a Pandas DataFrame
Parameters
----------
name : str
call `.list` to see all availble datasets
Returns
-------
pd.DataFrame
def unpack(self, name):
"""
Unpacks a data set to a Pandas DataFrame
Parameters
... |
translate each sequence into six reading frames
def six_frame(genome, table, minimum = 10):
"""
translate each sequence into six reading frames
"""
for seq in parse_fasta(genome):
dna = Seq(seq[1].upper().replace('U', 'T'), IUPAC.ambiguous_dna)
counter = 0
for sequence in ['f', ... |
# Redis/RabbitMQ/SQS messaging endpoints for pub-sub
routing_key = ev("PUBLISH_EXCHANGE",
"reporting.accounts")
queue_name = ev("PUBLISH_QUEUE",
"reporting.accounts")
auth_url = ev("PUB_BROKER_URL",
"redis://localhost:6379/15")
serializer = "jso... |
run_main
start the packet consumers and the packet processors
:param need_response: should send response back to publisher
:param callback: handler method
def run_main(
need_response=False,
callback=None):
"""run_main
start the packet consumers and the packet processors
:par... |
determine the best model: archaea, bacteria, eukarya (best score)
def best_model(seq2hmm):
"""
determine the best model: archaea, bacteria, eukarya (best score)
"""
for seq in seq2hmm:
best = []
for model in seq2hmm[seq]:
best.append([model, sorted([i[-1] for i in seq2hmm[se... |
check for large gaps between alignment windows
def check_gaps(matches, gap_threshold = 0):
"""
check for large gaps between alignment windows
"""
gaps = []
prev = None
for match in sorted(matches, key = itemgetter(0)):
if prev is None:
prev = match
continue
... |
determine if sequence has already hit the same part of the model,
indicating that this hit is for another 16S rRNA gene
def check_overlap(current, hit, overlap = 200):
"""
determine if sequence has already hit the same part of the model,
indicating that this hit is for another 16S rRNA gene
"""
... |
determine if hits are sequential on model and on the
same strand
* if not, they should be split into different groups
def check_order(current, hit, overlap = 200):
"""
determine if hits are sequential on model and on the
same strand
* if not, they should be split into different groups
... |
* each sequence may have more than one 16S rRNA gene
* group hits for each gene
def hit_groups(hits):
"""
* each sequence may have more than one 16S rRNA gene
* group hits for each gene
"""
groups = []
current = False
for hit in sorted(hits, key = itemgetter(0)):
if current is F... |
find 16S rRNA gene sequence coordinates
def find_coordinates(hmms, bit_thresh):
"""
find 16S rRNA gene sequence coordinates
"""
# get coordinates from cmsearch output
seq2hmm = parse_hmm(hmms, bit_thresh)
seq2hmm = best_model(seq2hmm)
group2hmm = {} # group2hmm[seq][group] = [model, strand,... |
get info from either ssu-cmsearch or cmsearch output
def get_info(line, bit_thresh):
"""
get info from either ssu-cmsearch or cmsearch output
"""
if len(line) >= 18: # output is from cmsearch
id, model, bit, inc = line[0].split()[0], line[2], float(line[14]), line[16]
sstart, send, stra... |
check to see how much of the buffer is being used
def check_buffer(coords, length, buffer):
"""
check to see how much of the buffer is being used
"""
s = min(coords[0], buffer)
e = min(length - coords[1], buffer)
return [s, e] |
:return: a parser of type parser_or_type, initialized with the properties of parser. If parser_or_type
is a type, an instance of it must contain a update method. The update method must also process
the set of properties supported by MetadataParser for the conversion to have any affect.
:param parser: the pa... |
Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file.
:return: a new instance of a parser corresponding to the standard represented by metadata_container
:see: get_parsed_content(metdata_content) for more on types of content that can be parsed
def get_metadata_parser... |
Parses any of the following types of content:
1. XML string or file object: parses XML content
2. MetadataParser instance: deep copies xml_tree
3. Dictionary with nested objects containing:
- name (required): the name of the element tag
- text: the text contained by element
- tail: t... |
Lazy imports to prevent circular dependencies between this module and utils
def _import_parsers():
""" Lazy imports to prevent circular dependencies between this module and utils """
global ARCGIS_NODES
global ARCGIS_ROOTS
global ArcGISParser
global FGDC_ROOT
global FgdcParser
global ISO... |
Dynamically sets attributes from a Dictionary passed in by children.
The Dictionary will contain the name of each attribute as keys, and
either an XPATH mapping to a text value in _xml_tree, or a function
that takes no parameters and returns the intended value.
def _init_metadata(self):
... |
Default data map initialization: MUST be overridden in children
def _init_data_map(self):
""" Default data map initialization: MUST be overridden in children """
if self._data_map is None:
self._data_map = {'_root': None}
self._data_map.update({}.fromkeys(self._metadata_props)) |
Iterate over items metadata_defaults {prop: val, ...} to populate template
def _get_template(self, root=None, **metadata_defaults):
""" Iterate over items metadata_defaults {prop: val, ...} to populate template """
if root is None:
if self._data_map is None:
self._init_data... |
:return: the configured xpath for a given property
def _get_xpath_for(self, prop):
""" :return: the configured xpath for a given property """
xpath = self._data_map.get(prop)
return getattr(xpath, 'xpath', xpath) |
Default parsing operation for a complex struct
def _parse_complex(self, prop):
""" Default parsing operation for a complex struct """
xpath_root = None
xpath_map = self._data_structures[prop]
return parse_complex(self._xml_tree, xpath_root, xpath_map, prop) |
Default parsing operation for lists of complex structs
def _parse_complex_list(self, prop):
""" Default parsing operation for lists of complex structs """
xpath_root = self._get_xroot_for(prop)
xpath_map = self._data_structures[prop]
return parse_complex_list(self._xml_tree, xpath_roo... |
Creates and returns a Date Types data structure parsed from the metadata
def _parse_dates(self, prop=DATES):
""" Creates and returns a Date Types data structure parsed from the metadata """
return parse_dates(self._xml_tree, self._data_structures[prop]) |
Default update operation for a complex struct
def _update_complex(self, **update_props):
""" Default update operation for a complex struct """
prop = update_props['prop']
xpath_root = self._get_xroot_for(prop)
xpath_map = self._data_structures[prop]
return update_complex(xpath... |
Default update operation for lists of complex structs
def _update_complex_list(self, **update_props):
""" Default update operation for lists of complex structs """
prop = update_props['prop']
xpath_root = self._get_xroot_for(prop)
xpath_map = self._data_structures[prop]
return... |
Default update operation for Dates metadata
:see: gis_metadata.utils._complex_definitions[DATES]
def _update_dates(self, xpath_root=None, **update_props):
"""
Default update operation for Dates metadata
:see: gis_metadata.utils._complex_definitions[DATES]
"""
tree_to_up... |
Validates instance properties, updates an XML tree with them, and writes the content to a file.
:param use_template: if True, updates a new template XML tree; otherwise the original XML tree
:param out_file_or_path: optionally override self.out_file_or_path with a custom file path
:param encodin... |
Default validation for updated properties: MAY be overridden in children
def validate(self):
""" Default validation for updated properties: MAY be overridden in children """
validate_properties(self._data_map, self._metadata_props)
for prop in self._data_map:
validate_any(prop, ge... |
Search order:
* specified regexps
* operators sorted from longer to shorter
def _search_regex(ops: dict, regex_pat: str):
"""
Search order:
* specified regexps
* operators sorted from longer to shorter
"""
custom_regexps = list(filter(None, [dic['regex'] for op, dic in ops.items... |
Return prefix unary operators list
def spec(self, postf_un_ops: str) -> list:
"""Return prefix unary operators list"""
spec = [(l + op, {'pat': self.pat(pat),
'postf': self.postf(r, postf_un_ops),
'regex': None})
for op, pat in self.st... |
Returns prefix unary operators list.
Sets only one regex for all items in the dict.
def spec(self) -> list:
"""Returns prefix unary operators list.
Sets only one regex for all items in the dict."""
spec = [item
for op, pat in self.ops.items()
for item in ... |
Insert:
* math styles
* other styles
* unary prefix operators without brackets
* defaults
def fill(self, postf_un_ops: str):
"""
Insert:
* math styles
* other styles
* unary prefix operators without brackets
* defaults
... |
Regex-escaped string with all one-symbol operators
def one_symbol_ops_str(self) -> str:
"""Regex-escaped string with all one-symbol operators"""
return re.escape(''.join((key for key in self.ops.keys() if len(key) == 1))) |
:return:
[compiled regex, function]
def _su_scripts_regex(self):
"""
:return:
[compiled regex, function]
"""
sups = re.escape(''.join([k for k in self.superscripts.keys()]))
subs = re.escape(''.join([k for k in self.subscripts.keys()])) # language=Python... |
:param match:
:param loc: str
"l" or "r" or "lr"
turns on/off left/right local area calculation
:return: list
list of the same size as the string + 2
it's the local map that counted { and }
list can contain: None or int>=0
from the ... |
Searches for first unary or binary operator (via self.op_regex
that has only one group that contain operator)
then replaces it (or escapes it if brackets do not match).
Everything until:
* space ' '
* begin/end of the string
* bracket from outer scope (like '{a/b}':... |
Extends LaTeX syntax via regex preprocess
:param src: str
LaTeX string
:return: str
New LaTeX string
def replace(self, src: str) -> str:
"""
Extends LaTeX syntax via regex preprocess
:param src: str
LaTeX string
:return: str
... |
plot % of gaps at each position
def plot_gaps(plot, columns):
"""
plot % of gaps at each position
"""
from plot_window import window_plot_convolve as plot_window
# plot_window([columns], len(columns)*.01, plot)
plot_window([[100 - i for i in columns]], len(columns)*.01, plot) |
strip out columns of a MSA that represent gaps for X percent (threshold) of sequences
def strip_msa_100(msa, threshold, plot = False):
"""
strip out columns of a MSA that represent gaps for X percent (threshold) of sequences
"""
msa = [seq for seq in parse_fasta(msa)]
columns = [[0, 0] for pos in msa[0][1]] # [[#... |
Iterate through all categories in an OrderedDict and return category name if SampleID
present in that category.
:type sid: str
:param sid: SampleID from dataset.
:type groups: OrderedDict
:param groups: Returned dict from phylotoast.util.gather_categories() function.
:return type: str
:re... |
Combine multiple sets to create a single larger set.
def combine_sets(*sets):
"""
Combine multiple sets to create a single larger set.
"""
combined = set()
for s in sets:
combined.update(s)
return combined |
Get unique OTUIDs of each category.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on category name and unique OTUIDs as values.
def unique_otuids(groups):
"""
Get unique OTUIDs of each category.
:type groups: Dict
:param ... |
Get shared OTUIDs between all unique combinations of groups.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on group combination and their shared OTUIDs as values.
def shared_otuids(groups):
"""
Get shared OTUIDs between all unique... |
Given a path, the method writes out one file for each group name in the
uniques dictionary with the file name in the pattern
PATH/prefix_group.txt
with each file containing the unique OTUIDs found when comparing that group
to all the other groups in uniques.
:type path: str
:param path: O... |
Parse the records in a FASTA-format file by first reading the entire file into memory.
:type source: path to FAST file or open file handle
:param source: The data source from which to parse the FASTA records. Expects the
input to resolve to a collection that can be iterated through, such as
... |
Parse the records in a FASTA-format file keeping the file open, and reading through
one line at a time.
:type source: path to FAST file or open file handle
:param source: The data source from which to parse the FASTA records.
Expects the input to resolve to a collection that can be itera... |
Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID
(default) or a user-supplied one. The only required fields are SampleID,
BarcodeSequence, LinkerPrimerSequence (in that order), and Description
(which must be the final field).
:type mapFNH: str
:param mapFNH: Eith... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.