text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def run_aconvasp_command(command, structure):
"""
Helper function for calling aconvasp with different arguments
"""
poscar = Poscar(structure)
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
ou... | [
"def",
"run_aconvasp_command",
"(",
"command",
",",
"structure",
")",
":",
"poscar",
"=",
"Poscar",
"(",
"structure",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stdin",
"=",
"subprocess",... | 37.6 | 10.8 |
def strip_size(self, location='top', num_lines=None):
"""
Breadth of the strip background in inches
Parameters
----------
location : str in ``['top', 'right']``
Location of the strip text
num_lines : int
Number of text lines
"""
dp... | [
"def",
"strip_size",
"(",
"self",
",",
"location",
"=",
"'top'",
",",
"num_lines",
"=",
"None",
")",
":",
"dpi",
"=",
"72",
"theme",
"=",
"self",
".",
"theme",
"get_property",
"=",
"theme",
".",
"themeables",
".",
"property",
"if",
"location",
"==",
"'... | 32.111111 | 17.444444 |
def onBinaryMessage(self, msg, fromClient):
data = bytearray()
data.extend(msg)
"""
self.print_debug("message length: {}".format(len(data)))
self.print_debug("message data: {}".format(hexlify(data)))
"""
try:
self.queue.put_nowait(data)
except asyncio.QueueFull:
pass | [
"def",
"onBinaryMessage",
"(",
"self",
",",
"msg",
",",
"fromClient",
")",
":",
"data",
"=",
"bytearray",
"(",
")",
"data",
".",
"extend",
"(",
"msg",
")",
"try",
":",
"self",
".",
"queue",
".",
"put_nowait",
"(",
"data",
")",
"except",
"asyncio",
".... | 21.461538 | 19.461538 |
def _delete_record(self, identifier=None, rtype=None, name=None, content=None):
"""
Connects to Hetzner account, removes an existing record from the zone and returns a
boolean, if deletion was successful or not. Uses identifier or rtype, name & content to
lookup over all records of the z... | [
"def",
"_delete_record",
"(",
"self",
",",
"identifier",
"=",
"None",
",",
"rtype",
"=",
"None",
",",
"name",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"with",
"self",
".",
"_session",
"(",
"self",
".",
"domain",
",",
"self",
".",
"domain_i... | 56.794872 | 27.512821 |
def _check_integrity(self, lons, lats):
"""
Ensure lons and lats are:
- 1D numpy arrays
- equal size
- within the appropriate range in radians
"""
lons = np.array(lons).ravel()
lats = np.array(lats).ravel()
if len(lons.shape) != 1 or len(lats.... | [
"def",
"_check_integrity",
"(",
"self",
",",
"lons",
",",
"lats",
")",
":",
"lons",
"=",
"np",
".",
"array",
"(",
"lons",
")",
".",
"ravel",
"(",
")",
"lats",
"=",
"np",
".",
"array",
"(",
"lats",
")",
".",
"ravel",
"(",
")",
"if",
"len",
"(",
... | 37.3 | 15 |
def to_dict(self, delimiter=DEFAULT_DELIMITER, dict_type=collections.OrderedDict):
""" Get the dictionary representation of the current parser.
:param str delimiter: The delimiter used for nested dictionaries,
defaults to ":", optional
:param class dict_type: The dictionary type to ... | [
"def",
"to_dict",
"(",
"self",
",",
"delimiter",
"=",
"DEFAULT_DELIMITER",
",",
"dict_type",
"=",
"collections",
".",
"OrderedDict",
")",
":",
"root_key",
"=",
"self",
".",
"sections",
"(",
")",
"[",
"0",
"]",
"return",
"self",
".",
"_build_dict",
"(",
"... | 45.6 | 22.6 |
def genweights(p,q,dt,error=None , n=False):
"""
;+
; GENWEIGTHS : return optimal weigthing coefficients from Powell and Leben 2004<br />
; translated from Matlab genweigths.m program to IDL<br /><br />
;
; Reference : Powell, B. S., et R. R. Leben (2004), An Optimal Filter for <br... | [
"def",
"genweights",
"(",
"p",
",",
"q",
",",
"dt",
",",
"error",
"=",
"None",
",",
"n",
"=",
"False",
")",
":",
"p",
"=",
"np",
".",
"abs",
"(",
"p",
")",
"q",
"=",
"np",
".",
"abs",
"(",
"q",
")",
"#check inputs\r",
"if",
"(",
"-",
"p",
... | 32.130435 | 23.652174 |
def get(self, limit=None, page=None):
"""
get results from the db
return -- Iterator()
"""
has_more = False
self.bounds.paginate = True
limit_paginate, offset = self.bounds.get(limit, page)
self.default_val = []
results = self._query('get')
... | [
"def",
"get",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
"has_more",
"=",
"False",
"self",
".",
"bounds",
".",
"paginate",
"=",
"True",
"limit_paginate",
",",
"offset",
"=",
"self",
".",
"bounds",
".",
"get",
"(",
"... | 30.45 | 14.75 |
def find_executable(name, names=None, required=True):
"""Utility function to find an executable in PATH
name: program to find. Use given value if absolute path
names: list of additional names. For instance
>>> find_executable('sed', names=['gsed'])
required: If True, then the function raises a... | [
"def",
"find_executable",
"(",
"name",
",",
"names",
"=",
"None",
",",
"required",
"=",
"True",
")",
":",
"path_from_env",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
".",
"upper",
"(",
")",
")",
"if",
"path_from_env",
"is",
"not",
"None",
":... | 32.814815 | 17.259259 |
def trigger_streamer(*inputs, **kwargs):
"""Trigger a streamer based on the index read from input b.
Returns:
list(IOTileReading)
"""
streamer_marker = kwargs['mark_streamer']
try:
reading = inputs[1].pop()
except StreamEmptyError:
return []
finally:
for in... | [
"def",
"trigger_streamer",
"(",
"*",
"inputs",
",",
"*",
"*",
"kwargs",
")",
":",
"streamer_marker",
"=",
"kwargs",
"[",
"'mark_streamer'",
"]",
"try",
":",
"reading",
"=",
"inputs",
"[",
"1",
"]",
".",
"pop",
"(",
")",
"except",
"StreamEmptyError",
":",... | 20.652174 | 19.347826 |
def metric_wind_dict_to_imperial(d):
"""
Converts all the wind values in a dict from meters/sec (metric measurement
system) to miles/hour (imperial measurement system)
.
:param d: the dictionary containing metric values
:type d: dict
:returns: a dict with the same keys as the input dict an... | [
"def",
"metric_wind_dict_to_imperial",
"(",
"d",
")",
":",
"result",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"key",
"!=",
"'deg'",
":",
"# do not convert wind degree",
"result",
"[",
"key",
"]",
... | 31.210526 | 20.894737 |
def print_file_results(file_result):
"""Print the results of validating a file.
Args:
file_result: A FileValidationResults instance.
"""
print_results_header(file_result.filepath, file_result.is_valid)
for object_result in file_result.object_results:
if object_result.warnings:
... | [
"def",
"print_file_results",
"(",
"file_result",
")",
":",
"print_results_header",
"(",
"file_result",
".",
"filepath",
",",
"file_result",
".",
"is_valid",
")",
"for",
"object_result",
"in",
"file_result",
".",
"object_results",
":",
"if",
"object_result",
".",
"... | 30.176471 | 18.117647 |
def validate(self, model_name, object):
"""Validate an object against its swagger model"""
if model_name not in self.swagger_dict['definitions']:
raise ValidationError("Swagger spec has no definition for model %s" % model_name)
model_def = self.swagger_dict['definitions'][model_name]... | [
"def",
"validate",
"(",
"self",
",",
"model_name",
",",
"object",
")",
":",
"if",
"model_name",
"not",
"in",
"self",
".",
"swagger_dict",
"[",
"'definitions'",
"]",
":",
"raise",
"ValidationError",
"(",
"\"Swagger spec has no definition for model %s\"",
"%",
"mode... | 61.428571 | 19.142857 |
def get_institutes_trend_graph_urls(start, end):
""" Get all institute trend graphs. """
graph_list = []
for institute in Institute.objects.all():
urls = get_institute_trend_graph_url(institute, start, end)
urls['institute'] = institute
graph_list.append(urls)
return graph_list | [
"def",
"get_institutes_trend_graph_urls",
"(",
"start",
",",
"end",
")",
":",
"graph_list",
"=",
"[",
"]",
"for",
"institute",
"in",
"Institute",
".",
"objects",
".",
"all",
"(",
")",
":",
"urls",
"=",
"get_institute_trend_graph_url",
"(",
"institute",
",",
... | 31.1 | 17.2 |
def get_seebeck(self, output='eigs', doping_levels=True):
"""
Gives the seebeck coefficient (microV/K) in either a
full 3x3 tensor form, as 3 eigenvalues, or as the average value
(trace/3.0) If doping_levels=True, the results are given at
different p and n doping
... | [
"def",
"get_seebeck",
"(",
"self",
",",
"output",
"=",
"'eigs'",
",",
"doping_levels",
"=",
"True",
")",
":",
"return",
"BoltztrapAnalyzer",
".",
"_format_to_output",
"(",
"self",
".",
"_seebeck",
",",
"self",
".",
"_seebeck_doping",
",",
"output",
",",
"dop... | 49.382353 | 22.441176 |
def get_tokens(tokens):
"""Recursively gets tokens from a match list
Args:
tokens : List of tokens ['(', 'S', '(', 'NP', ')', ')']
Returns:
Stack of tokens
"""
tokens = tokens[1:-1]
ret = []
start = 0
stack = 0
for i in range(len(tokens)):
if tokens[i] ==... | [
"def",
"get_tokens",
"(",
"tokens",
")",
":",
"tokens",
"=",
"tokens",
"[",
"1",
":",
"-",
"1",
"]",
"ret",
"=",
"[",
"]",
"start",
"=",
"0",
"stack",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"tokens",
")",
")",
":",
"if",
"token... | 26.931034 | 18.275862 |
def get_all_last_24h_kline(self):
"""
获取所有ticker
:param _async:
:return:
"""
params = {}
url = u.MARKET_URL + '/market/tickers'
def _wrapper(_func):
@wraps(_func)
def handle():
_func(http_get_request(url, params))
... | [
"def",
"get_all_last_24h_kline",
"(",
"self",
")",
":",
"params",
"=",
"{",
"}",
"url",
"=",
"u",
".",
"MARKET_URL",
"+",
"'/market/tickers'",
"def",
"_wrapper",
"(",
"_func",
")",
":",
"@",
"wraps",
"(",
"_func",
")",
"def",
"handle",
"(",
")",
":",
... | 20.823529 | 17.882353 |
def retrieve_profile_extension_records(self, profile_extension, field_list, ids_to_retrieve,
query_column='RIID'):
""" Responsys.retrieveProfileExtensionRecords call
Accepts:
InteractObject profile_extension
list field_list
... | [
"def",
"retrieve_profile_extension_records",
"(",
"self",
",",
"profile_extension",
",",
"field_list",
",",
"ids_to_retrieve",
",",
"query_column",
"=",
"'RIID'",
")",
":",
"profile_extension",
"=",
"profile_extension",
".",
"get_soap_object",
"(",
"self",
".",
"clien... | 40.411765 | 19.529412 |
def mimeData( self, items ):
"""
Returns the mime data for dragging for this instance.
:param items | [<QTableWidgetItem>, ..]
"""
func = self.dataCollector()
if ( func ):
return func(self, items)
return super(XTableWidget, s... | [
"def",
"mimeData",
"(",
"self",
",",
"items",
")",
":",
"func",
"=",
"self",
".",
"dataCollector",
"(",
")",
"if",
"(",
"func",
")",
":",
"return",
"func",
"(",
"self",
",",
"items",
")",
"return",
"super",
"(",
"XTableWidget",
",",
"self",
")",
".... | 30 | 13.636364 |
def resume(self, mask, filename, port, pos):
"""Resume a DCC send"""
self.connections['send']['masks'][mask][port].offset = pos
message = 'DCC ACCEPT %s %d %d' % (filename, port, pos)
self.bot.ctcp(mask, message) | [
"def",
"resume",
"(",
"self",
",",
"mask",
",",
"filename",
",",
"port",
",",
"pos",
")",
":",
"self",
".",
"connections",
"[",
"'send'",
"]",
"[",
"'masks'",
"]",
"[",
"mask",
"]",
"[",
"port",
"]",
".",
"offset",
"=",
"pos",
"message",
"=",
"'D... | 48 | 11.4 |
def _str_member_list(self, name):
"""
Generate a member listing, autosummary:: table where possible,
and a table where not.
"""
out = []
if self[name]:
out += ['.. rubric:: %s' % name, '']
prefix = getattr(self, '_name', '')
if prefix... | [
"def",
"_str_member_list",
"(",
"self",
",",
"name",
")",
":",
"out",
"=",
"[",
"]",
"if",
"self",
"[",
"name",
"]",
":",
"out",
"+=",
"[",
"'.. rubric:: %s'",
"%",
"name",
",",
"''",
"]",
"prefix",
"=",
"getattr",
"(",
"self",
",",
"'_name'",
",",... | 36.55814 | 18.372093 |
def spinner(self, spinner=None):
"""Setter for spinner property.
Parameters
----------
spinner : dict, str
Defines the spinner value with frame and interval
"""
self._spinner = self._get_spinner(spinner)
self._frame_index = 0
self._text_index ... | [
"def",
"spinner",
"(",
"self",
",",
"spinner",
"=",
"None",
")",
":",
"self",
".",
"_spinner",
"=",
"self",
".",
"_get_spinner",
"(",
"spinner",
")",
"self",
".",
"_frame_index",
"=",
"0",
"self",
".",
"_text_index",
"=",
"0"
] | 28.454545 | 14.454545 |
def is_valid_chunksize(chunk_size):
"""Check if size is valid."""
min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN']
max_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MAX']
return chunk_size >= min_csize and chunk_size <= max_csize | [
"def",
"is_valid_chunksize",
"(",
"chunk_size",
")",
":",
"min_csize",
"=",
"current_app",
".",
"config",
"[",
"'FILES_REST_MULTIPART_CHUNKSIZE_MIN'",
"]",
"max_csize",
"=",
"current_app",
".",
"config",
"[",
"'FILES_REST_MULTIPART_CHUNKSIZE_MAX'",
"]",
"return",
"chunk... | 58 | 20.6 |
def _create_singleframe_bvals_bvecs(grouped_dicoms, bval_file, bvec_file, nifti, nifti_file):
"""
Write the bvals from the sorted dicom files to a bval file
"""
# create the empty arrays
bvals = numpy.zeros([len(grouped_dicoms)], dtype=numpy.int32)
bvecs = numpy.zeros([len(grouped_dicoms), 3])
... | [
"def",
"_create_singleframe_bvals_bvecs",
"(",
"grouped_dicoms",
",",
"bval_file",
",",
"bvec_file",
",",
"nifti",
",",
"nifti_file",
")",
":",
"# create the empty arrays",
"bvals",
"=",
"numpy",
".",
"zeros",
"(",
"[",
"len",
"(",
"grouped_dicoms",
")",
"]",
",... | 46.875 | 23.175 |
def debug_object(obj, log_level: int = logging.DEBUG) -> None:
"""
Sends details about a Python to the log, specifically its ``repr()``
representation, and all of its attributes with their name, value, and type.
Args:
obj: object to debug
log_level: log level to use; default is ``loggin... | [
"def",
"debug_object",
"(",
"obj",
",",
"log_level",
":",
"int",
"=",
"logging",
".",
"DEBUG",
")",
"->",
"None",
":",
"msgs",
"=",
"[",
"\"For {o!r}:\"",
".",
"format",
"(",
"o",
"=",
"obj",
")",
"]",
"for",
"attrname",
"in",
"dir",
"(",
"obj",
")... | 40.2 | 17.266667 |
def path_lookup(data_obj, xj_path, create_dict_path=False):
"""Looks up a xj path in the data_obj.
:param dict|list data_obj: An object to look into.
:param str xj_path: A path to extract data from.
:param bool create_dict_path: Create an element if type is specified.
:return: A tuple where 0 value... | [
"def",
"path_lookup",
"(",
"data_obj",
",",
"xj_path",
",",
"create_dict_path",
"=",
"False",
")",
":",
"if",
"not",
"xj_path",
"or",
"xj_path",
"==",
"'.'",
":",
"return",
"data_obj",
",",
"True",
"res",
"=",
"list",
"(",
"split",
"(",
"xj_path",
",",
... | 41.836735 | 17.77551 |
def sample(self):
"""
This is the core sampling method. Samples a state from a
demonstration, in accordance with the configuration.
"""
# chooses a sampling scheme randomly based on the mixing ratios
seed = random.uniform(0, 1)
ratio = np.cumsum(self.scheme_ratio... | [
"def",
"sample",
"(",
"self",
")",
":",
"# chooses a sampling scheme randomly based on the mixing ratios",
"seed",
"=",
"random",
".",
"uniform",
"(",
"0",
",",
"1",
")",
"ratio",
"=",
"np",
".",
"cumsum",
"(",
"self",
".",
"scheme_ratios",
")",
"ratio",
"=",
... | 33.4375 | 18.9375 |
def validate(self, cmd, messages=None):
"""Returns True if the given Command is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
args = [ arg for arg in cmd.args if arg is not None ]
if self.nargs != ... | [
"def",
"validate",
"(",
"self",
",",
"cmd",
",",
"messages",
"=",
"None",
")",
":",
"valid",
"=",
"True",
"args",
"=",
"[",
"arg",
"for",
"arg",
"in",
"cmd",
".",
"args",
"if",
"arg",
"is",
"not",
"None",
"]",
"if",
"self",
".",
"nargs",
"!=",
... | 36.586207 | 17.551724 |
def apply_filters(target, lines):
"""
Applys filters to the lines of a datasource. This function is used only in
integration tests. Filters are applied in an equivalent but more performant
way at run time.
"""
filters = get_filters(target)
if filters:
for l in lines:
if a... | [
"def",
"apply_filters",
"(",
"target",
",",
"lines",
")",
":",
"filters",
"=",
"get_filters",
"(",
"target",
")",
"if",
"filters",
":",
"for",
"l",
"in",
"lines",
":",
"if",
"any",
"(",
"f",
"in",
"l",
"for",
"f",
"in",
"filters",
")",
":",
"yield"... | 29.5 | 17.357143 |
def add_header(self, name, value):
'''Attach an email header to send with the message.
:param name: The name of the header value.
:param value: The header value.
'''
if self.headers is None:
self.headers = []
self.headers.append(dict(Name=name, Value=value)) | [
"def",
"add_header",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"self",
".",
"headers",
"is",
"None",
":",
"self",
".",
"headers",
"=",
"[",
"]",
"self",
".",
"headers",
".",
"append",
"(",
"dict",
"(",
"Name",
"=",
"name",
",",
"Val... | 34.555556 | 15.666667 |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._uuid is not None:
return False
if self._avatar is not None:
return False
if self._public_nick_name is not None:
return False
if self._display_name is not None:
... | [
"def",
"is_all_field_none",
"(",
"self",
")",
":",
"if",
"self",
".",
"_uuid",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_avatar",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_public_nick_name",
"is",
"not",
... | 19.238095 | 18.761905 |
def generic_visit(self, node):
"""Called if no explicit visitor function exists for a node."""
for field_name in node._fields:
setattr(node, field_name, self.visit(getattr(node, field_name)))
return node | [
"def",
"generic_visit",
"(",
"self",
",",
"node",
")",
":",
"for",
"field_name",
"in",
"node",
".",
"_fields",
":",
"setattr",
"(",
"node",
",",
"field_name",
",",
"self",
".",
"visit",
"(",
"getattr",
"(",
"node",
",",
"field_name",
")",
")",
")",
"... | 47 | 13.6 |
def _hash_file(self, algo):
"""Get the hash of the given file
:param algo: The algorithm to use.
:type algo: str
:return: The hexdigest of the data.
:rtype: str
"""
# We het the algorithm function.
hash_data = getattr(hashlib, algo)()
with open... | [
"def",
"_hash_file",
"(",
"self",
",",
"algo",
")",
":",
"# We het the algorithm function.",
"hash_data",
"=",
"getattr",
"(",
"hashlib",
",",
"algo",
")",
"(",
")",
"with",
"open",
"(",
"self",
".",
"path",
",",
"\"rb\"",
")",
"as",
"file",
":",
"# We o... | 25.875 | 16.291667 |
def _namematcher(regex):
"""Checks if a target name matches with an input regular expression."""
matcher = re_compile(regex)
def match(target):
target_name = getattr(target, '__name__', '')
result = matcher.match(target_name)
return result
return match | [
"def",
"_namematcher",
"(",
"regex",
")",
":",
"matcher",
"=",
"re_compile",
"(",
"regex",
")",
"def",
"match",
"(",
"target",
")",
":",
"target_name",
"=",
"getattr",
"(",
"target",
",",
"'__name__'",
",",
"''",
")",
"result",
"=",
"matcher",
".",
"ma... | 25.909091 | 20.181818 |
def getRing(startAtom, atomSet, lookup, oatoms):
"""getRing(startAtom, atomSet, lookup, oatoms)->atoms, bonds
starting at startAtom do a bfs traversal through the atoms
in atomSet and return the smallest ring found
returns (), () on failure
note: atoms and bonds are not returned in traversal order"... | [
"def",
"getRing",
"(",
"startAtom",
",",
"atomSet",
",",
"lookup",
",",
"oatoms",
")",
":",
"path",
"=",
"{",
"}",
"bpaths",
"=",
"{",
"}",
"for",
"atomID",
"in",
"atomSet",
".",
"keys",
"(",
")",
":",
"# initially the paths are empty",
"path",
"[",
"a... | 29.209677 | 19.177419 |
def getIPaddresses(self):
"""identify the IP addresses where this process client will launch the SC2 client"""
if not self.ipAddress:
self.ipAddress = ipAddresses.getAll() # update with IP address
return self.ipAddress | [
"def",
"getIPaddresses",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"ipAddress",
":",
"self",
".",
"ipAddress",
"=",
"ipAddresses",
".",
"getAll",
"(",
")",
"# update with IP address",
"return",
"self",
".",
"ipAddress"
] | 50 | 14 |
def getPrioritySortkey(self):
"""Returns the key that will be used to sort the current Analysis
Request based on both its priority and creation date. On ASC sorting,
the oldest item with highest priority will be displayed.
:return: string used for sorting
"""
priority = s... | [
"def",
"getPrioritySortkey",
"(",
"self",
")",
":",
"priority",
"=",
"self",
".",
"getPriority",
"(",
")",
"created_date",
"=",
"self",
".",
"created",
"(",
")",
".",
"ISO8601",
"(",
")",
"return",
"'%s.%s'",
"%",
"(",
"priority",
",",
"created_date",
")... | 47.444444 | 10.111111 |
def current():
"""
Returns the current environment manager for the projex system.
:return <EnvManager>
"""
if not EnvManager._current:
path = os.environ.get('PROJEX_ENVMGR_PATH')
module = os.environ.get('PROJEX_ENVMGR_MODULE')
clsn... | [
"def",
"current",
"(",
")",
":",
"if",
"not",
"EnvManager",
".",
"_current",
":",
"path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PROJEX_ENVMGR_PATH'",
")",
"module",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PROJEX_ENVMGR_MODULE'",
")",
"clsna... | 34.648649 | 19.567568 |
def mag_roll(RAW_IMU, inclination, declination):
'''estimate roll from mag'''
m = mag_rotation(RAW_IMU, inclination, declination)
(r, p, y) = m.to_euler()
return degrees(r) | [
"def",
"mag_roll",
"(",
"RAW_IMU",
",",
"inclination",
",",
"declination",
")",
":",
"m",
"=",
"mag_rotation",
"(",
"RAW_IMU",
",",
"inclination",
",",
"declination",
")",
"(",
"r",
",",
"p",
",",
"y",
")",
"=",
"m",
".",
"to_euler",
"(",
")",
"retur... | 36.8 | 12.4 |
def harvest(lancet, config_section):
"""Construct a new Harvest client."""
url, username, password = lancet.get_credentials(
config_section, credentials_checker
)
project_id_getter = lancet.get_instance_from_config(
"timer", "project_id_getter", lancet
)
task_id_getter = lancet.... | [
"def",
"harvest",
"(",
"lancet",
",",
"config_section",
")",
":",
"url",
",",
"username",
",",
"password",
"=",
"lancet",
".",
"get_credentials",
"(",
"config_section",
",",
"credentials_checker",
")",
"project_id_getter",
"=",
"lancet",
".",
"get_instance_from_co... | 29.142857 | 16.047619 |
def location(self, wave_field, depth=None, index=None):
"""Create a Location for a specific depth.
Parameters
----------
wave_field: str
Wave field. See :class:`Location` for possible values.
depth: float, optional
Depth corresponding to the :class`Locati... | [
"def",
"location",
"(",
"self",
",",
"wave_field",
",",
"depth",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"wave_field",
",",
"WaveField",
")",
":",
"wave_field",
"=",
"WaveField",
"[",
"wave_field",
"]",
"if",
"... | 34.195122 | 17.536585 |
def forward(self, # pylint: disable=arguments-differ
inputs: torch.Tensor,
mask: torch.LongTensor) -> torch.Tensor:
"""
Parameters
----------
inputs : ``torch.Tensor``, required.
A Tensor of shape ``(batch_size, sequence_length, hidden_size)``... | [
"def",
"forward",
"(",
"self",
",",
"# pylint: disable=arguments-differ",
"inputs",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"LongTensor",
")",
"->",
"torch",
".",
"Tensor",
":",
"batch_size",
",",
"total_sequence_length",
"=",
"mask",
".",... | 54.545455 | 28.727273 |
def pb(name, data, display_name=None, description=None):
"""Create a legacy text summary protobuf.
Arguments:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
data: A Python bytestring (of type bytes), or Unicode string. Or a numpy
data array of those types.... | [
"def",
"pb",
"(",
"name",
",",
"data",
",",
"display_name",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"# TODO(nickfelt): remove on-demand imports once dep situation is fixed.",
"import",
"tensorflow",
".",
"compat",
".",
"v1",
"as",
"tf",
"try",
":",... | 34.157895 | 20.315789 |
def get_item_balances(self, acc: Account) -> list:
"""
Returns balances of items of the invoice.
:param acc: Account
:return: list (AccountEntry, Decimal) in item id order
"""
items = []
entries = self.get_entries(acc)
for item in entries.filter(source_inv... | [
"def",
"get_item_balances",
"(",
"self",
",",
"acc",
":",
"Account",
")",
"->",
"list",
":",
"items",
"=",
"[",
"]",
"entries",
"=",
"self",
".",
"get_entries",
"(",
"acc",
")",
"for",
"item",
"in",
"entries",
".",
"filter",
"(",
"source_invoice",
"=",... | 43.142857 | 15.714286 |
def get_common_payload_template(services=None):
"""
Get a template dictionary that can be used to create a payload object.
TODO: services s/b a list. Specify required fields for each service in list.
None means all services.
"""
available_services = {'citrine', 'materials_commons', '... | [
"def",
"get_common_payload_template",
"(",
"services",
"=",
"None",
")",
":",
"available_services",
"=",
"{",
"'citrine'",
",",
"'materials_commons'",
",",
"'materials_data_facility'",
"}",
"if",
"services",
"is",
"None",
":",
"services",
"=",
"list",
"(",
"availa... | 36.696429 | 12.535714 |
def readConfig(self, configuration):
"""Read configuration from dict.
Read configuration from a JSON configuration file.
:param configuration: configuration to load.
:type configuration: dict.
"""
self.__logger.debug("Reading configuration")
self.city = configur... | [
"def",
"readConfig",
"(",
"self",
",",
"configuration",
")",
":",
"self",
".",
"__logger",
".",
"debug",
"(",
"\"Reading configuration\"",
")",
"self",
".",
"city",
"=",
"configuration",
"[",
"\"name\"",
"]",
"self",
".",
"__logger",
".",
"info",
"(",
"\"C... | 38.255814 | 15.255814 |
def read_tsv(cls, path, encoding='utf-8'):
"""Read a gene set database from a tab-delimited text file.
Parameters
----------
path: str
The path name of the the file.
encoding: str
The encoding of the text file.
Returns
-------
Non... | [
"def",
"read_tsv",
"(",
"cls",
",",
"path",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"gene_sets",
"=",
"[",
"]",
"n",
"=",
"0",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"fh",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"fh",
",... | 29.28 | 16.4 |
def p_property_assignment(self, p):
"""property_assignment \
: property_name COLON assignment_expr
| GETPROP property_name LPAREN RPAREN LBRACE function_body RBRACE
| SETPROP property_name LPAREN property_set_parameter_list RPAREN\
LBRACE function_body R... | [
"def",
"p_property_assignment",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"4",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Assign",
"(",
"left",
"=",
"p",
"[",
"1",
"]",
",",
"op",
"=",
"p",
"[",
"2... | 42.941176 | 17.235294 |
def create_token(
self,
registry_address,
initial_alloc=10 ** 6,
name='raidentester',
symbol='RDT',
decimals=2,
timeout=60,
auto_register=True,
):
""" Create a proxy for a new HumanStandardToken (ERC20), that is
... | [
"def",
"create_token",
"(",
"self",
",",
"registry_address",
",",
"initial_alloc",
"=",
"10",
"**",
"6",
",",
"name",
"=",
"'raidentester'",
",",
"symbol",
"=",
"'RDT'",
",",
"decimals",
"=",
"2",
",",
"timeout",
"=",
"60",
",",
"auto_register",
"=",
"Tr... | 36.833333 | 18.190476 |
def __geomToPointList(self, geom):
""" converts a geometry object to a common.Geometry object """
sr = geom.spatialReference
wkid = None
wkt = None
if sr is None:
if self._wkid is None and self._wkt is not None:
wkt = self._wkt
else:
... | [
"def",
"__geomToPointList",
"(",
"self",
",",
"geom",
")",
":",
"sr",
"=",
"geom",
".",
"spatialReference",
"wkid",
"=",
"None",
"wkt",
"=",
"None",
"if",
"sr",
"is",
"None",
":",
"if",
"self",
".",
"_wkid",
"is",
"None",
"and",
"self",
".",
"_wkt",
... | 31.9 | 15.5 |
def draw_collection(self, ax, collection,
force_pathtrans=None,
force_offsettrans=None):
"""Process a matplotlib collection and call renderer.draw_collection"""
(transform, transOffset,
offsets, paths) = collection._prepare_points()
offse... | [
"def",
"draw_collection",
"(",
"self",
",",
"ax",
",",
"collection",
",",
"force_pathtrans",
"=",
"None",
",",
"force_offsettrans",
"=",
"None",
")",
":",
"(",
"transform",
",",
"transOffset",
",",
"offsets",
",",
"paths",
")",
"=",
"collection",
".",
"_pr... | 47.25 | 20.454545 |
def all(cls, client, symbols):
""""
fetch data for multiple stocks
"""
params = {"symbol": ",".join(symbols)}
request_url = "https://api.robinhood.com/instruments/"
data = client.get(request_url, params=params)
results = data["results"]
while data["next"... | [
"def",
"all",
"(",
"cls",
",",
"client",
",",
"symbols",
")",
":",
"params",
"=",
"{",
"\"symbol\"",
":",
"\",\"",
".",
"join",
"(",
"symbols",
")",
"}",
"request_url",
"=",
"\"https://api.robinhood.com/instruments/\"",
"data",
"=",
"client",
".",
"get",
"... | 30 | 12.642857 |
def _get_entity_by_class(self, entity_cls):
"""Fetch Entity record with Entity class details"""
entity_qualname = fully_qualified_name(entity_cls)
if entity_qualname in self._registry:
return self._registry[entity_qualname]
else:
return self._find_entity_in_record... | [
"def",
"_get_entity_by_class",
"(",
"self",
",",
"entity_cls",
")",
":",
"entity_qualname",
"=",
"fully_qualified_name",
"(",
"entity_cls",
")",
"if",
"entity_qualname",
"in",
"self",
".",
"_registry",
":",
"return",
"self",
".",
"_registry",
"[",
"entity_qualname... | 50 | 15 |
def get_intrinsic_rewards(self, curr_info, next_info):
"""
Generates intrinsic reward used for Curiosity-based training.
:BrainInfo curr_info: Current BrainInfo.
:BrainInfo next_info: Next BrainInfo.
:return: Intrinsic rewards for all agents.
"""
if self.use_curio... | [
"def",
"get_intrinsic_rewards",
"(",
"self",
",",
"curr_info",
",",
"next_info",
")",
":",
"if",
"self",
".",
"use_curiosity",
":",
"if",
"len",
"(",
"curr_info",
".",
"agents",
")",
"==",
"0",
":",
"return",
"[",
"]",
"feed_dict",
"=",
"{",
"self",
".... | 51.75 | 23 |
def custom_decode(encoding):
"""Overrides encoding when charset declaration
or charset determination is a subset of a larger
charset. Created because of issues with Chinese websites"""
encoding = encoding.lower()
alternates = {
'big5': 'big5hkscs',
'gb2312': 'gb18030',
... | [
"def",
"custom_decode",
"(",
"encoding",
")",
":",
"encoding",
"=",
"encoding",
".",
"lower",
"(",
")",
"alternates",
"=",
"{",
"'big5'",
":",
"'big5hkscs'",
",",
"'gb2312'",
":",
"'gb18030'",
",",
"'ascii'",
":",
"'utf-8'",
",",
"'MacCyrillic'",
":",
"'cp... | 30.933333 | 13.533333 |
def _GetPurgeMessage(most_recent_step, most_recent_wall_time, event_step,
event_wall_time, num_expired_scalars, num_expired_histos,
num_expired_comp_histos, num_expired_images,
num_expired_audio):
"""Return the string message associated with TensorBoard p... | [
"def",
"_GetPurgeMessage",
"(",
"most_recent_step",
",",
"most_recent_wall_time",
",",
"event_step",
",",
"event_wall_time",
",",
"num_expired_scalars",
",",
"num_expired_histos",
",",
"num_expired_comp_histos",
",",
"num_expired_images",
",",
"num_expired_audio",
")",
":",... | 66.8 | 24.866667 |
def load_simple_endpoint(category, name):
'''fetches the entry point for a plugin and calls it with the given
aux_info'''
for ep in pkg_resources.iter_entry_points(category):
if ep.name == name:
return ep.load()
raise KeyError(name) | [
"def",
"load_simple_endpoint",
"(",
"category",
",",
"name",
")",
":",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"category",
")",
":",
"if",
"ep",
".",
"name",
"==",
"name",
":",
"return",
"ep",
".",
"load",
"(",
")",
"raise",
... | 37.428571 | 16.285714 |
def global_get(self, key):
"""Return the value for the given key in the ``globals`` table."""
key = self.pack(key)
r = self.sql('global_get', key).fetchone()
if r is None:
raise KeyError("Not set")
return self.unpack(r[0]) | [
"def",
"global_get",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"self",
".",
"pack",
"(",
"key",
")",
"r",
"=",
"self",
".",
"sql",
"(",
"'global_get'",
",",
"key",
")",
".",
"fetchone",
"(",
")",
"if",
"r",
"is",
"None",
":",
"raise",
"Key... | 38.285714 | 9.428571 |
def check_dataset(self, dataset_id, project_id=None):
"""Check to see if a dataset exists.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
-------
bool
... | [
"def",
"check_dataset",
"(",
"self",
",",
"dataset_id",
",",
"project_id",
"=",
"None",
")",
":",
"dataset",
"=",
"self",
".",
"get_dataset",
"(",
"dataset_id",
",",
"project_id",
")",
"return",
"bool",
"(",
"dataset",
")"
] | 27.529412 | 17.764706 |
def get_indexes(self, db_name, tbl_name, max_indexes):
"""
Parameters:
- db_name
- tbl_name
- max_indexes
"""
self.send_get_indexes(db_name, tbl_name, max_indexes)
return self.recv_get_indexes() | [
"def",
"get_indexes",
"(",
"self",
",",
"db_name",
",",
"tbl_name",
",",
"max_indexes",
")",
":",
"self",
".",
"send_get_indexes",
"(",
"db_name",
",",
"tbl_name",
",",
"max_indexes",
")",
"return",
"self",
".",
"recv_get_indexes",
"(",
")"
] | 24.555556 | 15 |
def encode(cls, value):
"""
take a list and turn it into a utf-8 encoded byte-string for redis.
:param value: list
:return: bytes
"""
try:
coerced = list(value)
if coerced == value:
return json.dumps(coerced).encode(cls._encoding)
... | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"try",
":",
"coerced",
"=",
"list",
"(",
"value",
")",
"if",
"coerced",
"==",
"value",
":",
"return",
"json",
".",
"dumps",
"(",
"coerced",
")",
".",
"encode",
"(",
"cls",
".",
"_encoding",
")",
... | 26 | 18 |
def get(self, key):
""" Fetch entry from database. """
c = self.conn.cursor()
for row in c.execute("SELECT key, nonce, key_handle, aead, oath_C, oath_T FROM oath WHERE key = ?", (key,)):
return ValOathEntry(row)
raise Exception("OATH token for '%s' not found in database (%s)"... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"for",
"row",
"in",
"c",
".",
"execute",
"(",
"\"SELECT key, nonce, key_handle, aead, oath_C, oath_T FROM oath WHERE key = ?\"",
",",
"(",
"key",
",",
")... | 56.5 | 27.833333 |
def run_multiple(self, eventLoops):
"""run the event loops in the background.
Args:
eventLoops (list): a list of event loops to run
"""
self.nruns += len(eventLoops)
return self.communicationChannel.put_multiple(eventLoops) | [
"def",
"run_multiple",
"(",
"self",
",",
"eventLoops",
")",
":",
"self",
".",
"nruns",
"+=",
"len",
"(",
"eventLoops",
")",
"return",
"self",
".",
"communicationChannel",
".",
"put_multiple",
"(",
"eventLoops",
")"
] | 26.9 | 19.9 |
def dataset(
node_parser,
include=lambda x: True,
input_transform=None,
target_transform=None):
"""Convert immediate children of a GroupNode into a torch.data.Dataset
Keyword arguments
* node_parser=callable that converts a DataNode to a Dataset item
* include=lambda x: T... | [
"def",
"dataset",
"(",
"node_parser",
",",
"include",
"=",
"lambda",
"x",
":",
"True",
",",
"input_transform",
"=",
"None",
",",
"target_transform",
"=",
"None",
")",
":",
"def",
"_dataset",
"(",
"node",
",",
"paths",
")",
":",
"# pylint: disable=unused-argu... | 38.4 | 17.3 |
def wake_lock_size(self):
"""Get the size of the current wake lock."""
output = self.adb_shell(WAKE_LOCK_SIZE_CMD)
if not output:
return None
return int(output.split("=")[1].strip()) | [
"def",
"wake_lock_size",
"(",
"self",
")",
":",
"output",
"=",
"self",
".",
"adb_shell",
"(",
"WAKE_LOCK_SIZE_CMD",
")",
"if",
"not",
"output",
":",
"return",
"None",
"return",
"int",
"(",
"output",
".",
"split",
"(",
"\"=\"",
")",
"[",
"1",
"]",
".",
... | 36.833333 | 11.5 |
def extractDates(self, inp):
"""Extract semantic date information from an input string.
In effect, runs both parseDay and parseTime on the input
string and merges the results to produce a comprehensive
datetime object.
Args:
inp (str): Input string to be parsed.
... | [
"def",
"extractDates",
"(",
"self",
",",
"inp",
")",
":",
"def",
"merge",
"(",
"param",
")",
":",
"day",
",",
"time",
"=",
"param",
"if",
"not",
"(",
"day",
"or",
"time",
")",
":",
"return",
"None",
"if",
"not",
"day",
":",
"return",
"time",
"if"... | 31.433333 | 19.6 |
def debug(self, s, level=2):
"""Write a debug message."""
self.write(s, level=level, color='white') | [
"def",
"debug",
"(",
"self",
",",
"s",
",",
"level",
"=",
"2",
")",
":",
"self",
".",
"write",
"(",
"s",
",",
"level",
"=",
"level",
",",
"color",
"=",
"'white'",
")"
] | 37.666667 | 7 |
def pingback_url(self, server_name, target_url):
"""
Do a pingback call for the target URL.
"""
try:
server = ServerProxy(server_name)
reply = server.pingback.ping(self.entry_url, target_url)
except (Error, socket.error):
reply = '%s cannot be ... | [
"def",
"pingback_url",
"(",
"self",
",",
"server_name",
",",
"target_url",
")",
":",
"try",
":",
"server",
"=",
"ServerProxy",
"(",
"server_name",
")",
"reply",
"=",
"server",
".",
"pingback",
".",
"ping",
"(",
"self",
".",
"entry_url",
",",
"target_url",
... | 35.3 | 11.3 |
def cancel_pending_requests(self):
'''Cancel all pending requests.'''
exception = CancelledError()
for _request, event in self._requests.values():
event.result = exception
event.set()
self._requests.clear() | [
"def",
"cancel_pending_requests",
"(",
"self",
")",
":",
"exception",
"=",
"CancelledError",
"(",
")",
"for",
"_request",
",",
"event",
"in",
"self",
".",
"_requests",
".",
"values",
"(",
")",
":",
"event",
".",
"result",
"=",
"exception",
"event",
".",
... | 36.571429 | 8.285714 |
def get_sorted_nts_omit_section(self, hdrgo_prt, hdrgo_sort):
"""Return a flat list of sections (wo/section names) with GO terms grouped and sorted."""
nts_flat = []
# print("SSSS SorterNts:get_sorted_nts_omit_section(hdrgo_prt={}, hdrgo_sort={})".format(
# hdrgo_prt, hdrgo_sort))
... | [
"def",
"get_sorted_nts_omit_section",
"(",
"self",
",",
"hdrgo_prt",
",",
"hdrgo_sort",
")",
":",
"nts_flat",
"=",
"[",
"]",
"# print(\"SSSS SorterNts:get_sorted_nts_omit_section(hdrgo_prt={}, hdrgo_sort={})\".format(",
"# hdrgo_prt, hdrgo_sort))",
"hdrgos_seen",
"=",
"set",
... | 62.0625 | 25 |
def FromMicroseconds(self, micros):
"""Converts microseconds to Duration."""
self._NormalizeDuration(
micros // _MICROS_PER_SECOND,
(micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND) | [
"def",
"FromMicroseconds",
"(",
"self",
",",
"micros",
")",
":",
"self",
".",
"_NormalizeDuration",
"(",
"micros",
"//",
"_MICROS_PER_SECOND",
",",
"(",
"micros",
"%",
"_MICROS_PER_SECOND",
")",
"*",
"_NANOS_PER_MICROSECOND",
")"
] | 41.4 | 8.6 |
def run_with_werkzeug(self, **options):
"""Run with werkzeug simple wsgi container."""
threaded = self.threads is not None and (self.threads > 0)
self.app.run(
host=self.host,
port=self.port,
debug=self.debug,
threaded=threaded,
**optio... | [
"def",
"run_with_werkzeug",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"threaded",
"=",
"self",
".",
"threads",
"is",
"not",
"None",
"and",
"(",
"self",
".",
"threads",
">",
"0",
")",
"self",
".",
"app",
".",
"run",
"(",
"host",
"=",
"self",
... | 32.3 | 14.3 |
def set_attributes(trace):
"""Automatically set attributes for Google Cloud environment."""
spans = trace.get('spans')
for span in spans:
if span.get('attributes') is None:
span['attributes'] = {}
if is_gae_environment():
set_gae_attributes(span)
set_common_... | [
"def",
"set_attributes",
"(",
"trace",
")",
":",
"spans",
"=",
"trace",
".",
"get",
"(",
"'spans'",
")",
"for",
"span",
"in",
"spans",
":",
"if",
"span",
".",
"get",
"(",
"'attributes'",
")",
"is",
"None",
":",
"span",
"[",
"'attributes'",
"]",
"=",
... | 28.692308 | 14.846154 |
def get_member_details(self, member_id, **kwargs): # noqa: E501
"""Get member details # noqa: E501
Get your member details (quota and role) # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> t... | [
"def",
"get_member_details",
"(",
"self",
",",
"member_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"self",
".",
"get_me... | 43.095238 | 20.142857 |
def get_enrollments_for_regid(self, regid, params={},
include_courses=True):
"""
Return a list of enrollments for the passed user regid.
https://canvas.instructure.com/doc/api/enrollments.html#method.enrollments_api.index
"""
sis_user_id = self.... | [
"def",
"get_enrollments_for_regid",
"(",
"self",
",",
"regid",
",",
"params",
"=",
"{",
"}",
",",
"include_courses",
"=",
"True",
")",
":",
"sis_user_id",
"=",
"self",
".",
"_sis_id",
"(",
"regid",
",",
"sis_field",
"=",
"\"user\"",
")",
"url",
"=",
"USE... | 41.125 | 19.3125 |
def action_rename(self):
"""
Rename a shortcut
"""
# get old and new name from args
old = self.args['<old>']
new = self.args['<new>']
# select the old shortcut
self.db_query('''
SELECT id FROM shortcuts WHERE name=?
''', (old,))
... | [
"def",
"action_rename",
"(",
"self",
")",
":",
"# get old and new name from args",
"old",
"=",
"self",
".",
"args",
"[",
"'<old>'",
"]",
"new",
"=",
"self",
".",
"args",
"[",
"'<new>'",
"]",
"# select the old shortcut",
"self",
".",
"db_query",
"(",
"'''\n ... | 24.852941 | 18.323529 |
def _set_protocol_vrrp(self, v, load=False):
"""
Setter method for protocol_vrrp, mapped from YANG variable /protocol_vrrp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_protocol_vrrp is considered as a private
method. Backends looking to populate this v... | [
"def",
"_set_protocol_vrrp",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | 73.833333 | 36.041667 |
def getSpec(cls):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getSpec`.
The parameters collection is constructed based on the parameters specified
by the various components (spatialSpec, temporalSpec and otherSpec)
"""
spec = cls.getBaseSpec()
t, o = _getAdditionalSpecs(t... | [
"def",
"getSpec",
"(",
"cls",
")",
":",
"spec",
"=",
"cls",
".",
"getBaseSpec",
"(",
")",
"t",
",",
"o",
"=",
"_getAdditionalSpecs",
"(",
"temporalImp",
"=",
"gDefaultTemporalImp",
")",
"spec",
"[",
"'parameters'",
"]",
".",
"update",
"(",
"t",
")",
"s... | 32.461538 | 21.538462 |
def _check_configure_args(configure_args: Dict[str, Any]) -> Dict[str, Any]:
""" Check the arguments passed to configure.
Raises an exception on failure. On success, returns a dict of
configure_args with any necessary mutations.
"""
# SSID must always be present
if not configure_args.get('ssid'... | [
"def",
"_check_configure_args",
"(",
"configure_args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"# SSID must always be present",
"if",
"not",
"configure_args",
".",
"get",
"(",
"'ssid'",
")",
"or",
"not... | 42 | 18.243243 |
def build(cls, seqs: Iterable[int], uid: bool = False) -> 'SequenceSet':
"""Build a new sequence set that contains the given values using as
few groups as possible.
Args:
seqs: The sequence values to build.
uid: True if the sequences refer to message UIDs.
"""
... | [
"def",
"build",
"(",
"cls",
",",
"seqs",
":",
"Iterable",
"[",
"int",
"]",
",",
"uid",
":",
"bool",
"=",
"False",
")",
"->",
"'SequenceSet'",
":",
"seqs_list",
"=",
"sorted",
"(",
"set",
"(",
"seqs",
")",
")",
"groups",
":",
"List",
"[",
"Union",
... | 37.392857 | 10.607143 |
def add_args():
"""Adds commandline arguments and formatted Help"""
parser = argparse.ArgumentParser()
parser.add_argument('-host', action='store', dest='host', default='127.0.0.1', help='DEFAULT "127.0.0.1"')
parser.add_argument('-port', action='store', dest='port', default='2947', help='DEFAULT 2947'... | [
"def",
"add_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-host'",
",",
"action",
"=",
"'store'",
",",
"dest",
"=",
"'host'",
",",
"default",
"=",
"'127.0.0.1'",
",",
"help",
"=",
... | 87.684211 | 57.736842 |
def send(self, request_id, payload):
"""
Send a request to Kafka
Arguments::
request_id (int): can be any int (used only for debug logging...)
payload: an encoded kafka packet (see KafkaProtocol)
"""
log.debug("About to send %d bytes to Kafka, request %d... | [
"def",
"send",
"(",
"self",
",",
"request_id",
",",
"payload",
")",
":",
"log",
".",
"debug",
"(",
"\"About to send %d bytes to Kafka, request %d\"",
"%",
"(",
"len",
"(",
"payload",
")",
",",
"request_id",
")",
")",
"# Make sure we have a connection",
"if",
"no... | 30.7 | 20 |
def process_document(self, doc):
"""
Add your code for processing the document
"""
raw = doc.select_segments("$.raw_content")[0]
extractions = doc.extract(self.inferlink_extractor, raw)
doc.store(extractions, "inferlink_extraction")
return list() | [
"def",
"process_document",
"(",
"self",
",",
"doc",
")",
":",
"raw",
"=",
"doc",
".",
"select_segments",
"(",
"\"$.raw_content\"",
")",
"[",
"0",
"]",
"extractions",
"=",
"doc",
".",
"extract",
"(",
"self",
".",
"inferlink_extractor",
",",
"raw",
")",
"d... | 32.777778 | 14.111111 |
def stop(self, force=False):
"""
Send a terminate request.
:param bool force: ignore the remote devices response
"""
if self._initialized:
self.send(C1218TerminateRequest())
data = self.recv()
if data == b'\x00' or force:
self._initialized = False
self._toggle_bit = False
return True
r... | [
"def",
"stop",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"_initialized",
":",
"self",
".",
"send",
"(",
"C1218TerminateRequest",
"(",
")",
")",
"data",
"=",
"self",
".",
"recv",
"(",
")",
"if",
"data",
"==",
"b'\\x00'",
... | 22.714286 | 14.428571 |
def add_node(self, node, attrs = None):
"""
Add given node to the graph.
@attention: While nodes can be of any type, it's strongly recommended to use only
numbers and single-line strings as node identifiers if you intend to use write().
@type node: node
@param ... | [
"def",
"add_node",
"(",
"self",
",",
"node",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"attrs",
"is",
"None",
":",
"attrs",
"=",
"[",
"]",
"if",
"(",
"node",
"not",
"in",
"self",
".",
"node_neighbors",
")",
":",
"self",
".",
"node_neighbors",
"[",... | 36.238095 | 18.142857 |
def set_data(self, data=None, **kwargs):
"""Set the line data
Parameters
----------
data : array-like
The data.
**kwargs : dict
Keywoard arguments to pass to MarkerVisual and LineVisal.
"""
if data is None:
pos = None
e... | [
"def",
"set_data",
"(",
"self",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"data",
"is",
"None",
":",
"pos",
"=",
"None",
"else",
":",
"if",
"isinstance",
"(",
"data",
",",
"tuple",
")",
":",
"pos",
"=",
"np",
".",
"arra... | 38.105263 | 18.052632 |
def subtract_and_intersect_circle(self, center, radius):
'''
Circle subtraction / intersection only supported by 2-gon regions, otherwise a VennRegionException is thrown.
In addition, such an exception will be thrown if the circle to be subtracted is completely within the region and forms a "hol... | [
"def",
"subtract_and_intersect_circle",
"(",
"self",
",",
"center",
",",
"radius",
")",
":",
"if",
"len",
"(",
"self",
".",
"arcs",
")",
"!=",
"2",
":",
"raise",
"VennRegionException",
"(",
"\"Circle subtraction and intersection with poly-arc regions is currently only s... | 59.864407 | 31.062147 |
def grouper(iterable, n, fillvalue=None):
"""Group iterable by n elements.
>>> for t in grouper('abcdefg', 3, fillvalue='x'):
... print(''.join(t))
abc
def
gxx
"""
return list(zip_longest(*[iter(iterable)] * n, fillvalue=fillvalue)) | [
"def",
"grouper",
"(",
"iterable",
",",
"n",
",",
"fillvalue",
"=",
"None",
")",
":",
"return",
"list",
"(",
"zip_longest",
"(",
"*",
"[",
"iter",
"(",
"iterable",
")",
"]",
"*",
"n",
",",
"fillvalue",
"=",
"fillvalue",
")",
")"
] | 26 | 19.7 |
def enrichment_from_msp(dfmsp, modification="Phospho (STY)"):
"""
Calculate relative enrichment of peptide modifications from modificationSpecificPeptides.txt.
Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified
modification in the table.
The returned data ... | [
"def",
"enrichment_from_msp",
"(",
"dfmsp",
",",
"modification",
"=",
"\"Phospho (STY)\"",
")",
":",
"dfmsp",
"[",
"'Modifications'",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"modification",
"in",
"m",
"for",
"m",
"in",
"dfmsp",
"[",
"'Modifications'",
"]",
... | 38.24 | 26.32 |
def integer(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Integer` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Integer`
"""
kwargs['description'] = description
return type('Inte... | [
"def",
"integer",
"(",
"description",
",",
"*",
"*",
"kwargs",
")",
"->",
"typing",
".",
"Type",
":",
"kwargs",
"[",
"'description'",
"]",
"=",
"description",
"return",
"type",
"(",
"'Integer'",
",",
"(",
"Integer",
",",
")",
",",
"kwargs",
")"
] | 37.444444 | 9.333333 |
def raise_(type_, value=None, traceback=None): # pylint: disable=W0613
"""
Does the same as ordinary ``raise`` with arguments do in Python 2.
But works in Python 3 (>= 3.3) also!
Please checkout README on https://github.com/9seconds/pep3134
to get an idea about possible pitfals. But short story is... | [
"def",
"raise_",
"(",
"type_",
",",
"value",
"=",
"None",
",",
"traceback",
"=",
"None",
")",
":",
"# pylint: disable=W0613",
"if",
"type_",
".",
"__traceback__",
"is",
"not",
"traceback",
":",
"raise",
"type_",
".",
"with_traceback",
"(",
"traceback",
")",
... | 40.428571 | 20.142857 |
def is_denied(self, role, method, resource):
"""Check wherther role is denied to access resource
:param role: Role to be checked.
:param method: Method to be checked.
:param resource: View function to be checked.
"""
return (role, method, resource) in self._denied | [
"def",
"is_denied",
"(",
"self",
",",
"role",
",",
"method",
",",
"resource",
")",
":",
"return",
"(",
"role",
",",
"method",
",",
"resource",
")",
"in",
"self",
".",
"_denied"
] | 38.25 | 9.5 |
def main():
'''
main function.
'''
args = parse_args()
if args.multi_thread:
enable_multi_thread()
if args.advisor_class_name:
# advisor is enabled and starts to run
if args.multi_phase:
raise AssertionError('multi_phase has not been supported in advisor')
... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"if",
"args",
".",
"multi_thread",
":",
"enable_multi_thread",
"(",
")",
"if",
"args",
".",
"advisor_class_name",
":",
"# advisor is enabled and starts to run",
"if",
"args",
".",
"multi_phase",
... | 33.717949 | 15.384615 |
def index():
"""Basic test view."""
identity = g.identity
actions = {}
for action in access.actions.values():
actions[action.value] = DynamicPermission(action).allows(identity)
if current_user.is_anonymous:
return render_template("invenio_access/open.html",
... | [
"def",
"index",
"(",
")",
":",
"identity",
"=",
"g",
".",
"identity",
"actions",
"=",
"{",
"}",
"for",
"action",
"in",
"access",
".",
"actions",
".",
"values",
"(",
")",
":",
"actions",
"[",
"action",
".",
"value",
"]",
"=",
"DynamicPermission",
"(",... | 36.875 | 15.875 |
def normalizeGlyphUnicodes(value):
"""
Normalizes glyph unicodes.
* **value** must be a ``list``.
* **value** items must normalize as glyph unicodes with
:func:`normalizeGlyphUnicode`.
* **value** must not repeat unicode values.
* Returned value will be a ``tuple`` of ints.
"""
if... | [
"def",
"normalizeGlyphUnicodes",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Glyph unicodes must be a list, not %s.\"",
"%",
"type",
"(",
"value",
")",
".",
"__... | 39.222222 | 13.222222 |
def set_extension(self, ext):
"""
RETURN NEW FILE WITH GIVEN EXTENSION
"""
path = self._filename.split("/")
parts = path[-1].split(".")
if len(parts) == 1:
parts.append(ext)
else:
parts[-1] = ext
path[-1] = ".".join(parts)
... | [
"def",
"set_extension",
"(",
"self",
",",
"ext",
")",
":",
"path",
"=",
"self",
".",
"_filename",
".",
"split",
"(",
"\"/\"",
")",
"parts",
"=",
"path",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"parts",
")",
"==",
... | 25.769231 | 10.384615 |
def set_soup(self):
"""Sets soup and strips items"""
self.soup = BeautifulSoup(self.feed_content, "html.parser")
for item in self.soup.findAll('item'):
item.decompose()
for image in self.soup.findAll('image'):
image.decompose() | [
"def",
"set_soup",
"(",
"self",
")",
":",
"self",
".",
"soup",
"=",
"BeautifulSoup",
"(",
"self",
".",
"feed_content",
",",
"\"html.parser\"",
")",
"for",
"item",
"in",
"self",
".",
"soup",
".",
"findAll",
"(",
"'item'",
")",
":",
"item",
".",
"decompo... | 39.571429 | 12.142857 |
def parse_workflow_call_body_declarations(self, i):
"""
Have not seen this used, so expects to return "[]".
:param i:
:return:
"""
declaration_array = []
if isinstance(i, wdl_parser.Terminal):
declaration_array = [i.source_string]
elif isinsta... | [
"def",
"parse_workflow_call_body_declarations",
"(",
"self",
",",
"i",
")",
":",
"declaration_array",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"i",
",",
"wdl_parser",
".",
"Terminal",
")",
":",
"declaration_array",
"=",
"[",
"i",
".",
"source_string",
"]",
"e... | 31.666667 | 15.095238 |
def FileEntryExistsByPathSpec(self, path_spec):
"""Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): path specification.
Returns:
bool: True if the file entry exists.
"""
location = getattr(path_spec, 'location', None)
if (location is None or
... | [
"def",
"FileEntryExistsByPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"location",
"=",
"getattr",
"(",
"path_spec",
",",
"'location'",
",",
"None",
")",
"if",
"(",
"location",
"is",
"None",
"or",
"not",
"location",
".",
"startswith",
"(",
"self",
".... | 24.9375 | 20.71875 |
def sample(self, n):
"""Samples data into a Pandas DataFrame. Note that it calls BigQuery so it will
incur cost.
Args:
n: number of sampled counts. Note that the number of counts returned is approximated.
Returns:
A dataframe containing sampled data.
Raises:
Exception if n is l... | [
"def",
"sample",
"(",
"self",
",",
"n",
")",
":",
"total",
"=",
"bq",
".",
"Query",
"(",
"'select count(*) from %s'",
"%",
"self",
".",
"_get_source",
"(",
")",
")",
".",
"execute",
"(",
")",
".",
"result",
"(",
")",
"[",
"0",
"]",
".",
"values",
... | 36 | 20.26087 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.