Search is not available for this dataset
text stringlengths 75 104k |
|---|
def recommend_k_items_slow(self, test, top_k=10, remove_seen=True):
"""Recommend top K items for all users which are in the test set.
Args:
test: test Spark dataframe
top_k: top n items to return
remove_seen: remove items test users have already seen in the past from... |
def setauth(self,basic_auth):
""" setauth can be used during runtime to make sure that authentication is reset.
it can be used when changing passwords/apikeys to make sure reconnects succeed """
self.headers = []
# If we have auth
if basic_auth is not None:
# we use a... |
def send(self, cmd):
"""Send the given command thru the websocket"""
with self.ws_sendlock:
self.ws.send(json.dumps(cmd)) |
def subscribe(self, stream, callback, transform=""):
"""Given a stream, a callback and an optional transform, sets up the subscription"""
if self.status == "disconnected" or self.status == "disconnecting" or self.status == "connecting":
self.connect()
if self.status is not "connected... |
def unsubscribe(self, stream, transform=""):
"""Unsubscribe from the given stream (with the optional transform)"""
if self.status is not "connected":
return False
logging.debug("Unsubscribing from %s", stream)
self.send(
{"cmd": "unsubscribe",
"arg": ... |
def connect(self):
"""Attempt to connect to the websocket - and returns either True or False depending on if
the connection was successful or not"""
# Wait for the lock to be available (ie, the websocket is not being used (yet))
self.ws_openlock.acquire()
self.ws_openlock.releas... |
def __reconnect(self):
"""This is called when a connection is lost - it attempts to reconnect to the server"""
self.status = "reconnecting"
# Reset the disconnect time after 15 minutes
if self.disconnected_time - self.connected_time > 15 * 60:
self.reconnect_time = self.reco... |
def __resubscribe(self):
"""Send subscribe command for all existing subscriptions. This allows to resume a connection
that was closed"""
with self.subscription_lock:
for sub in self.subscriptions:
logging.debug("Resubscribing to %s", sub)
stream_transf... |
def __on_open(self, ws):
"""Called when the websocket is opened"""
logging.debug("ConnectorDB: Websocket opened")
# Connection success - decrease the wait time for next connection
self.reconnect_time /= self.reconnect_time_backoff_multiplier
self.status = "connected"
s... |
def __on_close(self, ws):
"""Called when the websocket is closed"""
if self.status == "disconnected":
return # This can be double-called on disconnect
logging.debug("ConnectorDB:WS: Websocket closed")
# Turn off the ping timer
if self.pingtimer is not None:
... |
def __on_error(self, ws, err):
"""Called when there is an error in the websocket"""
logging.debug("ConnectorDB:WS: Connection Error")
if self.status == "connecting":
self.status = "errored"
self.ws_openlock.release() |
def __on_message(self, ws, msg):
"""This function is called whenever there is a message received from the server"""
msg = json.loads(msg)
logging.debug("ConnectorDB:WS: Msg '%s'", msg["stream"])
# Build the subcription key
stream_key = msg["stream"] + ":"
if "transform" ... |
def __on_ping(self, ws, data):
"""The server periodically sends us websocket ping messages to keep the connection alive. To
ensure that the connection to the server is still active, we memorize the most recent ping's time
and we periodically ensure that a ping was received in __ensure_ping"""
... |
def __ensure_ping(self):
"""Each time the server sends a ping message, we record the timestamp. If we haven't received a ping
within the given interval, then we assume that the connection was lost, close the websocket and
attempt to reconnect"""
logging.debug("ConnectorDB:WS: pingcheck"... |
def gatk_select_variants(job, mode, vcf_id, ref_fasta, ref_fai, ref_dict):
"""
Isolates a particular variant type from a VCF file using GATK SelectVariants
:param JobFunctionWrappingJob job: passed automatically by Toil
:param str mode: variant type (i.e. SNP or INDEL)
:param str vcf_id: FileStoreI... |
def gatk_variant_filtration(job, vcf_id, filter_name, filter_expression, ref_fasta, ref_fai, ref_dict):
"""
Filters VCF file using GATK VariantFiltration. Fixes extra pair of quotation marks in VCF header that
may interfere with other VCF tools.
:param JobFunctionWrappingJob job: passed automatically b... |
def gatk_variant_recalibrator(job,
mode,
vcf,
ref_fasta, ref_fai, ref_dict,
annotations,
hapmap=None, omni=None, phase=None, dbsnp=None, mills=None,
... |
def gatk_apply_variant_recalibration(job,
mode,
vcf,
recal_table, tranches,
ref_fasta, ref_fai, ref_dict,
ts_filter_level=99.0,
... |
def gatk_combine_variants(job, vcfs, ref_fasta, ref_fai, ref_dict, merge_option='UNIQUIFY'):
"""
Merges VCF files using GATK CombineVariants
:param JobFunctionWrappingJob job: Toil Job instance
:param dict vcfs: Dictionary of VCF FileStoreIDs {sample identifier: FileStoreID}
:param str ref_fasta: F... |
def bam_quickcheck(bam_path):
"""
Perform a quick check on a BAM via `samtools quickcheck`.
This will detect obvious BAM errors such as truncation.
:param str bam_path: path to BAM file to checked
:rtype: boolean
:return: True if the BAM is valid, False is BAM is invalid or something related t... |
def load_handlers(handler_mapping):
"""
Given a dictionary mapping which looks like the following, import the
objects based on the dotted path and yield the packet type and handler as
pairs.
If the special string '*' is passed, don't process that, pass it on as it
is a wildcard.
If an non-... |
def write_config(configuration):
"""Helper to write the JSON configuration to a file"""
with open(CONFIG_PATH, 'w') as f:
json.dump(configuration, f, indent=2, sort_keys=True) |
def get_config():
"""Gets the configuration for this project from the default JSON file, or writes one if it doesn't exist
:rtype: dict
"""
if not os.path.exists(CONFIG_PATH):
write_config({})
with open(CONFIG_PATH) as f:
return json.load(f) |
def get_ontology(self, ontology):
"""Gets the metadata for a given ontology
:param str ontology: The name of the ontology
:return: The dictionary representing the JSON from the OLS
:rtype: dict
"""
url = self.ontology_metadata_fmt.format(ontology=ontology)
respon... |
def get_term(self, ontology, iri):
"""Gets the data for a given term
:param str ontology: The name of the ontology
:param str iri: The IRI of a term
:rtype: dict
"""
url = self.ontology_term_fmt.format(ontology, iri)
response = requests.get(url)
return r... |
def search(self, name, query_fields=None):
"""Searches the OLS with the given term
:param str name:
:param list[str] query_fields: Fields to query
:return: dict
"""
params = {'q': name}
if query_fields is not None:
params['queryFields'] = '{{{}}}'.for... |
def suggest(self, name, ontology=None):
"""Suggest terms from an optional list of ontologies
:param str name:
:param list[str] ontology:
:rtype: dict
.. seealso:: https://www.ebi.ac.uk/ols/docs/api#_suggest_term
"""
params = {'q': name}
if ontology:
... |
def _iter_terms_helper(url, size=None, sleep=None):
"""Iterates over all terms, lazily with paging
:param str url: The url to query
:param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI.
:param int sleep: The amount of time to sleep between pag... |
def iter_terms(self, ontology, size=None, sleep=None):
"""Iterates over all terms, lazily with paging
:param str ontology: The name of the ontology
:param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI.
:param int sleep: The amount of time to s... |
def iter_descendants(self, ontology, iri, size=None, sleep=None):
"""Iterates over the descendants of a given term
:param str ontology: The name of the ontology
:param str iri: The IRI of a term
:param int size: The size of each page. Defaults to 500, which is the maximum allowed by the... |
def iter_descendants_labels(self, ontology, iri, size=None, sleep=None):
"""Iterates over the labels for the descendants of a given term
:param str ontology: The name of the ontology
:param str iri: The IRI of a term
:param int size: The size of each page. Defaults to 500, which is the ... |
def iter_labels(self, ontology, size=None, sleep=None):
"""Iterates over the labels of terms in the ontology. Automatically wraps the pager returned by the OLS.
:param str ontology: The name of the ontology
:param int size: The size of each page. Defaults to 500, which is the maximum allowed by... |
def iter_hierarchy(self, ontology, size=None, sleep=None):
"""Iterates over parent-child relations
:param str ontology: The name of the ontology
:param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI.
:param int sleep: The amount of time to slee... |
def run_fastqc(job, r1_id, r2_id):
"""
Run Fastqc on the input reads
:param JobFunctionWrappingJob job: passed automatically by Toil
:param str r1_id: FileStoreID of fastq read 1
:param str r2_id: FileStoreID of fastq read 2
:return: FileStoreID of fastQC output (tarball)
:rtype: str
""... |
def addStream(self, stream, t1=None, t2=None, limit=None, i1=None, i2=None, transform=None):
"""Adds the given stream to the query construction. The function supports both stream
names and Stream objects."""
params = query_maker(t1, t2, limit, i1, i2, transform)
params["stream"] = ... |
def create_app(config=None):
""" This needs some tidying up. To avoid circular imports we import
everything here but it makes this method a bit more gross.
"""
# Initialise the app
from home.config import TEMPLATE_FOLDER, STATIC_FOLDER
app = Flask(__name__, static_folder=STATIC_FOLDER,
... |
def spawn_spark_cluster(job,
numWorkers,
cores=None,
memory=None,
disk=None,
overrideLeaderIP=None):
'''
:param numWorkers: The number of worker nodes to have in the cluster. \
Must be gre... |
def start(self, job):
"""
Start spark and hdfs master containers
:param job: The underlying job.
"""
if self.hostname is None:
self.hostname = subprocess.check_output(["hostname", "-f",])[:-1]
_log.info("Started Spark master container.")
self.sparkC... |
def start(self, job):
"""
Start spark and hdfs worker containers
:param job: The underlying job.
"""
# start spark and our datanode
self.sparkContainerID = dockerCheckOutput(job=job,
defer=STOP,
... |
def __start_datanode(self, job):
"""
Launches the Hadoop datanode.
:param job: The underlying job.
"""
self.hdfsContainerID = dockerCheckOutput(job=job,
defer=STOP,
workDir=os.getcw... |
def stop(self, fileStore):
"""
Stop spark and hdfs worker containers
:param job: The underlying job.
"""
subprocess.call(["docker", "exec", self.sparkContainerID, "rm", "-r", "/ephemeral/spark"])
subprocess.call(["docker", "stop", self.sparkContainerID])
subproc... |
def check(self):
"""
Checks to see if Spark worker and HDFS datanode are still running.
"""
status = _checkContainerStatus(self.sparkContainerID,
self.hdfsContainerID,
sparkNoun='worker',
... |
def base_tokenizer(fp):
'Tokenizer. Generates tokens stream from text'
if isinstance(fp, StringIO):
template_file = fp
size = template_file.len
else:
#empty file check
if os.fstat(fp.fileno()).st_size == 0:
yield TOKEN_EOF, 'EOF', 0, 0
return
t... |
def get_mint_tree(tokens_stream):
'''
This function is wrapper to normal parsers (tag_parser, block_parser, etc.).
Returns mint tree.
'''
smart_stack = RecursiveStack()
block_parser.parse(tokens_stream, smart_stack)
return MintTemplate(body=smart_stack.stack) |
def lookup_zone(conn, zone):
"""Look up a zone ID for a zone string.
Args: conn: boto.route53.Route53Connection
zone: string eg. foursquare.com
Returns: zone ID eg. ZE2DYFZDWGSL4.
Raises: ZoneNotFoundError if zone not found."""
all_zones = conn.get_all_hosted_zones()
for resp in all_zones['ListHost... |
def fetch_config(zone, conn):
"""Fetch all pieces of a Route 53 config from Amazon.
Args: zone: string, hosted zone id.
conn: boto.route53.Route53Connection
Returns: list of ElementTrees, one for each piece of config."""
more_to_fetch = True
cfg_chunks = []
next_name = None
next_type = None
nex... |
def merge_config(cfg_chunks):
"""Merge a set of fetched Route 53 config Etrees into a canonical form.
Args: cfg_chunks: [ lxml.etree.ETree ]
Returns: lxml.etree.Element"""
root = lxml.etree.XML('<ResourceRecordSets xmlns="%s"></ResourceRecordSets>' % R53_XMLNS, parser=XML_PARSER)
for chunk in cfg_chunks:
... |
def normalize_rrs(rrsets):
"""Lexically sort the order of every ResourceRecord in a ResourceRecords
element so we don't generate spurious changes: ordering of e.g. NS records
is irrelevant to the DNS line protocol, but XML sees it differently.
Also rewrite any wildcard records to use the ascii hex code: somewh... |
def generate_changeset(old, new, comment=None):
"""Diff two XML configs and return an object with changes to be written.
Args: old, new: lxml.etree.Element (<ResourceRecordSets>).
Returns: lxml.etree.ETree (<ChangeResourceRecordSetsRequest>) or None"""
rrsets_tag = '{%s}ResourceRecordSets' % R53_XMLNS
if rrs... |
def validate_changeset(changeset):
"""Validate a changeset is compatible with Amazon's API spec.
Args: changeset: lxml.etree.Element (<ChangeResourceRecordSetsRequest>)
Returns: [ errors ] list of error strings or []."""
errors = []
changes = changeset.findall('.//{%s}Change' % R53_XMLNS)
num_changes = len... |
def minimize_best_n(Members):
'''
Orders population members from lowest fitness to highest fitness
Args:
Members (list): list of PyGenetics Member objects
Returns:
lsit: ordered lsit of Members, from highest fitness to lowest fitness
'''
return(list(reversed(sorted(
Me... |
def fitness(self):
'''Population fitness == average member fitness score'''
if len(self.__members) != 0:
if self.__num_processes > 1:
members = [m.get() for m in self.__members]
else:
members = self.__members
return sum(m.fitness_score... |
def ave_cost_fn_val(self):
'''Returns average cost function return value for all members'''
if len(self.__members) != 0:
if self.__num_processes > 1:
members = [m.get() for m in self.__members]
else:
members = self.__members
return sum... |
def med_cost_fn_val(self):
'''Returns median cost function return value for all members'''
if len(self.__members) != 0:
if self.__num_processes > 1:
members = [m.get() for m in self.__members]
else:
members = self.__members
return medi... |
def parameters(self):
'''Population parameter vals == average member parameter vals'''
if len(self.__members) != 0:
if self.__num_processes > 1:
members = [m.get() for m in self.__members]
else:
members = self.__members
params = {}
... |
def members(self):
'''Returns Member objects of population'''
if self.__num_processes > 1:
return [m.get() for m in self.__members]
else:
return self.__members |
def add_parameter(self, name, min_val, max_val):
'''Adds a paramber to the Population
Args:
name (str): name of the parameter
min_val (int or float): minimum value for the parameter
max_val (int or float): maximum value for the parameter
'''
self.__p... |
def generate_population(self):
'''Generates self.__pop_size Members with randomly initialized values
for each parameter added with add_parameter(), evaluates their fitness
'''
if self.__num_processes > 1:
process_pool = Pool(processes=self.__num_processes)
self.__mem... |
def next_generation(self, mut_rate=0, max_mut_amt=0, log_base=10):
'''Generates the next population from a previously evaluated generation
Args:
mut_rate (float): mutation rate for new members (0.0 - 1.0)
max_mut_amt (float): how much the member is allowed to mutate
... |
def __mutate_parameter(value, param, mut_rate, max_mut_amt):
'''Private, static method: mutates parameter
Args:
value (int or float): current value for Member's parameter
param (Parameter): parameter object
mut_rate (float): mutation rate of the value
max... |
def __determine_best_member(self):
'''Private method: determines if any current population members have a
fitness score better than the current best
'''
if self.__num_processes > 1:
members = [m.get() for m in self.__members]
else:
members = self.__member... |
def update_defaults(self, defaults):
"""Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists)."""
# Then go and look for the other sources of configuration:
config = {}
# 1. config... |
def normalize_keys(self, items):
"""Return a config dictionary with normalized keys regardless of
whether the keys were specified in environment variables or in config
files"""
normalized = {}
for key, val in items:
key = key.replace('_', '-')
if not key.s... |
def get_environ_vars(self):
"""Returns a generator with all environmental vars with prefix PIP_"""
for key, val in os.environ.items():
if _environ_prefix_re.search(key):
yield (_environ_prefix_re.sub("", key).lower(), val) |
def throws_exception(callable, *exceptions):
"""
Return True if the callable throws the specified exception
>>> throws_exception(lambda: int('3'))
False
>>> throws_exception(lambda: int('a'))
True
>>> throws_exception(lambda: int('a'), KeyError)
False
"""
with context.ExceptionTrap():
with context.Exceptio... |
def transform_hits(hits):
"""
The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use.
"""
packages = {}
for hit in hits:
name = hit['name']
summary = hit['summar... |
def _transform_result(typ, result):
"""Convert the result back into the input type.
"""
if issubclass(typ, bytes):
return tostring(result, encoding='utf-8')
elif issubclass(typ, unicode):
return tostring(result, encoding='unicode')
else:
return result |
def fragments_fromstring(html, no_leading_text=False, base_url=None,
parser=None, **kw):
"""
Parses several HTML elements, returning a list of elements.
The first item in the list may be a string (though leading
whitespace is removed). If no_leading_text is true, then it will
... |
def fragment_fromstring(html, create_parent=False, base_url=None,
parser=None, **kw):
"""
Parses a single HTML element; it is an error if there is more than
one element, or if anything but whitespace precedes or follows the
element.
If ``create_parent`` is true (or is a tag ... |
def fromstring(html, base_url=None, parser=None, **kw):
"""
Parse the html, returning a single element/document.
This tries to minimally parse the chunk of text, without knowing if it
is a fragment or a document.
base_url will set the document's base_url attribute (and the tree's docinfo.URL)
... |
def parse(filename_or_url, parser=None, base_url=None, **kw):
"""
Parse a filename, URL, or file-like object into an HTML document
tree. Note: this returns a tree, not an element. Use
``parse(...).getroot()`` to get the document root.
You can override the base URL with the ``base_url`` keyword. ... |
def submit_form(form, extra_values=None, open_http=None):
"""
Helper function to submit a form. Returns a file-like object, as from
``urllib.urlopen()``. This object also has a ``.geturl()`` function,
which shows the URL if there were any redirects.
You can use this like::
form = doc.for... |
def html_to_xhtml(html):
"""Convert all tags in an HTML tree to XHTML by moving them to the
XHTML namespace.
"""
try:
html = html.getroot()
except AttributeError:
pass
prefix = "{%s}" % XHTML_NAMESPACE
for el in html.iter(etree.Element):
tag = el.tag
if tag[0]... |
def xhtml_to_html(xhtml):
"""Convert all tags in an XHTML tree to HTML by removing their
XHTML namespace.
"""
try:
xhtml = xhtml.getroot()
except AttributeError:
pass
prefix = "{%s}" % XHTML_NAMESPACE
prefix_len = len(prefix)
for el in xhtml.iter(prefix + "*"):
el... |
def tostring(doc, pretty_print=False, include_meta_content_type=False,
encoding=None, method="html", with_tail=True, doctype=None):
"""Return an HTML string representation of the document.
Note: if include_meta_content_type is true this will create a
``<meta http-equiv="Content-Type" ...>`` ta... |
def open_in_browser(doc, encoding=None):
"""
Open the HTML document in a web browser, saving it to a temporary
file to open it. Note that this does not delete the file after
use. This is mainly meant for debugging.
"""
import os
import webbrowser
import tempfile
if not isinstance(d... |
def _label__get(self):
"""
Get or set any <label> element associated with this element.
"""
id = self.get('id')
if not id:
return None
result = _label_xpath(self, id=id)
if not result:
return None
else:
return result[0] |
def drop_tree(self):
"""
Removes this element from the tree, including its children and
text. The tail text is joined to the previous element or
parent.
"""
parent = self.getparent()
assert parent is not None
if self.tail:
previous = self.getp... |
def drop_tag(self):
"""
Remove the tag, but not its children or text. The children and text
are merged into the parent.
Example::
>>> h = fragment_fromstring('<div>Hello <b>World!</b></div>')
>>> h.find('.//b').drop_tag()
>>> print(tostring(h, encod... |
def find_rel_links(self, rel):
"""
Find any links like ``<a rel="{rel}">...</a>``; returns a list of elements.
"""
rel = rel.lower()
return [el for el in _rel_links_xpath(self)
if el.get('rel').lower() == rel] |
def get_element_by_id(self, id, *default):
"""
Get the first element in a document with the given id. If none is
found, return the default argument if provided or raise KeyError
otherwise.
Note that there can be more than one element with the same id,
and this isn't unc... |
def cssselect(self, expr, translator='html'):
"""
Run the CSS expression on this element and its children,
returning a list of the results.
Equivalent to lxml.cssselect.CSSSelect(expr, translator='html')(self)
-- note that pre-compiling the expression can provide a substantial
... |
def make_links_absolute(self, base_url=None, resolve_base_href=True,
handle_failures=None):
"""
Make all links in the document absolute, given the
``base_url`` for the document (the full URL where the document
came from), or if no ``base_url`` is given, then t... |
def resolve_base_href(self, handle_failures=None):
"""
Find any ``<base href>`` tag in the document, and apply its
values to all links found in the document. Also remove the
tag once it has been applied.
If ``handle_failures`` is None (default), a failure to process
a U... |
def iterlinks(self):
"""
Yield (element, attribute, link, pos), where attribute may be None
(indicating the link is in the text). ``pos`` is the position
where the link occurs; often 0, but sometimes something else in
the case of links in stylesheets or style tags.
Note... |
def rewrite_links(self, link_repl_func, resolve_base_href=True,
base_href=None):
"""
Rewrite all the links in the document. For each link
``link_repl_func(link)`` will be called, and the return value
will replace the old link.
Note that links may not be ab... |
def form_values(self):
"""
Return a list of tuples of the field values for the form.
This is suitable to be passed to ``urllib.urlencode()``.
"""
results = []
for el in self.inputs:
name = el.name
if not name:
continue
t... |
def _action__get(self):
"""
Get/set the form's ``action`` attribute.
"""
base_url = self.base_url
action = self.get('action')
if base_url and action is not None:
return urljoin(base_url, action)
else:
return action |
def _value__get(self):
"""
Get/set the value (which is the contents of this element)
"""
content = self.text or ''
if self.tag.startswith("{%s}" % XHTML_NAMESPACE):
serialisation_method = 'xml'
else:
serialisation_method = 'html'
for el in ... |
def _value__get(self):
"""
Get/set the value of this select (the selected option).
If this is a multi-select, this is a set-like object that
represents all the selected options.
"""
if self.multiple:
return MultipleSelectOptions(self)
for el in _optio... |
def value_options(self):
"""
All the possible values this select can have (the ``value``
attribute of all the ``<option>`` elements.
"""
options = []
for el in _options_xpath(self):
value = el.get('value')
if value is None:
value = ... |
def _value__get(self):
"""
Get/set the value of this element, using the ``value`` attribute.
Also, if this is a checkbox and it has no value, this defaults
to ``'on'``. If it is a checkbox or radio that is not
checked, this returns None.
"""
if self.checkable:
... |
def _for_element__get(self):
"""
Get/set the element this label points to. Return None if it
can't be found.
"""
id = self.get('for')
if not id:
return None
return self.body.get_element_by_id(id) |
def classpath(v):
"""given a class/instance return the full class path (eg, prefix.module.Classname)
:param v: class or instance
:returns: string, the full classpath of v
"""
if isinstance(v, type):
ret = strclass(v)
else:
ret = strclass(v.__class__)
return ret |
def loghandler_members():
"""iterate through the attributes of every logger's handler
this is used to switch out stderr and stdout in tests when buffer is True
:returns: generator of tuples, each tuple has (name, handler, member_name, member_val)
"""
Members = namedtuple("Members", ["name", "handl... |
def get_counts():
"""return test counts that are set via pyt environment variables when pyt
runs the test
:returns: dict, 3 keys (classes, tests, modules) and how many tests of each
were found by pyt
"""
counts = {}
ks = [
('PYT_TEST_CLASS_COUNT', "classes"),
('PYT_TEST... |
def is_single_class():
"""Returns True if only a single class is being run or some tests within a single class"""
ret = False
counts = get_counts()
if counts["classes"] < 1 and counts["modules"] < 1:
ret = counts["tests"] > 0
else:
ret = counts["classes"] <= 1 and counts["modules"] <... |
def is_single_module():
"""Returns True if only a module is being run"""
ret = False
counts = get_counts()
if counts["modules"] == 1:
ret = True
elif counts["modules"] < 1:
ret = is_single_class()
return ret |
def validate_params(request):
"""Validate request params."""
if 'params' in request:
correct_params = isinstance(request['params'], (list, dict))
error = 'Incorrect parameter values'
assert correct_params, error |
def validate_id(request):
"""Validate request id."""
if 'id' in request:
correct_id = isinstance(
request['id'],
(string_types, int, None),
)
error = 'Incorrect identifier'
assert correct_id, error |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.