text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def addGagUser(self, userId, chatroomId, minute):
"""
添加禁言聊天室成员方法(在 App 中如果不想让某一用户在聊天室中发言时,可将此用户在聊天室中禁言,被禁言用户可以接收查看聊天室中用户聊天信息,但不能发送消息.) 方法
@param userId:用户 Id。(必传)
@param chatroomId:聊天室 Id。(必传)
@param minute:禁言时长,以分钟为单位,最大值为43200分钟。(必传)
@return code:返回码,200 为正常。
... | [
"def",
"addGagUser",
"(",
"self",
",",
"userId",
",",
"chatroomId",
",",
"minute",
")",
":",
"desc",
"=",
"{",
"\"name\"",
":",
"\"CodeSuccessReslut\"",
",",
"\"desc\"",
":",
"\" http 成功返回结果\",",
"",
"\"fields\"",
":",
"[",
"{",
"\"name\"",
":",
"\"code\"",
... | 31.212121 | 13.848485 |
def create(self, metric_id, value, timestamp=None):
"""Add a Metric Point to a Metric
:param int metric_id: Metric ID
:param int value: Value to plot on the metric graph
:param str timestamp: Unix timestamp of the point was measured
:return: Created metric point data (:class:`di... | [
"def",
"create",
"(",
"self",
",",
"metric_id",
",",
"value",
",",
"timestamp",
"=",
"None",
")",
":",
"data",
"=",
"ApiParams",
"(",
")",
"data",
"[",
"'value'",
"]",
"=",
"value",
"data",
"[",
"'timestamp'",
"]",
"=",
"timestamp",
"return",
"self",
... | 40.857143 | 18.428571 |
def addAsn1MibSource(self, *asn1Sources, **kwargs):
"""Adds path to a repository to search ASN.1 MIB files.
Parameters
----------
*asn1Sources :
one or more URL in form of :py:obj:`str` identifying local or
remote ASN.1 MIB repositories. Path must include the *@m... | [
"def",
"addAsn1MibSource",
"(",
"self",
",",
"*",
"asn1Sources",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_asn1SourcesToAdd",
"is",
"None",
":",
"self",
".",
"_asn1SourcesToAdd",
"=",
"asn1Sources",
"else",
":",
"self",
".",
"_asn1SourcesToAdd"... | 31.571429 | 23.333333 |
def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT):
"""
Create a Plot object representing the SArray.
Notes
-----
- The plot will render either inline in a Jupyter Notebook, or in a
native GUI window, depending on the value provided in
... | [
"def",
"plot",
"(",
"self",
",",
"title",
"=",
"LABEL_DEFAULT",
",",
"xlabel",
"=",
"LABEL_DEFAULT",
",",
"ylabel",
"=",
"LABEL_DEFAULT",
")",
":",
"if",
"title",
"==",
"\"\"",
":",
"title",
"=",
"\" \"",
"if",
"xlabel",
"==",
"\"\"",
":",
"xlabel",
"=... | 29.423729 | 25.830508 |
def get_edge_list(self):
r"""Return an edge list, an alternative representation of the graph.
Each edge :math:`e_k = (v_i, v_j) \in \mathcal{E}` from :math:`v_i` to
:math:`v_j` is associated with the weight :math:`W[i, j]`. For each
edge :math:`e_k`, the method returns :math:`(i, j, W[i... | [
"def",
"get_edge_list",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_directed",
"(",
")",
":",
"W",
"=",
"self",
".",
"W",
".",
"tocoo",
"(",
")",
"else",
":",
"W",
"=",
"sparse",
".",
"triu",
"(",
"self",
".",
"W",
",",
"format",
"=",
"'coo'"... | 31.338235 | 21.117647 |
def run_recipe(recipe, task, rinput, workenv, logger_control):
"""Recipe execution mode of numina."""
# Creating custom logger file
recipe_logger = logging.getLogger(logger_control['default'])
if logger_control['enabled']:
logfile = os.path.join(workenv.resultsdir, logger_control['logfile'])
... | [
"def",
"run_recipe",
"(",
"recipe",
",",
"task",
",",
"rinput",
",",
"workenv",
",",
"logger_control",
")",
":",
"# Creating custom logger file",
"recipe_logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger_control",
"[",
"'default'",
"]",
")",
"if",
"logger_... | 34.863636 | 20.954545 |
def regex_to_sql_like(regex_text: str,
single_wildcard: str = "_",
zero_or_more_wildcard: str = "%") -> List[str]:
"""
Converts regular expression text to a reasonably close fragment
for the SQL ``LIKE`` operator.
NOT PERFECT, but work... | [
"def",
"regex_to_sql_like",
"(",
"regex_text",
":",
"str",
",",
"single_wildcard",
":",
"str",
"=",
"\"_\"",
",",
"zero_or_more_wildcard",
":",
"str",
"=",
"\"%\"",
")",
"->",
"List",
"[",
"str",
"]",
":",
"def",
"append_to_all",
"(",
"new_content",
":",
"... | 39.103896 | 17.883117 |
def _compute_distance(self, rup, dists, C):
"""
Compute the distance function, equation (9):
"""
mref = 3.6
rref = 1.0
rval = np.sqrt(dists.rhypo ** 2 + C['h'] ** 2)
return (C['c1'] + C['c2'] * (rup.mag - mref)) *\
np.log10(rval / rref) + C['c3'] * (rv... | [
"def",
"_compute_distance",
"(",
"self",
",",
"rup",
",",
"dists",
",",
"C",
")",
":",
"mref",
"=",
"3.6",
"rref",
"=",
"1.0",
"rval",
"=",
"np",
".",
"sqrt",
"(",
"dists",
".",
"rhypo",
"**",
"2",
"+",
"C",
"[",
"'h'",
"]",
"**",
"2",
")",
"... | 35.777778 | 12 |
def resolve_schema_instance(schema):
"""Return schema instance for given schema (instance or class)
:param type|Schema|str schema: instance, class or class name of marshmallow.Schema
:return: schema instance of given schema (instance or class)
"""
if isinstance(schema, type) and issubclass(schema, ... | [
"def",
"resolve_schema_instance",
"(",
"schema",
")",
":",
"if",
"isinstance",
"(",
"schema",
",",
"type",
")",
"and",
"issubclass",
"(",
"schema",
",",
"marshmallow",
".",
"Schema",
")",
":",
"return",
"schema",
"(",
")",
"if",
"isinstance",
"(",
"schema"... | 43.176471 | 22.176471 |
def delete_csi_node(self, name, **kwargs):
"""
delete a CSINode
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_csi_node(name, async_req=True)
>>> result = thread.get()
... | [
"def",
"delete_csi_node",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"delete_csi_node_with_http_in... | 90.653846 | 63.807692 |
def bounds(self) -> Tuple[float, float, float, float]:
"""Returns the bounds of the shape.
Bounds are given in the following order in the origin crs:
west, south, east, north
"""
return self.shape.bounds | [
"def",
"bounds",
"(",
"self",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
",",
"float",
"]",
":",
"return",
"self",
".",
"shape",
".",
"bounds"
] | 39.666667 | 9.333333 |
def histogram_intersection(h1, h2): # 6 us @array, 30 us @list \w 100 bins
r"""
Calculate the common part of two histograms.
The histogram intersection between two histograms :math:`H` and :math:`H'` of size :math:`m` is
defined as:
.. math::
d_{\cap}(H, H') = \sum_{m=1}^M\min... | [
"def",
"histogram_intersection",
"(",
"h1",
",",
"h2",
")",
":",
"# 6 us @array, 30 us @list \\w 100 bins",
"h1",
",",
"h2",
"=",
"__prepare_histogram",
"(",
"h1",
",",
"h2",
")",
"return",
"scipy",
".",
"sum",
"(",
"scipy",
".",
"minimum",
"(",
"h1",
",",
... | 23.27907 | 22.604651 |
def comma_join(fields, oxford=True):
""" Join together words. """
def fmt(field):
return "'%s'" % field
if not fields:
return "nothing"
elif len(fields) == 1:
return fmt(fields[0])
elif len(fields) == 2:
return " and ".join([fmt(f) for f in fields])
else:
... | [
"def",
"comma_join",
"(",
"fields",
",",
"oxford",
"=",
"True",
")",
":",
"def",
"fmt",
"(",
"field",
")",
":",
"return",
"\"'%s'\"",
"%",
"field",
"if",
"not",
"fields",
":",
"return",
"\"nothing\"",
"elif",
"len",
"(",
"fields",
")",
"==",
"1",
":"... | 25.944444 | 17.5 |
def search_form(context, search_model_names=None):
"""
Includes the search form with a list of models to use as choices
for filtering the search by. Models should be a string with models
in the format ``app_label.model_name`` separated by spaces. The
string ``all`` can also be used, in which case th... | [
"def",
"search_form",
"(",
"context",
",",
"search_model_names",
"=",
"None",
")",
":",
"template_vars",
"=",
"{",
"\"request\"",
":",
"context",
"[",
"\"request\"",
"]",
",",
"}",
"if",
"not",
"search_model_names",
"or",
"not",
"settings",
".",
"SEARCH_MODEL_... | 41.357143 | 19.285714 |
def load_model(model_cls_path, model_cls_name, model_load_args):
"""Get an instance of the described model.
Args:
model_cls_path: Path to the module in which the model class
is defined.
model_cls_name: Name of the model class.
model_load_args: Dictionary of args to pass to t... | [
"def",
"load_model",
"(",
"model_cls_path",
",",
"model_cls_name",
",",
"model_load_args",
")",
":",
"spec",
"=",
"importlib",
".",
"util",
".",
"spec_from_file_location",
"(",
"'active_model'",
",",
"model_cls_path",
")",
"model_module",
"=",
"importlib",
".",
"u... | 39.32 | 20.4 |
def safe_unit_norm(a):
"""
Ensure that the vector or vectors have unit norm
"""
if 1 == len(a.shape):
n = np.linalg.norm(a)
if n:
return a / n
return a
norm = np.sum(np.abs(a) ** 2, axis=-1) ** (1. / 2)
# Dividing by a norm of zero will cause a warning to be... | [
"def",
"safe_unit_norm",
"(",
"a",
")",
":",
"if",
"1",
"==",
"len",
"(",
"a",
".",
"shape",
")",
":",
"n",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"a",
")",
"if",
"n",
":",
"return",
"a",
"/",
"n",
"return",
"a",
"norm",
"=",
"np",
"."... | 31.235294 | 19.823529 |
def append_multi(self, keys, format=None, persist_to=0, replicate_to=0):
"""Append to multiple keys. Multi variant of :meth:`append`.
.. warning::
If using the `Item` interface, use the :meth:`append_items`
and :meth:`prepend_items` instead, as those will
automatica... | [
"def",
"append_multi",
"(",
"self",
",",
"keys",
",",
"format",
"=",
"None",
",",
"persist_to",
"=",
"0",
",",
"replicate_to",
"=",
"0",
")",
":",
"return",
"_Base",
".",
"append_multi",
"(",
"self",
",",
"keys",
",",
"format",
"=",
"format",
",",
"p... | 43.666667 | 22.4 |
def __dp(self):
"""
Get the I{default} port if defined in the I{options}.
@return: A L{MethodSelector} for the I{default} port.
@rtype: L{MethodSelector}.
"""
dp = self.__client.options.port
if dp is None:
return None
else:
return s... | [
"def",
"__dp",
"(",
"self",
")",
":",
"dp",
"=",
"self",
".",
"__client",
".",
"options",
".",
"port",
"if",
"dp",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"self",
".",
"__find",
"(",
"dp",
")"
] | 29.454545 | 12.909091 |
def get_publish_profile(self, webspace_name, website_name):
'''
Get a site's publish profile as an object
webspace_name:
The name of the webspace.
website_name:
The name of the website.
'''
return self._perform_get(self._get_publishxml_path(webspa... | [
"def",
"get_publish_profile",
"(",
"self",
",",
"webspace_name",
",",
"website_name",
")",
":",
"return",
"self",
".",
"_perform_get",
"(",
"self",
".",
"_get_publishxml_path",
"(",
"webspace_name",
",",
"website_name",
")",
",",
"PublishData",
")"
] | 34.454545 | 20.272727 |
def plot(self):
"""Plot the empirical histogram versus best-fit distribution's PDF."""
plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf) | [
"def",
"plot",
"(",
"self",
")",
":",
"plt",
".",
"plot",
"(",
"self",
".",
"bin_edges",
",",
"self",
".",
"hist",
",",
"self",
".",
"bin_edges",
",",
"self",
".",
"best_pdf",
")"
] | 56.333333 | 19.333333 |
def run_transgene(job, snpeffed_file, rna_bam, univ_options, transgene_options, tumor_dna_bam=None,
fusion_calls=None):
"""
Run transgene on an input snpeffed vcf file and return the peptides for MHC prediction.
:param toil.fileStore.FileID snpeffed_file: fsID for snpeffed vcf
:param... | [
"def",
"run_transgene",
"(",
"job",
",",
"snpeffed_file",
",",
"rna_bam",
",",
"univ_options",
",",
"transgene_options",
",",
"tumor_dna_bam",
"=",
"None",
",",
"fusion_calls",
"=",
"None",
")",
":",
"assert",
"snpeffed_file",
"or",
"fusion_calls",
"work_dir",
"... | 52.22807 | 28.263158 |
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args ``block`` is ``True`` and ``timeout`` is
``None`` (the default), block if necessary until an item is
available. If ``timeout`` is a positive number, it blocks at
most ``timeou... | [
"def",
"get",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"block",
":",
"return",
"self",
".",
"get_nowait",
"(",
")",
"item",
"=",
"self",
".",
"_bpop",
"(",
"[",
"self",
".",
"name",
"]",
",",
"... | 42.105263 | 21 |
def add_optionals(self, optionals_in, optionals_out):
"""
Add optional inputs and outputs to the model spec.
Parameters
----------
optionals_in: [str]
List of inputs that are optionals.
optionals_out: [str]
List of outputs that are optionals.
... | [
"def",
"add_optionals",
"(",
"self",
",",
"optionals_in",
",",
"optionals_out",
")",
":",
"spec",
"=",
"self",
".",
"spec",
"if",
"(",
"not",
"optionals_in",
")",
"and",
"(",
"not",
"optionals_out",
")",
":",
"return",
"# assuming single sizes here",
"input_ty... | 37.095238 | 25.619048 |
def make_const_handler(data):
"""
Create a handler for a data opcode that returns a constant.
"""
data = bytes_as_hex(data)
def constant_data_opcode_handler(script, pc, verify_minimal_data=False):
return pc+1, data
return constant_data_opcode_handler | [
"def",
"make_const_handler",
"(",
"data",
")",
":",
"data",
"=",
"bytes_as_hex",
"(",
"data",
")",
"def",
"constant_data_opcode_handler",
"(",
"script",
",",
"pc",
",",
"verify_minimal_data",
"=",
"False",
")",
":",
"return",
"pc",
"+",
"1",
",",
"data",
"... | 30.555556 | 15.222222 |
def _verify_type(self, spec, path):
"""Verify that the 'type' in the spec is valid"""
field_type = spec['type']
if isinstance(field_type, Schema):
# Nested documents cannot have validation
if not set(spec.keys()).issubset(set(['type', 'required', 'nullable', 'default']))... | [
"def",
"_verify_type",
"(",
"self",
",",
"spec",
",",
"path",
")",
":",
"field_type",
"=",
"spec",
"[",
"'type'",
"]",
"if",
"isinstance",
"(",
"field_type",
",",
"Schema",
")",
":",
"# Nested documents cannot have validation",
"if",
"not",
"set",
"(",
"spec... | 57.8125 | 36 |
def _exec(self, binary, stdin='', args=(), env={}):
"""
Executes the binary using stdin and args with environment
variables.
Returns a tuple of stdout, stderr. Format determined by the
input text (either str or bytes), and the encoding of str will
be determined by the l... | [
"def",
"_exec",
"(",
"self",
",",
"binary",
",",
"stdin",
"=",
"''",
",",
"args",
"=",
"(",
")",
",",
"env",
"=",
"{",
"}",
")",
":",
"call_kw",
"=",
"self",
".",
"_gen_call_kws",
"(",
"*",
"*",
"env",
")",
"call_args",
"=",
"[",
"self",
".",
... | 38.285714 | 18.428571 |
def lithospheric_stress(step, trench, ridge, time):
"""calculate stress in the lithosphere"""
timestep = step.isnap
base_lith = step.geom.rcmb + 1 - 0.105
stressfld = step.fields['sII'][0, :, :, 0]
stressfld = np.ma.masked_where(step.geom.r_mesh[0] < base_lith, stressfld)
# stress integration ... | [
"def",
"lithospheric_stress",
"(",
"step",
",",
"trench",
",",
"ridge",
",",
"time",
")",
":",
"timestep",
"=",
"step",
".",
"isnap",
"base_lith",
"=",
"step",
".",
"geom",
".",
"rcmb",
"+",
"1",
"-",
"0.105",
"stressfld",
"=",
"step",
".",
"fields",
... | 42.3 | 17.622222 |
def _logs_options(p):
""" Add options specific to logs subcommand. """
_default_options(p, blacklist=['cache', 'quiet'])
# default time range is 0 to "now" (to include all log entries)
p.add_argument(
'--start',
default='the beginning', # invalid, will result in 0
help='Start d... | [
"def",
"_logs_options",
"(",
"p",
")",
":",
"_default_options",
"(",
"p",
",",
"blacklist",
"=",
"[",
"'cache'",
",",
"'quiet'",
"]",
")",
"# default time range is 0 to \"now\" (to include all log entries)",
"p",
".",
"add_argument",
"(",
"'--start'",
",",
"default"... | 30.4 | 19.333333 |
def convert_reaction_entry(self, reaction):
"""Convert reaction entry to YAML dict."""
d = OrderedDict()
d['id'] = reaction.id
def is_equation_valid(equation):
# If the equation is a Reaction object, it must have non-zero
# number of compounds.
return... | [
"def",
"convert_reaction_entry",
"(",
"self",
",",
"reaction",
")",
":",
"d",
"=",
"OrderedDict",
"(",
")",
"d",
"[",
"'id'",
"]",
"=",
"reaction",
".",
"id",
"def",
"is_equation_valid",
"(",
"equation",
")",
":",
"# If the equation is a Reaction object, it must... | 39.68 | 17.52 |
def start(self):
"""Union[Datetime, None]: Datetime when the stage started."""
if self._properties.get("startMs") is None:
return None
return _helpers._datetime_from_microseconds(
int(self._properties.get("startMs")) * 1000.0
) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_properties",
".",
"get",
"(",
"\"startMs\"",
")",
"is",
"None",
":",
"return",
"None",
"return",
"_helpers",
".",
"_datetime_from_microseconds",
"(",
"int",
"(",
"self",
".",
"_properties",
".",
... | 39.571429 | 16 |
def check_for_update(self, force=True, download=False):
""" Returns a :class:`~plexapi.base.Release` object containing release info.
Parameters:
force (bool): Force server to check for new releases
download (bool): Download if a update is available.
"""
... | [
"def",
"check_for_update",
"(",
"self",
",",
"force",
"=",
"True",
",",
"download",
"=",
"False",
")",
":",
"part",
"=",
"'/updater/check?download=%s'",
"%",
"(",
"1",
"if",
"download",
"else",
"0",
")",
"if",
"force",
":",
"self",
".",
"query",
"(",
"... | 42.615385 | 17.769231 |
def cmd_param(self, args):
'''control parameters'''
self.pstate.handle_command(self.master, self.mpstate, args) | [
"def",
"cmd_param",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"pstate",
".",
"handle_command",
"(",
"self",
".",
"master",
",",
"self",
".",
"mpstate",
",",
"args",
")"
] | 41.666667 | 16.333333 |
def unpack(self, buff, offset=0):
"""Unpack *buff* into this object.
Do nothing, since the _length is already defined and it is just a Pad.
Keep buff and offset just for compability with other unpack methods.
Args:
buff (bytes): Binary buffer.
offset (int): Wher... | [
"def",
"unpack",
"(",
"self",
",",
"buff",
",",
"offset",
"=",
"0",
")",
":",
"super",
"(",
")",
".",
"unpack",
"(",
"buff",
",",
"offset",
")",
"self",
".",
"wildcards",
"=",
"UBInt32",
"(",
"value",
"=",
"FlowWildCards",
".",
"OFPFW_ALL",
",",
"e... | 34.555556 | 20.833333 |
def get_forecast(self):
'''
If configured to do so, make an API request to retrieve the forecast
data for the configured/queried weather station, and return the low and
high temperatures. Otherwise, return two empty strings.
'''
no_data = ('', '')
if self.forecast... | [
"def",
"get_forecast",
"(",
"self",
")",
":",
"no_data",
"=",
"(",
"''",
",",
"''",
")",
"if",
"self",
".",
"forecast",
":",
"query_url",
"=",
"STATION_QUERY_URL",
"%",
"(",
"self",
".",
"api_key",
",",
"'forecast'",
",",
"self",
".",
"station_id",
")"... | 44.615385 | 22.076923 |
def write(self, filename, encoding='utf-8'):
"""Write the list of entries to a file.
:param filename:
:param encoding:
:return:
"""
with io.open(str(filename), 'w', encoding=encoding) as fp:
for entry in self:
fp.write(entry.__unicode__())
... | [
"def",
"write",
"(",
"self",
",",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"with",
"io",
".",
"open",
"(",
"str",
"(",
"filename",
")",
",",
"'w'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"fp",
":",
"for",
"entry",
"in",
"self",
... | 30.818182 | 13.545455 |
def min_eta_for_em_bright(bh_spin_z, ns_g_mass, mNS_pts, sBH_pts, eta_mins):
"""
Function that uses the end product of generate_em_constraint_data
to swipe over a set of NS-BH binaries and determine the minimum
symmetric mass ratio required by each binary to yield a remnant
disk mass that exceeds a ... | [
"def",
"min_eta_for_em_bright",
"(",
"bh_spin_z",
",",
"ns_g_mass",
",",
"mNS_pts",
",",
"sBH_pts",
",",
"eta_mins",
")",
":",
"f",
"=",
"scipy",
".",
"interpolate",
".",
"RectBivariateSpline",
"(",
"mNS_pts",
",",
"sBH_pts",
",",
"eta_mins",
",",
"kx",
"=",... | 43.24 | 22.52 |
def integrate_ivp(u0=1.0, v0=0.0, mu=1.0, tend=10.0, dt0=1e-8, nt=0,
nsteps=600, t0=0.0, atol=1e-8, rtol=1e-8, plot=False,
savefig='None', method='bdf', dpi=100, verbose=False):
"""
Example program integrating an IVP problem of van der Pol oscillator
"""
f, j = get_f_... | [
"def",
"integrate_ivp",
"(",
"u0",
"=",
"1.0",
",",
"v0",
"=",
"0.0",
",",
"mu",
"=",
"1.0",
",",
"tend",
"=",
"10.0",
",",
"dt0",
"=",
"1e-8",
",",
"nt",
"=",
"0",
",",
"nsteps",
"=",
"600",
",",
"t0",
"=",
"0.0",
",",
"atol",
"=",
"1e-8",
... | 39 | 17.153846 |
def disconnect(self):
"""
Disconnects from Telegram.
If the event loop is already running, this method returns a
coroutine that you should await on your own code; otherwise
the loop is ran until said coroutine completes.
"""
if self._loop.is_running():
... | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_loop",
".",
"is_running",
"(",
")",
":",
"return",
"self",
".",
"_disconnect_coro",
"(",
")",
"else",
":",
"self",
".",
"_loop",
".",
"run_until_complete",
"(",
"self",
".",
"_disconnect_co... | 35.166667 | 16.166667 |
def _cursor_position_changed(self):
""" Updates the tip based on user cursor movement.
"""
cursor = self._text_edit.textCursor()
if cursor.position() <= self._start_position:
self.hide()
else:
position, commas = self._find_parenthesis(self._start_position ... | [
"def",
"_cursor_position_changed",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"_text_edit",
".",
"textCursor",
"(",
")",
"if",
"cursor",
".",
"position",
"(",
")",
"<=",
"self",
".",
"_start_position",
":",
"self",
".",
"hide",
"(",
")",
"else",
... | 37.4 | 12.9 |
def del_widget(self, ref):
""" Delete/Remove A Widget """
self.server.request("widget_del %s %s" % (self.name, ref))
del(self.widgets[ref]) | [
"def",
"del_widget",
"(",
"self",
",",
"ref",
")",
":",
"self",
".",
"server",
".",
"request",
"(",
"\"widget_del %s %s\"",
"%",
"(",
"self",
".",
"name",
",",
"ref",
")",
")",
"del",
"(",
"self",
".",
"widgets",
"[",
"ref",
"]",
")"
] | 40 | 12.5 |
def _as_array(self, fmt):
'''Unpack the raw bytes of this param using the given data format.'''
assert self.dimensions, \
'{}: cannot get value as {} array!'.format(self.name, fmt)
elems = array.array(fmt)
elems.fromstring(self.bytes)
return np.array(elems).reshape(se... | [
"def",
"_as_array",
"(",
"self",
",",
"fmt",
")",
":",
"assert",
"self",
".",
"dimensions",
",",
"'{}: cannot get value as {} array!'",
".",
"format",
"(",
"self",
".",
"name",
",",
"fmt",
")",
"elems",
"=",
"array",
".",
"array",
"(",
"fmt",
")",
"elems... | 46.857143 | 16.571429 |
def initialize():
"""Initialize all the uninitialized variables in the global scope."""
new_variables = set(tf.global_variables()) - ALREADY_INITIALIZED
get_session().run(tf.variables_initializer(new_variables))
ALREADY_INITIALIZED.update(new_variables) | [
"def",
"initialize",
"(",
")",
":",
"new_variables",
"=",
"set",
"(",
"tf",
".",
"global_variables",
"(",
")",
")",
"-",
"ALREADY_INITIALIZED",
"get_session",
"(",
")",
".",
"run",
"(",
"tf",
".",
"variables_initializer",
"(",
"new_variables",
")",
")",
"A... | 53 | 15.6 |
def draw_graph(self):
"""
The central logic for drawing the graph.
Sets self.graph (the 'g' element in the SVG root)
"""
transform = 'translate (%s %s)' % (self.border_left, self.border_top)
self.graph = etree.SubElement(self.root, 'g', transform=transform)
etree.SubElement(self.graph, 'rect', {
'x':... | [
"def",
"draw_graph",
"(",
"self",
")",
":",
"transform",
"=",
"'translate (%s %s)'",
"%",
"(",
"self",
".",
"border_left",
",",
"self",
".",
"border_top",
")",
"self",
".",
"graph",
"=",
"etree",
".",
"SubElement",
"(",
"self",
".",
"root",
",",
"'g'",
... | 23.903226 | 19.83871 |
def get_season(self, season_key, card_type="micro_card"):
"""
Calling Season API.
Arg:
season_key: key of the season
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card
Return:
json data
"""
... | [
"def",
"get_season",
"(",
"self",
",",
"season_key",
",",
"card_type",
"=",
"\"micro_card\"",
")",
":",
"season_url",
"=",
"self",
".",
"api_path",
"+",
"\"season/\"",
"+",
"season_key",
"+",
"\"/\"",
"params",
"=",
"{",
"}",
"params",
"[",
"\"card_type\"",
... | 29.823529 | 17.705882 |
def spawn(self, context=None):
"""
context may be a callable or a dict.
"""
if context is None:
context = self.default_context
if isinstance(context, collections.Callable):
context = context()
if not isinstance(context, collections.Mapping):
... | [
"def",
"spawn",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"self",
".",
"default_context",
"if",
"isinstance",
"(",
"context",
",",
"collections",
".",
"Callable",
")",
":",
"context",
"=",
"... | 31.642857 | 17.5 |
def set_resize_parameters(
self,
degrad=6,
labels=None,
resize_mm=None,
resize_voxel_number=None,
):
"""
set_input_data() should be called before
:param degrad:
:param labels:
:param resize_mm:
:param resize... | [
"def",
"set_resize_parameters",
"(",
"self",
",",
"degrad",
"=",
"6",
",",
"labels",
"=",
"None",
",",
"resize_mm",
"=",
"None",
",",
"resize_voxel_number",
"=",
"None",
",",
")",
":",
"# from . import show_segmentation",
"logger",
".",
"debug",
"(",
"\"set_re... | 33.045455 | 17.272727 |
def run(
self,
*, # Force keyword args.
program: Union[circuits.Circuit, Schedule],
job_config: Optional[JobConfig] = None,
param_resolver: ParamResolver = ParamResolver({}),
repetitions: int = 1,
priority: int = 50,
proces... | [
"def",
"run",
"(",
"self",
",",
"*",
",",
"# Force keyword args.",
"program",
":",
"Union",
"[",
"circuits",
".",
"Circuit",
",",
"Schedule",
"]",
",",
"job_config",
":",
"Optional",
"[",
"JobConfig",
"]",
"=",
"None",
",",
"param_resolver",
":",
"ParamRes... | 42.833333 | 17.866667 |
def from_dict(cls, d):
"""
Create from dict.
Args:
A dict with all data for a band structure object.
Returns:
A BandStructure object
"""
labels_dict = d['labels_dict']
projections = {}
structure = None
if isinstance(list(d... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"labels_dict",
"=",
"d",
"[",
"'labels_dict'",
"]",
"projections",
"=",
"{",
"}",
"structure",
"=",
"None",
"if",
"isinstance",
"(",
"list",
"(",
"d",
"[",
"'bands'",
"]",
".",
"values",
"(",
")",
... | 34.821429 | 18.75 |
def _current_color(self, which=0):
"""Returns a color for the queue.
Parameters
----------
which : int (optional, default: ``0``)
Specifies the type of color to return.
Returns
-------
color : list
Returns a RGBA color that is represented... | [
"def",
"_current_color",
"(",
"self",
",",
"which",
"=",
"0",
")",
":",
"if",
"which",
"==",
"1",
":",
"color",
"=",
"self",
".",
"colors",
"[",
"'edge_loop_color'",
"]",
"elif",
"which",
"==",
"2",
":",
"color",
"=",
"self",
".",
"colors",
"[",
"'... | 38.729167 | 21.520833 |
def run_muse_sump_perchrom(job, muse_output, univ_options, muse_options, chrom):
"""
Run MuSE sump on the MuSE call generated vcf.
:param toil.fileStore.FileID muse_output: vcf generated by MuSE call
:param dict univ_options: Dict of universal options used by almost all tools
:param dict muse_optio... | [
"def",
"run_muse_sump_perchrom",
"(",
"job",
",",
"muse_output",
",",
"univ_options",
",",
"muse_options",
",",
"chrom",
")",
":",
"work_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"input_files",
"=",
"{",
"'MuSE.txt'",
":",
"muse_output",
",",
"'dbsnp_coding.vc... | 46 | 22.421053 |
def async_comp_check(self, original, loc, tokens):
"""Check for Python 3.6 async comprehension."""
return self.check_py("36", "async comprehension", original, loc, tokens) | [
"def",
"async_comp_check",
"(",
"self",
",",
"original",
",",
"loc",
",",
"tokens",
")",
":",
"return",
"self",
".",
"check_py",
"(",
"\"36\"",
",",
"\"async comprehension\"",
",",
"original",
",",
"loc",
",",
"tokens",
")"
] | 61.666667 | 16.666667 |
def smart_search_pool(self, auth, query_str, search_options=None, extra_query=None):
""" Perform a smart search on pool list.
* `auth` [BaseAuth]
AAA options.
* `query_str` [string]
Search string
* `search_options` [options_dict]
... | [
"def",
"smart_search_pool",
"(",
"self",
",",
"auth",
",",
"query_str",
",",
"search_options",
"=",
"None",
",",
"extra_query",
"=",
"None",
")",
":",
"if",
"search_options",
"is",
"None",
":",
"search_options",
"=",
"{",
"}",
"self",
".",
"_logger",
".",
... | 39.357143 | 23.771429 |
def get_seed(self):
"""
Collects the required information to generate a data estructure
that can be used to recreate exactly the same geometry object
via *\*\*kwargs*.
:returns: Object's sufficient info to initialize it.
:rtype: dict
..... | [
"def",
"get_seed",
"(",
"self",
")",
":",
"self",
".",
"seed",
"=",
"{",
"'places'",
":",
"[",
"place",
".",
"get_seed",
"(",
")",
"for",
"place",
"in",
"self",
"]",
"}",
"return",
"self",
".",
"seed"
] | 29.15 | 19.35 |
def attach_file(self, path, mimetype=None):
"""Attache a file from the filesystem."""
filename = os.path.basename(path)
content = open(path, "rb").read()
self.attach(filename, content, mimetype) | [
"def",
"attach_file",
"(",
"self",
",",
"path",
",",
"mimetype",
"=",
"None",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"content",
"=",
"open",
"(",
"path",
",",
"\"rb\"",
")",
".",
"read",
"(",
")",
"self",
... | 45.2 | 3.2 |
def chung_dense(T, MW, Tc, Vc, omega, Cvm, Vm, mu, dipole, association=0):
r'''Estimates the thermal conductivity of a gas at high pressure as a
function of temperature using the reference fluid method of
Chung [1]_ as shown in [2]_.
.. math::
\lambda = \frac{31.2 \eta^\circ \Psi}{M'}(G_2^{-1} ... | [
"def",
"chung_dense",
"(",
"T",
",",
"MW",
",",
"Tc",
",",
"Vc",
",",
"omega",
",",
"Cvm",
",",
"Vm",
",",
"mu",
",",
"dipole",
",",
"association",
"=",
"0",
")",
":",
"ais",
"=",
"[",
"2.4166E+0",
",",
"-",
"5.0924E-1",
",",
"6.6107E+0",
",",
... | 35.111111 | 27.518519 |
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as in... | [
"def",
"__load_project_from_file_path",
"(",
"file_path",
")",
":",
"try",
":",
"project",
"=",
"get_project",
"(",
"project_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"file_path",
")",
",",
"config_path",
"=",
"[",
"os",
".",
"path",
".",
"basenam... | 28.230769 | 23.153846 |
def get_public_domain_metadata(self):
"""Gets the metadata for the public domain flag.
return: (osid.Metadata) - metadata for the public domain
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.get_group_m... | [
"def",
"get_public_domain_metadata",
"(",
"self",
")",
":",
"# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template",
"metadata",
"=",
"dict",
"(",
"self",
".",
"_mdata",
"[",
"'public_domain'",
"]",
")",
"metadata",
".",
"update",
"(",
"{"... | 45.363636 | 22.545455 |
def fit_freq_min_max(self, training_signal):
"""Defines a spectral mask based on training data using min and max values of each
frequency component
Args:
training_signal: Training data
"""
window_length = len(self.window)
window_weight = sum(... | [
"def",
"fit_freq_min_max",
"(",
"self",
",",
"training_signal",
")",
":",
"window_length",
"=",
"len",
"(",
"self",
".",
"window",
")",
"window_weight",
"=",
"sum",
"(",
"self",
".",
"window",
")",
"max_mask",
"=",
"np",
".",
"zeros",
"(",
"int",
"(",
... | 37.681818 | 17.363636 |
def process_iter():
"""Return a generator yielding a Process class instance for all
running processes on the local machine.
Every new Process instance is only created once and then cached
into an internal table which is updated every time this is used.
The sorting order in which processes are yiel... | [
"def",
"process_iter",
"(",
")",
":",
"def",
"add",
"(",
"pid",
")",
":",
"proc",
"=",
"Process",
"(",
"pid",
")",
"_pmap",
"[",
"proc",
".",
"pid",
"]",
"=",
"proc",
"return",
"proc",
"def",
"remove",
"(",
"pid",
")",
":",
"_pmap",
".",
"pop",
... | 32.25 | 19.886364 |
def main(args):
"""
%prog newicktree
Plot Newick formatted tree. The gene structure can be plotted along if
--gffdir is given. The gff file needs to be `genename.gff`. If --sizes is
on, also show the number of amino acids.
With --barcode a mapping file can be provided to convert seq names to
... | [
"def",
"main",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"main",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--outgroup\"",
",",
"help",
"=",
"\"Outgroup for rerooting the tree. \"",
"+",
"\"Use comma to separate multiple taxa.\"",
")",
"p",
... | 40.647059 | 21.564706 |
def before_request():
"""Checks to ensure that the session is valid and validates the users CSRF token is present
Returns:
`None`
"""
if not request.path.startswith('/saml') and not request.path.startswith('/auth'):
# Validate the session has the items we need
if 'accounts' not ... | [
"def",
"before_request",
"(",
")",
":",
"if",
"not",
"request",
".",
"path",
".",
"startswith",
"(",
"'/saml'",
")",
"and",
"not",
"request",
".",
"path",
".",
"startswith",
"(",
"'/auth'",
")",
":",
"# Validate the session has the items we need",
"if",
"'acco... | 49.722222 | 27.388889 |
def add_labels(self, objects, count=1):
"""Add multiple labels to the sheet.
Parameters
----------
objects: iterable
An iterable of the objects to add. Each of these will be passed to
the add_label method. Note that if this is a generator it will be
c... | [
"def",
"add_labels",
"(",
"self",
",",
"objects",
",",
"count",
"=",
"1",
")",
":",
"# If we can convert it to an int, do so and use the itertools.repeat()",
"# method to create an infinite iterator from it. Otherwise, assume it",
"# is an iterable or sequence.",
"try",
":",
"count... | 41.28 | 24.14 |
def setKeySequenceCounter(self, iKeySequenceValue):
""" set the Key sequence counter corresponding to Thread Network master key
Args:
iKeySequenceValue: key sequence value
Returns:
True: successful to set the key sequence
False: fail to set the key sequence
... | [
"def",
"setKeySequenceCounter",
"(",
"self",
",",
"iKeySequenceValue",
")",
":",
"print",
"'%s call setKeySequenceCounter'",
"%",
"self",
".",
"port",
"print",
"iKeySequenceValue",
"try",
":",
"cmd",
"=",
"WPANCTL_CMD",
"+",
"'setprop Network:KeyIndex %s'",
"%",
"str"... | 37.047619 | 19.142857 |
def unset_values(self):
"""
Resets the user values of all symbols, as if Kconfig.load_config() or
Symbol.set_value() had never been called.
"""
self._warn_for_no_prompt = False
try:
# set_value() already rejects undefined symbols, and they don't
# ... | [
"def",
"unset_values",
"(",
"self",
")",
":",
"self",
".",
"_warn_for_no_prompt",
"=",
"False",
"try",
":",
"# set_value() already rejects undefined symbols, and they don't",
"# need to be invalidated (because their value never changes), so we",
"# can just iterate over defined symbols... | 38.235294 | 15.764706 |
def loop_through_agency(self):
"""Loop through an agency to grab the definitions for its tables."""
agency = self.agency
with open(agency + '.txt') as f:
data = eval(f.read())
for table in data:
for column in data[table]:
value_link = data[table][c... | [
"def",
"loop_through_agency",
"(",
"self",
")",
":",
"agency",
"=",
"self",
".",
"agency",
"with",
"open",
"(",
"agency",
"+",
"'.txt'",
")",
"as",
"f",
":",
"data",
"=",
"eval",
"(",
"f",
".",
"read",
"(",
")",
")",
"for",
"table",
"in",
"data",
... | 41.916667 | 9.583333 |
def reset_mysql(self):
"""
Resets the MySQL database.
"""
confirm = self.no_confirm
print("""
Cleanup MySQL database:
This will truncate all tables and reset the whole database.
""")
if not confirm:
confirm = 'yes' in builtins.input(
"""... | [
"def",
"reset_mysql",
"(",
"self",
")",
":",
"confirm",
"=",
"self",
".",
"no_confirm",
"print",
"(",
"\"\"\"\nCleanup MySQL database:\n This will truncate all tables and reset the whole database.\n\"\"\"",
")",
"if",
"not",
"confirm",
":",
"confirm",
"=",
"'yes'",
"in... | 34.794872 | 19.538462 |
def unassign_authorization_from_vault(self, authorization_id, vault_id):
"""Removes an ``Authorization`` from a ``Vault``.
arg: authorization_id (osid.id.Id): the ``Id`` of the
``Authorization``
arg: vault_id (osid.id.Id): the ``Id`` of the ``Vault``
raise: NotFou... | [
"def",
"unassign_authorization_from_vault",
"(",
"self",
",",
"authorization_id",
",",
"vault_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinAssignmentSession.unassign_resource_from_bin",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'AUTH... | 51.272727 | 22.363636 |
def get_data(datastore, path):
'''
Get the configuration of the device tree at the given path
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the val... | [
"def",
"get_data",
"(",
"datastore",
",",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"six",
".",
"string_types",
")",
":",
"path",
"=",
"'/'",
".",
"split",
"(",
"path",
")",
"return",
"_proxy_cmd",
"(",
"'get_data'",
",",
"datastore",
","... | 32 | 21.272727 |
def start_time(self):
"""The start time of this experiment."""
t = self.redis.hget('experiment_start_times', self.name)
if t:
return datetime.strptime(t, '%Y-%m-%dT%H:%M:%S') | [
"def",
"start_time",
"(",
"self",
")",
":",
"t",
"=",
"self",
".",
"redis",
".",
"hget",
"(",
"'experiment_start_times'",
",",
"self",
".",
"name",
")",
"if",
"t",
":",
"return",
"datetime",
".",
"strptime",
"(",
"t",
",",
"'%Y-%m-%dT%H:%M:%S'",
")"
] | 41.2 | 18 |
def pusher_connected(self, data):
"""Called when the pusherclient is connected
"""
# Inform user that pusher is done connecting
self.logger.info("Pusherclient connected")
# Bind the events we want to listen to
self.callback_client.bind("payment_authorized",
... | [
"def",
"pusher_connected",
"(",
"self",
",",
"data",
")",
":",
"# Inform user that pusher is done connecting",
"self",
".",
"logger",
".",
"info",
"(",
"\"Pusherclient connected\"",
")",
"# Bind the events we want to listen to",
"self",
".",
"callback_client",
".",
"bind"... | 42.545455 | 12.636364 |
async def declareWorkerType(self, *args, **kwargs):
"""
Update a worker-type
Declare a workerType, supplying some details about it.
`declareWorkerType` allows updating one or more properties of a worker-type as long as the required scopes are
possessed. For example, a request t... | [
"async",
"def",
"declareWorkerType",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"declareWorkerType\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kw... | 45.263158 | 34.947368 |
def get_config_applied_machine_groups(self, project_name, config_name):
""" get machine group names where the logtail config applies to
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type config_name:... | [
"def",
"get_config_applied_machine_groups",
"(",
"self",
",",
"project_name",
",",
"config_name",
")",
":",
"headers",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"resource",
"=",
"\"/configs/\"",
"+",
"config_name",
"+",
"\"/machinegroups\"",
"(",
"resp",
",",
"h... | 37.75 | 22.35 |
def cnfwAlpha(self, R, Rs, rho0, r_core, ax_x, ax_y):
"""
deflection angel of NFW profile along the projection to coordinate axis
:param R: radius of interest
:type R: float/numpy array
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization (c... | [
"def",
"cnfwAlpha",
"(",
"self",
",",
"R",
",",
"Rs",
",",
"rho0",
",",
"r_core",
",",
"ax_x",
",",
"ax_y",
")",
":",
"if",
"isinstance",
"(",
"R",
",",
"int",
")",
"or",
"isinstance",
"(",
"R",
",",
"float",
")",
":",
"R",
"=",
"max",
"(",
"... | 31.25 | 15.535714 |
def _push_property_schema(self, prop):
"""Construct a sub-schema from a property of the current schema."""
schema = Schema(self._schema.properties[prop])
self._push_schema(schema, ".properties." + prop) | [
"def",
"_push_property_schema",
"(",
"self",
",",
"prop",
")",
":",
"schema",
"=",
"Schema",
"(",
"self",
".",
"_schema",
".",
"properties",
"[",
"prop",
"]",
")",
"self",
".",
"_push_schema",
"(",
"schema",
",",
"\".properties.\"",
"+",
"prop",
")"
] | 55.75 | 8 |
def send(self, data):
"""
Send text to the client.
"""
assert isinstance(data, text_type)
# When data is send back to the client, we should replace the line
# endings. (We didn't allocate a real pseudo terminal, and the telnet
# connection is raw, so we are respo... | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"text_type",
")",
"# When data is send back to the client, we should replace the line",
"# endings. (We didn't allocate a real pseudo terminal, and the telnet",
"# connection is raw, so we ... | 37.909091 | 17.727273 |
def lookupmodule(name):
"""lookupmodule()->(module, file) translates a possibly incomplete
file or module name into an absolute file name. None can be
returned for either of the values positions of module or file when
no or module or file is found.
"""
if sys.modules.get(name):
return (s... | [
"def",
"lookupmodule",
"(",
"name",
")",
":",
"if",
"sys",
".",
"modules",
".",
"get",
"(",
"name",
")",
":",
"return",
"(",
"sys",
".",
"modules",
"[",
"name",
"]",
",",
"sys",
".",
"modules",
"[",
"name",
"]",
".",
"__file__",
")",
"if",
"os",
... | 33.25 | 13 |
def do_fileplaceholder(parser, token):
"""
Method that parse the fileplaceholder template tag.
"""
name, params = parse_placeholder(parser, token)
return FilePlaceholderNode(name, **params) | [
"def",
"do_fileplaceholder",
"(",
"parser",
",",
"token",
")",
":",
"name",
",",
"params",
"=",
"parse_placeholder",
"(",
"parser",
",",
"token",
")",
"return",
"FilePlaceholderNode",
"(",
"name",
",",
"*",
"*",
"params",
")"
] | 34 | 5.666667 |
def Run(self, unused_arg):
"""Run the kill."""
# Send a message back to the service to say that we are about to shutdown.
reply = rdf_flows.GrrStatus(status=rdf_flows.GrrStatus.ReturnedStatus.OK)
# Queue up the response message, jump the queue.
self.SendReply(reply, message_type=rdf_flows.GrrMessage... | [
"def",
"Run",
"(",
"self",
",",
"unused_arg",
")",
":",
"# Send a message back to the service to say that we are about to shutdown.",
"reply",
"=",
"rdf_flows",
".",
"GrrStatus",
"(",
"status",
"=",
"rdf_flows",
".",
"GrrStatus",
".",
"ReturnedStatus",
".",
"OK",
")",... | 37.384615 | 21.923077 |
def import_code(mod_code, mod_name):
"""Create a module object by code.
@param mod_code: the code that the module contains.
@param mod_name: module name.
"""
mod_obj = imp.new_module(mod_name)
mod_obj.__file__ = None
exec_(mod_code, mod_obj.__dict__, mod_obj.__dict__)
add_to_sys_modu... | [
"def",
"import_code",
"(",
"mod_code",
",",
"mod_name",
")",
":",
"mod_obj",
"=",
"imp",
".",
"new_module",
"(",
"mod_name",
")",
"mod_obj",
".",
"__file__",
"=",
"None",
"exec_",
"(",
"mod_code",
",",
"mod_obj",
".",
"__dict__",
",",
"mod_obj",
".",
"__... | 24.333333 | 19.733333 |
def convert(kml_path, output_dir, separate_folders=False,
style_type=None, style_filename='style.json'):
"""
Given a path to a KML file, convert it to one or several GeoJSON FeatureCollection files and save the result(s) to the given output directory.
If not ``separate_folders`` (the default), then creat... | [
"def",
"convert",
"(",
"kml_path",
",",
"output_dir",
",",
"separate_folders",
"=",
"False",
",",
"style_type",
"=",
"None",
",",
"style_filename",
"=",
"'style.json'",
")",
":",
"# Create absolute paths",
"kml_path",
"=",
"Path",
"(",
"kml_path",
")",
".",
"r... | 40.509804 | 22.784314 |
def accounts(self):
"""
Access the Accounts Twilio Domain
:returns: Accounts Twilio Domain
:rtype: twilio.rest.accounts.Accounts
"""
if self._accounts is None:
from twilio.rest.accounts import Accounts
self._accounts = Accounts(self)
retur... | [
"def",
"accounts",
"(",
"self",
")",
":",
"if",
"self",
".",
"_accounts",
"is",
"None",
":",
"from",
"twilio",
".",
"rest",
".",
"accounts",
"import",
"Accounts",
"self",
".",
"_accounts",
"=",
"Accounts",
"(",
"self",
")",
"return",
"self",
".",
"_acc... | 29.636364 | 9.090909 |
def fasta(self):
"""Generates sequence data for the protein in FASTA format."""
max_line_length = 79
fasta_str = '>{0}:{1}|PDBID|CHAIN|SEQUENCE\n'.format(
self.parent.id.upper(), self.id)
seq = self.sequence
split_seq = [seq[i: i + max_line_length]
... | [
"def",
"fasta",
"(",
"self",
")",
":",
"max_line_length",
"=",
"79",
"fasta_str",
"=",
"'>{0}:{1}|PDBID|CHAIN|SEQUENCE\\n'",
".",
"format",
"(",
"self",
".",
"parent",
".",
"id",
".",
"upper",
"(",
")",
",",
"self",
".",
"id",
")",
"seq",
"=",
"self",
... | 42.454545 | 12.636364 |
def remove_extension(self, ext=None):
""" Remove extension from IOSystem
For single Extensions the same can be achieved with del
IOSystem_name.Extension_name
Parameters
----------
ext : string or list, optional
The extension to remove, this can be given as t... | [
"def",
"remove_extension",
"(",
"self",
",",
"ext",
"=",
"None",
")",
":",
"if",
"ext",
"is",
"None",
":",
"ext",
"=",
"list",
"(",
"self",
".",
"get_extensions",
"(",
")",
")",
"if",
"type",
"(",
"ext",
")",
"is",
"str",
":",
"ext",
"=",
"[",
... | 34.4375 | 18.15625 |
def show_clusters(clusters, sample, covariances, means, figure = None, display = True):
"""!
@brief Draws clusters and in case of two-dimensional dataset draws their ellipses.
@param[in] clusters (list): Clusters that were allocated by the algorithm.
@param[in] sample (list... | [
"def",
"show_clusters",
"(",
"clusters",
",",
"sample",
",",
"covariances",
",",
"means",
",",
"figure",
"=",
"None",
",",
"display",
"=",
"True",
")",
":",
"visualizer",
"=",
"cluster_visualizer",
"(",
")",
"visualizer",
".",
"append_clusters",
"(",
"cluste... | 43.21875 | 27.4375 |
def flags(self, index):
"""
Reimplements the :meth:`QAbstractItemModel.flags` method.
:param index: Index.
:type index: QModelIndex
:return: Flags. ( Qt.ItemFlags )
"""
if not index.isValid():
return Qt.NoItemFlags
node = self.get_node(index... | [
"def",
"flags",
"(",
"self",
",",
"index",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"Qt",
".",
"NoItemFlags",
"node",
"=",
"self",
".",
"get_node",
"(",
"index",
")",
"if",
"index",
".",
"column",
"(",
")",
"==",
"... | 34.277778 | 21.277778 |
def maintained_selection():
"""Maintain selection during context
Example:
>>> with maintained_selection():
... # Modify selection
... node.setSelected(on=False, clear_all_selected=True)
>>> # Selection restored
"""
previous_selection = hou.selectedNodes()
t... | [
"def",
"maintained_selection",
"(",
")",
":",
"previous_selection",
"=",
"hou",
".",
"selectedNodes",
"(",
")",
"try",
":",
"yield",
"finally",
":",
"if",
"previous_selection",
":",
"for",
"node",
"in",
"previous_selection",
":",
"node",
".",
"setSelected",
"(... | 26.095238 | 16.142857 |
def num_or_str(x):
"""The argument is a string; convert to a number if possible, or strip it.
>>> num_or_str('42')
42
>>> num_or_str(' 42x ')
'42x'
"""
if isnumber(x): return x
try:
return int(x)
except ValueError:
try:
return float(x)
except Value... | [
"def",
"num_or_str",
"(",
"x",
")",
":",
"if",
"isnumber",
"(",
"x",
")",
":",
"return",
"x",
"try",
":",
"return",
"int",
"(",
"x",
")",
"except",
"ValueError",
":",
"try",
":",
"return",
"float",
"(",
"x",
")",
"except",
"ValueError",
":",
"retur... | 23.066667 | 17.266667 |
def value(self):
"""
The current value of the field. If no value is set when this attribute
is accessed for reading, the :meth:`default` of the field is invoked
and the result is set and returned as value.
Only values contained in the :attr:`~.BoundOptionsField.options` can be
... | [
"def",
"value",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_value",
"except",
"AttributeError",
":",
"self",
".",
"_value",
"=",
"self",
".",
"field",
".",
"default",
"(",
")",
"return",
"self",
".",
"_value"
] | 40.4375 | 21.1875 |
def column_map_expectation(cls, func):
"""For SqlAlchemy, this decorator allows individual column_map_expectations to simply return the filter
that describes the expected condition on their data.
The decorator will then use that filter to obtain unexpected elements, relevant counts, and return ... | [
"def",
"column_map_expectation",
"(",
"cls",
",",
"func",
")",
":",
"if",
"PY3",
":",
"argspec",
"=",
"inspect",
".",
"getfullargspec",
"(",
"func",
")",
"[",
"0",
"]",
"[",
"1",
":",
"]",
"else",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(... | 48.068702 | 25.305344 |
def handle_stderr(stderr_pipe):
"""
Takes stderr from the command's output and displays it AFTER the stdout
is printed by run_command().
"""
stderr_output = stderr_pipe.read()
if len(stderr_output) > 0:
click.secho("\n__ Error Output {0}".format('_'*62), fg='white',
... | [
"def",
"handle_stderr",
"(",
"stderr_pipe",
")",
":",
"stderr_output",
"=",
"stderr_pipe",
".",
"read",
"(",
")",
"if",
"len",
"(",
"stderr_output",
")",
">",
"0",
":",
"click",
".",
"secho",
"(",
"\"\\n__ Error Output {0}\"",
".",
"format",
"(",
"'_'",
"*... | 28.384615 | 16.692308 |
def get_events_with_error_code(event_number, event_status, select_mask=0b1111111111111111, condition=0b0000000000000000):
'''Selects the events with a certain error code.
Parameters
----------
event_number : numpy.array
event_status : numpy.array
select_mask : int
The mask that selects ... | [
"def",
"get_events_with_error_code",
"(",
"event_number",
",",
"event_status",
",",
"select_mask",
"=",
"0b1111111111111111",
",",
"condition",
"=",
"0b0000000000000000",
")",
":",
"logging",
".",
"debug",
"(",
"\"Calculate events with certain error code\"",
")",
"return"... | 31.631579 | 28.263158 |
def get_content_models(self):
""" Return all subclasses that are admin registered. """
models = []
for model in self.concrete_model.get_content_models():
try:
admin_url(model, "add")
except NoReverseMatch:
continue
else:
... | [
"def",
"get_content_models",
"(",
"self",
")",
":",
"models",
"=",
"[",
"]",
"for",
"model",
"in",
"self",
".",
"concrete_model",
".",
"get_content_models",
"(",
")",
":",
"try",
":",
"admin_url",
"(",
"model",
",",
"\"add\"",
")",
"except",
"NoReverseMatc... | 33.6 | 19.333333 |
def parse_meta(self, selected_meta_data):
"""
Parses all of the metadata files
:param selected_meta_data: if specified then only the columns that are contained here are going to be parsed
:return:
"""
# reads all meta data files
files = self._get_files("meta", sel... | [
"def",
"parse_meta",
"(",
"self",
",",
"selected_meta_data",
")",
":",
"# reads all meta data files",
"files",
"=",
"self",
".",
"_get_files",
"(",
"\"meta\"",
",",
"self",
".",
"path",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"print",
"(",
"\"Par... | 37.833333 | 14.833333 |
def recursive_find_search(folder_path, regex=''):
"""
Returns absolute paths of files that match the regex within file_dir and
all its children folders.
Note: The regex matching is done using the search function
of the re module.
Parameters
----------
folder_path: string
regex: st... | [
"def",
"recursive_find_search",
"(",
"folder_path",
",",
"regex",
"=",
"''",
")",
":",
"outlist",
"=",
"[",
"]",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"folder_path",
")",
":",
"outlist",
".",
"extend",
"(",
"[",
"op"... | 22 | 23.36 |
def hash_(self, keys: Index, salt: int = 0) -> pd.Series:
"""Hashes the given index into an integer index in the range [0, self.stride]
Parameters
----------
keys :
The new index to hash.
salt :
An integer used to perturb the hash in a deterministic way. ... | [
"def",
"hash_",
"(",
"self",
",",
"keys",
":",
"Index",
",",
"salt",
":",
"int",
"=",
"0",
")",
"->",
"pd",
".",
"Series",
":",
"key_frame",
"=",
"keys",
".",
"to_frame",
"(",
")",
"new_map",
"=",
"pd",
".",
"Series",
"(",
"0",
",",
"index",
"=... | 41.285714 | 23.571429 |
def languages(macrolanguage):
"""
Get a list of :class:`language_tags.Subtag.Subtag` objects given the string macrolanguage.
:param string macrolanguage: subtag macrolanguage.
:return: a list of the macrolanguage :class:`language_tags.Subtag.Subtag` objects.
:raise Exception: if... | [
"def",
"languages",
"(",
"macrolanguage",
")",
":",
"results",
"=",
"[",
"]",
"macrolanguage",
"=",
"macrolanguage",
".",
"lower",
"(",
")",
"macrolanguage_data",
"=",
"data",
".",
"get",
"(",
"'macrolanguage'",
")",
"if",
"macrolanguage",
"not",
"in",
"macr... | 41.952381 | 21.571429 |
def get_object(
self, object_t, object_id=None, relation=None, parent=None, **kwargs
):
"""
Actually query the Deezer API to retrieve the object
:returns: json dictionary
"""
url = self.object_url(object_t, object_id, relation, **kwargs)
response = self.sessi... | [
"def",
"get_object",
"(",
"self",
",",
"object_t",
",",
"object_id",
"=",
"None",
",",
"relation",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"object_url",
"(",
"object_t",
",",
"object_id",
"... | 34.545455 | 19.090909 |
def fetchUserInfo(self, *user_ids):
"""
Get users' info from IDs, unordered
.. warning::
Sends two requests, to fetch all available info!
:param user_ids: One or more user ID(s) to query
:return: :class:`models.User` objects, labeled by their ID
:rtype: dict... | [
"def",
"fetchUserInfo",
"(",
"self",
",",
"*",
"user_ids",
")",
":",
"threads",
"=",
"self",
".",
"fetchThreadInfo",
"(",
"*",
"user_ids",
")",
"users",
"=",
"{",
"}",
"for",
"id_",
",",
"thread",
"in",
"threads",
".",
"items",
"(",
")",
":",
"if",
... | 32.380952 | 17.52381 |
def __get_query_basic(cls, date_field=None, start=None, end=None,
filters={}):
"""
Create a es_dsl query object with the date range and filters.
:param date_field: field with the date value
:param start: date with the from value, should be a datetime.datetime o... | [
"def",
"__get_query_basic",
"(",
"cls",
",",
"date_field",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"filters",
"=",
"{",
"}",
")",
":",
"query_basic",
"=",
"Search",
"(",
")",
"query_filters",
"=",
"cls",
".",
"__get_query_... | 44.473684 | 23.947368 |
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist...
if not self.stats:
return ret
# Max size for the interface name
name_max_widt... | [
"def",
"msg_curse",
"(",
"self",
",",
"args",
"=",
"None",
",",
"max_width",
"=",
"None",
")",
":",
"# Init the return message",
"ret",
"=",
"[",
"]",
"# Only process if stats exist...",
"if",
"not",
"self",
".",
"stats",
":",
"return",
"ret",
"# Max size for ... | 49.863014 | 19.068493 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.