text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def requestField(self, field_name, required=False, strict=False):
"""Request the specified field from the OpenID user
@param field_name: the unqualified simple registration field name
@type field_name: str
@param required: whether the given field should be presented
to the ... | [
"def",
"requestField",
"(",
"self",
",",
"field_name",
",",
"required",
"=",
"False",
",",
"strict",
"=",
"False",
")",
":",
"checkFieldName",
"(",
"field_name",
")",
"if",
"strict",
":",
"if",
"field_name",
"in",
"self",
".",
"required",
"or",
"field_name... | 34.583333 | 21.361111 |
def use_active_sequence_rule_enabler_view(self):
"""Pass through to provider SequenceRuleEnablerLookupSession.use_active_sequence_rule_enabler_view"""
self._operable_views['sequence_rule_enabler'] = ACTIVE
# self._get_provider_session('sequence_rule_enabler_lookup_session') # To make sure the s... | [
"def",
"use_active_sequence_rule_enabler_view",
"(",
"self",
")",
":",
"self",
".",
"_operable_views",
"[",
"'sequence_rule_enabler'",
"]",
"=",
"ACTIVE",
"# self._get_provider_session('sequence_rule_enabler_lookup_session') # To make sure the session is tracked",
"for",
"session",
... | 57.777778 | 21.222222 |
def encode(self, version, padding, extension, cc, seqnum, marker, pt, ssrc, payload):
"""Encode the RTP packet with header fields and payload."""
timestamp = int(time())
print("timestamp: " + str(timestamp))
self.header = bytearray(HEADER_SIZE)
#--------------
# TO COMPLETE
#--------------
# Fill the h... | [
"def",
"encode",
"(",
"self",
",",
"version",
",",
"padding",
",",
"extension",
",",
"cc",
",",
"seqnum",
",",
"marker",
",",
"pt",
",",
"ssrc",
",",
"payload",
")",
":",
"timestamp",
"=",
"int",
"(",
"time",
"(",
")",
")",
"print",
"(",
"\"timesta... | 29.875 | 21.645833 |
def _iterContours(self, **kwargs):
"""
This must return an iterator that returns wrapped contours.
Subclasses may override this method.
"""
count = len(self)
index = 0
while count:
yield self[index]
count -= 1
index += 1 | [
"def",
"_iterContours",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"count",
"=",
"len",
"(",
"self",
")",
"index",
"=",
"0",
"while",
"count",
":",
"yield",
"self",
"[",
"index",
"]",
"count",
"-=",
"1",
"index",
"+=",
"1"
] | 25.166667 | 15.166667 |
def _add_gmaf(self, variant_obj, info_dict):
"""Add the gmaf frequency
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary
"""
##TODO search for max freq in info dict
for transcript in variant_obj.transcripts:
... | [
"def",
"_add_gmaf",
"(",
"self",
",",
"variant_obj",
",",
"info_dict",
")",
":",
"##TODO search for max freq in info dict",
"for",
"transcript",
"in",
"variant_obj",
".",
"transcripts",
":",
"gmaf_raw",
"=",
"transcript",
".",
"GMAF",
"if",
"gmaf_raw",
":",
"gmaf"... | 34.647059 | 12.411765 |
def keys(self, element=None, mode=None):
r"""
This subclass works exactly like ``keys`` when no arguments are passed,
but optionally accepts an ``element`` and/or a ``mode``, which filters
the output to only the requested keys.
The default behavior is exactly equivalent to the n... | [
"def",
"keys",
"(",
"self",
",",
"element",
"=",
"None",
",",
"mode",
"=",
"None",
")",
":",
"if",
"mode",
"is",
"None",
":",
"return",
"super",
"(",
")",
".",
"keys",
"(",
")",
"element",
"=",
"self",
".",
"_parse_element",
"(",
"element",
"=",
... | 35.057971 | 23.710145 |
def libvlc_log_set_file(p_instance, stream):
'''Sets up logging to a file.
@param p_instance: libvlc instance.
@param stream: FILE pointer opened for writing (the FILE pointer must remain valid until L{libvlc_log_unset}()).
@version: LibVLC 2.1.0 or later.
'''
f = _Cfunctions.get('libvlc_log_set... | [
"def",
"libvlc_log_set_file",
"(",
"p_instance",
",",
"stream",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_log_set_file'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_log_set_file'",
",",
"(",
"(",
"1",
",",
")",
",",
"(",
"1",
... | 47.1 | 17.7 |
def reverse_set(self, subid, ipaddr, entry, params=None):
''' /v1/server/reverse_set_ipv4
POST - account
Set a reverse DNS entry for an IPv4 address of a virtual machine. Upon
success, DNS changes may take 6-12 hours to become active.
Link: https://www.vultr.com/api/#server_reve... | [
"def",
"reverse_set",
"(",
"self",
",",
"subid",
",",
"ipaddr",
",",
"entry",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"update_params",
"(",
"params",
",",
"{",
"'SUBID'",
":",
"subid",
",",
"'ip'",
":",
"ipaddr",
",",
"'entry'",
":",
"en... | 38.5 | 21.357143 |
def _calc_ML(sampler, modelidx=0, e_range=None, e_npoints=100):
"""Get ML model from blob or compute them from chain and sampler.modelfn
"""
ML, MLp, MLerr, ML_model = find_ML(sampler, modelidx)
if e_range is not None:
# prepare bogus data for calculation
e_range = validate_array(
... | [
"def",
"_calc_ML",
"(",
"sampler",
",",
"modelidx",
"=",
"0",
",",
"e_range",
"=",
"None",
",",
"e_npoints",
"=",
"100",
")",
":",
"ML",
",",
"MLp",
",",
"MLerr",
",",
"ML_model",
"=",
"find_ML",
"(",
"sampler",
",",
"modelidx",
")",
"if",
"e_range",... | 29.72093 | 17.651163 |
def get_file(self,
path,
dest='',
makedirs=False,
saltenv='base',
gzip=None,
cachedir=None):
'''
Copies a file from the local files or master depending on
implementation
'''
rais... | [
"def",
"get_file",
"(",
"self",
",",
"path",
",",
"dest",
"=",
"''",
",",
"makedirs",
"=",
"False",
",",
"saltenv",
"=",
"'base'",
",",
"gzip",
"=",
"None",
",",
"cachedir",
"=",
"None",
")",
":",
"raise",
"NotImplementedError"
] | 27.5 | 16.666667 |
def get_version(package):
"""Get version without importing the lib"""
with io.open(os.path.join(BASE_DIR, package, '__init__.py'), encoding='utf-8') as fh:
return [
l.split('=', 1)[1].strip().strip("'").strip('"')
for l in fh.readlines()
if '__version__' in l][0] | [
"def",
"get_version",
"(",
"package",
")",
":",
"with",
"io",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"BASE_DIR",
",",
"package",
",",
"'__init__.py'",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fh",
":",
"return",
"[",
"l",
"... | 44.142857 | 16.571429 |
def append_utc_time_only(self, tag, timestamp=None, precision=3,
header=False):
"""Append a field with a UTCTimeOnly value.
:param tag: Integer or string FIX tag number.
:param timestamp: Time value, see below.
:param precision: Number of decimal places: 0, ... | [
"def",
"append_utc_time_only",
"(",
"self",
",",
"tag",
",",
"timestamp",
"=",
"None",
",",
"precision",
"=",
"3",
",",
"header",
"=",
"False",
")",
":",
"return",
"self",
".",
"_append_utc_datetime",
"(",
"tag",
",",
"\"%H:%M:%S\"",
",",
"timestamp",
",",... | 48.75 | 20.958333 |
def _at_include(self, calculator, rule, scope, block):
"""
Implements @include, for @mixins
"""
caller_namespace = rule.namespace
caller_calculator = self._make_calculator(caller_namespace)
funct, caller_argspec = self._get_funct_def(rule, caller_calculator, block.argumen... | [
"def",
"_at_include",
"(",
"self",
",",
"calculator",
",",
"rule",
",",
"scope",
",",
"block",
")",
":",
"caller_namespace",
"=",
"rule",
".",
"namespace",
"caller_calculator",
"=",
"self",
".",
"_make_calculator",
"(",
"caller_namespace",
")",
"funct",
",",
... | 37.164179 | 18.119403 |
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... | [
"def",
"random_draw",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"draw_1",
"=",
"self",
".",
"p1",
".",
"random_draw",
"(",
"size",
"=",
"size",
")",
"draw_2",
"=",
"self",
".",
"p2",
".",
"random_draw",
"(",
"size",
"=",
"size",
")",
"if",
... | 34.111111 | 15.833333 |
def image(value, width='', height=''):
"""
Accepts a URL and returns an HTML image tag ready to be displayed.
Optionally, you can set the height and width with keyword arguments.
"""
style = ""
if width:
style += "width:%s" % width
if height:
style += "height:%s" % heigh... | [
"def",
"image",
"(",
"value",
",",
"width",
"=",
"''",
",",
"height",
"=",
"''",
")",
":",
"style",
"=",
"\"\"",
"if",
"width",
":",
"style",
"+=",
"\"width:%s\"",
"%",
"width",
"if",
"height",
":",
"style",
"+=",
"\"height:%s\"",
"%",
"height",
"dat... | 32.076923 | 16.384615 |
def Run(self, unused_arg, ttl=None):
"""Returns the startup information."""
logging.debug("Sending startup information.")
boot_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(psutil.boot_time())
response = rdf_client.StartupInfo(
boot_time=boot_time, client_info=GetClientInformation())
se... | [
"def",
"Run",
"(",
"self",
",",
"unused_arg",
",",
"ttl",
"=",
"None",
")",
":",
"logging",
".",
"debug",
"(",
"\"Sending startup information.\"",
")",
"boot_time",
"=",
"rdfvalue",
".",
"RDFDatetime",
".",
"FromSecondsSinceEpoch",
"(",
"psutil",
".",
"boot_ti... | 36.333333 | 16.066667 |
def prepare_infrastructure():
"""Entry point for preparing the infrastructure in a specific env."""
runner = ForemastRunner()
runner.write_configs()
runner.create_app()
archaius = runner.configs[runner.env]['app']['archaius_enabled']
eureka = runner.configs[runner.env]['app']['eureka_enabled']... | [
"def",
"prepare_infrastructure",
"(",
")",
":",
"runner",
"=",
"ForemastRunner",
"(",
")",
"runner",
".",
"write_configs",
"(",
")",
"runner",
".",
"create_app",
"(",
")",
"archaius",
"=",
"runner",
".",
"configs",
"[",
"runner",
".",
"env",
"]",
"[",
"'... | 31.882353 | 17.735294 |
def standardize_smiles(smiles):
"""Return a standardized canonical SMILES string given a SMILES string.
Note: This is a convenience function for quickly standardizing a single SMILES string. It is more efficient to use
the :class:`~molvs.standardize.Standardizer` class directly when working with many molec... | [
"def",
"standardize_smiles",
"(",
"smiles",
")",
":",
"# Skip sanitize as standardize does this anyway",
"mol",
"=",
"Chem",
".",
"MolFromSmiles",
"(",
"smiles",
",",
"sanitize",
"=",
"False",
")",
"mol",
"=",
"Standardizer",
"(",
")",
".",
"standardize",
"(",
"... | 46 | 23.866667 |
def yticks(self):
"""Compute the yticks labels of this grid_stack, used for plotting the y-axis ticks when visualizing an image \
"""
return np.linspace(np.amin(self.grid_stack.regular[:, 0]), np.amax(self.grid_stack.regular[:, 0]), 4) | [
"def",
"yticks",
"(",
"self",
")",
":",
"return",
"np",
".",
"linspace",
"(",
"np",
".",
"amin",
"(",
"self",
".",
"grid_stack",
".",
"regular",
"[",
":",
",",
"0",
"]",
")",
",",
"np",
".",
"amax",
"(",
"self",
".",
"grid_stack",
".",
"regular",... | 64 | 23 |
def cell(self, row_idx, col_idx):
"""
Return |_Cell| instance correponding to table cell at *row_idx*,
*col_idx* intersection, where (0, 0) is the top, left-most cell.
"""
cell_idx = col_idx + (row_idx * self._column_count)
return self._cells[cell_idx] | [
"def",
"cell",
"(",
"self",
",",
"row_idx",
",",
"col_idx",
")",
":",
"cell_idx",
"=",
"col_idx",
"+",
"(",
"row_idx",
"*",
"self",
".",
"_column_count",
")",
"return",
"self",
".",
"_cells",
"[",
"cell_idx",
"]"
] | 42 | 13.428571 |
def get_connection(hostname, username, logger, threads=5, use_sudo=None, detect_sudo=True):
"""
A very simple helper, meant to return a connection
that will know about the need to use sudo.
"""
if username:
hostname = "%s@%s" % (username, hostname)
try:
conn = remoto.Connection(
... | [
"def",
"get_connection",
"(",
"hostname",
",",
"username",
",",
"logger",
",",
"threads",
"=",
"5",
",",
"use_sudo",
"=",
"None",
",",
"detect_sudo",
"=",
"True",
")",
":",
"if",
"username",
":",
"hostname",
"=",
"\"%s@%s\"",
"%",
"(",
"username",
",",
... | 33.6 | 17.6 |
def write_string(self, s, codec):
""" Write string encoding it with codec into stream """
for i in range(0, len(s), self.bufsize):
chunk = s[i:i + self.bufsize]
buf, consumed = codec.encode(chunk)
assert consumed == len(chunk)
self.write(buf) | [
"def",
"write_string",
"(",
"self",
",",
"s",
",",
"codec",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"s",
")",
",",
"self",
".",
"bufsize",
")",
":",
"chunk",
"=",
"s",
"[",
"i",
":",
"i",
"+",
"self",
".",
"bufsize",
... | 42.857143 | 5.285714 |
def get_viewer_names(self, dataobj):
"""Returns a list of viewer names that are registered that
can view `dataobj`.
"""
res = []
for bnch in self.viewer_db.values():
for vtype in bnch.vtypes:
if isinstance(dataobj, vtype):
res.appen... | [
"def",
"get_viewer_names",
"(",
"self",
",",
"dataobj",
")",
":",
"res",
"=",
"[",
"]",
"for",
"bnch",
"in",
"self",
".",
"viewer_db",
".",
"values",
"(",
")",
":",
"for",
"vtype",
"in",
"bnch",
".",
"vtypes",
":",
"if",
"isinstance",
"(",
"dataobj",... | 34.3 | 7.8 |
def removeLayout(self, layout):
'''Iteratively remove graphical objects from layout.'''
for cnt in reversed(range(layout.count())):
item = layout.takeAt(cnt)
widget = item.widget()
if widget is not None:
widget.deleteLater()
else:
... | [
"def",
"removeLayout",
"(",
"self",
",",
"layout",
")",
":",
"for",
"cnt",
"in",
"reversed",
"(",
"range",
"(",
"layout",
".",
"count",
"(",
")",
")",
")",
":",
"item",
"=",
"layout",
".",
"takeAt",
"(",
"cnt",
")",
"widget",
"=",
"item",
".",
"w... | 41.9 | 12.1 |
def recursepath(path, reverse=False):
# type: (Text, bool) -> List[Text]
"""Get intermediate paths from the root to the given path.
Arguments:
path (str): A PyFilesystem path
reverse (bool): Reverses the order of the paths
(default `False`).
Returns:
list: A list of... | [
"def",
"recursepath",
"(",
"path",
",",
"reverse",
"=",
"False",
")",
":",
"# type: (Text, bool) -> List[Text]",
"if",
"path",
"in",
"\"/\"",
":",
"return",
"[",
"\"/\"",
"]",
"path",
"=",
"abspath",
"(",
"normpath",
"(",
"path",
")",
")",
"+",
"\"/\"",
... | 20.361111 | 20.166667 |
def connect(self):
"""
Connects the client to the server and
returns it.
"""
key = paramiko.RSAKey(data=base64.b64decode(
app.config['SSH_HOST_KEY']
))
client = paramiko.SSHClient()
client.get_host_keys().add(
app.config['SSH_HOST']... | [
"def",
"connect",
"(",
"self",
")",
":",
"key",
"=",
"paramiko",
".",
"RSAKey",
"(",
"data",
"=",
"base64",
".",
"b64decode",
"(",
"app",
".",
"config",
"[",
"'SSH_HOST_KEY'",
"]",
")",
")",
"client",
"=",
"paramiko",
".",
"SSHClient",
"(",
")",
"cli... | 26.85 | 13.15 |
def _parse_seq(self, p):
"""Helper to parse sequence rules.
Sequence rules are in the form::
foo : foo_item sep foo
| foo_item foo
|
This function builds a deque of the items in-order.
If the number of tokens doesn't match, an exception is ... | [
"def",
"_parse_seq",
"(",
"self",
",",
"p",
")",
":",
"# This basically says:",
"#",
"# - When you reach the end of the list, construct and return an empty",
"# deque.",
"# - Otherwise, prepend to start of what you got from the parser.",
"#",
"# So this ends up constructing an in-order... | 29.545455 | 19.878788 |
def state(pre, post, attr='state'):
"""State decorator"""
def decorator(method):
@six.wraps(method)
def inner(self, *args, **kwargs):
setattr(self, attr, pre)
result = method(self, *args, **kwargs)
setattr(self, attr, post)
return result
r... | [
"def",
"state",
"(",
"pre",
",",
"post",
",",
"attr",
"=",
"'state'",
")",
":",
"def",
"decorator",
"(",
"method",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"method",
")",
"def",
"inner",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
"... | 28.416667 | 12.166667 |
def make_extra_json_fields(args):
"""
From the parsed command-line arguments, generate a dictionary of additional
fields to be inserted into JSON logs (logstash_formatter module)
"""
extra_json_fields = {
'data_group': _get_data_group(args.query),
'data_type': _get_data_type(args.que... | [
"def",
"make_extra_json_fields",
"(",
"args",
")",
":",
"extra_json_fields",
"=",
"{",
"'data_group'",
":",
"_get_data_group",
"(",
"args",
".",
"query",
")",
",",
"'data_type'",
":",
"_get_data_type",
"(",
"args",
".",
"query",
")",
",",
"'data_group_data_type'... | 41.928571 | 16.5 |
def simxAuxiliaryConsoleOpen(clientID, title, maxLines, mode, position, size, textColor, backgroundColor, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
consoleHandle = ct.c_int()
if (sys.version_info[0] == 3) and (type(title) is str):
... | [
"def",
"simxAuxiliaryConsoleOpen",
"(",
"clientID",
",",
"title",
",",
"maxLines",
",",
"mode",
",",
"position",
",",
"size",
",",
"textColor",
",",
"backgroundColor",
",",
"operationMode",
")",
":",
"consoleHandle",
"=",
"ct",
".",
"c_int",
"(",
")",
"if",
... | 38.2 | 27.4 |
def _assert_recur_is_tail(node: Node) -> None: # pylint: disable=too-many-branches
"""Assert that `recur` forms only appear in the tail position of this
or child AST nodes.
`recur` forms may only appear in `do` nodes (both literal and synthetic
`do` nodes) and in either the :then or :else expression o... | [
"def",
"_assert_recur_is_tail",
"(",
"node",
":",
"Node",
")",
"->",
"None",
":",
"# pylint: disable=too-many-branches",
"if",
"node",
".",
"op",
"==",
"NodeOp",
".",
"DO",
":",
"assert",
"isinstance",
"(",
"node",
",",
"Do",
")",
"for",
"child",
"in",
"no... | 39.829268 | 9 |
def URL(base, path, segments=None, defaults=None):
"""
URL segment handler capable of getting and setting segments by name. The
URL is constructed by joining base, path and segments.
For each segment a property capable of getting and setting that segment is
created dynamically.
"""
# Make a... | [
"def",
"URL",
"(",
"base",
",",
"path",
",",
"segments",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"# Make a copy of the Segments class",
"url_class",
"=",
"type",
"(",
"Segments",
".",
"__name__",
",",
"Segments",
".",
"__bases__",
",",
"dict",
... | 45.388889 | 16.722222 |
def object_path(collection, id):
"""Returns path to the backing file of the object
with the given ``id`` in the given ``collection``.
Note that the ``id`` is made filesystem-safe by
"normalizing" its string representation."""
_logger.debug(type(id))
_logger.debug(id)
if isinstance(id, dict) ... | [
"def",
"object_path",
"(",
"collection",
",",
"id",
")",
":",
"_logger",
".",
"debug",
"(",
"type",
"(",
"id",
")",
")",
"_logger",
".",
"debug",
"(",
"id",
")",
"if",
"isinstance",
"(",
"id",
",",
"dict",
")",
"and",
"'id'",
"in",
"id",
":",
"id... | 40.916667 | 9.083333 |
def removeAboveValue(requestContext, seriesList, n):
"""
Removes data above the given threshold from the series or list of series
provided. Values above this threshold are assigned a value of None.
"""
for s in seriesList:
s.name = 'removeAboveValue(%s, %g)' % (s.name, n)
s.pathExpre... | [
"def",
"removeAboveValue",
"(",
"requestContext",
",",
"seriesList",
",",
"n",
")",
":",
"for",
"s",
"in",
"seriesList",
":",
"s",
".",
"name",
"=",
"'removeAboveValue(%s, %g)'",
"%",
"(",
"s",
".",
"name",
",",
"n",
")",
"s",
".",
"pathExpression",
"=",... | 32.933333 | 15.6 |
def next_event(self):
"""Simulates the queue forward one event.
This method behaves identically to a :class:`.LossQueue` if the
arriving/departing agent is anything other than a
:class:`.ResourceAgent`. The differences are;
Arriving:
* If the :class:`.ResourceAgent` ha... | [
"def",
"next_event",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_arrivals",
"[",
"0",
"]",
",",
"ResourceAgent",
")",
":",
"if",
"self",
".",
"_departures",
"[",
"0",
"]",
".",
"_time",
"<",
"self",
".",
"_arrivals",
"[",
"0",
"]... | 43.69697 | 24.090909 |
def factorize(self):
""" Factorize s.t. CUR = data
Updated Values
--------------
.C : updated values for C.
.U : updated values for U.
.R : updated values for R.
"""
[prow, pcol] = self.sample_probability()
self._rid = self.s... | [
"def",
"factorize",
"(",
"self",
")",
":",
"[",
"prow",
",",
"pcol",
"]",
"=",
"self",
".",
"sample_probability",
"(",
")",
"self",
".",
"_rid",
"=",
"self",
".",
"sample",
"(",
"self",
".",
"_rrank",
",",
"prow",
")",
"self",
".",
"_cid",
"=",
"... | 23.888889 | 17.444444 |
def bytes2human(n, fmt='%(value).1f %(symbol)s', symbols='customary'):
"""
Convert n bytes into a human readable string based on format.
symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
see: http://goo.gl/kTQMs
"""
n = int(n)
if n < 0:
raise ValueError("n < 0")... | [
"def",
"bytes2human",
"(",
"n",
",",
"fmt",
"=",
"'%(value).1f %(symbol)s'",
",",
"symbols",
"=",
"'customary'",
")",
":",
"n",
"=",
"int",
"(",
"n",
")",
"if",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"n < 0\"",
")",
"symbols",
"=",
"SYMBOLS"... | 35.277778 | 13.5 |
def emit_event(project_slug, action_slug):
"""Publish message to action.
Rio will trigger all registered webhooks related to this action and
trace running process.
"""
if request.headers.get('Content-Type') == 'application/json':
payload = request.get_json()
elif request.method == 'POS... | [
"def",
"emit_event",
"(",
"project_slug",
",",
"action_slug",
")",
":",
"if",
"request",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
")",
"==",
"'application/json'",
":",
"payload",
"=",
"request",
".",
"get_json",
"(",
")",
"elif",
"request",
".",
... | 31.5 | 20.3 |
def login(self, email=None, password=None, user=None):
"""
Logs the user in and setups the header with the private token
:param email: Gitlab user Email
:param user: Gitlab username
:param password: Gitlab user password
:return: True if login successful
:raise: H... | [
"def",
"login",
"(",
"self",
",",
"email",
"=",
"None",
",",
"password",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"if",
"user",
"is",
"not",
"None",
":",
"data",
"=",
"{",
"'login'",
":",
"user",
",",
"'password'",
":",
"password",
"}",
"... | 35.16 | 15 |
def get_status(self, refobj):
"""Return the status of the given reftrack node
See: :data:`Reftrack.LOADED`, :data:`Reftrack.UNLOADED`, :data:`Reftrack.IMPORTED`.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the status of the given reftrack node
... | [
"def",
"get_status",
"(",
"self",
",",
"refobj",
")",
":",
"reference",
"=",
"self",
".",
"get_reference",
"(",
"refobj",
")",
"return",
"Reftrack",
".",
"IMPORTED",
"if",
"not",
"reference",
"else",
"Reftrack",
".",
"LOADED",
"if",
"cmds",
".",
"reference... | 41.769231 | 25.307692 |
def devices(self):
""" Return all devices."""
service_root = self.webservices['findme']['url']
return FindMyiPhoneServiceManager(
service_root,
self.session,
self.params
) | [
"def",
"devices",
"(",
"self",
")",
":",
"service_root",
"=",
"self",
".",
"webservices",
"[",
"'findme'",
"]",
"[",
"'url'",
"]",
"return",
"FindMyiPhoneServiceManager",
"(",
"service_root",
",",
"self",
".",
"session",
",",
"self",
".",
"params",
")"
] | 29 | 14.75 |
async def set_async(self, type_name, entity):
"""Sets an entity asynchronously using the API. Shortcut for using async_call() with the 'Set' method.
:param type_name: The type of entity
:param entity: The entity to set
:raise MyGeotabException: Raises when an exception occurs on the MyG... | [
"async",
"def",
"set_async",
"(",
"self",
",",
"type_name",
",",
"entity",
")",
":",
"return",
"await",
"self",
".",
"call_async",
"(",
"'Set'",
",",
"type_name",
"=",
"type_name",
",",
"entity",
"=",
"entity",
")"
] | 52.125 | 17 |
def move_file_to_file(old_path, new_path):
"""Moves file from old location to new one
:param old_path: path of file to move
:param new_path: new path
"""
try:
os.rename(old_path, new_path)
except:
old_file = os.path.basename(old_path)
... | [
"def",
"move_file_to_file",
"(",
"old_path",
",",
"new_path",
")",
":",
"try",
":",
"os",
".",
"rename",
"(",
"old_path",
",",
"new_path",
")",
"except",
":",
"old_file",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"old_path",
")",
"target_directory",
... | 40.555556 | 15.277778 |
def chromosomes_from_fai(genome_fai):
"""
Read a fasta index (fai) file and parse the input chromosomes.
:param str genome_fai: Path to the fai file.
:return: list of input chromosomes
:rtype: list[str]
"""
chromosomes = []
with open(genome_fai) as fai_file:
for line in fai_file... | [
"def",
"chromosomes_from_fai",
"(",
"genome_fai",
")",
":",
"chromosomes",
"=",
"[",
"]",
"with",
"open",
"(",
"genome_fai",
")",
"as",
"fai_file",
":",
"for",
"line",
"in",
"fai_file",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(... | 29.357143 | 10.785714 |
def run(self, positionals=None):
'''run the entire helper procedure, including:
- start: initialize the helper, collection preferences
- record: record any relevant features for the environment / session
- interact: interact with the user for additional informatoin
... | [
"def",
"run",
"(",
"self",
",",
"positionals",
"=",
"None",
")",
":",
"# Step 0: Each run session is given a fun name",
"self",
".",
"run_id",
"=",
"RobotNamer",
"(",
")",
".",
"generate",
"(",
")",
"# Step 1: get config steps",
"steps",
"=",
"self",
".",
"confi... | 43.6875 | 25.125 |
def _get_shape_without_batch_dimension(tensor_nest):
"""Converts Tensor nest to a TensorShape nest, removing batch dimension."""
def _strip_batch_and_convert_to_shape(tensor):
return tensor.get_shape()[1:]
return nest.map_structure(_strip_batch_and_convert_to_shape, tensor_nest) | [
"def",
"_get_shape_without_batch_dimension",
"(",
"tensor_nest",
")",
":",
"def",
"_strip_batch_and_convert_to_shape",
"(",
"tensor",
")",
":",
"return",
"tensor",
".",
"get_shape",
"(",
")",
"[",
"1",
":",
"]",
"return",
"nest",
".",
"map_structure",
"(",
"_str... | 57 | 12.4 |
def project(self, annotation, timeline):
"""Project annotation onto timeline segments
reference |__A__| |__B__|
|____C____|
timeline |---|---|---| |---|
projection |_A_|_A_|_C_| |_B_|
|_C_|
Parameters
---... | [
"def",
"project",
"(",
"self",
",",
"annotation",
",",
"timeline",
")",
":",
"projection",
"=",
"annotation",
".",
"empty",
"(",
")",
"timeline_",
"=",
"annotation",
".",
"get_timeline",
"(",
"copy",
"=",
"False",
")",
"for",
"segment_",
",",
"segment",
... | 30.62963 | 17.703704 |
def remove(self, stuff):
"""Remove variables and constraints.
Parameters
----------
stuff : iterable, str, Variable, Constraint
Either an iterable containing variables and constraints to be removed from the model or a single variable or contstraint (or their names).
... | [
"def",
"remove",
"(",
"self",
",",
"stuff",
")",
":",
"if",
"self",
".",
"_pending_modifications",
".",
"toggle",
"==",
"'add'",
":",
"self",
".",
"update",
"(",
")",
"self",
".",
"_pending_modifications",
".",
"toggle",
"=",
"'remove'",
"if",
"isinstance"... | 42.487179 | 22.25641 |
def eval_script(self, expr):
""" Evaluates a piece of Javascript in the context of the current page and
returns its value. """
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0] | [
"def",
"eval_script",
"(",
"self",
",",
"expr",
")",
":",
"ret",
"=",
"self",
".",
"conn",
".",
"issue_command",
"(",
"\"Evaluate\"",
",",
"expr",
")",
"return",
"json",
".",
"loads",
"(",
"\"[%s]\"",
"%",
"ret",
")",
"[",
"0",
"]"
] | 44.2 | 5 |
def random_string_alphanumeric(size):
"""
Generate a random string of *size* length consisting of mixed case letters
and numbers. This function is not meant for cryptographic purposes.
:param int size: The length of the string to return.
:return: A string consisting of random characters.
:rtype: str
"""
# requ... | [
"def",
"random_string_alphanumeric",
"(",
"size",
")",
":",
"# requirements = random, string",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
"for",
"x",
"in",
"range",
"(",
... | 38.636364 | 19.545455 |
def declare_artefact(self, value):
# type: (Any) -> ProvEntity
"""Create data artefact entities for all file objects."""
if value is None:
# FIXME: If this can happen in CWL, we'll
# need a better way to represent this in PROV
return self.document.entity(
... | [
"def",
"declare_artefact",
"(",
"self",
",",
"value",
")",
":",
"# type: (Any) -> ProvEntity",
"if",
"value",
"is",
"None",
":",
"# FIXME: If this can happen in CWL, we'll",
"# need a better way to represent this in PROV",
"return",
"self",
".",
"document",
".",
"entity",
... | 45.025862 | 17.637931 |
def restore_placeholders(msgid, translation):
"""Restore placeholders in the translated message."""
placehoders = re.findall(r'(\s*)(%(?:\(\w+\))?[sd])(\s*)', msgid)
return re.sub(
r'(\s*)(__[\w]+?__)(\s*)',
lambda matches: '{0}{1}{2}'.format(placehoders[0][0], placehoders[0][1], placehoders... | [
"def",
"restore_placeholders",
"(",
"msgid",
",",
"translation",
")",
":",
"placehoders",
"=",
"re",
".",
"findall",
"(",
"r'(\\s*)(%(?:\\(\\w+\\))?[sd])(\\s*)'",
",",
"msgid",
")",
"return",
"re",
".",
"sub",
"(",
"r'(\\s*)(__[\\w]+?__)(\\s*)'",
",",
"lambda",
"m... | 49.571429 | 20.857143 |
def open_shapefile(shapefile_path, file_geodatabase=None):
"""Opens a shapefile using either a shapefile path
or a file geodatabase
"""
if file_geodatabase:
gdb_driver = ogr.GetDriverByName("OpenFileGDB")
ogr_shapefile = gdb_driver.Open(file_geodatabase)
ogr_shapefile_lyr = o... | [
"def",
"open_shapefile",
"(",
"shapefile_path",
",",
"file_geodatabase",
"=",
"None",
")",
":",
"if",
"file_geodatabase",
":",
"gdb_driver",
"=",
"ogr",
".",
"GetDriverByName",
"(",
"\"OpenFileGDB\"",
")",
"ogr_shapefile",
"=",
"gdb_driver",
".",
"Open",
"(",
"f... | 41.833333 | 13.083333 |
def _var_names(var_names, data):
"""Handle var_names input across arviz.
Parameters
----------
var_names: str, list, or None
data : xarray.Dataset
Posterior data in an xarray
Returns
-------
var_name: list or None
"""
if var_names is not None:
if isinstance(var_... | [
"def",
"_var_names",
"(",
"var_names",
",",
"data",
")",
":",
"if",
"var_names",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"var_names",
",",
"str",
")",
":",
"var_names",
"=",
"[",
"var_names",
"]",
"if",
"isinstance",
"(",
"data",
",",
"(",
... | 30.636364 | 19.454545 |
def hostname_text(self):
"""Return hostname text and collect if not collected."""
if self._hostname_text is None:
self.chain.connection.log("Collecting hostname information")
self._hostname_text = self.driver.get_hostname_text()
if self._hostname_text:
... | [
"def",
"hostname_text",
"(",
"self",
")",
":",
"if",
"self",
".",
"_hostname_text",
"is",
"None",
":",
"self",
".",
"chain",
".",
"connection",
".",
"log",
"(",
"\"Collecting hostname information\"",
")",
"self",
".",
"_hostname_text",
"=",
"self",
".",
"dri... | 49 | 16.8 |
def get_info(self):
"""Get the information about the channel groups.
Returns
-------
dict
information about this channel group
Notes
-----
The items in selectedItems() are ordered based on the user's selection
(which appears pretty random). I... | [
"def",
"get_info",
"(",
"self",
")",
":",
"selectedItems",
"=",
"self",
".",
"idx_l0",
".",
"selectedItems",
"(",
")",
"selected_chan",
"=",
"[",
"x",
".",
"text",
"(",
")",
"for",
"x",
"in",
"selectedItems",
"]",
"chan_to_plot",
"=",
"[",
"]",
"for",
... | 30.117647 | 18.72549 |
def try_utf8_decode(value):
"""Try to decode an object.
:param value:
:return:
"""
if not value or not is_string(value):
return value
elif PYTHON3 and not isinstance(value, bytes):
return value
elif not PYTHON3 and not isinstance(value, unicode):
return value
tr... | [
"def",
"try_utf8_decode",
"(",
"value",
")",
":",
"if",
"not",
"value",
"or",
"not",
"is_string",
"(",
"value",
")",
":",
"return",
"value",
"elif",
"PYTHON3",
"and",
"not",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"return",
"value",
"elif",
... | 21.210526 | 19.421053 |
def flatten_dict(d, prefix='', sep='.'):
"""In place dict flattening.
"""
def apply_and_resolve_conflicts(dest, item, prefix):
for k, v in flatten_dict(item, prefix=prefix, sep=sep).items():
new_key = k
i = 2
while new_key in d:
new_key = '{key}{se... | [
"def",
"flatten_dict",
"(",
"d",
",",
"prefix",
"=",
"''",
",",
"sep",
"=",
"'.'",
")",
":",
"def",
"apply_and_resolve_conflicts",
"(",
"dest",
",",
"item",
",",
"prefix",
")",
":",
"for",
"k",
",",
"v",
"in",
"flatten_dict",
"(",
"item",
",",
"prefi... | 38 | 16.806452 |
def urlparse(uri):
"""Parse and decode the parts of a URI."""
scheme, netloc, path, params, query, fragment = parse.urlparse(uri)
return (
parse.unquote(scheme),
parse.unquote(netloc),
parse.unquote(path),
parse.unquote(params),
parse.unquote(query),
parse.unq... | [
"def",
"urlparse",
"(",
"uri",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
"=",
"parse",
".",
"urlparse",
"(",
"uri",
")",
"return",
"(",
"parse",
".",
"unquote",
"(",
"scheme",
")",
",",
"parse",
"... | 30 | 16.181818 |
def validate(self, table: pd.DataFrame) -> bool:
"""Return True if all validation tests pass: False otherwise."""
validations = self._make_validations(table=table)
results = [df.all().all() for df in validations]
return all(results) | [
"def",
"validate",
"(",
"self",
",",
"table",
":",
"pd",
".",
"DataFrame",
")",
"->",
"bool",
":",
"validations",
"=",
"self",
".",
"_make_validations",
"(",
"table",
"=",
"table",
")",
"results",
"=",
"[",
"df",
".",
"all",
"(",
")",
".",
"all",
"... | 37.142857 | 19.142857 |
def get_instance(self, instance_id, **kwargs):
"""Get details about a virtual server instance.
:param integer instance_id: the instance ID
:returns: A dictionary containing a large amount of information about
the specified instance.
Example::
# Print out ... | [
"def",
"get_instance",
"(",
"self",
",",
"instance_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'mask'",
"]",
"=",
"(",
"'id,'",
"'globalIdentifier,'",
"'fullyQualifiedDomainName,'",
"'hostname,'",
"'domai... | 41.644737 | 17.434211 |
def from_string(cls, string):
"""
Constructor from string parsing.
Args:
string (str): Input string.
"""
lines = string.split("\n")
timestep = int(lines[1])
natoms = int(lines[3])
box_arr = np.loadtxt(StringIO("\n".join(lines[5:8])))
... | [
"def",
"from_string",
"(",
"cls",
",",
"string",
")",
":",
"lines",
"=",
"string",
".",
"split",
"(",
"\"\\n\"",
")",
"timestep",
"=",
"int",
"(",
"lines",
"[",
"1",
"]",
")",
"natoms",
"=",
"int",
"(",
"lines",
"[",
"3",
"]",
")",
"box_arr",
"="... | 35.291667 | 14.541667 |
def stylize_comment_block(lines):
"""Parse comment lines and make subsequent indented lines into a code block
block.
"""
normal, sep, in_code = range(3)
state = normal
for line in lines:
indented = line.startswith(' ')
empty_line = line.strip() == ''
if state == normal and empty_line:
... | [
"def",
"stylize_comment_block",
"(",
"lines",
")",
":",
"normal",
",",
"sep",
",",
"in_code",
"=",
"range",
"(",
"3",
")",
"state",
"=",
"normal",
"for",
"line",
"in",
"lines",
":",
"indented",
"=",
"line",
".",
"startswith",
"(",
"' '",
")",
"empty... | 24.965517 | 16.965517 |
def find_portgroup(self, si, dv_switch_path, name):
"""
Returns the portgroup on the dvSwitch
:param name: str
:param dv_switch_path: str
:param si: service instance
"""
dv_switch = self.get_folder(si, dv_switch_path)
if dv_switch and dv_switch.portgroup:
... | [
"def",
"find_portgroup",
"(",
"self",
",",
"si",
",",
"dv_switch_path",
",",
"name",
")",
":",
"dv_switch",
"=",
"self",
".",
"get_folder",
"(",
"si",
",",
"dv_switch_path",
")",
"if",
"dv_switch",
"and",
"dv_switch",
".",
"portgroup",
":",
"for",
"port",
... | 34 | 7.692308 |
def add_to_path(p):
"""Adds a given path to the PATH."""
if p not in os.environ["PATH"]:
os.environ["PATH"] = "{0}{1}{2}".format(p, os.pathsep, os.environ["PATH"]) | [
"def",
"add_to_path",
"(",
"p",
")",
":",
"if",
"p",
"not",
"in",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
":",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
"=",
"\"{0}{1}{2}\"",
".",
"format",
"(",
"p",
",",
"os",
".",
"pathsep",
",",
"os",
".... | 44 | 17 |
def write(self, data):
"""Write data to the file. There is no return value.
`data` can be either a string of bytes or a file-like object
(implementing :meth:`read`).
Due to buffering, the data may not actually be written to the
database until the :meth:`close` method is called.... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"_closed",
":",
"raise",
"ValueError",
"(",
"\"TxMongo: cannot write to a closed file.\"",
")",
"try",
":",
"# file-like",
"read",
"=",
"data",
".",
"read",
"except",
"AttributeError",
":",... | 39.596154 | 19.5 |
def tokenize_line_comment(text):
r"""Process a line comment
:param Buffer text: iterator over line, with current position
>>> tokenize_line_comment(Buffer('hello %world'))
>>> tokenize_line_comment(Buffer('%hello world'))
'%hello world'
>>> tokenize_line_comment(Buffer('%hello\n world'))
'... | [
"def",
"tokenize_line_comment",
"(",
"text",
")",
":",
"result",
"=",
"TokenWithPosition",
"(",
"''",
",",
"text",
".",
"position",
")",
"if",
"text",
".",
"peek",
"(",
")",
"==",
"'%'",
"and",
"text",
".",
"peek",
"(",
"-",
"1",
")",
"!=",
"'\\\\'",... | 33.529412 | 15.705882 |
def _get_snippet_ctime(self, snip_name):
"""Returns and remembers (during this DevAssistant invocation) last ctime of given
snippet.
Calling ctime costs lost of time and some snippets, like common_args, are used widely,
so we don't want to call ctime bazillion times on them during one i... | [
"def",
"_get_snippet_ctime",
"(",
"self",
",",
"snip_name",
")",
":",
"if",
"snip_name",
"not",
"in",
"self",
".",
"snip_ctimes",
":",
"snippet",
"=",
"yaml_snippet_loader",
".",
"YamlSnippetLoader",
".",
"get_snippet_by_name",
"(",
"snip_name",
")",
"self",
"."... | 43.8125 | 22.875 |
def coercer(self, dataSets):
"""
Coerce all of the repetitions and sort them into creations, edits and
deletions.
@rtype: L{ListChanges}
@return: An object describing all of the creations, modifications, and
deletions represented by C{dataSets}.
"""
#... | [
"def",
"coercer",
"(",
"self",
",",
"dataSets",
")",
":",
"# Xxx - This does a slightly complex (hey, it's like 20 lines, how",
"# complex could it really be?) thing to figure out which elements are",
"# newly created, which elements were edited, and which elements no",
"# longer exist. It mi... | 45.627119 | 21.322034 |
def decodetx(tx_hex, coin_symbol='btc', api_key=None):
'''
Takes a signed transaction hex binary (and coin_symbol) and decodes it to JSON.
Does NOT broadcast the transaction to the bitcoin network.
Especially useful for testing/debugging and sanity checking
'''
assert is_valid_coin_symbol(coin... | [
"def",
"decodetx",
"(",
"tx_hex",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"assert",
"is_valid_coin_symbol",
"(",
"coin_symbol",
")",
"assert",
"api_key",
",",
"'api_key required'",
"url",
"=",
"make_url",
"(",
"coin_symbol",
",... | 29.809524 | 26.571429 |
def sendMediaGroup(self, chat_id, media,
disable_notification=None,
reply_to_message_id=None):
"""
See: https://core.telegram.org/bots/api#sendmediagroup
:type media: array of `InputMedia <https://core.telegram.org/bots/api#inputmedia>`_ objects
... | [
"def",
"sendMediaGroup",
"(",
"self",
",",
"chat_id",
",",
"media",
",",
"disable_notification",
"=",
"None",
",",
"reply_to_message_id",
"=",
"None",
")",
":",
"p",
"=",
"_strip",
"(",
"locals",
"(",
")",
",",
"more",
"=",
"[",
"'media'",
"]",
")",
"l... | 48.592593 | 24.962963 |
def create_service(
self, task_template, name=None, labels=None, mode=None,
update_config=None, networks=None, endpoint_config=None,
endpoint_spec=None, rollback_config=None
):
"""
Create a service.
Args:
task_template (TaskTemplate): Specific... | [
"def",
"create_service",
"(",
"self",
",",
"task_template",
",",
"name",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"update_config",
"=",
"None",
",",
"networks",
"=",
"None",
",",
"endpoint_config",
"=",
"None",
",",
"endpoi... | 38.164384 | 21.506849 |
def parse_global_args(argv):
"""Parse all global iotile tool arguments.
Any flag based argument at the start of the command line is considered as
a global flag and parsed. The first non flag argument starts the commands
that are passed to the underlying hierarchical shell.
Args:
argv (lis... | [
"def",
"parse_global_args",
"(",
"argv",
")",
":",
"parser",
"=",
"create_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"argv",
")",
"should_log",
"=",
"args",
".",
"include",
"or",
"args",
".",
"exclude",
"or",
"(",
"args",
".",
"v... | 32.516129 | 22.629032 |
def pad_hex(value, bit_size):
"""
Pads a hex string up to the given bit_size
"""
value = remove_0x_prefix(value)
return add_0x_prefix(value.zfill(int(bit_size / 4))) | [
"def",
"pad_hex",
"(",
"value",
",",
"bit_size",
")",
":",
"value",
"=",
"remove_0x_prefix",
"(",
"value",
")",
"return",
"add_0x_prefix",
"(",
"value",
".",
"zfill",
"(",
"int",
"(",
"bit_size",
"/",
"4",
")",
")",
")"
] | 30 | 6.333333 |
def fill_jacobian_column(self, jaccol, coordinates):
"""Fill in a column of the Jacobian.
Arguments:
| ``jaccol`` -- The column of Jacobian to which the result must be
added.
| ``coordinates`` -- A numpy array with Cartesian coordinates,
... | [
"def",
"fill_jacobian_column",
"(",
"self",
",",
"jaccol",
",",
"coordinates",
")",
":",
"q",
",",
"g",
"=",
"self",
".",
"icfn",
"(",
"coordinates",
"[",
"list",
"(",
"self",
".",
"indexes",
")",
"]",
",",
"1",
")",
"for",
"i",
",",
"j",
"in",
"... | 40 | 15.307692 |
def rsa_eq(key1, key2):
"""
Only works for RSAPublic Keys
:param key1:
:param key2:
:return:
"""
pn1 = key1.public_numbers()
pn2 = key2.public_numbers()
# Check if two RSA keys are in fact the same
if pn1 == pn2:
return True
else:
return False | [
"def",
"rsa_eq",
"(",
"key1",
",",
"key2",
")",
":",
"pn1",
"=",
"key1",
".",
"public_numbers",
"(",
")",
"pn2",
"=",
"key2",
".",
"public_numbers",
"(",
")",
"# Check if two RSA keys are in fact the same",
"if",
"pn1",
"==",
"pn2",
":",
"return",
"True",
... | 19.333333 | 17.333333 |
def create_database(destroy_existing=False):
""" Create db and tables if it doesn't exist """
if not os.path.exists(DB_NAME):
logger.info('Create database: {0}'.format(DB_NAME))
open(DB_NAME, 'a').close()
Show.create_table()
Episode.create_table()
Setting.create_ta... | [
"def",
"create_database",
"(",
"destroy_existing",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"DB_NAME",
")",
":",
"logger",
".",
"info",
"(",
"'Create database: {0}'",
".",
"format",
"(",
"DB_NAME",
")",
")",
"open",
"("... | 39.75 | 8.125 |
def _promote(self, request_url):
"""
Moves the cache item specified by request_url to the front of the
'usage_recency' list
"""
self._usage_recency.remove(request_url)
self._usage_recency.add(request_url) | [
"def",
"_promote",
"(",
"self",
",",
"request_url",
")",
":",
"self",
".",
"_usage_recency",
".",
"remove",
"(",
"request_url",
")",
"self",
".",
"_usage_recency",
".",
"add",
"(",
"request_url",
")"
] | 35.142857 | 9.142857 |
def _set_mcast(self, v, load=False):
"""
Setter method for mcast, mapped from YANG variable /fabric/route/mcast (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mcast is considered as a private
method. Backends looking to populate this variable should
... | [
"def",
"_set_mcast",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 64.535714 | 29.964286 |
def create(self, num):
"""
Creates the environment
in your subclassed create function include the line below
super().build(arg1, arg2, arg2, ...)
"""
self.log.record_process('enviroment.py', 'Creating ' + str(num) + ' environments - ' + self.name) | [
"def",
"create",
"(",
"self",
",",
"num",
")",
":",
"self",
".",
"log",
".",
"record_process",
"(",
"'enviroment.py'",
",",
"'Creating '",
"+",
"str",
"(",
"num",
")",
"+",
"' environments - '",
"+",
"self",
".",
"name",
")"
] | 41.285714 | 17.285714 |
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr | [
"def",
"_set_trusted_option_if_needed",
"(",
"repostr",
",",
"trusted",
")",
":",
"if",
"trusted",
"is",
"True",
":",
"repostr",
"+=",
"' [trusted=yes]'",
"elif",
"trusted",
"is",
"False",
":",
"repostr",
"+=",
"' [trusted=no]'",
"return",
"repostr"
] | 26.888889 | 15.777778 |
def is_changed(self, field, from_db=False):
"""
Args:
field (string): Field name.
from_db (bool): Check changes against actual db data
Returns:
bool: True if given fields value is changed.
"""
return field in self.changed_fields(from_db=from_d... | [
"def",
"is_changed",
"(",
"self",
",",
"field",
",",
"from_db",
"=",
"False",
")",
":",
"return",
"field",
"in",
"self",
".",
"changed_fields",
"(",
"from_db",
"=",
"from_db",
")"
] | 31.3 | 15.5 |
def _read_message(self):
"""Reads the contents of a message.
Returns:
body of message if parsable else None
"""
line = self._rfile.readline()
if not line:
return None
content_length = self._content_length(line)
# Blindly consume all hea... | [
"def",
"_read_message",
"(",
"self",
")",
":",
"line",
"=",
"self",
".",
"_rfile",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"return",
"None",
"content_length",
"=",
"self",
".",
"_content_length",
"(",
"line",
")",
"# Blindly consume all header l... | 23 | 18.545455 |
def last_datetime(self):
"""Return the time of the last operation on the bundle as a datetime object"""
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.lasttime)
except TypeError:
return None | [
"def",
"last_datetime",
"(",
"self",
")",
":",
"from",
"datetime",
"import",
"datetime",
"try",
":",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"self",
".",
"state",
".",
"lasttime",
")",
"except",
"TypeError",
":",
"return",
"None"
] | 33.625 | 17.625 |
def implicitly_wait(self, time_to_wait):
"""
Sets a sticky timeout to implicitly wait for an element to be found,
or a command to complete. This method only needs to be called one
time per session. To set the timeout for calls to
execute_async_script, see set_script_time... | [
"def",
"implicitly_wait",
"(",
"self",
",",
"time_to_wait",
")",
":",
"if",
"self",
".",
"w3c",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"SET_TIMEOUTS",
",",
"{",
"'implicit'",
":",
"int",
"(",
"float",
"(",
"time_to_wait",
")",
"*",
"1000",
"... | 34.095238 | 20.095238 |
def _send_request(self):
"""
Sends the request to the backend.
"""
if isinstance(self._worker, str):
classname = self._worker
else:
classname = '%s.%s' % (self._worker.__module__,
self._worker.__name__)
self.reque... | [
"def",
"_send_request",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_worker",
",",
"str",
")",
":",
"classname",
"=",
"self",
".",
"_worker",
"else",
":",
"classname",
"=",
"'%s.%s'",
"%",
"(",
"self",
".",
"_worker",
".",
"__module__... | 37.083333 | 9.916667 |
def dflt_sortby_objgoea(goea_res):
"""Default sorting of GOEA results."""
return [getattr(goea_res, 'enrichment'),
getattr(goea_res, 'namespace'),
getattr(goea_res, 'p_uncorrected'),
getattr(goea_res, 'depth'),
getattr(goea_res, 'GO')] | [
"def",
"dflt_sortby_objgoea",
"(",
"goea_res",
")",
":",
"return",
"[",
"getattr",
"(",
"goea_res",
",",
"'enrichment'",
")",
",",
"getattr",
"(",
"goea_res",
",",
"'namespace'",
")",
",",
"getattr",
"(",
"goea_res",
",",
"'p_uncorrected'",
")",
",",
"getatt... | 44.142857 | 5 |
def getPrice(self, searches):
""" Prices all quest items and returns result
Searches the shop wizard x times (x being number given in searches) for each
quest item and finds the lowest price for each item. Combines all item prices
and sets KitchenQuest.npSpent to the final value... | [
"def",
"getPrice",
"(",
"self",
",",
"searches",
")",
":",
"totalPrice",
"=",
"0",
"for",
"item",
"in",
"self",
".",
"items",
":",
"res",
"=",
"ShopWizard",
".",
"priceItem",
"(",
"self",
".",
"usr",
",",
"item",
".",
"name",
",",
"searches",
",",
... | 35.928571 | 22.142857 |
def _escaped_token_to_subtoken_strings(self, escaped_token):
"""Converts an escaped token string to a list of subtoken strings.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtokens as unicode strings.
"""
# NOTE: This algorithm is greedy; it won't nece... | [
"def",
"_escaped_token_to_subtoken_strings",
"(",
"self",
",",
"escaped_token",
")",
":",
"# NOTE: This algorithm is greedy; it won't necessarily produce the \"best\"",
"# list of subtokens.",
"ret",
"=",
"[",
"]",
"start",
"=",
"0",
"token_len",
"=",
"len",
"(",
"escaped_t... | 35.206897 | 21.310345 |
def get_store(url_details):
"""
The state of the mock server will be stored in the resulting
object created here
"""
store = {}
for detail in url_details:
base_url = detail['url'].strip()
# If a url detail has instances, it means that
# we want to also create an endpoint... | [
"def",
"get_store",
"(",
"url_details",
")",
":",
"store",
"=",
"{",
"}",
"for",
"detail",
"in",
"url_details",
":",
"base_url",
"=",
"detail",
"[",
"'url'",
"]",
".",
"strip",
"(",
")",
"# If a url detail has instances, it means that",
"# we want to also create a... | 50.814516 | 20.362903 |
def splitSymbol(self, index):
"""Give relevant values for computations:
(insertSymbol, copySymbol, dist0flag)
"""
#determine insert and copy upper bits from table
row = [0,0,1,1,2,2,1,3,2,3,3][index>>6]
col = [0,1,0,1,0,1,2,0,2,1,2][index>>6]
#determine inserts an... | [
"def",
"splitSymbol",
"(",
"self",
",",
"index",
")",
":",
"#determine insert and copy upper bits from table",
"row",
"=",
"[",
"0",
",",
"0",
",",
"1",
",",
"1",
",",
"2",
",",
"2",
",",
"1",
",",
"3",
",",
"2",
",",
"3",
",",
"3",
"]",
"[",
"in... | 39 | 11.125 |
def get_stock(self, symbol: str) -> Commodity:
"""Returns the stock/commodity object for the given symbol"""
# Check if we have the exchange name (namespace).
if ":" in symbol:
# We have a namespace
symbol_parts = symbol.split(":")
exchange = symbol_parts[0]
... | [
"def",
"get_stock",
"(",
"self",
",",
"symbol",
":",
"str",
")",
"->",
"Commodity",
":",
"# Check if we have the exchange name (namespace).",
"if",
"\":\"",
"in",
"symbol",
":",
"# We have a namespace",
"symbol_parts",
"=",
"symbol",
".",
"split",
"(",
"\":\"",
")... | 39.333333 | 17.666667 |
def copy(
self,
extractor=None,
needs=None,
store=None,
data_writer=None,
persistence=None,
extractor_args=None):
"""
Use self as a template to build a new feature, replacing
values in kwargs
"""
... | [
"def",
"copy",
"(",
"self",
",",
"extractor",
"=",
"None",
",",
"needs",
"=",
"None",
",",
"store",
"=",
"None",
",",
"data_writer",
"=",
"None",
",",
"persistence",
"=",
"None",
",",
"extractor_args",
"=",
"None",
")",
":",
"f",
"=",
"Feature",
"(",... | 29.083333 | 13.083333 |
def read_data(self, f_start=None, f_stop=None,t_start=None, t_stop=None):
""" Read data
"""
self._setup_selection_range(f_start=f_start, f_stop=f_stop, t_start=t_start, t_stop=t_stop)
#check if selection is small enough.
if self.isheavy():
logger.warning("Selection ... | [
"def",
"read_data",
"(",
"self",
",",
"f_start",
"=",
"None",
",",
"f_stop",
"=",
"None",
",",
"t_start",
"=",
"None",
",",
"t_stop",
"=",
"None",
")",
":",
"self",
".",
"_setup_selection_range",
"(",
"f_start",
"=",
"f_start",
",",
"f_stop",
"=",
"f_s... | 51.166667 | 37.944444 |
def n_way_models(mdr_instance, X, y, n=[2], feature_names=None):
"""Fits a MDR model to all n-way combinations of the features in X.
Note that this function performs an exhaustive search through all feature combinations and can be computationally expensive.
Parameters
----------
mdr_instance: obje... | [
"def",
"n_way_models",
"(",
"mdr_instance",
",",
"X",
",",
"y",
",",
"n",
"=",
"[",
"2",
"]",
",",
"feature_names",
"=",
"None",
")",
":",
"if",
"feature_names",
"is",
"None",
":",
"feature_names",
"=",
"list",
"(",
"range",
"(",
"X",
".",
"shape",
... | 44.447368 | 24.657895 |
def _create_http_client():
"""Create the HTTP client with authentication credentials if required."""
global _http_client
defaults = {'user_agent': USER_AGENT}
auth_username, auth_password = _credentials
if auth_username and auth_password:
defaults['auth_username'] = auth_username
de... | [
"def",
"_create_http_client",
"(",
")",
":",
"global",
"_http_client",
"defaults",
"=",
"{",
"'user_agent'",
":",
"USER_AGENT",
"}",
"auth_username",
",",
"auth_password",
"=",
"_credentials",
"if",
"auth_username",
"and",
"auth_password",
":",
"defaults",
"[",
"'... | 36.692308 | 12.153846 |
def transform_expression_columns(df, fn=np.log2, prefix='Intensity '):
"""
Apply transformation to expression columns.
Default is log2 transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return:
"""
df = df.copy(... | [
"def",
"transform_expression_columns",
"(",
"df",
",",
"fn",
"=",
"np",
".",
"log2",
",",
"prefix",
"=",
"'Intensity '",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"mask",
"=",
"np",
".",
"array",
"(",
"[",
"l",
".",
"startswith",
"(",
"pref... | 26.052632 | 25.210526 |
def ec2_route_table_tagged_route_table_id(self, lookup, default=None):
"""
Args:
lookup: the tagged route table name, should be unique
default: the optional value to return if lookup failed; returns None if not set
Returns:
the ID of the route table, or default if no match/multiple matches... | [
"def",
"ec2_route_table_tagged_route_table_id",
"(",
"self",
",",
"lookup",
",",
"default",
"=",
"None",
")",
":",
"route_table",
"=",
"EFAwsResolver",
".",
"__CLIENTS",
"[",
"\"ec2\"",
"]",
".",
"describe_route_tables",
"(",
"Filters",
"=",
"[",
"{",
"'Name'",
... | 42 | 21.466667 |
def reset(self):
'''Restores the starting position.'''
self.piece_bb = [
BB_VOID, # NONE
BB_RANK_C | BB_RANK_G, # PAWN
BB_A1 | BB_I1 | BB_A9 | BB_I9, # LANCE
BB_A2 | BB_A8 | BB_I2 | BB_I8, # KNIGHT
... | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"piece_bb",
"=",
"[",
"BB_VOID",
",",
"# NONE",
"BB_RANK_C",
"|",
"BB_RANK_G",
",",
"# PAWN",
"BB_A1",
"|",
"BB_I1",
"|",
"BB_A9",
"|",
"BB_I9",
",",
"# LANCE",
"BB_A2",
"|",
"BB_A8",
"|",
"BB_I2",
... | 43.871795 | 20.487179 |
def middle(self):
""" Returns the middle point of the bounding box
:return: middle point
:rtype: (float, float)
"""
return (self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2 | [
"def",
"middle",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"min_x",
"+",
"self",
".",
"max_x",
")",
"/",
"2",
",",
"(",
"self",
".",
"min_y",
"+",
"self",
".",
"max_y",
")",
"/",
"2"
] | 31.142857 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.