text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def define_magic(self, name, func):
"""[Deprecated] Expose own function as magic function for IPython.
Example::
def foo_impl(self, parameter_s=''):
'My very own magic!. (Use docstrings, IPython reads them).'
print 'Magic function. Passed parameter is betwee... | [
"def",
"define_magic",
"(",
"self",
",",
"name",
",",
"func",
")",
":",
"meth",
"=",
"types",
".",
"MethodType",
"(",
"func",
",",
"self",
".",
"user_magics",
")",
"setattr",
"(",
"self",
".",
"user_magics",
",",
"name",
",",
"meth",
")",
"record_magic... | 38.625 | 16.8125 |
def list_joined_groups(self, user_alias=None):
"""
已加入的小组列表
:param user_alias: 用户名,默认为当前用户名
:return: 单页列表
"""
xml = self.api.xml(API_GROUP_LIST_JOINED_GROUPS % (user_alias or self.api.user_alias))
xml_results = xml.xpath('//div[@class="group-list group-ca... | [
"def",
"list_joined_groups",
"(",
"self",
",",
"user_alias",
"=",
"None",
")",
":",
"xml",
"=",
"self",
".",
"api",
".",
"xml",
"(",
"API_GROUP_LIST_JOINED_GROUPS",
"%",
"(",
"user_alias",
"or",
"self",
".",
"api",
".",
"user_alias",
")",
")",
"xml_results... | 39.607143 | 16.107143 |
def bb_photlam_arcsec(wave, temperature):
"""Evaluate Planck's law in ``photlam`` per square arcsec.
.. note::
Uses :func:`llam_SI` for calculation, and then converts
SI units back to CGS.
Parameters
----------
wave : array_like
Wavelength values in Angstrom.
temperat... | [
"def",
"bb_photlam_arcsec",
"(",
"wave",
",",
"temperature",
")",
":",
"lam",
"=",
"wave",
"*",
"1.0E-10",
"# Angstrom -> meter",
"return",
"F",
"*",
"llam_SI",
"(",
"lam",
",",
"temperature",
")",
"/",
"(",
"HS",
"*",
"C",
"/",
"lam",
")"
] | 23 | 22.08 |
def _pys2row_heights(self, line):
"""Updates row_heights in code_array"""
# Split with maxsplit 3
split_line = self._split_tidy(line)
key = row, tab = self._get_key(*split_line[:2])
height = float(split_line[2])
shape = self.code_array.shape
try:
if... | [
"def",
"_pys2row_heights",
"(",
"self",
",",
"line",
")",
":",
"# Split with maxsplit 3",
"split_line",
"=",
"self",
".",
"_split_tidy",
"(",
"line",
")",
"key",
"=",
"row",
",",
"tab",
"=",
"self",
".",
"_get_key",
"(",
"*",
"split_line",
"[",
":",
"2",... | 27.6875 | 18.25 |
def migrate_abci_chain(self):
"""Generate and record a new ABCI chain ID. New blocks are not
accepted until we receive an InitChain ABCI request with
the matching chain ID and validator set.
Chain ID is generated based on the current chain and height.
`chain-X` => `chain-X-migra... | [
"def",
"migrate_abci_chain",
"(",
"self",
")",
":",
"latest_chain",
"=",
"self",
".",
"get_latest_abci_chain",
"(",
")",
"if",
"latest_chain",
"is",
"None",
":",
"return",
"block",
"=",
"self",
".",
"get_latest_block",
"(",
")",
"suffix",
"=",
"'-migrated-at-h... | 39.521739 | 20.608696 |
def to_unicode(value):
"""Returns a unicode string from a string, using UTF-8 to decode if needed.
This function comes from `Tornado`_.
:param value:
A unicode or string to be decoded.
:returns:
The decoded string.
"""
if isinstance(value, str):
return value.decode('utf-8')
assert isinstanc... | [
"def",
"to_unicode",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"value",
".",
"decode",
"(",
"'utf-8'",
")",
"assert",
"isinstance",
"(",
"value",
",",
"unicode",
")",
"return",
"value"
] | 22.533333 | 17.6 |
def purge(context, resource, **kwargs):
"""Purge resource type."""
uri = '%s/%s/purge' % (context.dci_cs_api, resource)
if 'force' in kwargs and kwargs['force']:
r = context.session.post(uri, timeout=HTTP_TIMEOUT)
else:
r = context.session.get(uri, timeout=HTTP_TIMEOUT)
return r | [
"def",
"purge",
"(",
"context",
",",
"resource",
",",
"*",
"*",
"kwargs",
")",
":",
"uri",
"=",
"'%s/%s/purge'",
"%",
"(",
"context",
".",
"dci_cs_api",
",",
"resource",
")",
"if",
"'force'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'force'",
"]",
":",
... | 38.5 | 14.75 |
def update(self, pbar):
"""
Handle progress bar updates
@type pbar: ProgressBar
@rtype: str
"""
if pbar.label != self._label:
self.label = pbar.label
return self.label | [
"def",
"update",
"(",
"self",
",",
"pbar",
")",
":",
"if",
"pbar",
".",
"label",
"!=",
"self",
".",
"_label",
":",
"self",
".",
"label",
"=",
"pbar",
".",
"label",
"return",
"self",
".",
"label"
] | 23.1 | 11.1 |
def mail_sent_count(self, count):
"""
Test that `count` mails have been sent.
Syntax:
I have sent `count` emails
Example:
.. code-block:: gherkin
Then I have sent 2 emails
"""
expected = int(count)
actual = len(mail.outbox)
assert expected == actual, \
"E... | [
"def",
"mail_sent_count",
"(",
"self",
",",
"count",
")",
":",
"expected",
"=",
"int",
"(",
"count",
")",
"actual",
"=",
"len",
"(",
"mail",
".",
"outbox",
")",
"assert",
"expected",
"==",
"actual",
",",
"\"Expected to send {0} email(s), got {1}.\"",
".",
"f... | 20.388889 | 20.055556 |
def _lookup(self, skip_cache, fun, *args, **kwargs):
"""
Checks for cached responses, before requesting from
web-service
"""
if args not in self.cache or skip_cache:
self.cache[args] = fun(*args, **kwargs)
return self.cache[args] | [
"def",
"_lookup",
"(",
"self",
",",
"skip_cache",
",",
"fun",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"not",
"in",
"self",
".",
"cache",
"or",
"skip_cache",
":",
"self",
".",
"cache",
"[",
"args",
"]",
"=",
"fun",
"(",
... | 35.5 | 10.125 |
def qos_map_dscp_cos_dscp_cos_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
map = ET.SubElement(qos, "map")
dscp_cos = ET.SubElement(map, "dscp-cos")
... | [
"def",
"qos_map_dscp_cos_dscp_cos_map_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"qos",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"qos\"",
",",
"xmlns",
"=",
"\"urn:brocade.... | 44.083333 | 16.166667 |
def _resolve_lookup_chain(self, chain, instance):
"""Return the value of inst.chain[0].chain[1].chain[...].chain[n]."""
value = instance
for link in chain:
value = getattr(value, link)
return value | [
"def",
"_resolve_lookup_chain",
"(",
"self",
",",
"chain",
",",
"instance",
")",
":",
"value",
"=",
"instance",
"for",
"link",
"in",
"chain",
":",
"value",
"=",
"getattr",
"(",
"value",
",",
"link",
")",
"return",
"value"
] | 29.5 | 17.375 |
def sniff_extension(file_path,verbose=True):
'''sniff_extension will attempt to determine the file type based on the extension,
and return the proper mimetype
:param file_path: the full path to the file to sniff
:param verbose: print stuff out
'''
mime_types = { "xls": 'application/vnd.ms-exc... | [
"def",
"sniff_extension",
"(",
"file_path",
",",
"verbose",
"=",
"True",
")",
":",
"mime_types",
"=",
"{",
"\"xls\"",
":",
"'application/vnd.ms-excel'",
",",
"\"xlsx\"",
":",
"'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'",
",",
"\"xml\"",
":",
"'t... | 41.76087 | 14.934783 |
def _keynat(string):
"""A natural sort helper function for sort() and sorted()
without using regular expression.
"""
r = []
for c in string:
if c.isdigit():
if r and isinstance(r[-1], int):
r[-1] = r[-1] * 10 + int(c)
else:
r.append(int... | [
"def",
"_keynat",
"(",
"string",
")",
":",
"r",
"=",
"[",
"]",
"for",
"c",
"in",
"string",
":",
"if",
"c",
".",
"isdigit",
"(",
")",
":",
"if",
"r",
"and",
"isinstance",
"(",
"r",
"[",
"-",
"1",
"]",
",",
"int",
")",
":",
"r",
"[",
"-",
"... | 26.5 | 13.642857 |
def set_max_entries(self):
"""
Define the maximum of entries for computing the priority
of each items later.
"""
if self.cache:
self.max_entries = float(max([i[0] for i in self.cache.values()])) | [
"def",
"set_max_entries",
"(",
"self",
")",
":",
"if",
"self",
".",
"cache",
":",
"self",
".",
"max_entries",
"=",
"float",
"(",
"max",
"(",
"[",
"i",
"[",
"0",
"]",
"for",
"i",
"in",
"self",
".",
"cache",
".",
"values",
"(",
")",
"]",
")",
")"... | 34.285714 | 15.142857 |
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 Pyramid(pos=(0, 0, 0), s=1, height=1, axis=(0, 0, 1), c="dg", alpha=1):
"""
Build a pyramid of specified base size `s` and `height`, centered at `pos`.
"""
return Cone(pos, s, height, axis, c, alpha, 4) | [
"def",
"Pyramid",
"(",
"pos",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"s",
"=",
"1",
",",
"height",
"=",
"1",
",",
"axis",
"=",
"(",
"0",
",",
"0",
",",
"1",
")",
",",
"c",
"=",
"\"dg\"",
",",
"alpha",
"=",
"1",
")",
":",
"return",... | 43.6 | 16.8 |
def get_headers_global():
"""Defines the so-called global column headings for Arbin .res-files"""
headers = dict()
# - global column headings (specific for Arbin)
headers["applications_path_txt"] = 'Applications_Path'
headers["channel_index_txt"] = 'Channel_Index'
headers... | [
"def",
"get_headers_global",
"(",
")",
":",
"headers",
"=",
"dict",
"(",
")",
"# - global column headings (specific for Arbin)",
"headers",
"[",
"\"applications_path_txt\"",
"]",
"=",
"'Applications_Path'",
"headers",
"[",
"\"channel_index_txt\"",
"]",
"=",
"'Channel_Inde... | 61.931034 | 23.965517 |
def dense_to_sparse(x, ignore_value=None, name=None):
"""Converts dense `Tensor` to `SparseTensor`, dropping `ignore_value` cells.
Args:
x: A `Tensor`.
ignore_value: Entries in `x` equal to this value will be
absent from the return `SparseTensor`. If `None`, default value of
`x` dtype will be u... | [
"def",
"dense_to_sparse",
"(",
"x",
",",
"ignore_value",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"# Copied (with modifications) from:",
"# tensorflow/contrib/layers/python/ops/sparse_ops.py.",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
... | 40.96875 | 21.125 |
def _mirrorStructure(dictionary, value):
''' create a new nested dictionary object with the same structure as
'dictionary', but with all scalar values replaced with 'value'
'''
result = type(dictionary)()
for k in dictionary.keys():
if isinstance(dictionary[k], dict):
result[... | [
"def",
"_mirrorStructure",
"(",
"dictionary",
",",
"value",
")",
":",
"result",
"=",
"type",
"(",
"dictionary",
")",
"(",
")",
"for",
"k",
"in",
"dictionary",
".",
"keys",
"(",
")",
":",
"if",
"isinstance",
"(",
"dictionary",
"[",
"k",
"]",
",",
"dic... | 37.727273 | 18.090909 |
def spent_outputs(self):
"""Tuple of :obj:`dict`: Inputs of this transaction. Each input
is represented as a dictionary containing a transaction id and
output index.
"""
return (
input_.fulfills.to_dict()
for input_ in self.inputs if input_.fulfills
... | [
"def",
"spent_outputs",
"(",
"self",
")",
":",
"return",
"(",
"input_",
".",
"fulfills",
".",
"to_dict",
"(",
")",
"for",
"input_",
"in",
"self",
".",
"inputs",
"if",
"input_",
".",
"fulfills",
")"
] | 35 | 15.444444 |
def inventory(self, modules_inventory=False):
""" Get chassis inventory.
:param modules_inventory: True - read modules inventory, false - don't read.
"""
self.c_info = self.get_attributes()
for m_index, m_portcounts in enumerate(self.c_info['c_portcounts'].split()):
... | [
"def",
"inventory",
"(",
"self",
",",
"modules_inventory",
"=",
"False",
")",
":",
"self",
".",
"c_info",
"=",
"self",
".",
"get_attributes",
"(",
")",
"for",
"m_index",
",",
"m_portcounts",
"in",
"enumerate",
"(",
"self",
".",
"c_info",
"[",
"'c_portcount... | 39.333333 | 17.583333 |
def unit(self):
""" Returns the unit attribute of the underlying ncdf variable.
If the units has a length (e.g is a list) and has precisely one element per field,
the unit for this field is returned.
"""
unit = ncVarUnit(self._ncVar)
fieldNames = self._ncVar.dtyp... | [
"def",
"unit",
"(",
"self",
")",
":",
"unit",
"=",
"ncVarUnit",
"(",
"self",
".",
"_ncVar",
")",
"fieldNames",
"=",
"self",
".",
"_ncVar",
".",
"dtype",
".",
"names",
"# If the missing value attribute is a list with the same length as the number of fields,",
"# return... | 42.0625 | 22.4375 |
def auto_delete_files_on_instance_delete(instance: Any,
fieldnames: Iterable[str]) -> None:
"""
Deletes files from filesystem when object is deleted.
"""
for fieldname in fieldnames:
filefield = getattr(instance, fieldname, None)
if filefield:
... | [
"def",
"auto_delete_files_on_instance_delete",
"(",
"instance",
":",
"Any",
",",
"fieldnames",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"fieldname",
"in",
"fieldnames",
":",
"filefield",
"=",
"getattr",
"(",
"instance",
",",
"fieldname"... | 39.6 | 11.6 |
def geometry(self):
"""returns the feature geometry"""
if arcpyFound:
if self._geom is None:
if 'feature' in self._dict:
self._geom = arcpy.AsShape(self._dict['feature']['geometry'], esri_json=True)
elif 'geometry' in self._dict:
... | [
"def",
"geometry",
"(",
"self",
")",
":",
"if",
"arcpyFound",
":",
"if",
"self",
".",
"_geom",
"is",
"None",
":",
"if",
"'feature'",
"in",
"self",
".",
"_dict",
":",
"self",
".",
"_geom",
"=",
"arcpy",
".",
"AsShape",
"(",
"self",
".",
"_dict",
"["... | 43.7 | 18.9 |
def a10_allocate_ip_from_dhcp_range(self, subnet, interface_id, mac, port_id):
"""Search for an available IP.addr from unallocated nmodels.IPAllocationPool range.
If no addresses are available then an error is raised. Returns the address as a string.
This search is conducted by a difference of t... | [
"def",
"a10_allocate_ip_from_dhcp_range",
"(",
"self",
",",
"subnet",
",",
"interface_id",
",",
"mac",
",",
"port_id",
")",
":",
"subnet_id",
"=",
"subnet",
"[",
"\"id\"",
"]",
"network_id",
"=",
"subnet",
"[",
"\"network_id\"",
"]",
"iprange_result",
"=",
"se... | 41.612903 | 23.870968 |
def minimum_spanning_subtree(self):
'''Returns the (undirected) minimum spanning tree subgraph.'''
dist = self.matrix('dense', copy=True)
dist[dist==0] = np.inf
np.fill_diagonal(dist, 0)
mst = ssc.minimum_spanning_tree(dist)
return self.__class__.from_adj_matrix(mst + mst.T) | [
"def",
"minimum_spanning_subtree",
"(",
"self",
")",
":",
"dist",
"=",
"self",
".",
"matrix",
"(",
"'dense'",
",",
"copy",
"=",
"True",
")",
"dist",
"[",
"dist",
"==",
"0",
"]",
"=",
"np",
".",
"inf",
"np",
".",
"fill_diagonal",
"(",
"dist",
",",
"... | 41.857143 | 10.428571 |
def parse_args(self):
"""Parses the command-line arguments to this script, and parse the given
configuration file (if any). Returns a Namespace containing the resulting
options. This method will use the configuration file parameters if any exist,
otherwise it will use the command-line arguments... | [
"def",
"parse_args",
"(",
"self",
")",
":",
"# Parse sys.argv",
"cli_args",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
")",
"if",
"cli_args",
".",
"config",
":",
"# Parse the configuration file",
"config_file",
"=",
"open",
"(",
"cli_args",
".",
"conf... | 37.97619 | 19.97619 |
def get(self):
"""
Returns the value for the slot.
:return: the entry value
"""
values = [e.get() for e in self._entries]
if len(self._entries) == 1:
return values[0]
else:
return values | [
"def",
"get",
"(",
"self",
")",
":",
"values",
"=",
"[",
"e",
".",
"get",
"(",
")",
"for",
"e",
"in",
"self",
".",
"_entries",
"]",
"if",
"len",
"(",
"self",
".",
"_entries",
")",
"==",
"1",
":",
"return",
"values",
"[",
"0",
"]",
"else",
":"... | 25.7 | 10.3 |
def _patch_argument_parser(self):
'''
Since argparse doesn't support much introspection, we monkey-patch it to replace the parse_known_args method and
all actions with hooks that tell us which action was last taken or about to be taken, and let us have the parser
figure out which subpars... | [
"def",
"_patch_argument_parser",
"(",
"self",
")",
":",
"active_parsers",
"=",
"[",
"self",
".",
"_parser",
"]",
"parsed_args",
"=",
"argparse",
".",
"Namespace",
"(",
")",
"visited_actions",
"=",
"[",
"]",
"def",
"patch",
"(",
"parser",
")",
":",
"parser"... | 52.644444 | 27.977778 |
def _add_thousand_g(self, variant_obj, info_dict):
"""Add the thousand genomes frequency
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary
"""
thousand_g = info_dict.get('1000GAF')
if thousand_g:
lo... | [
"def",
"_add_thousand_g",
"(",
"self",
",",
"variant_obj",
",",
"info_dict",
")",
":",
"thousand_g",
"=",
"info_dict",
".",
"get",
"(",
"'1000GAF'",
")",
"if",
"thousand_g",
":",
"logger",
".",
"debug",
"(",
"\"Updating thousand_g to: {0}\"",
".",
"format",
"(... | 37.071429 | 16.071429 |
def revisionId(self):
"""
revisionId differs from id, it is details of implementation use self.id
:return: RevisionId
"""
log.warning("'RevisionId' requested, ensure that you are don't need 'id'")
revision_id = self.json()['revisionId']
assert revision_id == self.... | [
"def",
"revisionId",
"(",
"self",
")",
":",
"log",
".",
"warning",
"(",
"\"'RevisionId' requested, ensure that you are don't need 'id'\"",
")",
"revision_id",
"=",
"self",
".",
"json",
"(",
")",
"[",
"'revisionId'",
"]",
"assert",
"revision_id",
"==",
"self",
".",... | 45.888889 | 22.555556 |
def get_current_info(self, symbolList, columns=None):
"""get_current_info() uses the yahoo.finance.quotes datatable to get all of the stock information presented in the main table on a typical stock page
and a bunch of data from the key statistics page.
"""
response = self.select('yahoo... | [
"def",
"get_current_info",
"(",
"self",
",",
"symbolList",
",",
"columns",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"select",
"(",
"'yahoo.finance.quotes'",
",",
"columns",
")",
".",
"where",
"(",
"[",
"'symbol'",
",",
"'in'",
",",
"symbolList"... | 66.333333 | 17.166667 |
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
... | [
"def",
"list_nodes_full",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_full function must be called with -f or '",
"'--function.'",
")",
"if",
"not",
"conn",
... | 21.95 | 24.15 |
def GetDateRangeWithOrigins(self):
"""Returns a tuple of (earliest, latest, earliest_origin, latest_origin)
dates on which the service periods in the schedule define service, in
YYYYMMDD form.
The origins specify where the earliest or latest dates come from. In
particular, whether the date is a regu... | [
"def",
"GetDateRangeWithOrigins",
"(",
"self",
")",
":",
"period_list",
"=",
"self",
".",
"GetServicePeriodList",
"(",
")",
"ranges",
"=",
"[",
"period",
".",
"GetDateRange",
"(",
")",
"for",
"period",
"in",
"period_list",
"]",
"starts",
"=",
"filter",
"(",
... | 46.657895 | 22.789474 |
def business_hours_schedule_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/schedules#delete-a-schedule"
api_path = "/api/v2/business_hours/schedules/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwargs) | [
"def",
"business_hours_schedule_delete",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/business_hours/schedules/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
... | 61.2 | 21.2 |
def subscribe(self, frame):
"""
Handle the SUBSCRIBE command: Adds this connection to destination.
"""
ack = frame.headers.get('ack')
reliable = ack and ack.lower() == 'client'
self.engine.connection.reliable_subscriber = reliable
dest = frame.headers.get('desti... | [
"def",
"subscribe",
"(",
"self",
",",
"frame",
")",
":",
"ack",
"=",
"frame",
".",
"headers",
".",
"get",
"(",
"'ack'",
")",
"reliable",
"=",
"ack",
"and",
"ack",
".",
"lower",
"(",
")",
"==",
"'client'",
"self",
".",
"engine",
".",
"connection",
"... | 36.529412 | 21.588235 |
def parse_redir(self, redir_cmd):
""" Parse a command :redir content. """
redir_cmd_str = redir_cmd['str']
matched = re.match(r'redir?!?\s*(=>>?\s*)(\S+)', redir_cmd_str)
if matched:
redir_cmd_op = matched.group(1)
redir_cmd_body = matched.group(2)
a... | [
"def",
"parse_redir",
"(",
"self",
",",
"redir_cmd",
")",
":",
"redir_cmd_str",
"=",
"redir_cmd",
"[",
"'str'",
"]",
"matched",
"=",
"re",
".",
"match",
"(",
"r'redir?!?\\s*(=>>?\\s*)(\\S+)'",
",",
"redir_cmd_str",
")",
"if",
"matched",
":",
"redir_cmd_op",
"=... | 32.2 | 19.625 |
def populationStability(vectors, numSamples=None):
"""
Returns the stability for the population averaged over multiple time steps
Parameters:
-----------------------------------------------
vectors: the vectors for which the stability is calculated
numSamples the number of time steps where ... | [
"def",
"populationStability",
"(",
"vectors",
",",
"numSamples",
"=",
"None",
")",
":",
"# ----------------------------------------------------------------------",
"# Calculate the stability",
"numVectors",
"=",
"len",
"(",
"vectors",
")",
"if",
"numSamples",
"is",
"None",
... | 28.558824 | 23.088235 |
def ide(self):
"""
Generates a IDE number (9 digits).
http://www.bfs.admin.ch/bfs/portal/fr/index/themen/00/05/blank/03/02.html
"""
def _checksum(digits):
factors = (5, 4, 3, 2, 7, 6, 5, 4)
sum_ = 0
for i in range(len(digits)):
... | [
"def",
"ide",
"(",
"self",
")",
":",
"def",
"_checksum",
"(",
"digits",
")",
":",
"factors",
"=",
"(",
"5",
",",
"4",
",",
"3",
",",
"2",
",",
"7",
",",
"6",
",",
"5",
",",
"4",
")",
"sum_",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len"... | 37.857143 | 14.428571 |
def _mark_candidate_indexes(lines, candidate):
"""Mark candidate indexes with markers
Markers:
* c - line that could be a signature line
* l - long line
* d - line that starts with dashes but has other chars as well
>>> _mark_candidate_lines(['Some text', '', '-', 'Bob'], [0, 2, 3])
'cdc'... | [
"def",
"_mark_candidate_indexes",
"(",
"lines",
",",
"candidate",
")",
":",
"# at first consider everything to be potential signature lines",
"markers",
"=",
"list",
"(",
"'c'",
"*",
"len",
"(",
"candidate",
")",
")",
"# mark lines starting from bottom up",
"for",
"i",
... | 31.48 | 19.92 |
def find(name, path=(), parent=None):
"""
Return a Module instance describing the first matching module found on the
search path.
:param str name:
Module name.
:param list path:
List of directory names to search for the module.
:param Module parent:
Optional module paren... | [
"def",
"find",
"(",
"name",
",",
"path",
"=",
"(",
")",
",",
"parent",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"path",
",",
"tuple",
")",
"head",
",",
"_",
",",
"tail",
"=",
"name",
".",
"partition",
"(",
"'.'",
")",
"try",
":",
"tu... | 31.710526 | 19.131579 |
def cli(ctx, obj):
"""Show Alerta server and client versions."""
client = obj['client']
click.echo('alerta {}'.format(client.mgmt_status()['version']))
click.echo('alerta client {}'.format(client_version))
click.echo('requests {}'.format(requests_version))
click.echo('click {}'.format(click.__ve... | [
"def",
"cli",
"(",
"ctx",
",",
"obj",
")",
":",
"client",
"=",
"obj",
"[",
"'client'",
"]",
"click",
".",
"echo",
"(",
"'alerta {}'",
".",
"format",
"(",
"client",
".",
"mgmt_status",
"(",
")",
"[",
"'version'",
"]",
")",
")",
"click",
".",
"echo",... | 42.125 | 16.5 |
def list_musts(options):
"""Construct the list of 'MUST' validators to be run by the validator.
"""
validator_list = [
timestamp,
timestamp_compare,
observable_timestamp_compare,
object_marking_circular_refs,
granular_markings_circular_refs,
marking_selector_s... | [
"def",
"list_musts",
"(",
"options",
")",
":",
"validator_list",
"=",
"[",
"timestamp",
",",
"timestamp_compare",
",",
"observable_timestamp_compare",
",",
"object_marking_circular_refs",
",",
"granular_markings_circular_refs",
",",
"marking_selector_syntax",
",",
"observab... | 25.571429 | 15.25 |
def _trampoline(name, module, *args, **kwargs):
"""Trampoline function for decorators.
Lookups the function between the registered ones;
if not found, forces its registering and then executes it.
"""
function = _function_lookup(name, module)
return function(*args, **kwargs) | [
"def",
"_trampoline",
"(",
"name",
",",
"module",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"function",
"=",
"_function_lookup",
"(",
"name",
",",
"module",
")",
"return",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 29.2 | 17.1 |
def get_by_id(self, id_networkv6):
"""Get IPv6 network
:param id_networkv4: ID for NetworkIPv6
:return: IPv6 Network
"""
uri = 'api/networkv4/%s/' % id_networkv6
return super(ApiNetworkIPv6, self).get(uri) | [
"def",
"get_by_id",
"(",
"self",
",",
"id_networkv6",
")",
":",
"uri",
"=",
"'api/networkv4/%s/'",
"%",
"id_networkv6",
"return",
"super",
"(",
"ApiNetworkIPv6",
",",
"self",
")",
".",
"get",
"(",
"uri",
")"
] | 24.7 | 16.3 |
def text_array_to_html(text_arr):
"""Take a numpy.ndarray containing strings, and convert it into html.
If the ndarray contains a single scalar string, that string is converted to
html via our sanitized markdown parser. If it contains an array of strings,
the strings are individually converted to html and then... | [
"def",
"text_array_to_html",
"(",
"text_arr",
")",
":",
"if",
"not",
"text_arr",
".",
"shape",
":",
"# It is a scalar. No need to put it in a table, just apply markdown",
"return",
"plugin_util",
".",
"markdown_to_safe_html",
"(",
"np",
".",
"asscalar",
"(",
"text_arr",
... | 38.966667 | 23.1 |
def replace_zip_codes_geo_zone_by_id(cls, zip_codes_geo_zone_id, zip_codes_geo_zone, **kwargs):
"""Replace ZipCodesGeoZone
Replace all attributes of ZipCodesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
... | [
"def",
"replace_zip_codes_geo_zone_by_id",
"(",
"cls",
",",
"zip_codes_geo_zone_id",
",",
"zip_codes_geo_zone",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
... | 53.363636 | 29.772727 |
def attach_alternative(self, content, mimetype=None):
"""Attach an alternative content representation."""
self.attach(content=content, mimetype=mimetype) | [
"def",
"attach_alternative",
"(",
"self",
",",
"content",
",",
"mimetype",
"=",
"None",
")",
":",
"self",
".",
"attach",
"(",
"content",
"=",
"content",
",",
"mimetype",
"=",
"mimetype",
")"
] | 56.333333 | 9.666667 |
def _compare_strings(cls, source, target):
"""
Compares a source string to a target string,
and addresses the condition in which the source string
includes unquoted special characters.
It performs a simple regular expression match,
with the assumption that (as required) ... | [
"def",
"_compare_strings",
"(",
"cls",
",",
"source",
",",
"target",
")",
":",
"start",
"=",
"0",
"end",
"=",
"len",
"(",
"source",
")",
"begins",
"=",
"0",
"ends",
"=",
"0",
"# Reading of initial wildcard in source",
"if",
"source",
".",
"startswith",
"("... | 33.013333 | 20.506667 |
def multithread_predict_dataflow(dataflows, model_funcs):
"""
Running multiple `predict_dataflow` in multiple threads, and aggregate the results.
Args:
dataflows: a list of DataFlow to be used in :func:`predict_dataflow`
model_funcs: a list of callable to be used in :func:`predict_dataflow`... | [
"def",
"multithread_predict_dataflow",
"(",
"dataflows",
",",
"model_funcs",
")",
":",
"num_worker",
"=",
"len",
"(",
"model_funcs",
")",
"assert",
"len",
"(",
"dataflows",
")",
"==",
"num_worker",
"if",
"num_worker",
"==",
"1",
":",
"return",
"predict_dataflow"... | 45.541667 | 24.791667 |
def resolve_one_step(self):
"""
Resolves model references.
"""
metamodel = self.parser.metamodel
current_crossrefs = self.parser._crossrefs
# print("DEBUG: Current crossrefs #: {}".
# format(len(current_crossrefs)))
new_crossrefs = []
self.de... | [
"def",
"resolve_one_step",
"(",
"self",
")",
":",
"metamodel",
"=",
"self",
".",
"parser",
".",
"metamodel",
"current_crossrefs",
"=",
"self",
".",
"parser",
".",
"_crossrefs",
"# print(\"DEBUG: Current crossrefs #: {}\".",
"# format(len(current_crossrefs)))",
"new_c... | 46.225 | 17.625 |
def _handle_presentation(self, msg):
"""Process a MQTT presentation message."""
ret_msg = handle_presentation(msg)
if msg.child_id == 255 or ret_msg is None:
return
# this is a presentation of a child sensor
topics = [
'{}/{}/{}/{}/+/+'.format(
... | [
"def",
"_handle_presentation",
"(",
"self",
",",
"msg",
")",
":",
"ret_msg",
"=",
"handle_presentation",
"(",
"msg",
")",
"if",
"msg",
".",
"child_id",
"==",
"255",
"or",
"ret_msg",
"is",
"None",
":",
"return",
"# this is a presentation of a child sensor",
"topi... | 41.588235 | 12.411765 |
def _get_type(self, value):
"""Get the data type for *value*."""
if value is None:
return type(None)
elif type(value) in int_types:
return int
elif type(value) in float_types:
return float
elif isinstance(value, binary_type):
return... | [
"def",
"_get_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"type",
"(",
"None",
")",
"elif",
"type",
"(",
"value",
")",
"in",
"int_types",
":",
"return",
"int",
"elif",
"type",
"(",
"value",
")",
"in",
"flo... | 30.333333 | 10.666667 |
def parse_field_path(api_repr):
"""Parse a **field path** from into a list of nested field names.
See :func:`field_path` for more on **field paths**.
Args:
api_repr (str):
The unique Firestore api representation which consists of
either simple or UTF-8 field names. It canno... | [
"def",
"parse_field_path",
"(",
"api_repr",
")",
":",
"# code dredged back up from",
"# https://github.com/googleapis/google-cloud-python/pull/5109/files",
"field_names",
"=",
"[",
"]",
"for",
"field_name",
"in",
"split_field_path",
"(",
"api_repr",
")",
":",
"# non-simple fi... | 41 | 20.62963 |
def CreateGaugeMetadata(metric_name,
value_type,
fields=None,
docstring=None,
units=None):
"""Helper function for creating MetricMetadata for gauge metrics."""
return rdf_stats.MetricMetadata(
varname=metric_name,
... | [
"def",
"CreateGaugeMetadata",
"(",
"metric_name",
",",
"value_type",
",",
"fields",
"=",
"None",
",",
"docstring",
"=",
"None",
",",
"units",
"=",
"None",
")",
":",
"return",
"rdf_stats",
".",
"MetricMetadata",
"(",
"varname",
"=",
"metric_name",
",",
"metri... | 41.461538 | 10.538462 |
def __replace(config, wildcards, config_file):
"""For each kvp in config, do wildcard substitution on the values"""
for config_key in config:
config_value = config[config_key]
original_value = config_value
if isinstance(config_value, str):
for token in wildcards:
if wildcards[token]:
... | [
"def",
"__replace",
"(",
"config",
",",
"wildcards",
",",
"config_file",
")",
":",
"for",
"config_key",
"in",
"config",
":",
"config_value",
"=",
"config",
"[",
"config_key",
"]",
"original_value",
"=",
"config_value",
"if",
"isinstance",
"(",
"config_value",
... | 45.333333 | 16.666667 |
def symbolic(self, A):
"""
Return the symbolic factorization of sparse matrix ``A``
Parameters
----------
sparselib
Library name in ``umfpack`` and ``klu``
A
Sparse matrix
Returns
symbolic factorization
-------
""... | [
"def",
"symbolic",
"(",
"self",
",",
"A",
")",
":",
"if",
"self",
".",
"sparselib",
"==",
"'umfpack'",
":",
"return",
"umfpack",
".",
"symbolic",
"(",
"A",
")",
"elif",
"self",
".",
"sparselib",
"==",
"'klu'",
":",
"return",
"klu",
".",
"symbolic",
"... | 20.636364 | 19.909091 |
def AppendData(self, data, custom_properties=None):
"""Appends new data to the table.
Data is appended in rows. Data must comply with
the table schema passed in to __init__(). See CoerceValue() for a list
of acceptable data types. See the class documentation for more information
and examples of sch... | [
"def",
"AppendData",
"(",
"self",
",",
"data",
",",
"custom_properties",
"=",
"None",
")",
":",
"# If the maximal depth is 0, we simply iterate over the data table",
"# lines and insert them using _InnerAppendData. Otherwise, we simply",
"# let the _InnerAppendData handle all the levels.... | 42.88 | 23.44 |
def run(self, callback=None, limit=0):
"""
Start pcap's loop over the interface, calling the given callback for each packet
:param callback: a function receiving (win_pcap, param, header, pkt_data) for each packet intercepted
:param limit: how many packets to capture (A value of -1 or 0 ... | [
"def",
"run",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"limit",
"=",
"0",
")",
":",
"if",
"self",
".",
"_handle",
"is",
"None",
":",
"raise",
"self",
".",
"DeviceIsNotOpen",
"(",
")",
"# Set new callback",
"self",
".",
"_callback",
"=",
"callbac... | 49.916667 | 19.916667 |
def get_name(model_id):
"""
Get the name for a model.
:returns str: The model's name. If the id has no associated name, then "id = {ID} (no name)" is returned.
"""
name = _names.get(model_id)
if name is None:
name = 'id = %s (no name)' % str(model_id)
return name | [
"def",
"get_name",
"(",
"model_id",
")",
":",
"name",
"=",
"_names",
".",
"get",
"(",
"model_id",
")",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"'id = %s (no name)'",
"%",
"str",
"(",
"model_id",
")",
"return",
"name"
] | 29.2 | 20.2 |
def get_component_types(topic_id, remoteci_id, db_conn=None):
"""Returns either the topic component types or the rconfigration's
component types."""
db_conn = db_conn or flask.g.db_conn
rconfiguration = remotecis.get_remoteci_configuration(topic_id,
... | [
"def",
"get_component_types",
"(",
"topic_id",
",",
"remoteci_id",
",",
"db_conn",
"=",
"None",
")",
":",
"db_conn",
"=",
"db_conn",
"or",
"flask",
".",
"g",
".",
"db_conn",
"rconfiguration",
"=",
"remotecis",
".",
"get_remoteci_configuration",
"(",
"topic_id",
... | 45.578947 | 21 |
def download_and_parse_mnist_file(fname, target_dir=None, force=False):
"""Download the IDX file named fname from the URL specified in dataset_url
and return it as a numpy array.
Parameters
----------
fname : str
File name to download and parse
target_dir : str
Directory where ... | [
"def",
"download_and_parse_mnist_file",
"(",
"fname",
",",
"target_dir",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"fname",
"=",
"download_file",
"(",
"fname",
",",
"target_dir",
"=",
"target_dir",
",",
"force",
"=",
"force",
")",
"fopen",
"=",
"g... | 30 | 21.375 |
def close_streaming_interface(self):
"""Called when someone closes the streaming interface to the device.
This method will automatically notify sensor_graph that there is a no
longer a streaming interface opened.
"""
super(ReferenceDevice, self).close_streaming_interface()
... | [
"def",
"close_streaming_interface",
"(",
"self",
")",
":",
"super",
"(",
"ReferenceDevice",
",",
"self",
")",
".",
"close_streaming_interface",
"(",
")",
"self",
".",
"rpc",
"(",
"8",
",",
"rpcs",
".",
"SG_GRAPH_INPUT",
",",
"8",
",",
"streams",
".",
"COMM... | 37.7 | 21.8 |
def add_toc_entry(self, title, level, slide_number):
""" Adds a new entry to current presentation Table of Contents.
"""
self.__toc.append({'title': title, 'number': slide_number,
'level': level}) | [
"def",
"add_toc_entry",
"(",
"self",
",",
"title",
",",
"level",
",",
"slide_number",
")",
":",
"self",
".",
"__toc",
".",
"append",
"(",
"{",
"'title'",
":",
"title",
",",
"'number'",
":",
"slide_number",
",",
"'level'",
":",
"level",
"}",
")"
] | 48.6 | 8.2 |
def _increase_logging(self, loggers):
"""! @brief Increase logging level for a set of subloggers."""
if self._log_level_delta <= 0:
level = max(1, self._default_log_level + self._log_level_delta - 10)
for logger in loggers:
logging.getLogger(logger).setLevel(level... | [
"def",
"_increase_logging",
"(",
"self",
",",
"loggers",
")",
":",
"if",
"self",
".",
"_log_level_delta",
"<=",
"0",
":",
"level",
"=",
"max",
"(",
"1",
",",
"self",
".",
"_default_log_level",
"+",
"self",
".",
"_log_level_delta",
"-",
"10",
")",
"for",
... | 52.666667 | 11.333333 |
def setCustomColorRamp(self, colors=[], interpolatedPoints=10):
"""
Accepts a list of RGB tuples and interpolates between them to create a custom color ramp.
Returns the color ramp as a list of RGB tuples.
"""
self._colorRamp = ColorRampGenerator.generateCustomColorRamp(colors, i... | [
"def",
"setCustomColorRamp",
"(",
"self",
",",
"colors",
"=",
"[",
"]",
",",
"interpolatedPoints",
"=",
"10",
")",
":",
"self",
".",
"_colorRamp",
"=",
"ColorRampGenerator",
".",
"generateCustomColorRamp",
"(",
"colors",
",",
"interpolatedPoints",
")"
] | 55.5 | 25.166667 |
def can_access_api(self):
"""
:return: True when we can access the REST API
"""
try:
version_dict = self.get_version()
except Exception, e:
msg = 'An exception was raised when connecting to REST API: "%s"'
raise APIException(msg % e)
el... | [
"def",
"can_access_api",
"(",
"self",
")",
":",
"try",
":",
"version_dict",
"=",
"self",
".",
"get_version",
"(",
")",
"except",
"Exception",
",",
"e",
":",
"msg",
"=",
"'An exception was raised when connecting to REST API: \"%s\"'",
"raise",
"APIException",
"(",
... | 32.72 | 14.16 |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(PRC... | [
"def",
"fix_config",
"(",
"self",
",",
"options",
")",
":",
"options",
"=",
"super",
"(",
"PRC",
",",
"self",
")",
".",
"fix_config",
"(",
"options",
")",
"opt",
"=",
"\"class_index\"",
"if",
"opt",
"not",
"in",
"options",
":",
"options",
"[",
"opt",
... | 31.547619 | 19.309524 |
def separate(df, column, into, sep="[\W_]+", remove=True, convert=False,
extra='drop', fill='right'):
"""
Splits columns into multiple columns.
Args:
df (pandas.DataFrame): DataFrame passed in through the pipe.
column (str, symbolic): Label of column to split.
into (lis... | [
"def",
"separate",
"(",
"df",
",",
"column",
",",
"into",
",",
"sep",
"=",
"\"[\\W_]+\"",
",",
"remove",
"=",
"True",
",",
"convert",
"=",
"False",
",",
"extra",
"=",
"'drop'",
",",
"fill",
"=",
"'right'",
")",
":",
"assert",
"isinstance",
"(",
"into... | 38.063492 | 23.904762 |
def update_currency_by_id(cls, currency_id, currency, **kwargs):
"""Update Currency
Update attributes of Currency
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_currency_by_id(currency... | [
"def",
"update_currency_by_id",
"(",
"cls",
",",
"currency_id",
",",
"currency",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"... | 44.636364 | 22.318182 |
def sphere(radius=0.5, sectors=32, rings=16) -> VAO:
"""
Creates a sphere.
Keyword Args:
radius (float): Radius or the sphere
rings (int): number or horizontal rings
sectors (int): number of vertical segments
Returns:
A :py:class:`demosys.opengl.vao.VAO` instance
""... | [
"def",
"sphere",
"(",
"radius",
"=",
"0.5",
",",
"sectors",
"=",
"32",
",",
"rings",
"=",
"16",
")",
"->",
"VAO",
":",
"R",
"=",
"1.0",
"/",
"(",
"rings",
"-",
"1",
")",
"S",
"=",
"1.0",
"/",
"(",
"sectors",
"-",
"1",
")",
"vertices",
"=",
... | 29.776119 | 18.044776 |
def cell_value(self, column_family_id, column, index=0):
"""Get a single cell value stored on this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_cell_value]
:end-before: [END bigtable_row_cell_value]
Args:
... | [
"def",
"cell_value",
"(",
"self",
",",
"column_family_id",
",",
"column",
",",
"index",
"=",
"0",
")",
":",
"cells",
"=",
"self",
".",
"find_cells",
"(",
"column_family_id",
",",
"column",
")",
"try",
":",
"cell",
"=",
"cells",
"[",
"index",
"]",
"exce... | 39.175 | 23.725 |
def convert(self, converters, in_place=False):
"""
Applies transformations to the dataset.
:param converters: A dictionary specifying the function to apply to each field. If a field is missing from the dictionary, then it will not be transformed.
:param in_place: Whether to perform the... | [
"def",
"convert",
"(",
"self",
",",
"converters",
",",
"in_place",
"=",
"False",
")",
":",
"dataset",
"=",
"self",
"if",
"in_place",
"else",
"self",
".",
"__class__",
"(",
"OrderedDict",
"(",
"[",
"(",
"name",
",",
"data",
"[",
":",
"]",
")",
"for",
... | 52.058824 | 31.705882 |
def mkdirs(remote_dir, use_sudo=False):
"""
Wrapper around mkdir -pv
Returns a list of directories created
"""
func = use_sudo and sudo or run
result = func(' '.join(['mkdir -pv',remote_dir])).split('\n')
#extract dir list from ["mkdir: created directory `example.com/some/dir'"]
if ... | [
"def",
"mkdirs",
"(",
"remote_dir",
",",
"use_sudo",
"=",
"False",
")",
":",
"func",
"=",
"use_sudo",
"and",
"sudo",
"or",
"run",
"result",
"=",
"func",
"(",
"' '",
".",
"join",
"(",
"[",
"'mkdir -pv'",
",",
"remote_dir",
"]",
")",
")",
".",
"split",... | 36.181818 | 16.181818 |
def update(self):
"""Update the FS stats using the input method."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
# Grab the stats using the psutil disk_partitions
# If 'a... | [
"def",
"update",
"(",
"self",
")",
":",
"# Init new stats",
"stats",
"=",
"self",
".",
"get_init_value",
"(",
")",
"if",
"self",
".",
"input_method",
"==",
"'local'",
":",
"# Update stats using the standard system lib",
"# Grab the stats using the psutil disk_partitions",... | 42.797872 | 17.787234 |
def rm_compressed(ctx, dataset, kwargs):
"removes the compressed files"
kwargs = parse_kwargs(kwargs)
data(dataset, **ctx.obj).rm_compressed(**kwargs) | [
"def",
"rm_compressed",
"(",
"ctx",
",",
"dataset",
",",
"kwargs",
")",
":",
"kwargs",
"=",
"parse_kwargs",
"(",
"kwargs",
")",
"data",
"(",
"dataset",
",",
"*",
"*",
"ctx",
".",
"obj",
")",
".",
"rm_compressed",
"(",
"*",
"*",
"kwargs",
")"
] | 31.8 | 13 |
def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
"""
Takes a number of wei and converts it to any other ether unit.
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if number == 0... | [
"def",
"from_wei",
"(",
"number",
":",
"int",
",",
"unit",
":",
"str",
")",
"->",
"Union",
"[",
"int",
",",
"decimal",
".",
"Decimal",
"]",
":",
"if",
"unit",
".",
"lower",
"(",
")",
"not",
"in",
"units",
":",
"raise",
"ValueError",
"(",
"\"Unknown... | 28.478261 | 21.434783 |
def handle(self, connection_id, message_content):
"""
The simplest authorization type will be Trust. If Trust authorization
is enabled, the validator will trust the connection and approve any
roles requested that are available on that endpoint. If the requester
wishes to gain acc... | [
"def",
"handle",
"(",
"self",
",",
"connection_id",
",",
"message_content",
")",
":",
"if",
"self",
".",
"_network",
".",
"get_connection_status",
"(",
"connection_id",
")",
"!=",
"ConnectionStatus",
".",
"CONNECTION_REQUEST",
":",
"LOGGER",
".",
"debug",
"(",
... | 46.15 | 19.875 |
def add_region_location(self, region, locations=None, use_live=True):
# type: (str, Optional[List[str]], bool) -> bool
"""Add all countries in a region. If a 3 digit UNStats M49 region code is not provided, value is parsed as a
region name. If any country is already added, it is ignored.
... | [
"def",
"add_region_location",
"(",
"self",
",",
"region",
",",
"locations",
"=",
"None",
",",
"use_live",
"=",
"True",
")",
":",
"# type: (str, Optional[List[str]], bool) -> bool",
"return",
"self",
".",
"add_country_locations",
"(",
"Country",
".",
"get_countries_in_... | 63.466667 | 37.8 |
def monitor_module(module, summary_writer,
track_data=True,
track_grad=True,
track_update=True,
track_update_ratio=False, # this is usually unnecessary
bins=51):
""" Allows for remote monitoring of a module's params and b... | [
"def",
"monitor_module",
"(",
"module",
",",
"summary_writer",
",",
"track_data",
"=",
"True",
",",
"track_grad",
"=",
"True",
",",
"track_update",
"=",
"True",
",",
"track_update_ratio",
"=",
"False",
",",
"# this is usually unnecessary",
"bins",
"=",
"51",
")"... | 42.792453 | 16.056604 |
def get_local_key(module_and_var_name, default_module=None):
"""
Get local setting for the keys.
:param module_and_var_name: for example: admin_account.admin_user, then you need to put admin_account.py in
local/local_keys/ and add variable admin_user="real admin username", module_name_and_var_name s... | [
"def",
"get_local_key",
"(",
"module_and_var_name",
",",
"default_module",
"=",
"None",
")",
":",
"if",
"\"-\"",
"in",
"module_and_var_name",
":",
"raise",
"ModuleAndVarNameShouldNotHaveDashCharacter",
"key_name_module_path",
"=",
"module_and_var_name",
".",
"split",
"(",... | 52.3125 | 21.6875 |
def set_instructions(self, instructions):
"""
Set the instructions
:param instructions: the list of instructions
:type instructions: a list of :class:`Instruction`
"""
if self.code == None:
return []
return self.code.get_bc().set_instructi... | [
"def",
"set_instructions",
"(",
"self",
",",
"instructions",
")",
":",
"if",
"self",
".",
"code",
"==",
"None",
":",
"return",
"[",
"]",
"return",
"self",
".",
"code",
".",
"get_bc",
"(",
")",
".",
"set_instructions",
"(",
"instructions",
")"
] | 32.8 | 14.2 |
def line_cont_after_delim(ctx, s, line_len=40, delim=(',',),
line_cont_token='&'):
"""
Insert newline (with preceeding `line_cont_token`) afer
passing over a delimiter after traversing at least `line_len`
number of characters
Mako convenience function. E.g. fortran does no... | [
"def",
"line_cont_after_delim",
"(",
"ctx",
",",
"s",
",",
"line_len",
"=",
"40",
",",
"delim",
"=",
"(",
"','",
",",
")",
",",
"line_cont_token",
"=",
"'&'",
")",
":",
"last",
"=",
"-",
"1",
"s",
"=",
"str",
"(",
"s",
")",
"for",
"i",
",",
"t"... | 33.75 | 15.666667 |
def _frank_help(alpha, tau):
"""Compute first order debye function to estimate theta."""
def debye(t):
return t / (np.exp(t) - 1)
debye_value = integrate.quad(debye, EPSILON, alpha)[0] / alpha
return 4 * (debye_value - 1) / alpha + 1 - tau | [
"def",
"_frank_help",
"(",
"alpha",
",",
"tau",
")",
":",
"def",
"debye",
"(",
"t",
")",
":",
"return",
"t",
"/",
"(",
"np",
".",
"exp",
"(",
"t",
")",
"-",
"1",
")",
"debye_value",
"=",
"integrate",
".",
"quad",
"(",
"debye",
",",
"EPSILON",
"... | 34.75 | 19.625 |
def importalma(asdm, ms):
"""Convert an ALMA low-level ASDM dataset to Measurement Set format.
asdm (str)
The path to the input ASDM dataset.
ms (str)
The path to the output MS dataset.
This implementation automatically infers the value of the "tbuff"
parameter.
Example::
f... | [
"def",
"importalma",
"(",
"asdm",
",",
"ms",
")",
":",
"from",
".",
"scripting",
"import",
"CasapyScript",
"script",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'cscript_importalma.py'",
")",
... | 26.636364 | 22.227273 |
def get_fields(desc2nts):
"""Return grouped, sorted namedtuples in either format: flat, sections."""
if 'flat' in desc2nts:
nts_flat = desc2nts.get('flat')
if nts_flat:
return nts_flat[0]._fields
if 'sections' in desc2nts:
nts_sections = desc2n... | [
"def",
"get_fields",
"(",
"desc2nts",
")",
":",
"if",
"'flat'",
"in",
"desc2nts",
":",
"nts_flat",
"=",
"desc2nts",
".",
"get",
"(",
"'flat'",
")",
"if",
"nts_flat",
":",
"return",
"nts_flat",
"[",
"0",
"]",
".",
"_fields",
"if",
"'sections'",
"in",
"d... | 41.1 | 8.7 |
def hardware_custom_profile_kap_custom_profile_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
custom_profile = ET.SubElement(hardware, "custom-profile")
... | [
"def",
"hardware_custom_profile_kap_custom_profile_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hardware",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hardware\"",
",",
"xmlns",
... | 47.75 | 20 |
def doc_parser():
"""Utility function to allow getting the arguments for a single command, for Sphinx documentation"""
parser = argparse.ArgumentParser(
prog='ambry',
description='Ambry {}. Management interface for ambry, libraries '
'and repositories. '.format(ambry._meta._... | [
"def",
"doc_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"'ambry'",
",",
"description",
"=",
"'Ambry {}. Management interface for ambry, libraries '",
"'and repositories. '",
".",
"format",
"(",
"ambry",
".",
"_meta",
"... | 38.111111 | 23.888889 |
def unbounded(self):
"""Whether solution is unbounded"""
self._check_valid()
status = self._problem._p.Status
if (status == gurobipy.GRB.INF_OR_UNBD and
self._problem._p.params.DualReductions):
# Disable dual reductions to obtain a definitve answer
... | [
"def",
"unbounded",
"(",
"self",
")",
":",
"self",
".",
"_check_valid",
"(",
")",
"status",
"=",
"self",
".",
"_problem",
".",
"_p",
".",
"Status",
"if",
"(",
"status",
"==",
"gurobipy",
".",
"GRB",
".",
"INF_OR_UNBD",
"and",
"self",
".",
"_problem",
... | 36.5 | 15.9375 |
def entropy(string):
"""Compute entropy on the string"""
p, lns = Counter(string), float(len(string))
return -sum(count/lns * math.log(count/lns, 2) for count in p.values()) | [
"def",
"entropy",
"(",
"string",
")",
":",
"p",
",",
"lns",
"=",
"Counter",
"(",
"string",
")",
",",
"float",
"(",
"len",
"(",
"string",
")",
")",
"return",
"-",
"sum",
"(",
"count",
"/",
"lns",
"*",
"math",
".",
"log",
"(",
"count",
"/",
"lns"... | 45.5 | 15.75 |
def first(self, **kwargs):
"""
Retrieve the first node from the set matching supplied parameters
:param kwargs: same syntax as `filter()`
:return: node
"""
result = result = self._get(limit=1, **kwargs)
if result:
return result[0]
else:
... | [
"def",
"first",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"result",
"=",
"self",
".",
"_get",
"(",
"limit",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
"if",
"result",
":",
"return",
"result",
"[",
"0",
"]",
"else",
":",
"raise... | 30.416667 | 17.583333 |
def invcdf(x):
"""Inverse of normal cumulative density function."""
x_flat = np.ravel(x)
x_trans = np.array([flib.ppnd16(y, 1) for y in x_flat])
return np.reshape(x_trans, np.shape(x)) | [
"def",
"invcdf",
"(",
"x",
")",
":",
"x_flat",
"=",
"np",
".",
"ravel",
"(",
"x",
")",
"x_trans",
"=",
"np",
".",
"array",
"(",
"[",
"flib",
".",
"ppnd16",
"(",
"y",
",",
"1",
")",
"for",
"y",
"in",
"x_flat",
"]",
")",
"return",
"np",
".",
... | 39.2 | 12.8 |
def gabor(image, labels, frequency, theta):
'''Gabor-filter the objects in an image
image - 2-d grayscale image to filter
labels - a similarly shaped labels matrix
frequency - cycles per trip around the circle
theta - angle of the filter. 0 to 2 pi
Calculate the Gabor filter centered on the ce... | [
"def",
"gabor",
"(",
"image",
",",
"labels",
",",
"frequency",
",",
"theta",
")",
":",
"#",
"# The code inscribes the X and Y position of each pixel relative to",
"# the centroid of that pixel's object. After that, the Gabor filter",
"# for the image can be calculated per-pixel and the... | 38.54 | 19.98 |
def find_importer_frame():
"""Returns the outer frame importing this "end" module.
If this module is being imported by other means than import statement,
None is returned.
Returns:
A frame object or None.
"""
byte = lambda ch: ord(ch) if PY2 else ch
frame = inspect.currentframe()
... | [
"def",
"find_importer_frame",
"(",
")",
":",
"byte",
"=",
"lambda",
"ch",
":",
"ord",
"(",
"ch",
")",
"if",
"PY2",
"else",
"ch",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"try",
":",
"while",
"frame",
":",
"code",
"=",
"frame",
".",
"... | 28.290323 | 17.774194 |
def list_datastore_clusters(kwargs=None, call=None):
'''
List all the datastore clusters for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastore_clusters my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The ... | [
"def",
"list_datastore_clusters",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_datastore_clusters function must be called with '",
"'-f or --function.'",
")",
"retu... | 28.764706 | 27.117647 |
def plot_eq_cont(fignum, DIblock, color_map='coolwarm'):
"""
plots dec inc block as a color contour
Parameters
__________________
Input:
fignum : figure number
DIblock : nested pairs of [Declination, Inclination]
color_map : matplotlib color map [default is coolwarm]
Out... | [
"def",
"plot_eq_cont",
"(",
"fignum",
",",
"DIblock",
",",
"color_map",
"=",
"'coolwarm'",
")",
":",
"import",
"random",
"plt",
".",
"figure",
"(",
"num",
"=",
"fignum",
")",
"plt",
".",
"axis",
"(",
"\"off\"",
")",
"XY",
"=",
"[",
"]",
"centres",
"=... | 42.606061 | 19.333333 |
def find_lexer_class(name):
"""Lookup a lexer class by name.
Return None if not found.
"""
if name in _lexer_cache:
return _lexer_cache[name]
# lookup builtin lexers
for module_name, lname, aliases, _, _ in itervalues(LEXERS):
if name == lname:
_load_lexers(module_na... | [
"def",
"find_lexer_class",
"(",
"name",
")",
":",
"if",
"name",
"in",
"_lexer_cache",
":",
"return",
"_lexer_cache",
"[",
"name",
"]",
"# lookup builtin lexers",
"for",
"module_name",
",",
"lname",
",",
"aliases",
",",
"_",
",",
"_",
"in",
"itervalues",
"(",... | 30.625 | 11.8125 |
def is_ssl(self):
"""
Read-only boolean property indicating whether SSL is used for
this connection.
If this property is true, then all communication between this
object and the Couchbase cluster is encrypted using SSL.
See :meth:`__init__` for more information on conne... | [
"def",
"is_ssl",
"(",
"self",
")",
":",
"mode",
"=",
"self",
".",
"_cntl",
"(",
"op",
"=",
"_LCB",
".",
"LCB_CNTL_SSL_MODE",
",",
"value_type",
"=",
"'int'",
")",
"return",
"mode",
"&",
"_LCB",
".",
"LCB_SSL_ENABLED",
"!=",
"0"
] | 37.833333 | 22.5 |
def CLI(ctx, config, list_lookups):
"""Lookup basic phone number information or send SMS messages"""
loglevel = 'info'
verbosity = getattr(logging, loglevel.upper(), 'INFO')
#verbosity = logging.DEBUG
ctx.obj = {
'verbosity': verbosity,
'logfile': None,
'config': {'lookups': ... | [
"def",
"CLI",
"(",
"ctx",
",",
"config",
",",
"list_lookups",
")",
":",
"loglevel",
"=",
"'info'",
"verbosity",
"=",
"getattr",
"(",
"logging",
",",
"loglevel",
".",
"upper",
"(",
")",
",",
"'INFO'",
")",
"#verbosity = logging.DEBUG",
"ctx",
".",
"obj",
... | 41.666667 | 13.4375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.