text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 4)
self.set_attributes(priority, address, rtr)
self.closed = self.... | [
"def",
"populate",
"(",
"self",
",",
"priority",
",",
"address",
",",
"rtr",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"needs_low_priority",
"(",
"priority",
")",
"self",
".",
"needs_no_rtr",
"(",
"rtr",
... | 39.538462 | 10 |
def channels(self):
"""
List of channels of this slack team
"""
if not self._channels:
self._channels = self._call_api('channels.list')['channels']
return self._channels | [
"def",
"channels",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_channels",
":",
"self",
".",
"_channels",
"=",
"self",
".",
"_call_api",
"(",
"'channels.list'",
")",
"[",
"'channels'",
"]",
"return",
"self",
".",
"_channels"
] | 30.714286 | 11 |
def convert_entry_to_cid(i):
"""
Input: {
(repo_uoa) - Repo UOA
(repo_uid) - Repo UID
(module_uoa) - Module UOA
(module_uid) - Module UID
(data_uoa) - Data UOA
(data_uid) - Data UID
}
Output: {
... | [
"def",
"convert_entry_to_cid",
"(",
"i",
")",
":",
"xcuoa",
"=",
"''",
"xcid",
"=",
"''",
"if",
"i",
".",
"get",
"(",
"'module_uoa'",
",",
"''",
")",
"!=",
"''",
":",
"cuoa",
"=",
"i",
"[",
"'module_uoa'",
"]",
"else",
":",
"cuoa",
"=",
"'?'",
"i... | 26.9 | 24.14 |
def output_folder(self, value):
"""Output folder path for the rendering.
:param value: output folder path
:type value: str
"""
self._output_folder = value
if not os.path.exists(self._output_folder):
os.makedirs(self._output_folder) | [
"def",
"output_folder",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_output_folder",
"=",
"value",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_output_folder",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"_output_fol... | 31.555556 | 9.444444 |
def iteritems(self):
"""Present the email headers"""
for n,v in self.msgobj.__dict__["_headers"]:
yield n.lower(), v
return | [
"def",
"iteritems",
"(",
"self",
")",
":",
"for",
"n",
",",
"v",
"in",
"self",
".",
"msgobj",
".",
"__dict__",
"[",
"\"_headers\"",
"]",
":",
"yield",
"n",
".",
"lower",
"(",
")",
",",
"v",
"return"
] | 31 | 13.6 |
def _paint_colorbar_legend(ax, values, cmap, legend_kwargs):
"""
Creates a legend and attaches it to the axis. Meant to be used when a ``legend=True`` parameter is passed.
Parameters
----------
ax : matplotlib.Axes instance
The ``matplotlib.Axes`` instance on which a legend is being painted... | [
"def",
"_paint_colorbar_legend",
"(",
"ax",
",",
"values",
",",
"cmap",
",",
"legend_kwargs",
")",
":",
"if",
"legend_kwargs",
"is",
"None",
":",
"legend_kwargs",
"=",
"dict",
"(",
")",
"cmap",
".",
"set_array",
"(",
"values",
")",
"plt",
".",
"gcf",
"("... | 46.37037 | 31.62963 |
def commit(self, message, author, parents=None, branch=None, date=None,
**kwargs):
"""
Performs in-memory commit (doesn't check workdir in any way) and
returns newly created ``Changeset``. Updates repository's
``revisions``.
:param message: message of the commit
... | [
"def",
"commit",
"(",
"self",
",",
"message",
",",
"author",
",",
"parents",
"=",
"None",
",",
"branch",
"=",
"None",
",",
"date",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"check_integrity",
"(",
"parents",
")",
"from",
".",
"re... | 39.22549 | 18.578431 |
def extension_preselection(network, args, method, days = 3):
"""
Function that preselects lines which are extendend in snapshots leading to
overloading to reduce nubmer of extension variables.
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
... | [
"def",
"extension_preselection",
"(",
"network",
",",
"args",
",",
"method",
",",
"days",
"=",
"3",
")",
":",
"weighting",
"=",
"network",
".",
"snapshot_weightings",
"if",
"method",
"==",
"'extreme_situations'",
":",
"snapshots",
"=",
"find_snapshots",
"(",
"... | 38.834951 | 21.048544 |
def create_postgresql_pypostgresql(self, **kwargs):
"""
:rtype: Engine
"""
return self._ce(
self._ccs(self.DialectAndDriver.psql_pypostgresql), **kwargs
) | [
"def",
"create_postgresql_pypostgresql",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_ce",
"(",
"self",
".",
"_ccs",
"(",
"self",
".",
"DialectAndDriver",
".",
"psql_pypostgresql",
")",
",",
"*",
"*",
"kwargs",
")"
] | 28.571429 | 15.428571 |
def obj_or_import_string(value, default=None):
"""Import string or return object.
:params value: Import path or class object to instantiate.
:params default: Default object to return if the import fails.
:returns: The imported object.
"""
if isinstance(value, six.string_types):
return i... | [
"def",
"obj_or_import_string",
"(",
"value",
",",
"default",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"return",
"import_string",
"(",
"value",
")",
"elif",
"value",
":",
"return",
"value",
"return"... | 32 | 14.583333 |
def delete(self, service_name, *ids, **kwargs):
"""Delete an AppNexus object"""
return self._send(requests.delete, service_name, id=ids, **kwargs) | [
"def",
"delete",
"(",
"self",
",",
"service_name",
",",
"*",
"ids",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_send",
"(",
"requests",
".",
"delete",
",",
"service_name",
",",
"id",
"=",
"ids",
",",
"*",
"*",
"kwargs",
")"
] | 53.333333 | 13.666667 |
def Write(self, output_writer):
"""Writes the table to output writer.
Args:
output_writer (CLIOutputWriter): output writer.
"""
# Round up the column sizes to the nearest tab.
for column_index, column_size in enumerate(self._column_sizes):
column_size, _ = divmod(column_size, self._NUMB... | [
"def",
"Write",
"(",
"self",
",",
"output_writer",
")",
":",
"# Round up the column sizes to the nearest tab.",
"for",
"column_index",
",",
"column_size",
"in",
"enumerate",
"(",
"self",
".",
"_column_sizes",
")",
":",
"column_size",
",",
"_",
"=",
"divmod",
"(",
... | 35.882353 | 20.117647 |
def disease_term(self, disease_identifier):
"""Return a disease term
Checks if the identifier is a disease number or a id
Args:
disease_identifier(str)
Returns:
disease_obj(dict)
"""
query = {}
try:
disease_identifier = int(d... | [
"def",
"disease_term",
"(",
"self",
",",
"disease_identifier",
")",
":",
"query",
"=",
"{",
"}",
"try",
":",
"disease_identifier",
"=",
"int",
"(",
"disease_identifier",
")",
"query",
"[",
"'disease_nr'",
"]",
"=",
"disease_identifier",
"except",
"ValueError",
... | 26.684211 | 19.263158 |
def p_directive(self, p):
"""
directive : AT name arguments
| AT name
"""
arguments = p[3] if len(p) == 4 else None
p[0] = Directive(name=p[2], arguments=arguments) | [
"def",
"p_directive",
"(",
"self",
",",
"p",
")",
":",
"arguments",
"=",
"p",
"[",
"3",
"]",
"if",
"len",
"(",
"p",
")",
"==",
"4",
"else",
"None",
"p",
"[",
"0",
"]",
"=",
"Directive",
"(",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"arguments",
... | 30.857143 | 8 |
def _get_chain_by_pid(pid):
"""Find chain by pid.
Return None if not found.
"""
try:
return d1_gmn.app.models.ChainMember.objects.get(pid__did=pid).chain
except d1_gmn.app.models.ChainMember.DoesNotExist:
pass | [
"def",
"_get_chain_by_pid",
"(",
"pid",
")",
":",
"try",
":",
"return",
"d1_gmn",
".",
"app",
".",
"models",
".",
"ChainMember",
".",
"objects",
".",
"get",
"(",
"pid__did",
"=",
"pid",
")",
".",
"chain",
"except",
"d1_gmn",
".",
"app",
".",
"models",
... | 23.8 | 21.4 |
def get_requested_aosp_permissions(self):
"""
Returns requested permissions declared within AOSP project.
This includes several other permissions as well, which are in the platform apps.
:rtype: list of str
"""
aosp_permissions = []
all_permissions = self.get_pe... | [
"def",
"get_requested_aosp_permissions",
"(",
"self",
")",
":",
"aosp_permissions",
"=",
"[",
"]",
"all_permissions",
"=",
"self",
".",
"get_permissions",
"(",
")",
"for",
"perm",
"in",
"all_permissions",
":",
"if",
"perm",
"in",
"list",
"(",
"self",
".",
"p... | 35.214286 | 16.071429 |
def recv(self, timeout=None):
"""Receive a handover select message from the remote server."""
message = self._recv(timeout)
if message and message.type == "urn:nfc:wkt:Hs":
log.debug("received '{0}' message".format(message.type))
return nfc.ndef.HandoverSelectMessage(mess... | [
"def",
"recv",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"message",
"=",
"self",
".",
"_recv",
"(",
"timeout",
")",
"if",
"message",
"and",
"message",
".",
"type",
"==",
"\"urn:nfc:wkt:Hs\"",
":",
"log",
".",
"debug",
"(",
"\"received '{0}' mes... | 48.222222 | 17.666667 |
def sigmask(self, sigsetsize=None):
"""
Gets the current sigmask. If it's blank, a new one is created (of sigsetsize).
:param sigsetsize: the size (in *bytes* of the sigmask set)
:return: the sigmask
"""
if self._sigmask is None:
if sigsetsize is not None:
... | [
"def",
"sigmask",
"(",
"self",
",",
"sigsetsize",
"=",
"None",
")",
":",
"if",
"self",
".",
"_sigmask",
"is",
"None",
":",
"if",
"sigsetsize",
"is",
"not",
"None",
":",
"sc",
"=",
"self",
".",
"state",
".",
"solver",
".",
"eval",
"(",
"sigsetsize",
... | 49.533333 | 26.866667 |
def rouge_n(evaluated_sentences, reference_sentences, n=2):
"""
Computes ROUGE-N of two text collections of sentences.
Sourece: http://research.microsoft.com/en-us/um/people/cyl/download/
papers/rouge-working-note-v1.3.1.pdf
Args:
evaluated_sentences: The sentences that have been picked by th... | [
"def",
"rouge_n",
"(",
"evaluated_sentences",
",",
"reference_sentences",
",",
"n",
"=",
"2",
")",
":",
"if",
"len",
"(",
"evaluated_sentences",
")",
"<=",
"0",
"or",
"len",
"(",
"reference_sentences",
")",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Co... | 38.870968 | 22.419355 |
def request_patch(self, *args, **kwargs):
"""Maintains the existing api for Session.request.
Used by all of the higher level methods, e.g. Session.get.
The background_callback param allows you to do some processing on the
response in the background, e.g. call resp.json() so that json parsing
happens... | [
"def",
"request_patch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"sup",
"=",
"super",
"(",
"FuturesSession",
",",
"self",
")",
".",
"request",
"background_callback",
"=",
"kwargs",
".",
"pop",
"(",
"'background_callb... | 41.5 | 16 |
def get_assessment_admin_session(self):
"""Gets the ``OsidSession`` associated with the assessment administration service.
return: (osid.assessment.AssessmentAdminSession) - an
``AssessmentAdminSession``
raise: OperationFailed - unable to complete request
raise: Unimpl... | [
"def",
"get_assessment_admin_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_assessment_admin",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"AssessmentAdminSession",
... | 44.125 | 15.4375 |
def point_in_poly(p, poly):
"""Determine whether a point is within a polygon area
Uses the ray casting algorithm.
Parameters
----------
p: float
Coordinates of the point
poly: array_like of shape (N, 2)
Polygon (`PolygonFilter.points`)
R... | [
"def",
"point_in_poly",
"(",
"p",
",",
"poly",
")",
":",
"poly",
"=",
"np",
".",
"array",
"(",
"poly",
")",
"n",
"=",
"poly",
".",
"shape",
"[",
"0",
"]",
"inside",
"=",
"False",
"x",
",",
"y",
"=",
"p",
"# Coarse bounding box exclusion:",
"if",
"(... | 39.517857 | 20.482143 |
def split_sequence_as_iterable(self, values):
"""Group sequence into iterables
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
iterable of items in values
Notes
-----
... | [
"def",
"split_sequence_as_iterable",
"(",
"self",
",",
"values",
")",
":",
"print",
"(",
"self",
".",
"count",
")",
"s",
"=",
"iter",
"(",
"self",
".",
"index",
".",
"sorter",
")",
"for",
"c",
"in",
"self",
".",
"count",
":",
"yield",
"(",
"values",
... | 29.809524 | 20.428571 |
def convertToNative(self, aVal):
""" Convert to native bool; interpret certain strings. """
if aVal is None:
return None
if isinstance(aVal, bool): return aVal
# otherwise interpret strings
return str(aVal).lower() in ('1','on','yes','true') | [
"def",
"convertToNative",
"(",
"self",
",",
"aVal",
")",
":",
"if",
"aVal",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"aVal",
",",
"bool",
")",
":",
"return",
"aVal",
"# otherwise interpret strings",
"return",
"str",
"(",
"aVal",
")",
... | 41 | 9.857143 |
def put_conditional(self, cond, valiftrue, valiffalse, reg):
"""
Like put, except it checks a condition
to decide what to put in the destination register.
:param cond: The VexValue representing the logical expression for the condition
(if your expression only has constants, ... | [
"def",
"put_conditional",
"(",
"self",
",",
"cond",
",",
"valiftrue",
",",
"valiffalse",
",",
"reg",
")",
":",
"val",
"=",
"self",
".",
"irsb_c",
".",
"ite",
"(",
"cond",
".",
"rdt",
",",
"valiftrue",
".",
"rdt",
",",
"valiffalse",
".",
"rdt",
")",
... | 48.1875 | 24.6875 |
def _metatile_contents_equal(zip_1, zip_2):
"""
Given two open zip files as arguments, this returns True if the zips
both contain the same set of files, having the same names, and each
file within the zip is byte-wise identical to the one with the same
name in the other zip.
"""
names_1 = s... | [
"def",
"_metatile_contents_equal",
"(",
"zip_1",
",",
"zip_2",
")",
":",
"names_1",
"=",
"set",
"(",
"zip_1",
".",
"namelist",
"(",
")",
")",
"names_2",
"=",
"set",
"(",
"zip_2",
".",
"namelist",
"(",
")",
")",
"if",
"names_1",
"!=",
"names_2",
":",
... | 25.681818 | 20.136364 |
def get_bucket_type_props(self, bucket_type):
"""
Get properties for a bucket-type
"""
self._check_bucket_types(bucket_type)
url = self.bucket_type_properties_path(bucket_type.name)
status, headers, body = self._request('GET', url)
if status == 200:
p... | [
"def",
"get_bucket_type_props",
"(",
"self",
",",
"bucket_type",
")",
":",
"self",
".",
"_check_bucket_types",
"(",
"bucket_type",
")",
"url",
"=",
"self",
".",
"bucket_type_properties_path",
"(",
"bucket_type",
".",
"name",
")",
"status",
",",
"headers",
",",
... | 35.538462 | 13.692308 |
def ruamel_structure(data, validator=None):
"""
Take dicts and lists and return a ruamel.yaml style
structure of CommentedMaps, CommentedSeqs and
data.
If a validator is presented and the type is unknown,
it is checked against the validator to see if it will
turn it back in to YAML.
"""... | [
"def",
"ruamel_structure",
"(",
"data",
",",
"validator",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"raise",
"exceptions",
".",
"CannotBuildDocumentsFromEmptyDictOrList",
"... | 37.097561 | 18.95122 |
def get_equivalent_qpoints(self, index):
"""
Returns the list of qpoint indices equivalent (meaning they are the
same frac coords) to the given one.
Args:
index: the qpoint index
Returns:
a list of equivalent indices
TODO: now it uses the label ... | [
"def",
"get_equivalent_qpoints",
"(",
"self",
",",
"index",
")",
":",
"#if the qpoint has no label it can\"t have a repetition along the band",
"#structure line object",
"if",
"self",
".",
"qpoints",
"[",
"index",
"]",
".",
"label",
"is",
"None",
":",
"return",
"[",
"... | 30.384615 | 18.615385 |
def _parse_data(self):
"""Parses the byte array returned by the sensor.
The sensor returns 16 bytes in total. It's unclear what the meaning of these bytes
is beyond what is decoded in this method.
semantics of the data (in little endian encoding):
bytes 0-1: temperature in 0.... | [
"def",
"_parse_data",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"_cache",
"res",
"=",
"dict",
"(",
")",
"temp",
",",
"res",
"[",
"MI_LIGHT",
"]",
",",
"res",
"[",
"MI_MOISTURE",
"]",
",",
"res",
"[",
"MI_CONDUCTIVITY",
"]",
"=",
"unpack",
"(... | 35.6 | 14.95 |
def alias_event_handler(_, **kwargs):
"""
An event handler for alias transformation when EVENT_INVOKER_PRE_TRUNCATE_CMD_TBL event is invoked.
"""
try:
telemetry.start()
start_time = timeit.default_timer()
args = kwargs.get('args')
alias_manager = AliasManager(**kwargs)
... | [
"def",
"alias_event_handler",
"(",
"_",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"telemetry",
".",
"start",
"(",
")",
"start_time",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"args",
"=",
"kwargs",
".",
"get",
"(",
"'args'",
")",
"alias_manag... | 35.777778 | 22.222222 |
def applyTransformOnGroup(self, transform, group):
"""Apply an SVG transformation to a RL Group shape.
The transformation is the value of an SVG transform attribute
like transform="scale(1, -1) translate(10, 30)".
rotate(<angle> [<cx> <cy>]) is equivalent to:
translate(<cx> <... | [
"def",
"applyTransformOnGroup",
"(",
"self",
",",
"transform",
",",
"group",
")",
":",
"tr",
"=",
"self",
".",
"attrConverter",
".",
"convertTransform",
"(",
"transform",
")",
"for",
"op",
",",
"values",
"in",
"tr",
":",
"if",
"op",
"==",
"\"scale\"",
":... | 40.945946 | 13.054054 |
def add(self, other):
"""
Adds two block matrices together. The matrices must have the
same size and matching `rowsPerBlock` and `colsPerBlock` values.
If one of the sub matrix blocks that are being added is a
SparseMatrix, the resulting sub matrix block will also be a
Sp... | [
"def",
"add",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"BlockMatrix",
")",
":",
"raise",
"TypeError",
"(",
"\"Other should be a BlockMatrix, got %s\"",
"%",
"type",
"(",
"other",
")",
")",
"other_java_block_matrix",
"=... | 52 | 25.625 |
def cancel_job_button(self, description=None):
"""Display a button that will cancel the submitted job.
Used in a Jupyter IPython notebook to provide an interactive
mechanism to cancel a job submitted from the notebook.
Once clicked the button is disabled unless the cancel fails.
... | [
"def",
"cancel_job_button",
"(",
"self",
",",
"description",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'jobId'",
")",
":",
"return",
"try",
":",
"import",
"ipywidgets",
"as",
"widgets",
"if",
"not",
"description",
":",
"description"... | 36.563636 | 21.763636 |
def open_liftover_chain_file(from_db, to_db, search_dir='.', cache_dir=os.path.expanduser("~/.pyliftover"), use_web=True, write_cache=True):
'''
A "smart" way of obtaining liftover chain files.
By default acts as follows:
1. If the file ``<from_db>To<to_db>.over.chain.gz`` exists in <search_dir>,
... | [
"def",
"open_liftover_chain_file",
"(",
"from_db",
",",
"to_db",
",",
"search_dir",
"=",
"'.'",
",",
"cache_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.pyliftover\"",
")",
",",
"use_web",
"=",
"True",
",",
"write_cache",
"=",
"True",
")",
"... | 48.474576 | 22.101695 |
def with_name(self, name):
"""
Return a new path with the file name changed.
"""
obj = super(ArtifactoryPath, self).with_name(name)
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
obj.session = self.session
return obj | [
"def",
"with_name",
"(",
"self",
",",
"name",
")",
":",
"obj",
"=",
"super",
"(",
"ArtifactoryPath",
",",
"self",
")",
".",
"with_name",
"(",
"name",
")",
"obj",
".",
"auth",
"=",
"self",
".",
"auth",
"obj",
".",
"verify",
"=",
"self",
".",
"verify... | 29.9 | 10.5 |
def on_enter(__msg: Optional[Union[Callable, str]] = None) -> Callable:
"""Decorator to display a message when entering a function.
Args:
__msg: Message to display
Returns:
Wrapped function
"""
# pylint: disable=missing-docstring
def decorator(__func):
@wraps(__func)
... | [
"def",
"on_enter",
"(",
"__msg",
":",
"Optional",
"[",
"Union",
"[",
"Callable",
",",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"Callable",
":",
"# pylint: disable=missing-docstring",
"def",
"decorator",
"(",
"__func",
")",
":",
"@",
"wraps",
"(",
"__func",... | 28.363636 | 17.454545 |
def dimensions(self, full=0):
"""Return a dictionnary describing every dataset dimension.
Args::
full true to get complete info about each dimension
false to report only each dimension length
Returns::
Dictionnary where each key is a dimension nam... | [
"def",
"dimensions",
"(",
"self",
",",
"full",
"=",
"0",
")",
":",
"# Get the number of dimensions and their lengths.",
"nDims",
",",
"dimLen",
"=",
"self",
".",
"info",
"(",
")",
"[",
"1",
":",
"3",
"]",
"if",
"isinstance",
"(",
"dimLen",
",",
"int",
")... | 36.74 | 19.86 |
def _translate_jcc(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a JCC instruction.
"""
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
return [op1_var != 0x0] | [
"def",
"_translate_jcc",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd3",
".",
"size",
"op1_var",
"=",
"self",
".",
"_translate_src_oprnd",
"(",
"oprnd1",
")",
"return",
"[",
"op1_var",
... | 31 | 13.875 |
def search(
self,
q,
index="default",
fields=None,
Models=(),
object_types=(),
prefix=True,
facet_by_type=None,
**search_args,
):
"""Interface to search indexes.
:param q: unparsed search string.
:param index: name of i... | [
"def",
"search",
"(",
"self",
",",
"q",
",",
"index",
"=",
"\"default\"",
",",
"fields",
"=",
"None",
",",
"Models",
"=",
"(",
")",
",",
"object_types",
"=",
"(",
")",
",",
"prefix",
"=",
"True",
",",
"facet_by_type",
"=",
"None",
",",
"*",
"*",
... | 35.313559 | 20.110169 |
def kill_thread(self, name):
"""
Joins the thread in the `thread_pool` dict with the given `name` key.
"""
if name not in self.thread_pool:
return
self.thread_pool[name].join()
del self.thread_pool[name] | [
"def",
"kill_thread",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"thread_pool",
":",
"return",
"self",
".",
"thread_pool",
"[",
"name",
"]",
".",
"join",
"(",
")",
"del",
"self",
".",
"thread_pool",
"[",
"name",
"]"
] | 28.444444 | 13.333333 |
def result(self, timeout=None):
"""Enters polling loop on OperationsClient.get_operation, and once
Operation.done is true, then returns Operation.response if successful or
throws GaxError if not successful.
This method will wait up to timeout seconds. If the call hasn't
complete... | [
"def",
"result",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"# Check exceptional case: raise if no response",
"if",
"not",
"self",
".",
"_poll",
"(",
"timeout",
")",
".",
"HasField",
"(",
"'response'",
")",
":",
"raise",
"GaxError",
"(",
"self",
"."... | 47.9375 | 20.875 |
def cli(ctx, board, scons, project_dir, sayyes):
"""Manage apio projects."""
if scons:
Project().create_sconstruct(project_dir, sayyes)
elif board:
Project().create_ini(board, project_dir, sayyes)
else:
click.secho(ctx.get_help()) | [
"def",
"cli",
"(",
"ctx",
",",
"board",
",",
"scons",
",",
"project_dir",
",",
"sayyes",
")",
":",
"if",
"scons",
":",
"Project",
"(",
")",
".",
"create_sconstruct",
"(",
"project_dir",
",",
"sayyes",
")",
"elif",
"board",
":",
"Project",
"(",
")",
"... | 29.222222 | 18.666667 |
def get_encrypted_pin(self, clear_pin, card_number):
"""
Get PIN block in ISO 0 format, encrypted with the terminal key
"""
if not self.terminal_key:
print('Terminal key is not set')
return ''
if self.pinblock_format == '01':
try:
... | [
"def",
"get_encrypted_pin",
"(",
"self",
",",
"clear_pin",
",",
"card_number",
")",
":",
"if",
"not",
"self",
".",
"terminal_key",
":",
"print",
"(",
"'Terminal key is not set'",
")",
"return",
"''",
"if",
"self",
".",
"pinblock_format",
"==",
"'01'",
":",
"... | 32.857143 | 18.666667 |
def subfn(pattern, format, string, *args, **kwargs): # noqa A002
"""Wrapper for `subfn`."""
flags = args[4] if len(args) > 4 else kwargs.get('flags', 0)
is_replace = _is_replace(format)
is_string = isinstance(format, (str, bytes))
if is_replace and not format.use_format:
raise ValueError("... | [
"def",
"subfn",
"(",
"pattern",
",",
"format",
",",
"string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa A002",
"flags",
"=",
"args",
"[",
"4",
"]",
"if",
"len",
"(",
"args",
")",
">",
"4",
"else",
"kwargs",
".",
"get",
"(",
"... | 40.133333 | 21.333333 |
def get_key_from_cmdline(parser, args):
"""Return the signing key and signing algoritm from the commandline."""
if args.keyfiles:
signing_key = open(args.keyfiles[0], 'rb').read()
bits = get_keysize(signing_key)
if bits == 2048:
signing_algorithm = 'sha1'
elif bits ==... | [
"def",
"get_key_from_cmdline",
"(",
"parser",
",",
"args",
")",
":",
"if",
"args",
".",
"keyfiles",
":",
"signing_key",
"=",
"open",
"(",
"args",
".",
"keyfiles",
"[",
"0",
"]",
",",
"'rb'",
")",
".",
"read",
"(",
")",
"bits",
"=",
"get_keysize",
"("... | 37.333333 | 19.055556 |
def add_to_package_numpy(self, root, ndarray, node_path, target, source_path, transform, custom_meta):
"""
Save a Numpy array to the store.
"""
filehash = self.save_numpy(ndarray)
metahash = self.save_metadata(custom_meta)
self._add_to_package_contents(root, node_path, [f... | [
"def",
"add_to_package_numpy",
"(",
"self",
",",
"root",
",",
"ndarray",
",",
"node_path",
",",
"target",
",",
"source_path",
",",
"transform",
",",
"custom_meta",
")",
":",
"filehash",
"=",
"self",
".",
"save_numpy",
"(",
"ndarray",
")",
"metahash",
"=",
... | 52.142857 | 20.428571 |
def drop_column(self, name):
"""
Drops a Column from the Table
:param name: The name of the column
:type name: str
:rtype: Table
"""
name = self._normalize_identifier(name)
del self._columns[name]
return self | [
"def",
"drop_column",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"_normalize_identifier",
"(",
"name",
")",
"del",
"self",
".",
"_columns",
"[",
"name",
"]",
"return",
"self"
] | 20.846154 | 16.230769 |
def _fetch(self, key):
"""Helper function to fetch values from owning section.
Returns a 2-tuple: the value, and the section where it was found.
"""
# switch off interpolation before we try and fetch anything !
save_interp = self.section.main.interpolation
self.section.m... | [
"def",
"_fetch",
"(",
"self",
",",
"key",
")",
":",
"# switch off interpolation before we try and fetch anything !",
"save_interp",
"=",
"self",
".",
"section",
".",
"main",
".",
"interpolation",
"self",
".",
"section",
".",
"main",
".",
"interpolation",
"=",
"Fal... | 40.65625 | 16.34375 |
def _words_plus_punc(self):
"""
Returns mapping of form:
{
'cat,': 'cat',
',cat': 'cat',
}
"""
no_punc_text = REGEX_REMOVE_PUNCTUATION.sub('', self.text)
# removes punctuation (but loses emoticons & contractions)
words_only = no_pun... | [
"def",
"_words_plus_punc",
"(",
"self",
")",
":",
"no_punc_text",
"=",
"REGEX_REMOVE_PUNCTUATION",
".",
"sub",
"(",
"''",
",",
"self",
".",
"text",
")",
"# removes punctuation (but loses emoticons & contractions)",
"words_only",
"=",
"no_punc_text",
".",
"split",
"(",... | 38.789474 | 16.263158 |
def set_inteface_up(devid, ifindex, auth, url):
"""
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the spec
ified interface on the target device.
:param devid: int or str value of the target device
:param ifindex: int or str value of the t... | [
"def",
"set_inteface_up",
"(",
"devid",
",",
"ifindex",
",",
"auth",
",",
"url",
")",
":",
"set_int_up_url",
"=",
"\"/imcrs/plat/res/device/\"",
"+",
"str",
"(",
"devid",
")",
"+",
"\"/interface/\"",
"+",
"str",
"(",
"ifindex",
")",
"+",
"\"/up\"",
"f_url",
... | 50.764706 | 21.235294 |
def export_hdf5_v1(dataset, path, column_names=None, byteorder="=", shuffle=False, selection=False, progress=None, virtual=True):
"""
:param DatasetLocal dataset: dataset to export
:param str path: path for file
:param lis[str] column_names: list of column names to export or None for all columns
:pa... | [
"def",
"export_hdf5_v1",
"(",
"dataset",
",",
"path",
",",
"column_names",
"=",
"None",
",",
"byteorder",
"=",
"\"=\"",
",",
"shuffle",
"=",
"False",
",",
"selection",
"=",
"False",
",",
"progress",
"=",
"None",
",",
"virtual",
"=",
"True",
")",
":",
"... | 50.611765 | 24.305882 |
def create_update_event(self):
"""Parse the update messages DSL to insert the data into the Event.
Returns:
list[fleaker.peewee.EventStorageMixin]:
All the events that were created for the update.
"""
events = []
for fields, rules in iteritems(self._... | [
"def",
"create_update_event",
"(",
"self",
")",
":",
"events",
"=",
"[",
"]",
"for",
"fields",
",",
"rules",
"in",
"iteritems",
"(",
"self",
".",
"_meta",
".",
"update_messages",
")",
":",
"if",
"not",
"isinstance",
"(",
"fields",
",",
"(",
"list",
","... | 31.064516 | 19.967742 |
def scan_devices(fn, lfilter, iface=None):
"""Sniff packages
:param fn: callback on packet
:param lfilter: filter packages
:return: loop
"""
try:
sniff(prn=fn, store=0,
# filter="udp",
filter="arp or (udp and src port 68 and dst port 67 and src host 0.0.0.0)"... | [
"def",
"scan_devices",
"(",
"fn",
",",
"lfilter",
",",
"iface",
"=",
"None",
")",
":",
"try",
":",
"sniff",
"(",
"prn",
"=",
"fn",
",",
"store",
"=",
"0",
",",
"# filter=\"udp\",",
"filter",
"=",
"\"arp or (udp and src port 68 and dst port 67 and src host 0.0.0.... | 29.714286 | 14.285714 |
def update(self, old, new):
"""Replace an element in the heap
"""
i = self.rank[old] # change value at index i
del self.rank[old]
self.heap[i] = new
self.rank[new] = i
if old < new: # maintain heap order
self.down(i)
else:
... | [
"def",
"update",
"(",
"self",
",",
"old",
",",
"new",
")",
":",
"i",
"=",
"self",
".",
"rank",
"[",
"old",
"]",
"# change value at index i",
"del",
"self",
".",
"rank",
"[",
"old",
"]",
"self",
".",
"heap",
"[",
"i",
"]",
"=",
"new",
"self",
".",... | 29.454545 | 13.090909 |
def new_cipher(self, key, iv, digest=None):
"""
@param key: the secret key, a byte string
@param iv: the initialization vector, a byte string. Used as the
initial nonce in counter mode
@param digest: also known as tag or icv. A byte string containing the
... | [
"def",
"new_cipher",
"(",
"self",
",",
"key",
",",
"iv",
",",
"digest",
"=",
"None",
")",
":",
"if",
"type",
"(",
"key",
")",
"is",
"str",
":",
"key",
"=",
"key",
".",
"encode",
"(",
"'ascii'",
")",
"if",
"self",
".",
"is_aead",
"and",
"digest",
... | 37.615385 | 15.692308 |
def allowed_target_sdp_states(self):
"""Return a list of allowed target states for the current state."""
_current_state = self._sdp_state.current_state
_allowed_target_states = self._sdp_state.allowed_target_states[
_current_state]
return json.dumps(dict(allowed_target_sdp_st... | [
"def",
"allowed_target_sdp_states",
"(",
"self",
")",
":",
"_current_state",
"=",
"self",
".",
"_sdp_state",
".",
"current_state",
"_allowed_target_states",
"=",
"self",
".",
"_sdp_state",
".",
"allowed_target_states",
"[",
"_current_state",
"]",
"return",
"json",
"... | 53.571429 | 13.428571 |
def clear_agent(self, short_name, client_id):
"""Remove a client id from being the command handler for a service.
Args:
short_name (str): The name of the service to set an agent
for.
client_id (str): A globally unique id for the client that
should... | [
"def",
"clear_agent",
"(",
"self",
",",
"short_name",
",",
"client_id",
")",
":",
"if",
"short_name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown service name\"",
",",
"short_name",
"=",
"short_name",
")",
"if",
"short_... | 42.380952 | 26.095238 |
def configure():
"""Configure uWSGI.
This returns several configuration objects, which will be used
to spawn several uWSGI processes.
Applications are on 127.0.0.1 on ports starting from 8000.
"""
import os
from uwsgiconf.presets.nice import PythonSection
FILE = os.path.abspath(__fil... | [
"def",
"configure",
"(",
")",
":",
"import",
"os",
"from",
"uwsgiconf",
".",
"presets",
".",
"nice",
"import",
"PythonSection",
"FILE",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
"port",
"=",
"8000",
"configurations",
"=",
"[",
"]",
... | 24.632653 | 23.122449 |
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
condition = pretty_str(self.condition)
pretty = '{}if ({}):\n'.format(... | [
"def",
"pretty_str",
"(",
"self",
",",
"indent",
"=",
"0",
")",
":",
"spaces",
"=",
"' '",
"*",
"indent",
"condition",
"=",
"pretty_str",
"(",
"self",
".",
"condition",
")",
"pretty",
"=",
"'{}if ({}):\\n'",
".",
"format",
"(",
"spaces",
",",
"condition"... | 39.285714 | 15.928571 |
def png(self, file, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""This method writes the QR code out as an PNG image. The resulting
PNG has a bit depth of 1. The file parameter is used to specify where
to write the image to. It can either be... | [
"def",
"png",
"(",
"self",
",",
"file",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"255",
")",
",",
"background",
"=",
"(",
"255",
",",
"255",
",",
"255",
",",
"255",
")",
",",
"quiet_zone",
"=",
"4",... | 55.666667 | 29.1875 |
def main():
"""
Entry point, calling :py:func:`pastml.acr.pastml_pipeline` with command-line arguments.
:return: void
"""
import argparse
parser = argparse.ArgumentParser(description="Ancestral character reconstruction and visualisation "
"for r... | [
"def",
"main",
"(",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Ancestral character reconstruction and visualisation \"",
"\"for rooted phylogenetic trees.\"",
",",
"prog",
"=",
"'pastml'",
")",
"tree_group... | 75.317829 | 44.108527 |
def evaluate_json(annotations: Dict[str, Any], predicted_answers: Dict[str, Any]) -> Tuple[float, float]:
"""
Takes gold annotations and predicted answers and evaluates the predictions for each question
in the gold annotations. Both JSON dictionaries must have query_id keys, which are used to
match pr... | [
"def",
"evaluate_json",
"(",
"annotations",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"predicted_answers",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"instance_exact_match",
"=",
"[",
"]",
... | 52.883333 | 22.25 |
def getElementCtrlConf(self, elementKw):
""" return keyword's EPICS control configs,
if not setup, return {}
"""
try:
retval = self.all_elements['_epics'][elementKw.upper()]
except KeyError:
retval = {}
return retval | [
"def",
"getElementCtrlConf",
"(",
"self",
",",
"elementKw",
")",
":",
"try",
":",
"retval",
"=",
"self",
".",
"all_elements",
"[",
"'_epics'",
"]",
"[",
"elementKw",
".",
"upper",
"(",
")",
"]",
"except",
"KeyError",
":",
"retval",
"=",
"{",
"}",
"retu... | 28.4 | 15.2 |
def _wait_for_retransmit_thread(transaction):
"""
Only one retransmit thread at a time, wait for other to finish
"""
if hasattr(transaction, 'retransmit_thread'):
while transaction.retransmit_thread is not None:
logger.debug("Waiting for retransmit th... | [
"def",
"_wait_for_retransmit_thread",
"(",
"transaction",
")",
":",
"if",
"hasattr",
"(",
"transaction",
",",
"'retransmit_thread'",
")",
":",
"while",
"transaction",
".",
"retransmit_thread",
"is",
"not",
"None",
":",
"logger",
".",
"debug",
"(",
"\"Waiting for r... | 38.9 | 15.9 |
def uri(self):
"""return the uri, which is everything but base (no scheme, host, etc)"""
uristring = self.path
if self.query:
uristring += "?{}".format(self.query)
if self.fragment:
uristring += "#{}".format(self.fragment)
return uristring | [
"def",
"uri",
"(",
"self",
")",
":",
"uristring",
"=",
"self",
".",
"path",
"if",
"self",
".",
"query",
":",
"uristring",
"+=",
"\"?{}\"",
".",
"format",
"(",
"self",
".",
"query",
")",
"if",
"self",
".",
"fragment",
":",
"uristring",
"+=",
"\"#{}\""... | 32.888889 | 16.333333 |
def eye_plot(x,L,S=0):
"""
Eye pattern plot of a baseband digital communications waveform.
The signal must be real, but can be multivalued in terms of the underlying
modulation scheme. Used for BPSK eye plots in the Case Study article.
Parameters
----------
x : ndarray of the real input da... | [
"def",
"eye_plot",
"(",
"x",
",",
"L",
",",
"S",
"=",
"0",
")",
":",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"6",
",",
"4",
")",
")",
"idx",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"L",
"+",
"1",
")",
"plt",
".",
"plot",
"(",
"... | 26.52381 | 20.285714 |
def render(self, rect, data):
"""Draws the managed element in the correct alignment."""
# We can't use our get minimum size, because that enforces
# the size limits.
size = self.element.get_minimum_size(data)
# Assume we're bottom left at our natural size.
x = rect.x
... | [
"def",
"render",
"(",
"self",
",",
"rect",
",",
"data",
")",
":",
"# We can't use our get minimum size, because that enforces",
"# the size limits.",
"size",
"=",
"self",
".",
"element",
".",
"get_minimum_size",
"(",
"data",
")",
"# Assume we're bottom left at our natural... | 33.066667 | 18.766667 |
def _jobs_cursor(plugin_name, location=None, port=None, custom=None):
"""
generates a reql cursor for plugin_name
with status ready
and prepares to sort by StartTime
:param plugin_name:
:param location:
:param port:
:return:
"""
cur = RBJ.get_all(READY, index=STATUS_FIELD)
cu... | [
"def",
"_jobs_cursor",
"(",
"plugin_name",
",",
"location",
"=",
"None",
",",
"port",
"=",
"None",
",",
"custom",
"=",
"None",
")",
":",
"cur",
"=",
"RBJ",
".",
"get_all",
"(",
"READY",
",",
"index",
"=",
"STATUS_FIELD",
")",
"cur_filter",
"=",
"(",
... | 35.125 | 15.208333 |
def get(self, request, *args, **kwargs):
"""
method called on GET request on this view
:param django.http.HttpRequest request: The current request object
"""
logger.info("logout requested")
# initialize the class attributes
self.init_get(request)
... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"info",
"(",
"\"logout requested\"",
")",
"# initialize the class attributes",
"self",
".",
"init_get",
"(",
"request",
")",
"# if CAS federation mod... | 47.595238 | 20.166667 |
def set_mules_params(
self, mules=None, touch_reload=None, harakiri_timeout=None, farms=None, reload_mercy=None,
msg_buffer=None, msg_buffer_recv=None):
"""Sets mules related params.
http://uwsgi.readthedocs.io/en/latest/Mules.html
Mules are worker processes living in t... | [
"def",
"set_mules_params",
"(",
"self",
",",
"mules",
"=",
"None",
",",
"touch_reload",
"=",
"None",
",",
"harakiri_timeout",
"=",
"None",
",",
"farms",
"=",
"None",
",",
"reload_mercy",
"=",
"None",
",",
"msg_buffer",
"=",
"None",
",",
"msg_buffer_recv",
... | 32.575758 | 26.151515 |
def plot (data, headers=None, pconfig=None):
""" Return HTML for a MultiQC table.
:param data: 2D dict, first keys as sample names, then x:y data pairs
:param headers: list of optional dicts with column config in key:value pairs.
:return: HTML ready to be inserted into the page
"""
if headers is... | [
"def",
"plot",
"(",
"data",
",",
"headers",
"=",
"None",
",",
"pconfig",
"=",
"None",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"[",
"]",
"if",
"pconfig",
"is",
"None",
":",
"pconfig",
"=",
"{",
"}",
"# Allow user to overwrite any g... | 43.542857 | 25.228571 |
def tvBrowserAggregation_selection_changed(self):
"""Update layer description label."""
(is_compatible, desc) = self.get_layer_description_from_browser(
'aggregation')
self.lblDescribeBrowserAggLayer.setText(desc)
self.parent.pbnNext.setEnabled(is_compatible) | [
"def",
"tvBrowserAggregation_selection_changed",
"(",
"self",
")",
":",
"(",
"is_compatible",
",",
"desc",
")",
"=",
"self",
".",
"get_layer_description_from_browser",
"(",
"'aggregation'",
")",
"self",
".",
"lblDescribeBrowserAggLayer",
".",
"setText",
"(",
"desc",
... | 49.666667 | 13.5 |
def log_exceptions(self, c, broker):
"""Gets exceptions to be logged and sends to logit function to be logged to syslog"""
if c in broker.exceptions:
ex = broker.exceptions.get(c)
ex = "Exception in {0} - {1}".format(dr.get_name(c), str(ex))
self.logit(ex, self.pid, ... | [
"def",
"log_exceptions",
"(",
"self",
",",
"c",
",",
"broker",
")",
":",
"if",
"c",
"in",
"broker",
".",
"exceptions",
":",
"ex",
"=",
"broker",
".",
"exceptions",
".",
"get",
"(",
"c",
")",
"ex",
"=",
"\"Exception in {0} - {1}\"",
".",
"format",
"(",
... | 50.714286 | 17.428571 |
def parse_response(cls, response_string):
"""JSONRPC allows for **batch** responses to be communicated
as arrays of dicts. This method parses out each individual
element in the batch and returns a list of tuples, each
tuple a result of parsing of each item in the batch.
:Returns... | [
"def",
"parse_response",
"(",
"cls",
",",
"response_string",
")",
":",
"try",
":",
"batch",
"=",
"cls",
".",
"json_loads",
"(",
"response_string",
")",
"except",
"ValueError",
"as",
"err",
":",
"raise",
"errors",
".",
"RPCParseError",
"(",
"\"No valid JSON. (%... | 48.642857 | 24.107143 |
def check_object_permission(obj):
"""Retrieve object and abort if it doesn't exists."""
check_permission(current_permission_factory(
obj,
'object-read'
))
if not obj.is_head:
check_permission(
current_permission_factory(obj, 'object-rea... | [
"def",
"check_object_permission",
"(",
"obj",
")",
":",
"check_permission",
"(",
"current_permission_factory",
"(",
"obj",
",",
"'object-read'",
")",
")",
"if",
"not",
"obj",
".",
"is_head",
":",
"check_permission",
"(",
"current_permission_factory",
"(",
"obj",
"... | 33.181818 | 16.545455 |
def get_user_profile_photos(self, user_id, offset=None, limit=None):
"""
Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
https://core.telegram.org/bots/api#getuserprofilephotos
Parameters:
:param user_id: Uniqu... | [
"def",
"get_user_profile_photos",
"(",
"self",
",",
"user_id",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"assert_type_or_raise",
"(",
"user_id",
",",
"int",
",",
"parameter_name",
"=",
"\"user_id\"",
")",
"assert_type_or_raise",
"(",
"of... | 40.133333 | 28.133333 |
def get_process_threads(self):
"""Return the number of threads belonging to the process."""
rawlist = _psutil_bsd.get_process_threads(self.pid)
retlist = []
for thread_id, utime, stime in rawlist:
ntuple = nt_thread(thread_id, utime, stime)
retlist.append(ntuple)
... | [
"def",
"get_process_threads",
"(",
"self",
")",
":",
"rawlist",
"=",
"_psutil_bsd",
".",
"get_process_threads",
"(",
"self",
".",
"pid",
")",
"retlist",
"=",
"[",
"]",
"for",
"thread_id",
",",
"utime",
",",
"stime",
"in",
"rawlist",
":",
"ntuple",
"=",
"... | 41.875 | 11.875 |
def distinct(iterable, keyfunc=None):
'''Yields distinct items from `iterable` in the order that they appear.
'''
seen = set()
for item in iterable:
key = item if keyfunc is None else keyfunc(item)
if key not in seen:
seen.add(key)
yield item | [
"def",
"distinct",
"(",
"iterable",
",",
"keyfunc",
"=",
"None",
")",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"iterable",
":",
"key",
"=",
"item",
"if",
"keyfunc",
"is",
"None",
"else",
"keyfunc",
"(",
"item",
")",
"if",
"key",
"not... | 32.222222 | 19.111111 |
def main(argv=None):
"""Main program entry point for parsing command line arguments"""
parser = argparse.ArgumentParser(description="Parser benchmark")
parser.add_argument("--debug", default=False, action="store_true", help="Enable debugging")
parser.add_argument("--repetitions", type=int, default=10, ... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Parser benchmark\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--debug\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
... | 48.7 | 32.4 |
def create_directory(directory):
"""Creates a directory if it does not exist (in a thread-safe way)
@param directory: The directory to create
@return: The directory specified
"""
try:
os.makedirs(directory)
except OSError, e:
if e.errno == errno.EEXIST and os.path.isdir(director... | [
"def",
"create_directory",
"(",
"directory",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"directory",
")",
"except",
"OSError",
",",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
... | 26.923077 | 17.307692 |
def get_yeast_promoter_ypa(gene_name):
'''Retrieve promoter from Yeast Promoter Atlas
(http://ypa.csbb.ntu.edu.tw).
:param gene_name: Common name for yeast gene.
:type gene_name: str
:returns: Double-stranded DNA sequence of the promoter.
:rtype: coral.DNA
'''
import requests
loc ... | [
"def",
"get_yeast_promoter_ypa",
"(",
"gene_name",
")",
":",
"import",
"requests",
"loc",
"=",
"get_yeast_gene_location",
"(",
"gene_name",
")",
"gid",
"=",
"get_gene_id",
"(",
"gene_name",
")",
"ypa_baseurl",
"=",
"'http://ypa.csbb.ntu.edu.tw/do'",
"params",
"=",
"... | 29.921053 | 16.921053 |
def parse_buffer_to_png(data):
"""
Parse PNG file bytes to Pillow Image
"""
images = []
c1 = 0
c2 = 0
data_len = len(data)
while c1 < data_len:
# IEND can appear in a PNG without being the actual end
if data[c2:c2 + 4] == b'IEND' and (c2 + 8 == data_len or data[c2+9... | [
"def",
"parse_buffer_to_png",
"(",
"data",
")",
":",
"images",
"=",
"[",
"]",
"c1",
"=",
"0",
"c2",
"=",
"0",
"data_len",
"=",
"len",
"(",
"data",
")",
"while",
"c1",
"<",
"data_len",
":",
"# IEND can appear in a PNG without being the actual end",
"if",
"dat... | 24.421053 | 22.947368 |
def present(name, auth=None, **kwargs):
'''
Ensure domain exists and is up-to-date
name
Name of the domain
enabled
Boolean to control if domain is enabled
description
An arbitrary description of the domain
'''
ret = {'name': name,
'changes': {},
... | [
"def",
"present",
"(",
"name",
",",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"kwargs",
"=",
... | 26.45098 | 20.568627 |
def make_single_template_plots(workflow, segs, data_read_name, analyzed_name,
params, out_dir, inj_file=None, exclude=None,
require=None, tags=None, params_str=None,
use_exact_inj_params=False):
"""Function for cre... | [
"def",
"make_single_template_plots",
"(",
"workflow",
",",
"segs",
",",
"data_read_name",
",",
"analyzed_name",
",",
"params",
",",
"out_dir",
",",
"inj_file",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"require",
"=",
"None",
",",
"tags",
"=",
"None",
... | 51.746154 | 21.007692 |
def route_table_create_or_update(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Create or update a route table within a specified resource group.
:param name: The name of the route table to create.
:param resource_group: The resource group name assigned to the
route table... | [
"def",
"route_table_create_or_update",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'location'",
"not",
"in",
"kwargs",
":",
"rg_props",
"=",
"__salt__",
"[",
"'azurearm_resource.resource_group_get'",
"]",
"(",
"resource_group",
",... | 31.166667 | 25.796296 |
def resume_training(self, sgd=None, **cfg):
"""Continue training a pre-trained model.
Create and return an optimizer, and initialize "rehearsal" for any pipeline
component that has a .rehearse() method. Rehearsal is used to prevent
models from "forgetting" their initialised "knowledge".... | [
"def",
"resume_training",
"(",
"self",
",",
"sgd",
"=",
"None",
",",
"*",
"*",
"cfg",
")",
":",
"if",
"cfg",
".",
"get",
"(",
"\"device\"",
",",
"-",
"1",
")",
">=",
"0",
":",
"util",
".",
"use_gpu",
"(",
"cfg",
"[",
"\"device\"",
"]",
")",
"if... | 49.217391 | 17.130435 |
def task_estimates(channel, states):
"""
Estimate remaining time for all tasks in this channel.
:param channel: txkoji.channel.Channel
:param list states: list of task_states ints, eg [task_states.OPEN]
:returns: deferred that when fired returns a list of
(task, est_remaining) tuples
... | [
"def",
"task_estimates",
"(",
"channel",
",",
"states",
")",
":",
"for",
"state",
"in",
"states",
":",
"if",
"state",
"!=",
"task_states",
".",
"OPEN",
":",
"raise",
"NotImplementedError",
"(",
"'only estimate OPEN tasks'",
")",
"tasks",
"=",
"yield",
"channel... | 40.466667 | 12.933333 |
def file_exists(self, fid):
"""Checks if file with provided fid exists
Args:
**fid**: File identifier <volume_id>,<file_name_hash>
Returns:
True if file exists. False if not.
"""
res = self.get_file_size(fid)
if res is not None:
retur... | [
"def",
"file_exists",
"(",
"self",
",",
"fid",
")",
":",
"res",
"=",
"self",
".",
"get_file_size",
"(",
"fid",
")",
"if",
"res",
"is",
"not",
"None",
":",
"return",
"True",
"return",
"False"
] | 25.769231 | 17.538462 |
def _send_event_task(args):
"""
Actually sends the MixPanel event. Runs in a uwsgi worker process.
"""
endpoint = args['endpoint']
json_message = args['json_message']
_consumer_impl.send(endpoint, json_message) | [
"def",
"_send_event_task",
"(",
"args",
")",
":",
"endpoint",
"=",
"args",
"[",
"'endpoint'",
"]",
"json_message",
"=",
"args",
"[",
"'json_message'",
"]",
"_consumer_impl",
".",
"send",
"(",
"endpoint",
",",
"json_message",
")"
] | 32.571429 | 8.571429 |
def run(self, *args):
"""Show information about countries."""
params = self.parser.parse_args(args)
ct = params.code_or_term
if ct and len(ct) < 2:
self.error('Code country or term must have 2 or more characters length')
return CODE_INVALID_FORMAT_ERROR
... | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"ct",
"=",
"params",
".",
"code_or_term",
"if",
"ct",
"and",
"len",
"(",
"ct",
")",
"<",
"2",
":",
"self",
".",
"e... | 30.954545 | 21.909091 |
def parse_sphinx_docopts(index):
"""
Parse the Sphinx index for documentation options.
Parameters
----------
index : str
The Sphinx index page
Returns
-------
docopts : dict
The documentation options from the page.
"""
pos = index.find('var DOCUMENTATION_OPTION... | [
"def",
"parse_sphinx_docopts",
"(",
"index",
")",
":",
"pos",
"=",
"index",
".",
"find",
"(",
"'var DOCUMENTATION_OPTIONS'",
")",
"if",
"pos",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Documentation options could not be found in index.'",
")",
"pos",
"=",
"inde... | 28.576923 | 19.192308 |
def bitcast(self, typ):
"""
Bitcast this pointer constant to the given type.
"""
if typ == self.type:
return self
op = "bitcast ({0} {1} to {2})".format(self.type, self.get_reference(),
typ)
return FormattedConsta... | [
"def",
"bitcast",
"(",
"self",
",",
"typ",
")",
":",
"if",
"typ",
"==",
"self",
".",
"type",
":",
"return",
"self",
"op",
"=",
"\"bitcast ({0} {1} to {2})\"",
".",
"format",
"(",
"self",
".",
"type",
",",
"self",
".",
"get_reference",
"(",
")",
",",
... | 35.888889 | 12.555556 |
def tile_2d(input, k_x, k_y, name, reorder_required=True):
"""
A tiling layer like introduced in overfeat and huval papers.
:param input: Your input tensor.
:param k_x: The tiling factor in x direction.
:param k_y: The tiling factor in y direction.
:param name: The name of the layer.
:param ... | [
"def",
"tile_2d",
"(",
"input",
",",
"k_x",
",",
"k_y",
",",
"name",
",",
"reorder_required",
"=",
"True",
")",
":",
"size",
"=",
"input",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"c",
",",
"h",
",",
"w",
"=",
"size",
"[",
"3",
"]"... | 38.97561 | 18 |
def _insert_layer_after(self, layer_idx, new_layer, new_keras_layer):
"""
Insert the new_layer after layer, whose position is layer_idx. The new layer's
parameter is stored in a Keras layer called new_keras_layer
"""
# reminder: new_keras_layer is not part of the original Keras n... | [
"def",
"_insert_layer_after",
"(",
"self",
",",
"layer_idx",
",",
"new_layer",
",",
"new_keras_layer",
")",
":",
"# reminder: new_keras_layer is not part of the original Keras network,",
"# so it's input / output blob information is missing. It serves only as",
"# a parameter holder.",
... | 49.888889 | 15.666667 |
def get_referenced_object(self):
"""
:rtype: core.BunqModel
:raise: BunqException
"""
if self._BunqMeFundraiserResult is not None:
return self._BunqMeFundraiserResult
if self._BunqMeTab is not None:
return self._BunqMeTab
if self._BunqMe... | [
"def",
"get_referenced_object",
"(",
"self",
")",
":",
"if",
"self",
".",
"_BunqMeFundraiserResult",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_BunqMeFundraiserResult",
"if",
"self",
".",
"_BunqMeTab",
"is",
"not",
"None",
":",
"return",
"self",
".",
... | 28.369863 | 16.726027 |
def enumeratelet(iterable=None, start=0):
r"""
Enumerate chunks of data from an iterable or a chain
:param iterable: object supporting iteration, or an index
:type iterable: iterable, None or int
:param start: an index to start counting from
:type start: int
:raises TypeError: if both param... | [
"def",
"enumeratelet",
"(",
"iterable",
"=",
"None",
",",
"start",
"=",
"0",
")",
":",
"# shortcut directly to chain enumeration",
"if",
"iterable",
"is",
"None",
":",
"return",
"_enumeratelet",
"(",
"start",
"=",
"start",
")",
"try",
":",
"iterator",
"=",
"... | 37.7 | 24.525 |
def ystep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{y}`.
"""
self.Y = sp.proj_l1(self.AX + self.U, self.gamma,
axis=self.cri.axisN + (self.cri.axisC,
self.cri.axisM))
sup... | [
"def",
"ystep",
"(",
"self",
")",
":",
"self",
".",
"Y",
"=",
"sp",
".",
"proj_l1",
"(",
"self",
".",
"AX",
"+",
"self",
".",
"U",
",",
"self",
".",
"gamma",
",",
"axis",
"=",
"self",
".",
"cri",
".",
"axisN",
"+",
"(",
"self",
".",
"cri",
... | 38.222222 | 16.666667 |
def is_match(self, match):
"""Return whether this model is the same as `match`.
Matches if the model is the same as or has the same name as `match`.
"""
result = False
if self == match:
result = True
elif isinstance(match, str) and fnmatchcase(self.name, matc... | [
"def",
"is_match",
"(",
"self",
",",
"match",
")",
":",
"result",
"=",
"False",
"if",
"self",
"==",
"match",
":",
"result",
"=",
"True",
"elif",
"isinstance",
"(",
"match",
",",
"str",
")",
"and",
"fnmatchcase",
"(",
"self",
".",
"name",
",",
"match"... | 35.454545 | 18.272727 |
def delete(self, ids):
"""
Method to delete vip's by their id's
:param ids: Identifiers of vip's
:return: None
"""
url = build_uri_with_ids('api/v3/vip-request/%s/', ids)
return super(ApiVipRequest, self).delete(url) | [
"def",
"delete",
"(",
"self",
",",
"ids",
")",
":",
"url",
"=",
"build_uri_with_ids",
"(",
"'api/v3/vip-request/%s/'",
",",
"ids",
")",
"return",
"super",
"(",
"ApiVipRequest",
",",
"self",
")",
".",
"delete",
"(",
"url",
")"
] | 26.5 | 15.7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.