text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def create_hotkey(self, folder, description, modifiers, key, contents):
"""
Create a text hotkey
Usage: C{engine.create_hotkey(folder, description, modifiers, key, contents)}
When the given hotkey is pressed, it will be replaced with the given
text. Modifiers mu... | [
"def",
"create_hotkey",
"(",
"self",
",",
"folder",
",",
"description",
",",
"modifiers",
",",
"key",
",",
"contents",
")",
":",
"modifiers",
".",
"sort",
"(",
")",
"if",
"not",
"self",
".",
"configManager",
".",
"check_hotkey_unique",
"(",
"modifiers",
",... | 37.526316 | 23.052632 |
def visitExponentExpression(self, ctx):
"""
expression: expression EXPONENT expression
"""
arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_decimal(self.visit(ctx.expression(1)), self._eval_context)
return conversions.... | [
"def",
"visitExponentExpression",
"(",
"self",
",",
"ctx",
")",
":",
"arg1",
"=",
"conversions",
".",
"to_decimal",
"(",
"self",
".",
"visit",
"(",
"ctx",
".",
"expression",
"(",
"0",
")",
")",
",",
"self",
".",
"_eval_context",
")",
"arg2",
"=",
"conv... | 50.571429 | 19.142857 |
def _parse_sheet(workbook, sheet):
"""
The universal spreadsheet parser. Parse chron or paleo tables of type ensemble/model/summary.
:param str name: Filename
:param obj workbook: Excel Workbook
:param dict sheet: Sheet path and naming info
:return dict dict: Table metadata and numeric data
... | [
"def",
"_parse_sheet",
"(",
"workbook",
",",
"sheet",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter parse_sheet: {}\"",
".",
"format",
"(",
"sheet",
"[",
"\"old_name\"",
"]",
")",
")",
"# Markers to track where we are on the sheet",
"ensemble_on",
"=",
"False... | 44.420091 | 25.917808 |
def _get_token():
'''
Get an auth token
'''
username = __opts__.get('rallydev', {}).get('username', None)
password = __opts__.get('rallydev', {}).get('password', None)
path = 'https://rally1.rallydev.com/slm/webservice/v2.0/security/authorize'
result = salt.utils.http.query(
path,
... | [
"def",
"_get_token",
"(",
")",
":",
"username",
"=",
"__opts__",
".",
"get",
"(",
"'rallydev'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'username'",
",",
"None",
")",
"password",
"=",
"__opts__",
".",
"get",
"(",
"'rallydev'",
",",
"{",
"}",
")",
"."... | 27.434783 | 22.130435 |
def parse_tile_name(name):
"""
Parses and verifies tile name.
:param name: class input parameter `tile_name`
:type name: str
:return: parsed tile name
:rtype: str
"""
tile_name = name.lstrip('T0')
if len(tile_name) == 4:
tile_name = '0... | [
"def",
"parse_tile_name",
"(",
"name",
")",
":",
"tile_name",
"=",
"name",
".",
"lstrip",
"(",
"'T0'",
")",
"if",
"len",
"(",
"tile_name",
")",
"==",
"4",
":",
"tile_name",
"=",
"'0'",
"+",
"tile_name",
"if",
"len",
"(",
"tile_name",
")",
"!=",
"5",
... | 29.466667 | 11.866667 |
def data(self, index, role=QtCore.Qt.UserRole, mode=BuildMode):
"""Used by the view to determine data to present
See :qtdoc:`QAbstractItemModel<QAbstractItemModel.data>`,
and :qtdoc:`subclassing<qabstractitemmodel.subclassing>`
"""
if role == CursorRole:
if index.is... | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
"=",
"QtCore",
".",
"Qt",
".",
"UserRole",
",",
"mode",
"=",
"BuildMode",
")",
":",
"if",
"role",
"==",
"CursorRole",
":",
"if",
"index",
".",
"isValid",
"(",
")",
":",
"if",
"mode",
"==",
"B... | 44.939394 | 18.242424 |
def feed_line(self, line):
"""Feeds one line of input into the reader machine. This method is
a generator that yields all top-level S-expressions that have been
recognized on this line (including multi-line expressions whose last
character is on this line).
"""
self.line... | [
"def",
"feed_line",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"line",
"+=",
"1",
"pos",
"=",
"0",
"while",
"pos",
"<",
"len",
"(",
"line",
")",
":",
"loc_start",
"=",
"TextLocationSingle",
"(",
"self",
".",
"filename",
",",
"self",
".",
"lin... | 49.748148 | 14.474074 |
def valid_starter_settings(self):
'''check starter settings'''
if self.gasheli_settings.ignition_chan <= 0 or self.gasheli_settings.ignition_chan > 8:
print("Invalid ignition channel %d" % self.gasheli_settings.ignition_chan)
return False
if self.gasheli_settings.starter_... | [
"def",
"valid_starter_settings",
"(",
"self",
")",
":",
"if",
"self",
".",
"gasheli_settings",
".",
"ignition_chan",
"<=",
"0",
"or",
"self",
".",
"gasheli_settings",
".",
"ignition_chan",
">",
"8",
":",
"print",
"(",
"\"Invalid ignition channel %d\"",
"%",
"sel... | 55 | 29.222222 |
def export_debug(self, output_path):
"""
this method is used to generate a debug map for NEO debugger
"""
file_hash = hashlib.md5(open(output_path, 'rb').read()).hexdigest()
avm_name = os.path.splitext(os.path.basename(output_path))[0]
json_data = self.generate_debug_js... | [
"def",
"export_debug",
"(",
"self",
",",
"output_path",
")",
":",
"file_hash",
"=",
"hashlib",
".",
"md5",
"(",
"open",
"(",
"output_path",
",",
"'rb'",
")",
".",
"read",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"avm_name",
"=",
"os",
".",
"path",
... | 37.307692 | 21.307692 |
def __make_message(self, topic, content):
"""
Prepares the message content
"""
return {"uid": str(uuid.uuid4()).replace('-', '').upper(),
"topic": topic,
"content": content} | [
"def",
"__make_message",
"(",
"self",
",",
"topic",
",",
"content",
")",
":",
"return",
"{",
"\"uid\"",
":",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
".",
"upper",
"(",
")",
",",
"\"topic\"",
":... | 33 | 6.428571 |
def read_raid(self, raid_config=None):
"""Read the logical drives from the system
:param raid_config: None or a dictionary containing target raid
configuration data. This data stucture should be as
follows:
raid_config ... | [
"def",
"read_raid",
"(",
"self",
",",
"raid_config",
"=",
"None",
")",
":",
"self",
".",
"check_smart_storage_config_ids",
"(",
")",
"if",
"raid_config",
":",
"# When read called after create raid, user can pass raid config",
"# as a input",
"result",
"=",
"self",
".",
... | 48.227273 | 21.090909 |
def for_data_and_tracer(cls, lens_data, tracer, padded_tracer=None):
"""Fit lens data with a model tracer, automatically determining the type of fit based on the \
properties of the galaxies in the tracer.
Parameters
-----------
lens_data : lens_data.LensData or lens_data.LensDa... | [
"def",
"for_data_and_tracer",
"(",
"cls",
",",
"lens_data",
",",
"tracer",
",",
"padded_tracer",
"=",
"None",
")",
":",
"if",
"tracer",
".",
"has_light_profile",
"and",
"not",
"tracer",
".",
"has_pixelization",
":",
"return",
"LensProfileFit",
"(",
"lens_data",
... | 58.708333 | 29.833333 |
def _send_file(self, local, remote):
"""send a single file"""
remote = "%s:%s" % (self.location, remote)
for i in range(10):
if not os.path.exists(local):
self.log.debug("waiting for %s" % local)
time.sleep(1)
else:
break
... | [
"def",
"_send_file",
"(",
"self",
",",
"local",
",",
"remote",
")",
":",
"remote",
"=",
"\"%s:%s\"",
"%",
"(",
"self",
".",
"location",
",",
"remote",
")",
"for",
"i",
"in",
"range",
"(",
"10",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exis... | 37.909091 | 11.363636 |
def acquire(self):
"""
Acquire the lock.
If the lock can't be acquired immediately, retry a specified number of
times, with a specified wait time.
"""
retries = [0]
self._acquire_start_seconds = self._reactor.seconds()
def log_lock_acquired(result):
... | [
"def",
"acquire",
"(",
"self",
")",
":",
"retries",
"=",
"[",
"0",
"]",
"self",
".",
"_acquire_start_seconds",
"=",
"self",
".",
"_reactor",
".",
"seconds",
"(",
")",
"def",
"log_lock_acquired",
"(",
"result",
")",
":",
"self",
".",
"_lock_acquired_seconds... | 38.55814 | 20.976744 |
def vtrees(self):
"""
Get list of VTrees from ScaleIO cluster
:return: List of VTree objects - Can be empty of no VTrees exist
:rtype: VTree object
"""
self.connection._check_login()
response = self.connection._do_get("{}/{}".format(self.connection._api_url, "type... | [
"def",
"vtrees",
"(",
"self",
")",
":",
"self",
".",
"connection",
".",
"_check_login",
"(",
")",
"response",
"=",
"self",
".",
"connection",
".",
"_do_get",
"(",
"\"{}/{}\"",
".",
"format",
"(",
"self",
".",
"connection",
".",
"_api_url",
",",
"\"types/... | 35.928571 | 16.642857 |
def _normalize_branch_node(self, node):
# sys.stderr.write('nbn\n')
"""node should have only one item changed
"""
not_blank_items_count = sum(1 for x in range(17) if node[x])
assert not_blank_items_count >= 1
if not_blank_items_count > 1:
self._encode_node(no... | [
"def",
"_normalize_branch_node",
"(",
"self",
",",
"node",
")",
":",
"# sys.stderr.write('nbn\\n')",
"not_blank_items_count",
"=",
"sum",
"(",
"1",
"for",
"x",
"in",
"range",
"(",
"17",
")",
"if",
"node",
"[",
"x",
"]",
")",
"assert",
"not_blank_items_count",
... | 36.282051 | 14.846154 |
def store_file(self, remote_full_path, local_full_path):
"""
Transfers a local file to the remote location.
If local_full_path_or_buffer is a string path, the file will be read
from that location
:param remote_full_path: full path to the remote file
:type remote_full_path... | [
"def",
"store_file",
"(",
"self",
",",
"remote_full_path",
",",
"local_full_path",
")",
":",
"conn",
"=",
"self",
".",
"get_conn",
"(",
")",
"conn",
".",
"put",
"(",
"local_full_path",
",",
"remote_full_path",
")"
] | 42 | 12.666667 |
def monitor(i):
"""Given an iterator, yields data from it
but prints progress every 10,000 records"""
count = 0
for x in i:
count+=1
if count % 10000 == 0:
logger.info("%d records so far, current record is %s",
count, x["idx"])
yield x | [
"def",
"monitor",
"(",
"i",
")",
":",
"count",
"=",
"0",
"for",
"x",
"in",
"i",
":",
"count",
"+=",
"1",
"if",
"count",
"%",
"10000",
"==",
"0",
":",
"logger",
".",
"info",
"(",
"\"%d records so far, current record is %s\"",
",",
"count",
",",
"x",
"... | 29.4 | 17 |
def call_for_each_tower(
towers, func, devices=None, use_vs=None):
"""
Run `func` on all GPUs (towers) and return the results.
Args:
towers (list[int]): a list of GPU id.
func: a lambda to be called inside each tower
devices: a list of devices to ... | [
"def",
"call_for_each_tower",
"(",
"towers",
",",
"func",
",",
"devices",
"=",
"None",
",",
"use_vs",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"devices",
"is",
"not",
"None",
":",
"assert",
"len",
"(",
"devices",
")",
"==",
"len",
"(",
"t... | 43.536585 | 24.268293 |
def decay_indexpointer(self):
'''
This private method provides decay indexpointers which allow to
instantaneously decay an abundance vector. These are attributes
are.
Parameters
=================
decay_idp : list
points in the iso_to_plot (i.e. the undecayed abu... | [
"def",
"decay_indexpointer",
"(",
"self",
")",
":",
"a_iso_to_plot",
"=",
"self",
".",
"a_iso_to_plot",
"isotope_to_plot",
"=",
"self",
".",
"isotope_to_plot",
"z_iso_to_plot",
"=",
"self",
".",
"z_iso_to_plot",
"el_iso_to_plot",
"=",
"self",
".",
"el_iso_to_plot",
... | 54.75 | 27.83 |
def set_l2cap_options (sock, options):
"""set_l2cap_options (sock, options)
Sets L2CAP options for the specified L2CAP socket.
The option list must be in the same format supplied by
get_l2cap_options().
"""
# TODO this should be in the C module, because it depends
# directly on struct l2cap... | [
"def",
"set_l2cap_options",
"(",
"sock",
",",
"options",
")",
":",
"# TODO this should be in the C module, because it depends",
"# directly on struct l2cap_options layout.",
"s",
"=",
"struct",
".",
"pack",
"(",
"\"HHHBBBH\"",
",",
"*",
"options",
")",
"sock",
".",
"set... | 38 | 11.545455 |
def _verify_jws(self, payload, key):
"""Verify the given JWS payload with the given key and return the payload"""
jws = JWS.from_compact(payload)
try:
alg = jws.signature.combined.alg.name
except KeyError:
msg = 'No alg value found in header'
raise Su... | [
"def",
"_verify_jws",
"(",
"self",
",",
"payload",
",",
"key",
")",
":",
"jws",
"=",
"JWS",
".",
"from_compact",
"(",
"payload",
")",
"try",
":",
"alg",
"=",
"jws",
".",
"signature",
".",
"combined",
".",
"alg",
".",
"name",
"except",
"KeyError",
":"... | 36.148148 | 16.962963 |
def path_fraction_point(points, fraction):
'''Computes the point which corresponds to the fraction
of the path length along the piecewise linear curve which
is constructed from the set of points.
Args:
points: an iterable of indexable objects with indices
0, 1, 2 correspoding to 3D cart... | [
"def",
"path_fraction_point",
"(",
"points",
",",
"fraction",
")",
":",
"seg_id",
",",
"offset",
"=",
"path_fraction_id_offset",
"(",
"points",
",",
"fraction",
",",
"relative_offset",
"=",
"True",
")",
"return",
"linear_interpolate",
"(",
"points",
"[",
"seg_id... | 41.266667 | 24.2 |
def get_bbox(self, primitive):
"""Get the bounding box for the mesh"""
accessor = primitive.attributes.get('POSITION')
return accessor.min, accessor.max | [
"def",
"get_bbox",
"(",
"self",
",",
"primitive",
")",
":",
"accessor",
"=",
"primitive",
".",
"attributes",
".",
"get",
"(",
"'POSITION'",
")",
"return",
"accessor",
".",
"min",
",",
"accessor",
".",
"max"
] | 43.25 | 6.5 |
def hessian(pars, x, y):
"""
Create a hessian matrix corresponding to the source model 'pars'
Only parameters that vary will contribute to the hessian.
Thus there will be a total of nvar x nvar entries, each of which is a
len(x) x len(y) array.
Parameters
----------
pars : lmfit.Paramet... | [
"def",
"hessian",
"(",
"pars",
",",
"x",
",",
"y",
")",
":",
"j",
"=",
"0",
"# keeping track of the number of variable parameters",
"# total number of variable parameters",
"ntvar",
"=",
"np",
".",
"sum",
"(",
"[",
"pars",
"[",
"k",
"]",
".",
"vary",
"for",
... | 44.539519 | 29.130584 |
def VxLANTunnelState_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
VxLANTunnelState = ET.SubElement(config, "VxLANTunnelState", xmlns="http://brocade.com/ns/brocade-notification-stream")
originator_switch_info =... | [
"def",
"VxLANTunnelState_originator_switch_info_switchIpV4Address",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"VxLANTunnelState",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"VxLANTunnelSta... | 55.545455 | 28.545455 |
def logger(filter='WARN'):
"""Set up CASA to write log messages to standard output.
filter
The log level filter: less urgent messages will not be shown. Valid values
are strings: "DEBUG1", "INFO5", ... "INFO1", "INFO", "WARN", "SEVERE".
This function creates and returns a CASA ”log sink” objec... | [
"def",
"logger",
"(",
"filter",
"=",
"'WARN'",
")",
":",
"import",
"os",
",",
"shutil",
",",
"tempfile",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"tempdir",
"=",
"None",
"try",
":",
"tempdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
... | 32.162791 | 22.651163 |
def asdict(
inst,
recurse=True,
filter=None,
dict_factory=dict,
retain_collection_types=False,
):
"""
Return the ``attrs`` attribute values of *inst* as a dict.
Optionally recurse into other ``attrs``-decorated classes.
:param inst: Instance of an ``attrs``-decorated class.
:pa... | [
"def",
"asdict",
"(",
"inst",
",",
"recurse",
"=",
"True",
",",
"filter",
"=",
"None",
",",
"dict_factory",
"=",
"dict",
",",
"retain_collection_types",
"=",
"False",
",",
")",
":",
"attrs",
"=",
"fields",
"(",
"inst",
".",
"__class__",
")",
"rv",
"=",... | 36.082192 | 19.643836 |
def get_term_pillar(filter_name,
term_name,
pillar_key='acl',
pillarenv=None,
saltenv=None):
'''
Helper that can be used inside a state SLS,
in order to get the term configuration given its name,
under a certain filter uniqu... | [
"def",
"get_term_pillar",
"(",
"filter_name",
",",
"term_name",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
")",
":",
"return",
"__salt__",
"[",
"'capirca.get_term_pillar'",
"]",
"(",
"filter_name",
",",
"term_n... | 34.46875 | 22.15625 |
def get_bundle(self, bundle_id=None):
# type: (Union[Bundle, int]) -> Bundle
"""
Retrieves the :class:`~pelix.framework.Bundle` object for the bundle
matching the given ID (int). If no ID is given (None), the bundle
associated to this context is returned.
:param bundle_i... | [
"def",
"get_bundle",
"(",
"self",
",",
"bundle_id",
"=",
"None",
")",
":",
"# type: (Union[Bundle, int]) -> Bundle",
"if",
"bundle_id",
"is",
"None",
":",
"# Current bundle",
"return",
"self",
".",
"__bundle",
"elif",
"isinstance",
"(",
"bundle_id",
",",
"Bundle",... | 42.157895 | 17.210526 |
def read_configuration(
filepath, find_others=False, ignore_option_errors=False):
"""Read given configuration file and returns options from it as a dict.
:param str|unicode filepath: Path to configuration file
to get options from.
:param bool find_others: Whether to search for other config... | [
"def",
"read_configuration",
"(",
"filepath",
",",
"find_others",
"=",
"False",
",",
"ignore_option_errors",
"=",
"False",
")",
":",
"from",
"setuptools",
".",
"dist",
"import",
"Distribution",
",",
"_Distribution",
"filepath",
"=",
"os",
".",
"path",
".",
"ab... | 31.377778 | 21.244444 |
def _copy_calibration(self, calibration):
"""Copy another ``StereoCalibration`` object's values."""
for key, item in calibration.__dict__.items():
self.__dict__[key] = item | [
"def",
"_copy_calibration",
"(",
"self",
",",
"calibration",
")",
":",
"for",
"key",
",",
"item",
"in",
"calibration",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"self",
".",
"__dict__",
"[",
"key",
"]",
"=",
"item"
] | 49.25 | 4.5 |
def _pre_request(self, url, method = u"get", data = None, headers=None, **kwargs):
"""
hook for manipulating the _pre request data
"""
header = {
u"Content-Type": u"application/json",
u"User-Agent": u"salesking_api_py_v1",
}
if headers:
... | [
"def",
"_pre_request",
"(",
"self",
",",
"url",
",",
"method",
"=",
"u\"get\"",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"header",
"=",
"{",
"u\"Content-Type\"",
":",
"u\"application/json\"",
",",
"u\"User... | 34.133333 | 14 |
def visit_list(self, node):
"""return an astroid.List node as string"""
return "[%s]" % ", ".join(child.accept(self) for child in node.elts) | [
"def",
"visit_list",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"[%s]\"",
"%",
"\", \"",
".",
"join",
"(",
"child",
".",
"accept",
"(",
"self",
")",
"for",
"child",
"in",
"node",
".",
"elts",
")"
] | 51.333333 | 16.333333 |
def check_encoding_chars(encoding_chars):
"""
Validate the given encoding chars
:type encoding_chars: ``dict``
:param encoding_chars: the encoding chars (see :func:`hl7apy.set_default_encoding_chars`)
:raises: :exc:`hl7apy.exceptions.InvalidEncodingChars` if the given encoding chars are not valid
... | [
"def",
"check_encoding_chars",
"(",
"encoding_chars",
")",
":",
"if",
"not",
"isinstance",
"(",
"encoding_chars",
",",
"collections",
".",
"MutableMapping",
")",
":",
"raise",
"InvalidEncodingChars",
"required",
"=",
"{",
"'FIELD'",
",",
"'COMPONENT'",
",",
"'SUBC... | 44.722222 | 21.944444 |
async def _process_access_form(self, html: str) -> (str, str):
"""
Parsing page with access rights
:param html: html page
:return: url and html from redirected page
"""
# Parse page
p = AccessPageParser()
p.feed(html)
p.close()
form_url ... | [
"async",
"def",
"_process_access_form",
"(",
"self",
",",
"html",
":",
"str",
")",
"->",
"(",
"str",
",",
"str",
")",
":",
"# Parse page",
"p",
"=",
"AccessPageParser",
"(",
")",
"p",
".",
"feed",
"(",
"html",
")",
"p",
".",
"close",
"(",
")",
"for... | 25.722222 | 17.833333 |
def get_summary_dict(self):
"""
Returns a dict with a summary of the computed properties.
"""
d = defaultdict(list)
d["pressure"] = self.pressure
d["poisson"] = self.poisson
d["mass"] = self.mass
d["natoms"] = int(self.natoms)
d["bulk_modulus"] = s... | [
"def",
"get_summary_dict",
"(",
"self",
")",
":",
"d",
"=",
"defaultdict",
"(",
"list",
")",
"d",
"[",
"\"pressure\"",
"]",
"=",
"self",
".",
"pressure",
"d",
"[",
"\"poisson\"",
"]",
"=",
"self",
".",
"poisson",
"d",
"[",
"\"mass\"",
"]",
"=",
"self... | 43.277778 | 14.166667 |
def refresh(self, refresh_binary=True):
'''
Performs GET request and refreshes RDF information for resource.
Args:
None
Returns:
None
'''
updated_self = self.repo.get_resource(self.uri)
# if resource type of updated_self != self, raise exception
if not isinstance(self, type(updated_self)):
... | [
"def",
"refresh",
"(",
"self",
",",
"refresh_binary",
"=",
"True",
")",
":",
"updated_self",
"=",
"self",
".",
"repo",
".",
"get_resource",
"(",
"self",
".",
"uri",
")",
"# if resource type of updated_self != self, raise exception",
"if",
"not",
"isinstance",
"(",... | 24.06383 | 23.893617 |
def find_hba(self, all_atoms):
"""Find all possible hydrogen bond acceptors"""
data = namedtuple('hbondacceptor', 'a a_orig_atom a_orig_idx type')
a_set = []
for atom in filter(lambda at: at.OBAtom.IsHbondAcceptor(), all_atoms):
if atom.atomicnum not in [9, 17, 35, 53] and at... | [
"def",
"find_hba",
"(",
"self",
",",
"all_atoms",
")",
":",
"data",
"=",
"namedtuple",
"(",
"'hbondacceptor'",
",",
"'a a_orig_atom a_orig_idx type'",
")",
"a_set",
"=",
"[",
"]",
"for",
"atom",
"in",
"filter",
"(",
"lambda",
"at",
":",
"at",
".",
"OBAtom"... | 64.7 | 33.6 |
def get_db_filename(impl, working_dir):
"""
Get the absolute path to the last-block file.
"""
db_filename = impl.get_virtual_chain_name() + ".db"
return os.path.join(working_dir, db_filename) | [
"def",
"get_db_filename",
"(",
"impl",
",",
"working_dir",
")",
":",
"db_filename",
"=",
"impl",
".",
"get_virtual_chain_name",
"(",
")",
"+",
"\".db\"",
"return",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"db_filename",
")"
] | 34.333333 | 5.666667 |
def separate_scalar_factor(element):
"""Construct a monomial with the coefficient separated
from an element in a polynomial.
"""
coeff = 1.0
monomial = S.One
if isinstance(element, (int, float, complex)):
coeff *= element
return monomial, coeff
for var in element.as_coeff_mul... | [
"def",
"separate_scalar_factor",
"(",
"element",
")",
":",
"coeff",
"=",
"1.0",
"monomial",
"=",
"S",
".",
"One",
"if",
"isinstance",
"(",
"element",
",",
"(",
"int",
",",
"float",
",",
"complex",
")",
")",
":",
"coeff",
"*=",
"element",
"return",
"mon... | 32.6 | 10.25 |
def authenticator(function, challenges=()):
"""Wraps authentication logic, verify_user through to the authentication function.
The verify_user function passed in should accept an API key and return a user object to
store in the request context if authentication succeeded.
"""
challenges = challenge... | [
"def",
"authenticator",
"(",
"function",
",",
"challenges",
"=",
"(",
")",
")",
":",
"challenges",
"=",
"challenges",
"or",
"(",
"'{} realm=\"simple\"'",
".",
"format",
"(",
"function",
".",
"__name__",
")",
",",
")",
"def",
"wrapper",
"(",
"verify_user",
... | 40.171429 | 24.2 |
def eval(self, key, default=None, loc=None, correct_key=True):
"""Evaluates and sets the specified option value in
environment `loc`. Many options need ``N`` to be defined in
`loc`, some need `popsize`.
Details
-------
Keys that contain 'filename' are not evaluated.
... | [
"def",
"eval",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"loc",
"=",
"None",
",",
"correct_key",
"=",
"True",
")",
":",
"# TODO: try: loc['dim'] = loc['N'] etc",
"if",
"correct_key",
":",
"# in_key = key # for debugging only",
"key",
"=",
"self... | 33.894737 | 16.631579 |
def compact_view(self, merged_data, selected_meta, reference_no):
"""
Creates and returns the compact view where the index of the dataframe is a multi index of the selected metadata.
Side effect: Alters the merged_data parameter
:param merged_data: The merged data that is to be used to ... | [
"def",
"compact_view",
"(",
"self",
",",
"merged_data",
",",
"selected_meta",
",",
"reference_no",
")",
":",
"meta_names",
"=",
"list",
"(",
"selected_meta",
")",
"meta_index",
"=",
"[",
"]",
"for",
"x",
"in",
"meta_names",
":",
"meta_index",
".",
"append",
... | 49.7 | 28.9 |
def find(self, *args, **kwargs):
"""Find and return the files collection documents that match ``filter``.
Returns a cursor that iterates across files matching
arbitrary queries on the files collection. Can be combined
with other modifiers for additional control.
For example::
... | [
"def",
"find",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cursor",
"=",
"self",
".",
"delegate",
".",
"find",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"grid_out_cursor",
"=",
"create_class_with_framework",
"(",
"AgnosticG... | 40.310345 | 23.12069 |
def __IpsToServerIds(self):
""" Get list of mapping of ip address into a server id"""
master_instance = self.__GetMasterInstance()
assert(master_instance)
retval, response = self.__RunMaprCli('node list -columns id')
ip_to_id = {}
for line_num, line in enumerate(response.split('\n')):
toke... | [
"def",
"__IpsToServerIds",
"(",
"self",
")",
":",
"master_instance",
"=",
"self",
".",
"__GetMasterInstance",
"(",
")",
"assert",
"(",
"master_instance",
")",
"retval",
",",
"response",
"=",
"self",
".",
"__RunMaprCli",
"(",
"'node list -columns id'",
")",
"ip_t... | 37.846154 | 14.076923 |
def _maybe_strip_i18n_prefix_and_normalize(number, possible_idd_prefix):
"""Strips any international prefix (such as +, 00, 011) present in the
number provided, normalizes the resulting number, and indicates if an
international prefix was present.
Arguments:
number -- The non-normalized telephone n... | [
"def",
"_maybe_strip_i18n_prefix_and_normalize",
"(",
"number",
",",
"possible_idd_prefix",
")",
":",
"if",
"len",
"(",
"number",
")",
"==",
"0",
":",
"return",
"(",
"CountryCodeSource",
".",
"FROM_DEFAULT_COUNTRY",
",",
"number",
")",
"# Check to see if the number be... | 44.702703 | 20.783784 |
def get_suite_token(self, suite_id, suite_secret, suite_ticket):
"""
获取第三方应用凭证
https://work.weixin.qq.com/api/doc#90001/90143/9060
:param suite_id: 以ww或wx开头应用id(对应于旧的以tj开头的套件id)
:param suite_secret: 应用secret
:param suite_ticket: 企业微信后台推送的ticket
:return: 返回的 JSO... | [
"def",
"get_suite_token",
"(",
"self",
",",
"suite_id",
",",
"suite_secret",
",",
"suite_ticket",
")",
":",
"return",
"self",
".",
"_post",
"(",
"'service/get_suite_token'",
",",
"data",
"=",
"{",
"'suite_id'",
":",
"suite_id",
",",
"'suite_secret'",
":",
"sui... | 29.315789 | 15 |
def vertical_gradient(self, x0, y0, x1, y1, start, end):
"""Draw a vertical gradient"""
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
grad = gradient_list(start, end, y1 - y0)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
self.point(x, y, grad[y ... | [
"def",
"vertical_gradient",
"(",
"self",
",",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
",",
"start",
",",
"end",
")",
":",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
"=",
"self",
".",
"rect_helper",
"(",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
")",
... | 45.714286 | 7.714286 |
def preserve_view(*predicates):
""" Raising ViewNotMatched when applied request was not apposite.
preserve_view calls all Predicates and when return values of them was
all True it will call a wrapped view.
It raises ViewNotMatched if this is not the case.
Predicates:
This decorator takes Predi... | [
"def",
"preserve_view",
"(",
"*",
"predicates",
")",
":",
"def",
"wrapper",
"(",
"view_callable",
")",
":",
"def",
"_wrapped",
"(",
"self",
",",
"request",
",",
"context",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"all",
"(",
"[",
... | 40.75 | 19.85 |
def get_absolute_url(self):
"""Determine where I am coming from and where I am going"""
# Determine if this configuration is on a stage
if self.stage:
# Stage specific configurations go back to the stage view
url = reverse('projects_stage_view', args=(self.project.pk, se... | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"# Determine if this configuration is on a stage",
"if",
"self",
".",
"stage",
":",
"# Stage specific configurations go back to the stage view",
"url",
"=",
"reverse",
"(",
"'projects_stage_view'",
",",
"args",
"=",
"(",
"... | 40 | 24.416667 |
def groups_to_display(self, value):
"""An array containing the unsubscribe groups that you would like to be
displayed on the unsubscribe preferences page.
:param value: An array containing the unsubscribe groups that you
would like to be displayed on the unsubscribe
... | [
"def",
"groups_to_display",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
"and",
"len",
"(",
"value",
")",
">",
"25",
":",
"raise",
"ValueError",
"(",
"\"New groups_to_display exceeds max length of 25.\"",
")",
"self",
".",
"_groups_... | 46.333333 | 14.833333 |
def _init_ssh(self):
""" Configure SSH client options
"""
self.ssh_host = self.config.get('ssh_host', self.hostname)
self.known_hosts = self.config.get('ssh_knownhosts_file',
self.tensor.config.get('ssh_knownhosts_file', None))
self.ssh_keyfile = self.config.get('s... | [
"def",
"_init_ssh",
"(",
"self",
")",
":",
"self",
".",
"ssh_host",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'ssh_host'",
",",
"self",
".",
"hostname",
")",
"self",
".",
"known_hosts",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'ssh_knownhosts_... | 38.145161 | 23.677419 |
def auto_detect_serial_unix(preferred_list=['*']):
'''try to auto-detect serial ports on unix'''
import glob
glist = glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*') + glob.glob('/dev/serial/by-id/*')
ret = []
others = []
# try preferred ones first
for d in gli... | [
"def",
"auto_detect_serial_unix",
"(",
"preferred_list",
"=",
"[",
"'*'",
"]",
")",
":",
"import",
"glob",
"glist",
"=",
"glob",
".",
"glob",
"(",
"'/dev/ttyS*'",
")",
"+",
"glob",
".",
"glob",
"(",
"'/dev/ttyUSB*'",
")",
"+",
"glob",
".",
"glob",
"(",
... | 31.85 | 19.15 |
def use_json(self, *paths):
"""
Args:
*paths (str | unicode): Paths to files to add as static DictProvider-s, only existing files are added
"""
for path in paths:
if path:
fpath = os.path.expanduser(path)
if os.path.exists(fpath):
... | [
"def",
"use_json",
"(",
"self",
",",
"*",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"path",
":",
"fpath",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fpath",
")",
... | 39 | 16.166667 |
def restore_default_button_clicked(self, classification):
"""Action for restore default button clicked.
It will set the threshold with default value.
:param classification: The classification that being edited.
:type classification: dict
"""
# Obtain default value
... | [
"def",
"restore_default_button_clicked",
"(",
"self",
",",
"classification",
")",
":",
"# Obtain default value",
"class_dict",
"=",
"{",
"}",
"for",
"the_class",
"in",
"classification",
".",
"get",
"(",
"'classes'",
")",
":",
"class_dict",
"[",
"the_class",
"[",
... | 43 | 19.526316 |
def replace_units(self, units, copy=True):
"""Change the unit system of this potential.
Parameters
----------
units : `~gala.units.UnitSystem`
Set of non-reducable units that specify (at minimum) the
length, mass, time, and angle units.
copy : bool (optio... | [
"def",
"replace_units",
"(",
"self",
",",
"units",
",",
"copy",
"=",
"True",
")",
":",
"_lock",
"=",
"self",
".",
"lock",
"if",
"copy",
":",
"pots",
"=",
"self",
".",
"__class__",
"(",
")",
"else",
":",
"pots",
"=",
"self",
"pots",
".",
"_units",
... | 27.56 | 18.16 |
def fmt_delta(timestamp):
""" Format a UNIX timestamp to a delta (relative to now).
"""
try:
return fmt.human_duration(float(timestamp), precision=2, short=True)
except (ValueError, TypeError):
return "N/A".rjust(len(fmt.human_duration(0, precision=2, short=True))) | [
"def",
"fmt_delta",
"(",
"timestamp",
")",
":",
"try",
":",
"return",
"fmt",
".",
"human_duration",
"(",
"float",
"(",
"timestamp",
")",
",",
"precision",
"=",
"2",
",",
"short",
"=",
"True",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":"... | 41.571429 | 18.142857 |
def format(self):
"""PixelFormat: The raw format of the texture. The actual format may differ, but pixel transfers will use this
format.
"""
fmt = ffi.new('Uint32 *')
check_int_err(lib.SDL_QueryTexture(self._ptr, fmt, ffi.NULL, ffi.NULL, ffi.NULL))
return ... | [
"def",
"format",
"(",
"self",
")",
":",
"fmt",
"=",
"ffi",
".",
"new",
"(",
"'Uint32 *'",
")",
"check_int_err",
"(",
"lib",
".",
"SDL_QueryTexture",
"(",
"self",
".",
"_ptr",
",",
"fmt",
",",
"ffi",
".",
"NULL",
",",
"ffi",
".",
"NULL",
",",
"ffi",... | 47.571429 | 13.428571 |
def __check_response(self, msg):
""" Search general errors in server response and raise exceptions when found.
:keyword msg: Result message
:raises NotAllowed: Exception raised when operation was called with
insufficient privileges
:raises AuthorizationError:... | [
"def",
"__check_response",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"list",
")",
":",
"msg",
"=",
"msg",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"(",
"len",
"(",
"msg",
")",
">",
"2",
")",
"and",
"self",
"... | 53.526316 | 19.210526 |
def splitEkmDate(dateint):
"""Break out a date from Omnimeter read.
Note a corrupt date will raise an exception when you
convert it to int to hand to this method.
Args:
dateint (int): Omnimeter datetime as int.
Returns:
tuple: Named tuple which breaks ... | [
"def",
"splitEkmDate",
"(",
"dateint",
")",
":",
"date_str",
"=",
"str",
"(",
"dateint",
")",
"dt",
"=",
"namedtuple",
"(",
"'EkmDate'",
",",
"[",
"'yy'",
",",
"'mm'",
",",
"'dd'",
",",
"'weekday'",
",",
"'hh'",
",",
"'minutes'",
",",
"'ss'",
"]",
")... | 31.473684 | 16.605263 |
def create_build_configuration_process(repository, revision, **kwargs):
"""
Create a new BuildConfiguration. BuildConfigurations represent the settings and configuration required to run a build of a specific version of the associated Project's source code.
If a ProductVersion ID is provided, the BuildConfig... | [
"def",
"create_build_configuration_process",
"(",
"repository",
",",
"revision",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
".",
"get",
"(",
"\"dependency_ids\"",
")",
":",
"kwargs",
"[",
"\"dependency_ids\"",
"]",
"=",
"[",
"]",
"if",
"not",
... | 47.903226 | 31.83871 |
def requires_login(func, *args, **kwargs):
"""Decorator to check that the user is logged in. Raises `BetfairError`
if instance variable `session_token` is absent.
"""
self = args[0]
if self.session_token:
return func(*args, **kwargs)
raise exceptions.NotLoggedIn() | [
"def",
"requires_login",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"if",
"self",
".",
"session_token",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"raise",
"ex... | 36.125 | 7.375 |
def pdb(self):
"""Compiles the PDB strings for each state into a single file."""
header_title = '{:<80}\n'.format('HEADER {}'.format(self.id))
data_type = '{:<80}\n'.format('EXPDTA ISAMBARD Model')
pdb_strs = []
for ampal in self:
if isinstance(ampal, Assembly):... | [
"def",
"pdb",
"(",
"self",
")",
":",
"header_title",
"=",
"'{:<80}\\n'",
".",
"format",
"(",
"'HEADER {}'",
".",
"format",
"(",
"self",
".",
"id",
")",
")",
"data_type",
"=",
"'{:<80}\\n'",
".",
"format",
"(",
"'EXPDTA ISAMBARD Model'",
")",
"pdb_strs"... | 45 | 17.071429 |
def get_index_from_filename(self, filename):
"""
Return the position index of a file in the tab bar of the editorstack
from its name.
"""
filenames = [d.filename for d in self.data]
return filenames.index(filename) | [
"def",
"get_index_from_filename",
"(",
"self",
",",
"filename",
")",
":",
"filenames",
"=",
"[",
"d",
".",
"filename",
"for",
"d",
"in",
"self",
".",
"data",
"]",
"return",
"filenames",
".",
"index",
"(",
"filename",
")"
] | 37.428571 | 10.285714 |
def deploy_service(ctx, path, name, regions, disabled):
"""Deploys a new service JSON to multiple accounts. NAME is the service name you wish to deploy."""
enabled = False if disabled else True
swag = create_swag_from_ctx(ctx)
accounts = swag.get_all(search_filter=path)
log.debug('Searching for acc... | [
"def",
"deploy_service",
"(",
"ctx",
",",
"path",
",",
"name",
",",
"regions",
",",
"disabled",
")",
":",
"enabled",
"=",
"False",
"if",
"disabled",
"else",
"True",
"swag",
"=",
"create_swag_from_ctx",
"(",
"ctx",
")",
"accounts",
"=",
"swag",
".",
"get_... | 42.96875 | 22.5625 |
def to_new(self, data, perplexity=None, return_distances=False):
"""Compute the affinities of new samples to the initial samples.
This is necessary for embedding new data points into an existing
embedding.
Please see the :ref:`parameter-guide` for more information.
Parameters
... | [
"def",
"to_new",
"(",
"self",
",",
"data",
",",
"perplexity",
"=",
"None",
",",
"return_distances",
"=",
"False",
")",
":",
"perplexity",
"=",
"perplexity",
"if",
"perplexity",
"is",
"not",
"None",
"else",
"self",
".",
"perplexity",
"perplexity",
"=",
"sel... | 33.583333 | 24.9 |
async def paginate(self):
"""Actually paginate the entries and run the interactive loop if necessary."""
await self.show_page(1, first=True)
while self.paginating:
react = await self.bot.wait_for_reaction(message=self.message, check=self.react_check, timeout=120.0)
if re... | [
"async",
"def",
"paginate",
"(",
"self",
")",
":",
"await",
"self",
".",
"show_page",
"(",
"1",
",",
"first",
"=",
"True",
")",
"while",
"self",
".",
"paginating",
":",
"react",
"=",
"await",
"self",
".",
"bot",
".",
"wait_for_reaction",
"(",
"message"... | 36.52381 | 22.52381 |
def matchOnlyAtCol(n):
"""Helper method for defining parse actions that require matching at
a specific column in the input text.
"""
def verifyCol(strg,locn,toks):
if col(locn,strg) != n:
raise ParseException(strg,locn,"matched token not at column %d" % n)
return verifyCol | [
"def",
"matchOnlyAtCol",
"(",
"n",
")",
":",
"def",
"verifyCol",
"(",
"strg",
",",
"locn",
",",
"toks",
")",
":",
"if",
"col",
"(",
"locn",
",",
"strg",
")",
"!=",
"n",
":",
"raise",
"ParseException",
"(",
"strg",
",",
"locn",
",",
"\"matched token n... | 38.25 | 11.625 |
def _seconds_or_timedelta(duration):
"""Returns `datetime.timedelta` object for the passed duration.
Keyword Arguments:
duration -- `datetime.timedelta` object or seconds in `int` format.
"""
if isinstance(duration, int):
dt_timedelta = timedelta(seconds=duration)
elif isinstance(du... | [
"def",
"_seconds_or_timedelta",
"(",
"duration",
")",
":",
"if",
"isinstance",
"(",
"duration",
",",
"int",
")",
":",
"dt_timedelta",
"=",
"timedelta",
"(",
"seconds",
"=",
"duration",
")",
"elif",
"isinstance",
"(",
"duration",
",",
"timedelta",
")",
":",
... | 31.117647 | 16.529412 |
def _add_vector(self, hash_name, bucket_key, v, data, redis_object):
'''
Store vector and JSON-serializable data in bucket with specified key.
'''
redis_key = self._format_redis_key(hash_name, bucket_key)
val_dict = {}
# Depending on type (sparse or not) fill value dict... | [
"def",
"_add_vector",
"(",
"self",
",",
"hash_name",
",",
"bucket_key",
",",
"v",
",",
"data",
",",
"redis_object",
")",
":",
"redis_key",
"=",
"self",
".",
"_format_redis_key",
"(",
"hash_name",
",",
"bucket_key",
")",
"val_dict",
"=",
"{",
"}",
"# Depend... | 35.076923 | 20 |
def path_regex(self):
"""Return the regex for the path to the build folder."""
regex = r'%(PREFIX)s%(BUILD)s/%(PLATFORM)s/%(LOCALE)s/'
return regex % {'PREFIX': self.candidate_build_list_regex,
'BUILD': self.builds[self.build_index],
'LOCALE': self... | [
"def",
"path_regex",
"(",
"self",
")",
":",
"regex",
"=",
"r'%(PREFIX)s%(BUILD)s/%(PLATFORM)s/%(LOCALE)s/'",
"return",
"regex",
"%",
"{",
"'PREFIX'",
":",
"self",
".",
"candidate_build_list_regex",
",",
"'BUILD'",
":",
"self",
".",
"builds",
"[",
"self",
".",
"b... | 54.142857 | 16.142857 |
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
sedfile = args.sed_file
if is_not_null(args.config):
configfile = os.path.join(os.path.dirname(sedfile), args.config)
else:
configfile = os.path.join(os.path.dirn... | [
"def",
"run_analysis",
"(",
"self",
",",
"argv",
")",
":",
"args",
"=",
"self",
".",
"_parser",
".",
"parse_args",
"(",
"argv",
")",
"sedfile",
"=",
"args",
".",
"sed_file",
"if",
"is_not_null",
"(",
"args",
".",
"config",
")",
":",
"configfile",
"=",
... | 29.354839 | 19.774194 |
def _to_key_ranges_by_shard(cls, app, namespaces, shard_count, query_spec):
"""Get a list of key_ranges.KeyRanges objects, one for each shard.
This method uses scatter index to split each namespace into pieces
and assign those pieces to shards.
Args:
app: app_id in str.
namespaces: a list ... | [
"def",
"_to_key_ranges_by_shard",
"(",
"cls",
",",
"app",
",",
"namespaces",
",",
"shard_count",
",",
"query_spec",
")",
":",
"key_ranges_by_ns",
"=",
"[",
"]",
"# Split each ns into n splits. If a ns doesn't have enough scatter to",
"# split into n, the last few splits are Non... | 35.045455 | 17.977273 |
def _get_schema():
"""Get the schema for validation"""
schema_path = os.path.join(os.path.dirname(__file__),
'schema', 'scheduling_block_schema.json')
with open(schema_path, 'r') as file:
schema_data = file.read()
schema = json.loads(schema_... | [
"def",
"_get_schema",
"(",
")",
":",
"schema_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'schema'",
",",
"'scheduling_block_schema.json'",
")",
"with",
"open",
"(",
"schema_path",
",",
"... | 42.5 | 13.125 |
def record_messages(self):
"""Records all messages. Use in unit tests for example::
with mail.record_messages() as outbox:
response = app.test_client.get("/email-sending-view/")
assert len(outbox) == 1
assert outbox[0].subject == "testing"
Yo... | [
"def",
"record_messages",
"(",
"self",
")",
":",
"if",
"not",
"email_dispatched",
":",
"raise",
"RuntimeError",
"(",
"\"blinker must be installed\"",
")",
"outbox",
"=",
"[",
"]",
"def",
"_record",
"(",
"message",
",",
"mail",
")",
":",
"outbox",
".",
"appen... | 28 | 20.269231 |
def view_conflicts(L, normalize=True, colorbar=True):
"""Display an [m, m] matrix of conflicts"""
L = L.todense() if sparse.issparse(L) else L
C = _get_conflicts_matrix(L, normalize=normalize)
plt.imshow(C, aspect="auto")
plt.title("Conflicts")
if colorbar:
plt.colorbar()
plt.show() | [
"def",
"view_conflicts",
"(",
"L",
",",
"normalize",
"=",
"True",
",",
"colorbar",
"=",
"True",
")",
":",
"L",
"=",
"L",
".",
"todense",
"(",
")",
"if",
"sparse",
".",
"issparse",
"(",
"L",
")",
"else",
"L",
"C",
"=",
"_get_conflicts_matrix",
"(",
... | 34.555556 | 13.777778 |
def remove_transcript_preferences(course_id):
"""
Deletes course-wide transcript preferences.
Arguments:
course_id(str): course id
"""
try:
transcript_preference = TranscriptPreference.objects.get(course_id=course_id)
transcript_preference.delete()
except TranscriptPrefe... | [
"def",
"remove_transcript_preferences",
"(",
"course_id",
")",
":",
"try",
":",
"transcript_preference",
"=",
"TranscriptPreference",
".",
"objects",
".",
"get",
"(",
"course_id",
"=",
"course_id",
")",
"transcript_preference",
".",
"delete",
"(",
")",
"except",
"... | 28.416667 | 16.416667 |
def _index(array, item, key=None):
"""
Array search function.
Written, because ``.index()`` method for array doesn't have `key` parameter
and raises `ValueError`, if the item is not found.
Args:
array (list): List of items, which will be searched.
item (whatever): Item, which will ... | [
"def",
"_index",
"(",
"array",
",",
"item",
",",
"key",
"=",
"None",
")",
":",
"for",
"i",
",",
"el",
"in",
"enumerate",
"(",
"array",
")",
":",
"resolved_el",
"=",
"key",
"(",
"el",
")",
"if",
"key",
"else",
"el",
"if",
"resolved_el",
"==",
"ite... | 31.478261 | 24.086957 |
def get_pull_command(self, remote=None, revision=None):
"""
Get the command to pull changes from a remote repository into the local repository.
When you pull a specific branch using git, the default behavior is to
pull the change sets from the remote branch into the local repository
... | [
"def",
"get_pull_command",
"(",
"self",
",",
"remote",
"=",
"None",
",",
"revision",
"=",
"None",
")",
":",
"if",
"revision",
":",
"revision",
"=",
"'%s:%s'",
"%",
"(",
"revision",
",",
"revision",
")",
"if",
"self",
".",
"bare",
":",
"return",
"[",
... | 44.125 | 23.875 |
def _got_addresses(self, name, port, addrs):
"""Handler DNS address record lookup result.
:Parameters:
- `name`: the name requested
- `port`: port number to connect to
- `addrs`: list of (family, address) tuples
"""
with self.lock:
if not ... | [
"def",
"_got_addresses",
"(",
"self",
",",
"name",
",",
"port",
",",
"addrs",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"not",
"addrs",
":",
"if",
"self",
".",
"_dst_nameports",
":",
"self",
".",
"_set_state",
"(",
"\"resolve-hostname\"",
")",
... | 42.380952 | 15.380952 |
def paga_compare(
adata,
basis=None,
edges=False,
color=None,
alpha=None,
groups=None,
components=None,
projection='2d',
legend_loc='on data',
legend_fontsize=None,
legend_fontweight='bold',
color_map=None,
palette=N... | [
"def",
"paga_compare",
"(",
"adata",
",",
"basis",
"=",
"None",
",",
"edges",
"=",
"False",
",",
"color",
"=",
"None",
",",
"alpha",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"components",
"=",
"None",
",",
"projection",
"=",
"'2d'",
",",
"legend... | 28.648649 | 16.846847 |
def handle_backend_error(self, exception):
"""
See super class satosa.frontends.base.FrontendModule
:type exception: satosa.exception.SATOSAError
:rtype: oic.utils.http_util.Response
"""
auth_req = self._get_authn_request_from_state(exception.state)
# If the clien... | [
"def",
"handle_backend_error",
"(",
"self",
",",
"exception",
")",
":",
"auth_req",
"=",
"self",
".",
"_get_authn_request_from_state",
"(",
"exception",
".",
"state",
")",
"# If the client sent us a state parameter, we should reflect it back according to the spec",
"if",
"'st... | 59.823529 | 27.470588 |
def get(self, url):
'''Get the entity that corresponds to URL.'''
robots_url = Robots.robots_url(url)
if robots_url not in self.cache:
self.cache[robots_url] = ExpiringObject(partial(self.factory, robots_url))
return self.cache[robots_url].get() | [
"def",
"get",
"(",
"self",
",",
"url",
")",
":",
"robots_url",
"=",
"Robots",
".",
"robots_url",
"(",
"url",
")",
"if",
"robots_url",
"not",
"in",
"self",
".",
"cache",
":",
"self",
".",
"cache",
"[",
"robots_url",
"]",
"=",
"ExpiringObject",
"(",
"p... | 47.333333 | 14.333333 |
def list(self):
"""Retrieve all reports for parent app
Returns:
:class:`list` of :class:`~swimlane.core.resources.report.Report`: List of all returned reports
"""
raw_reports = self._swimlane.request('get', "reports?appId={}".format(self._app.id)).json()
# Ignore Sta... | [
"def",
"list",
"(",
"self",
")",
":",
"raw_reports",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"\"reports?appId={}\"",
".",
"format",
"(",
"self",
".",
"_app",
".",
"id",
")",
")",
".",
"json",
"(",
")",
"# Ignore StatsReports for... | 49.444444 | 32.444444 |
def get_splitting_stream(self, input_plate_value):
"""
Get the splitting stream
:param input_plate_value: The input plate value
:return: The splitting stream
"""
if not self.splitting_node:
return None
if len(self.splitting_node.plates) == 0:
... | [
"def",
"get_splitting_stream",
"(",
"self",
",",
"input_plate_value",
")",
":",
"if",
"not",
"self",
".",
"splitting_node",
":",
"return",
"None",
"if",
"len",
"(",
"self",
".",
"splitting_node",
".",
"plates",
")",
"==",
"0",
":",
"# Use global plate value",
... | 49.234043 | 23.744681 |
def urlunparse(parts):
"""Unparse and encode parts of a URI."""
scheme, netloc, path, params, query, fragment = parts
# Avoid encoding the windows drive letter colon
if RE_DRIVE_LETTER_PATH.match(path):
quoted_path = path[:3] + parse.quote(path[3:])
else:
quoted_path = parse.quote(p... | [
"def",
"urlunparse",
"(",
"parts",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
"=",
"parts",
"# Avoid encoding the windows drive letter colon",
"if",
"RE_DRIVE_LETTER_PATH",
".",
"match",
"(",
"path",
")",
":",
... | 28.388889 | 16.5 |
def _scheduleUpgrade(self,
ev_data: UpgradeLogData,
failTimeout) -> None:
"""
Schedules node upgrade to a newer version
:param ev_data: upgrade event parameters
"""
logger.info(
"{}'s upgrader processing upgrade for v... | [
"def",
"_scheduleUpgrade",
"(",
"self",
",",
"ev_data",
":",
"UpgradeLogData",
",",
"failTimeout",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"\"{}'s upgrader processing upgrade for version {}={}\"",
".",
"format",
"(",
"self",
",",
"ev_data",
".",
"pkg_n... | 39.153846 | 16.076923 |
def resolve_egg_link(path):
"""
Given a path to an .egg-link, resolve distributions
present in the referenced path.
"""
referenced_paths = non_empty_lines(path)
resolved_paths = (
os.path.join(os.path.dirname(path), ref)
for ref in referenced_paths
)
dist_groups = map(fin... | [
"def",
"resolve_egg_link",
"(",
"path",
")",
":",
"referenced_paths",
"=",
"non_empty_lines",
"(",
"path",
")",
"resolved_paths",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
",",
"ref",
")",
"for"... | 31.166667 | 10.666667 |
def order_market_sell(self, **params):
"""Send in a new market sell order
:param symbol: required
:type symbol: str
:param quantity: required
:type quantity: decimal
:param newClientOrderId: A unique id for the order. Automatically generated if not sent.
:type ne... | [
"def",
"order_market_sell",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"params",
".",
"update",
"(",
"{",
"'side'",
":",
"self",
".",
"SIDE_SELL",
"}",
")",
"return",
"self",
".",
"order_market",
"(",
"*",
"*",
"params",
")"
] | 40.8 | 27.96 |
def _parse_json(self, page, exactly_one):
"""Returns location, (latitude, longitude) from json feed."""
if not page.get('success'):
return None
latitude = page['latitude']
longitude = page['longitude']
place = page.get('place')
address = ", ".join([place['c... | [
"def",
"_parse_json",
"(",
"self",
",",
"page",
",",
"exactly_one",
")",
":",
"if",
"not",
"page",
".",
"get",
"(",
"'success'",
")",
":",
"return",
"None",
"latitude",
"=",
"page",
"[",
"'latitude'",
"]",
"longitude",
"=",
"page",
"[",
"'longitude'",
... | 30.625 | 17.4375 |
def set_zero_config(self):
"""Set config such that radiative forcing and temperature output will be zero
This method is intended as a convenience only, it does not handle everything in
an obvious way. Adjusting the parameter settings still requires great care and
may behave unepexctedly... | [
"def",
"set_zero_config",
"(",
"self",
")",
":",
"# zero_emissions is imported from scenarios module",
"zero_emissions",
".",
"write",
"(",
"join",
"(",
"self",
".",
"run_dir",
",",
"self",
".",
"_scen_file_name",
")",
",",
"self",
".",
"version",
")",
"time",
"... | 36.544715 | 15.243902 |
def tcp_traceflow(packet):
"""Trace packet flow for TCP."""
if 'TCP' in packet:
ip = packet.ip if 'IP' in packet else packet.ipv6
tcp = packet.tcp
data = dict(
protocol=LINKTYPE.get(packet.layers[0].layer_name.upper()), # data link type from global header
inde... | [
"def",
"tcp_traceflow",
"(",
"packet",
")",
":",
"if",
"'TCP'",
"in",
"packet",
":",
"ip",
"=",
"packet",
".",
"ip",
"if",
"'IP'",
"in",
"packet",
"else",
"packet",
".",
"ipv6",
"tcp",
"=",
"packet",
".",
"tcp",
"data",
"=",
"dict",
"(",
"protocol",
... | 63 | 37 |
def is_legal_sequence(self, packet: DataPacket) -> bool:
"""
Check if the Sequence number of the DataPacket is legal.
For more information see page 17 of http://tsp.esta.org/tsp/documents/docs/E1-31-2016.pdf.
:param packet: the packet to check
:return: true if the sequence is leg... | [
"def",
"is_legal_sequence",
"(",
"self",
",",
"packet",
":",
"DataPacket",
")",
"->",
"bool",
":",
"# if the sequence of the packet is smaller than the last received sequence, return false",
"# therefore calculate the difference between the two values:",
"try",
":",
"# try, because s... | 53.052632 | 25.684211 |
def _microcanonical_average_spanning_cluster(has_spanning_cluster, alpha):
r'''
Compute the average number of runs that have a spanning cluster
Helper function for :func:`microcanonical_averages`
Parameters
----------
has_spanning_cluster : 1-D :py:class:`numpy.ndarray` of bool
Each e... | [
"def",
"_microcanonical_average_spanning_cluster",
"(",
"has_spanning_cluster",
",",
"alpha",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"runs",
"=",
"has_spanning_cluster",
".",
"size",
"# Bayesian posterior mean for Binomial proportion (uniform prior)",
"k",
"=",
"has_spanni... | 31.609756 | 28.97561 |
def can_route(self, endpoint, method=None, **kwargs):
"""Make sure we can route to the given endpoint or url.
This checks for `http.get` permission (or other methods) on the ACL of
route functions, attached via the `ACL` decorator.
:param endpoint: A URL or endpoint to check for permis... | [
"def",
"can_route",
"(",
"self",
",",
"endpoint",
",",
"method",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"view",
"=",
"flask",
".",
"current_app",
".",
"view_functions",
".",
"get",
"(",
"endpoint",
")",
"if",
"not",
"view",
":",
"endpoint",
... | 40.05 | 25.95 |
def drive(self, speed, rotation_speed, tm_diff):
"""Call this from your :func:`PhysicsEngine.update_sim` function.
Will update the robot's position on the simulation field.
You can either calculate the speed & rotation manually, or you
can use the predefined functions in :mod:`... | [
"def",
"drive",
"(",
"self",
",",
"speed",
",",
"rotation_speed",
",",
"tm_diff",
")",
":",
"# if the robot is disabled, don't do anything",
"if",
"not",
"self",
".",
"robot_enabled",
":",
"return",
"distance",
"=",
"speed",
"*",
"tm_diff",
"angle",
"=",
"rotati... | 38.758621 | 22.62069 |
def create_host_template(resource_root, name, cluster_name):
"""
Create a host template.
@param resource_root: The root Resource object.
@param name: Host template name
@param cluster_name: Cluster name
@return: An ApiHostTemplate object for the created host template.
@since: API v3
"""
apitemplate = ... | [
"def",
"create_host_template",
"(",
"resource_root",
",",
"name",
",",
"cluster_name",
")",
":",
"apitemplate",
"=",
"ApiHostTemplate",
"(",
"resource_root",
",",
"name",
",",
"[",
"]",
")",
"return",
"call",
"(",
"resource_root",
".",
"post",
",",
"HOST_TEMPL... | 38 | 12.307692 |
def _print_daily_stats(self, conn):
"""
Prints a Today/Last 24 hour stats section.
"""
stats = conn.get_send_statistics()
stats = stats['GetSendStatisticsResponse']['GetSendStatisticsResult']
stats = stats['SendDataPoints']
today = datetime.date.today()
... | [
"def",
"_print_daily_stats",
"(",
"self",
",",
"conn",
")",
":",
"stats",
"=",
"conn",
".",
"get_send_statistics",
"(",
")",
"stats",
"=",
"stats",
"[",
"'GetSendStatisticsResponse'",
"]",
"[",
"'GetSendStatisticsResult'",
"]",
"stats",
"=",
"stats",
"[",
"'Se... | 41.444444 | 16.555556 |
def ephemeral(cls):
"""
Creates a new ephemeral key constructed using a raw 32-byte string from urandom.
Ephemeral keys are used once for each encryption task and are then discarded;
they are not intended for long-term or repeat use.
"""
private_key = nacl.public.PrivateK... | [
"def",
"ephemeral",
"(",
"cls",
")",
":",
"private_key",
"=",
"nacl",
".",
"public",
".",
"PrivateKey",
"(",
"os",
".",
"urandom",
"(",
"32",
")",
")",
"return",
"cls",
"(",
"private_key",
".",
"public_key",
",",
"private_key",
")"
] | 48.375 | 20.875 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.