text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def check_for_upload_create(self, relative_path=None):
"""Traverse the relative_path tree and check for files that need to be uploaded/created.
Relativity here refers to the shared directory tree."""
for f in os.listdir(
path_join(
self.local_path, relative_path) if ... | [
"def",
"check_for_upload_create",
"(",
"self",
",",
"relative_path",
"=",
"None",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path_join",
"(",
"self",
".",
"local_path",
",",
"relative_path",
")",
"if",
"relative_path",
"else",
"self",
".",
"lo... | 46.777778 | 20.222222 |
def delete_checkpoint(self, checkpoint_dir):
"""Removes subdirectory within checkpoint_folder
Parameters
----------
checkpoint_dir : path to checkpoint
"""
if os.path.isfile(checkpoint_dir):
shutil.rmtree(os.path.dirname(checkpoint_dir))
else:
... | [
"def",
"delete_checkpoint",
"(",
"self",
",",
"checkpoint_dir",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"checkpoint_dir",
")",
":",
"shutil",
".",
"rmtree",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"checkpoint_dir",
")",
")",
"else",
... | 34.8 | 10.3 |
def init_bounds(self):
"""
Process bounds this process is currently initialized with.
This gets triggered by using the ``init_bounds`` kwarg. If not set, it will
be equal to self.bounds.
"""
if self._raw["init_bounds"] is None:
return self.bounds
else... | [
"def",
"init_bounds",
"(",
"self",
")",
":",
"if",
"self",
".",
"_raw",
"[",
"\"init_bounds\"",
"]",
"is",
"None",
":",
"return",
"self",
".",
"bounds",
"else",
":",
"return",
"Bounds",
"(",
"*",
"_validate_bounds",
"(",
"self",
".",
"_raw",
"[",
"\"in... | 34.727273 | 18.727273 |
def is_dictlist(data):
'''
Returns True if data is a list of one-element dicts (as found in many SLS
schemas), otherwise returns False
'''
if isinstance(data, list):
for element in data:
if isinstance(element, dict):
if len(element) != 1:
retur... | [
"def",
"is_dictlist",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"for",
"element",
"in",
"data",
":",
"if",
"isinstance",
"(",
"element",
",",
"dict",
")",
":",
"if",
"len",
"(",
"element",
")",
"!=",
"1",
":",
... | 28.428571 | 17 |
def validate_additional_properties(self, valid_response, response):
"""Validates additional properties. In additional properties, we only
need to compare the values of the dict, not the keys
Args:
valid_response: An example response (for example generated in
... | [
"def",
"validate_additional_properties",
"(",
"self",
",",
"valid_response",
",",
"response",
")",
":",
"assert",
"isinstance",
"(",
"valid_response",
",",
"dict",
")",
"assert",
"isinstance",
"(",
"response",
",",
"dict",
")",
"# the type of the value of the first ke... | 42.3125 | 21.895833 |
def _read_file(self, filename):
"""
Read contents of given file.
"""
try:
with open(filename, "r") as fhandle:
stats = float(fhandle.readline().rstrip("\n"))
except Exception:
stats = None
return stats | [
"def",
"_read_file",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"fhandle",
":",
"stats",
"=",
"float",
"(",
"fhandle",
".",
"readline",
"(",
")",
".",
"rstrip",
"(",
"\"\\n\"",
")",
... | 25.454545 | 14.727273 |
def _ssid_inventory(self, inventory, ssid):
"""
Filters an inventory to only return servers matching ssid
"""
matching_hosts = {}
for host in inventory:
if inventory[host]['comment'] == ssid:
matching_hosts[host] = inventory[host]
return match... | [
"def",
"_ssid_inventory",
"(",
"self",
",",
"inventory",
",",
"ssid",
")",
":",
"matching_hosts",
"=",
"{",
"}",
"for",
"host",
"in",
"inventory",
":",
"if",
"inventory",
"[",
"host",
"]",
"[",
"'comment'",
"]",
"==",
"ssid",
":",
"matching_hosts",
"[",
... | 32 | 12.6 |
def _extract_germline(in_file, data):
"""Extract germline calls non-somatic, non-filtered calls.
"""
out_file = "%s-germline.vcf" % utils.splitext_plus(in_file)[0]
if not utils.file_uptodate(out_file, in_file) and not utils.file_uptodate(out_file + ".gz", in_file):
with file_transaction(data, ou... | [
"def",
"_extract_germline",
"(",
"in_file",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s-germline.vcf\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"[",
"0",
"]",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"in_file",
... | 54.5 | 18.9375 |
def angleDiff(angle1, angle2, take_smaller=True):
"""
smallest difference between 2 angles
code from http://stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles
"""
a = np.arctan2(np.sin(angle1 - angle2), np.cos(angle1 - angle2))
if isinstance(a, np.ndarray) and take_smal... | [
"def",
"angleDiff",
"(",
"angle1",
",",
"angle2",
",",
"take_smaller",
"=",
"True",
")",
":",
"a",
"=",
"np",
".",
"arctan2",
"(",
"np",
".",
"sin",
"(",
"angle1",
"-",
"angle2",
")",
",",
"np",
".",
"cos",
"(",
"angle1",
"-",
"angle2",
")",
")",... | 36.642857 | 14.928571 |
def _map_segmentation_mask_to_stft_domain(mask, times, frequencies, stft_times, stft_frequencies):
"""
Maps the given `mask`, which is in domain (`frequencies`, `times`) to the new domain (`stft_frequencies`, `stft_times`)
and returns the result.
"""
assert mask.shape == (frequencies.shape[0], times... | [
"def",
"_map_segmentation_mask_to_stft_domain",
"(",
"mask",
",",
"times",
",",
"frequencies",
",",
"stft_times",
",",
"stft_frequencies",
")",
":",
"assert",
"mask",
".",
"shape",
"==",
"(",
"frequencies",
".",
"shape",
"[",
"0",
"]",
",",
"times",
".",
"sh... | 45.956522 | 29 |
def estimate_rate_matrix(C, dt=1.0, method='KL', sparsity=None,
t_agg=None, pi=None, tol=1.0E7, K0=None,
maxiter=100000, on_error='raise'):
r"""Estimate a reversible rate matrix from a count matrix.
Parameters
----------
C : (N,N) ndarray
count ... | [
"def",
"estimate_rate_matrix",
"(",
"C",
",",
"dt",
"=",
"1.0",
",",
"method",
"=",
"'KL'",
",",
"sparsity",
"=",
"None",
",",
"t_agg",
"=",
"None",
",",
"pi",
"=",
"None",
",",
"tol",
"=",
"1.0E7",
",",
"K0",
"=",
"None",
",",
"maxiter",
"=",
"1... | 43.686131 | 27.226277 |
def redirect_display(self, on):
'''
on:
* True -> set $DISPLAY to virtual screen
* False -> set $DISPLAY to original screen
:param on: bool
'''
d = self.new_display_var if on else self.old_display_var
if d is None:
log.debug('unset DISPLAY')... | [
"def",
"redirect_display",
"(",
"self",
",",
"on",
")",
":",
"d",
"=",
"self",
".",
"new_display_var",
"if",
"on",
"else",
"self",
".",
"old_display_var",
"if",
"d",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"'unset DISPLAY'",
")",
"del",
"os",
".",... | 29 | 16.866667 |
def tasks_from_queue(self, tiger, queue, state, skip=0, limit=1000,
load_executions=0):
"""
Returns a tuple with the following information:
* total items in the queue
* tasks from the given queue in the given state, latest first.
An integer may be passed in th... | [
"def",
"tasks_from_queue",
"(",
"self",
",",
"tiger",
",",
"queue",
",",
"state",
",",
"skip",
"=",
"0",
",",
"limit",
"=",
"1000",
",",
"load_executions",
"=",
"0",
")",
":",
"key",
"=",
"tiger",
".",
"_key",
"(",
"state",
",",
"queue",
")",
"pipe... | 42.711111 | 24.044444 |
def parser(self):
"""
Creates a parser for the method based on the documentation.
:return <OptionParser>
"""
usage = self.usage()
if self.__doc__:
usage += '\n' + nstr(self.__doc__)
parse = PARSER_CLASS(usage=usage)
shorts = {v: ... | [
"def",
"parser",
"(",
"self",
")",
":",
"usage",
"=",
"self",
".",
"usage",
"(",
")",
"if",
"self",
".",
"__doc__",
":",
"usage",
"+=",
"'\\n'",
"+",
"nstr",
"(",
"self",
".",
"__doc__",
")",
"parse",
"=",
"PARSER_CLASS",
"(",
"usage",
"=",
"usage"... | 27.205882 | 17.676471 |
def load_from_json(data):
"""
Load a :class:`Item` from a dictionary ot string (that will be parsed
as json)
"""
if isinstance(data, str):
data = json.loads(data)
return Item(data['title'], data['uri']) | [
"def",
"load_from_json",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"return",
"Item",
"(",
"data",
"[",
"'title'",
"]",
",",
"data",
"[",
"'uri'",
"]",
")"
] | 31.875 | 11.875 |
def p_statement_switch(p):
'statement : SWITCH LPAREN expr RPAREN switch_case_list'
p[0] = ast.Switch(p[3], p[5], lineno=p.lineno(1)) | [
"def",
"p_statement_switch",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Switch",
"(",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"5",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 46.333333 | 15.666667 |
def cardinality(self):
"""
This is an over-approximation of the cardinality of this DSIS.
:return:
"""
cardinality = 0
for si in self._si_set:
cardinality += si.cardinality
return cardinality | [
"def",
"cardinality",
"(",
"self",
")",
":",
"cardinality",
"=",
"0",
"for",
"si",
"in",
"self",
".",
"_si_set",
":",
"cardinality",
"+=",
"si",
".",
"cardinality",
"return",
"cardinality"
] | 25.1 | 15.3 |
def import_admins(self):
""" save admins to local DB """
self.message('saving admins into local DB')
saved_admins = []
for olduser in OldUser.objects.all():
try:
user = User.objects.get(Q(username=olduser.username) | Q(email=olduser.email))
excep... | [
"def",
"import_admins",
"(",
"self",
")",
":",
"self",
".",
"message",
"(",
"'saving admins into local DB'",
")",
"saved_admins",
"=",
"[",
"]",
"for",
"olduser",
"in",
"OldUser",
".",
"objects",
".",
"all",
"(",
")",
":",
"try",
":",
"user",
"=",
"User"... | 42.179487 | 19.025641 |
def _is_valid_token(self, auth_token):
'''
Check if this is a valid salt-api token or valid Salt token
salt-api tokens are regular session tokens that tie back to a real Salt
token. Salt tokens are tokens generated by Salt's eauth system.
:return bool: True if valid, False if n... | [
"def",
"_is_valid_token",
"(",
"self",
",",
"auth_token",
")",
":",
"# Make sure that auth token is hex. If it's None, or something other",
"# than hex, this will raise a ValueError.",
"try",
":",
"int",
"(",
"auth_token",
",",
"16",
")",
"except",
"(",
"TypeError",
",",
... | 41.448276 | 26.758621 |
def sun_rise_set_transit_spa(times, latitude, longitude, how='numpy',
delta_t=67.0, numthreads=4):
"""
Calculate the sunrise, sunset, and sun transit times using the
NREL SPA algorithm described in [1].
If numba is installed, the functions can be compiled to
machine cod... | [
"def",
"sun_rise_set_transit_spa",
"(",
"times",
",",
"latitude",
",",
"longitude",
",",
"how",
"=",
"'numpy'",
",",
"delta_t",
"=",
"67.0",
",",
"numthreads",
"=",
"4",
")",
":",
"# Added by Tony Lorenzo (@alorenzo175), University of Arizona, 2015",
"lat",
"=",
"la... | 38.227848 | 22.379747 |
def print_last_values():
"""Print the last 10 values."""
iterable = archive.list_parameter_values('/YSS/SIMULATOR/BatteryVoltage1',
descending=True)
for pval in islice(iterable, 0, 10):
print(pval) | [
"def",
"print_last_values",
"(",
")",
":",
"iterable",
"=",
"archive",
".",
"list_parameter_values",
"(",
"'/YSS/SIMULATOR/BatteryVoltage1'",
",",
"descending",
"=",
"True",
")",
"for",
"pval",
"in",
"islice",
"(",
"iterable",
",",
"0",
",",
"10",
")",
":",
... | 42.833333 | 16 |
def add_client(self, client_identifier):
"""Add a client."""
if client_identifier in self.clients:
_LOGGER.error('%s already in group %s', client_identifier, self.identifier)
return
new_clients = self.clients
new_clients.append(client_identifier)
yield fro... | [
"def",
"add_client",
"(",
"self",
",",
"client_identifier",
")",
":",
"if",
"client_identifier",
"in",
"self",
".",
"clients",
":",
"_LOGGER",
".",
"error",
"(",
"'%s already in group %s'",
",",
"client_identifier",
",",
"self",
".",
"identifier",
")",
"return",... | 47.727273 | 17.090909 |
def buildable(self, values: Optional[dict]=None, method: Optional[str]=None) -> bool:
"""Return True if this rule can build with the values and method."""
if method is not None and method not in self.methods:
return False
defaults_match = all(
values[key] == self.defaults... | [
"def",
"buildable",
"(",
"self",
",",
"values",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"method",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"bool",
":",
"if",
"method",
"is",
"not",
"None",
"and",
"method",
"not",
"in",... | 59.375 | 29.375 |
def flush(self):
"""Flush GL commands
This is a wrapper for glFlush(). This also flushes the GLIR
command queue.
"""
if hasattr(self, 'flush_commands'):
context = self
else:
context = get_current_canvas().context
context.glir.command('... | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'flush_commands'",
")",
":",
"context",
"=",
"self",
"else",
":",
"context",
"=",
"get_current_canvas",
"(",
")",
".",
"context",
"context",
".",
"glir",
".",
"command",
"(",
"'... | 29.916667 | 14.5 |
def validate_order_params(self,
asset,
amount,
limit_price,
stop_price,
style):
"""
Helper method for validating parameters to the order API function.
... | [
"def",
"validate_order_params",
"(",
"self",
",",
"asset",
",",
"amount",
",",
"limit_price",
",",
"stop_price",
",",
"style",
")",
":",
"if",
"not",
"self",
".",
"initialized",
":",
"raise",
"OrderDuringInitialize",
"(",
"msg",
"=",
"\"order() can only be calle... | 34.794118 | 17.617647 |
def write_file(self, path, name, data, content_type=None, archive=False,
raw=False):
"""Write a file to the file data store at the given path
:param str path: The path (directory) into which the file should be written.
:param str name: The name of the file to be written.
... | [
"def",
"write_file",
"(",
"self",
",",
"path",
",",
"name",
",",
"data",
",",
"content_type",
"=",
"None",
",",
"archive",
"=",
"False",
",",
"raw",
"=",
"False",
")",
":",
"path",
"=",
"validate_type",
"(",
"path",
",",
"*",
"six",
".",
"string_type... | 41.584906 | 21.943396 |
def getNodeByNameChain(node, chain_list):
"""
Walk down a chain of node names and get the nodes they represent
e.g. [ "entry", "content", "bag", "fileCount" ]
"""
working_list = chain_list[:]
working_list.reverse()
current_node = node
while len(working_list):
current_name = work... | [
"def",
"getNodeByNameChain",
"(",
"node",
",",
"chain_list",
")",
":",
"working_list",
"=",
"chain_list",
"[",
":",
"]",
"working_list",
".",
"reverse",
"(",
")",
"current_node",
"=",
"node",
"while",
"len",
"(",
"working_list",
")",
":",
"current_name",
"="... | 34.125 | 13.875 |
def random_ipv4(cidr='10.0.0.0/8'):
"""
Return a random IPv4 address from the given CIDR block.
:key str cidr: CIDR block
:returns: An IPv4 address from the given CIDR block
:rtype: ipaddress.IPv4Address
"""
try:
u_cidr = unicode(cidr)
except NameError:
u_cidr = cidr
... | [
"def",
"random_ipv4",
"(",
"cidr",
"=",
"'10.0.0.0/8'",
")",
":",
"try",
":",
"u_cidr",
"=",
"unicode",
"(",
"cidr",
")",
"except",
"NameError",
":",
"u_cidr",
"=",
"cidr",
"network",
"=",
"ipaddress",
".",
"ip_network",
"(",
"u_cidr",
")",
"start",
"=",... | 30.176471 | 10.882353 |
def update_subtotals(self, current, sub_key):
"""
updates sub_total counts for the class instance based on the
current dictionary counts
args:
-----
current: current dictionary counts
sub_key: the key/value to use for the subtotals
"""
... | [
"def",
"update_subtotals",
"(",
"self",
",",
"current",
",",
"sub_key",
")",
":",
"if",
"not",
"self",
".",
"sub_counts",
".",
"get",
"(",
"sub_key",
")",
":",
"self",
".",
"sub_counts",
"[",
"sub_key",
"]",
"=",
"{",
"}",
"for",
"item",
"in",
"curre... | 31.166667 | 14.944444 |
def import_obj(clsname, default_module=None):
"""
Import the object given by clsname.
If default_module is specified, import from this module.
"""
if default_module is not None:
if not clsname.startswith(default_module + '.'):
clsname = '{0}.{1}'.format(default_module, clsname)
... | [
"def",
"import_obj",
"(",
"clsname",
",",
"default_module",
"=",
"None",
")",
":",
"if",
"default_module",
"is",
"not",
"None",
":",
"if",
"not",
"clsname",
".",
"startswith",
"(",
"default_module",
"+",
"'.'",
")",
":",
"clsname",
"=",
"'{0}.{1}'",
".",
... | 36.6 | 12.466667 |
def sbo_list():
"""Return all SBo packages
"""
sbo_packages = []
for pkg in os.listdir(_meta_.pkg_path):
if pkg.endswith("_SBo"):
sbo_packages.append(pkg)
return sbo_packages | [
"def",
"sbo_list",
"(",
")",
":",
"sbo_packages",
"=",
"[",
"]",
"for",
"pkg",
"in",
"os",
".",
"listdir",
"(",
"_meta_",
".",
"pkg_path",
")",
":",
"if",
"pkg",
".",
"endswith",
"(",
"\"_SBo\"",
")",
":",
"sbo_packages",
".",
"append",
"(",
"pkg",
... | 25.875 | 9.5 |
def ask_list(question: str, default: list = None) -> list:
"""Asks for a comma seperated list of strings"""
default_q = " [default: {0}]: ".format(
",".join(default)) if default is not None else ""
answer = input("{0} [{1}]: ".format(question, default_q))
if answer == "":
return default... | [
"def",
"ask_list",
"(",
"question",
":",
"str",
",",
"default",
":",
"list",
"=",
"None",
")",
"->",
"list",
":",
"default_q",
"=",
"\" [default: {0}]: \"",
".",
"format",
"(",
"\",\"",
".",
"join",
"(",
"default",
")",
")",
"if",
"default",
"is",
"not... | 40.666667 | 16.666667 |
def processEnded(self, reason):
"""
Connected process shut down
"""
log_debug("{name} process exited", name=self.name)
if self.deferred:
if reason.type == ProcessDone:
self.deferred.callback(reason.value.exitCode)
elif reason.type == Proces... | [
"def",
"processEnded",
"(",
"self",
",",
"reason",
")",
":",
"log_debug",
"(",
"\"{name} process exited\"",
",",
"name",
"=",
"self",
".",
"name",
")",
"if",
"self",
".",
"deferred",
":",
"if",
"reason",
".",
"type",
"==",
"ProcessDone",
":",
"self",
"."... | 36.090909 | 8.818182 |
def box_model_domain(num_points=2, **kwargs):
"""Creates a box model domain (a single abstract axis).
:param int num_points: number of boxes [default: 2]
:returns: Domain with single axis of type ``'abstract'``
and ``self.domain_type = 'box'``
:rty... | [
"def",
"box_model_domain",
"(",
"num_points",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"Axis",
"(",
"axis_type",
"=",
"'abstract'",
",",
"num_points",
"=",
"num_points",
")",
"boxes",
"=",
"_Domain",
"(",
"axes",
"=",
"ax",
",",
"*",
"... | 31.304348 | 22.26087 |
def adaptive_gaussian_prior_builder(
getter, name, *args, **kwargs):
"""A pre-canned builder for adaptive scalar gaussian prior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a scalar-valued adaptive gaussian prior
which will b... | [
"def",
"adaptive_gaussian_prior_builder",
"(",
"getter",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"shape\"",
"]",
"=",
"(",
")",
"loc_var",
"=",
"getter",
"(",
"name",
"+",
"\"_prior_loc\"",
",",
"*",
"args",
"... | 44.833333 | 20.9 |
def remove_vcf_info(keyword, variant_line=None, variant_dict=None):
"""Remove the information of a info field of a vcf variant line or a
variant dict.
Arguments:
variant_line (str): A vcf formatted variant line
variant_dict (dict): A variant dictionary
keyword (str): The in... | [
"def",
"remove_vcf_info",
"(",
"keyword",
",",
"variant_line",
"=",
"None",
",",
"variant_dict",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"Removing variant information {0}\"",
".",
"format",
"(",
"keyword",
")",
")",
"fixed_variant",
"=",
"None",
... | 31.982456 | 18.701754 |
def get_pattern(self, field_name):
"""
Get a regular expression to match a formatting directive that references the given field name.
:param field_name: The name of the field to match (a string).
:returns: A compiled regular expression object.
"""
return re.compile(self.... | [
"def",
"get_pattern",
"(",
"self",
",",
"field_name",
")",
":",
"return",
"re",
".",
"compile",
"(",
"self",
".",
"raw_pattern",
".",
"replace",
"(",
"r'\\w+'",
",",
"field_name",
")",
",",
"re",
".",
"VERBOSE",
")"
] | 45.625 | 24.375 |
async def move_rel(self, mount: top_types.Mount, delta: top_types.Point,
speed: float = None):
""" Move the critical point of the specified mount by a specified
displacement in a specified direction, at the specified speed.
'speed' sets the speed of all axes to the given v... | [
"async",
"def",
"move_rel",
"(",
"self",
",",
"mount",
":",
"top_types",
".",
"Mount",
",",
"delta",
":",
"top_types",
".",
"Point",
",",
"speed",
":",
"float",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_current_position",
":",
"raise",
"MustHo... | 40.32 | 17.36 |
def add_surface(self, name, surface):
"""Adds a top-level attribute with the given name to the module."""
assert surface is not None
if hasattr(self.module, name):
raise ThriftCompilerError(
'Cannot define "%s". The name has already been used.' % name
)
... | [
"def",
"add_surface",
"(",
"self",
",",
"name",
",",
"surface",
")",
":",
"assert",
"surface",
"is",
"not",
"None",
"if",
"hasattr",
"(",
"self",
".",
"module",
",",
"name",
")",
":",
"raise",
"ThriftCompilerError",
"(",
"'Cannot define \"%s\". The name has al... | 35.4 | 15.9 |
def not_next(e):
"""
Create a PEG function for negative lookahead.
"""
def match_not_next(s, grm=None, pos=0):
try:
e(s, grm, pos)
except PegreError as ex:
return PegreResult(s, Ignore, (pos, pos))
else:
raise PegreError('Negative lookahead fai... | [
"def",
"not_next",
"(",
"e",
")",
":",
"def",
"match_not_next",
"(",
"s",
",",
"grm",
"=",
"None",
",",
"pos",
"=",
"0",
")",
":",
"try",
":",
"e",
"(",
"s",
",",
"grm",
",",
"pos",
")",
"except",
"PegreError",
"as",
"ex",
":",
"return",
"Pegre... | 28.75 | 13.583333 |
def spy(iterable, n=1):
"""Return a 2-tuple with a list containing the first *n* elements of
*iterable*, and an iterator with the same items as *iterable*.
This allows you to "look ahead" at the items in the iterable without
advancing it.
There is one item in the list by default:
>>> itera... | [
"def",
"spy",
"(",
"iterable",
",",
"n",
"=",
"1",
")",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"head",
"=",
"take",
"(",
"n",
",",
"it",
")",
"return",
"head",
",",
"chain",
"(",
"head",
",",
"it",
")"
] | 25.926829 | 21.512195 |
def adaptive(u_kn, N_k, f_k, tol = 1.0e-12, options = None):
"""
Determine dimensionless free energies by a combination of Newton-Raphson iteration and self-consistent iteration.
Picks whichever method gives the lowest gradient.
Is slower than NR since it calculates the log norms twice each iteration.
... | [
"def",
"adaptive",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
",",
"tol",
"=",
"1.0e-12",
",",
"options",
"=",
"None",
")",
":",
"# put the defaults here in case we get passed an 'options' dictionary that is only partial",
"options",
".",
"setdefault",
"(",
"'verbose'",
","... | 45.938053 | 29.230088 |
def slice_shape(self, tensor_shape):
"""Shape of each slice of the Tensor.
Args:
tensor_shape: Shape.
Returns:
list of integers with length tensor_shape.ndims.
Raises:
ValueError: If a Tensor dimension is not divisible by the corresponding
Mesh dimension.
"""
tensor_... | [
"def",
"slice_shape",
"(",
"self",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"ret",
"=",
"[",
"]",
"for",
"tensor_dim",
",",
"mesh_axis",
"in",
"zip",
"(",
"tensor_shape",
",",
"tensor_layout... | 31.535714 | 18.392857 |
def index():
"""
This is not served anywhere in the web application.
It is used explicitly in the context of generating static files since
flask-frozen requires url_for's to crawl content.
url_for's are not used with host.show_host directly and are instead
dynamically generated through javascrip... | [
"def",
"index",
"(",
")",
":",
"if",
"current_app",
".",
"config",
"[",
"'ARA_PLAYBOOK_OVERRIDE'",
"]",
"is",
"not",
"None",
":",
"override",
"=",
"current_app",
".",
"config",
"[",
"'ARA_PLAYBOOK_OVERRIDE'",
"]",
"hosts",
"=",
"(",
"models",
".",
"Host",
... | 42.3125 | 19.6875 |
def acquire_read(self, timeout=None):
"""
Acquire a read lock for the current thread, waiting at most
timeout seconds or doing a non-blocking check in case timeout
is <= 0.
In case timeout is None, the call to acquire_read blocks until
the lock request can be serviced.
... | [
"def",
"acquire_read",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"endtime",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"me",
"=",
"threading",
".",
"currentThread",
"(",
")",
"self",
".",
... | 40.5 | 13.681818 |
def create_index(self, collection, index_name, **kwargs):
"""Safely attempt to create index."""
try:
self.connection[collection].create_index(index_name, **kwargs)
except Exception as exc:
LOG.warn("Error tuning mongodb database: %s", exc) | [
"def",
"create_index",
"(",
"self",
",",
"collection",
",",
"index_name",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
".",
"connection",
"[",
"collection",
"]",
".",
"create_index",
"(",
"index_name",
",",
"*",
"*",
"kwargs",
")",
"except",
... | 47 | 18.166667 |
def getTransformForOverlayCoordinates(self, ulOverlayHandle, eTrackingOrigin, coordinatesInOverlay):
"""Get the transform in 3d space associated with a specific 2d point in the overlay's coordinate space (where 0,0 is the lower left). -Z points out of the overlay"""
fn = self.function_table.getTransfor... | [
"def",
"getTransformForOverlayCoordinates",
"(",
"self",
",",
"ulOverlayHandle",
",",
"eTrackingOrigin",
",",
"coordinatesInOverlay",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getTransformForOverlayCoordinates",
"pmatTransform",
"=",
"HmdMatrix34_t",
"(",
... | 73 | 26.857143 |
def writelines(self, lines):
'''
Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
:param lines:
'''
if self.__closed:
raise OSError()
for line in lines:
... | [
"def",
"writelines",
"(",
"self",
",",
"lines",
")",
":",
"if",
"self",
".",
"__closed",
":",
"raise",
"OSError",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"self",
".",
"write",
"(",
"line",
")"
] | 37.666667 | 29.444444 |
def _traverse_relationship_rev_objs(self, rel2dst2srcs, goobj_parent, goids_seen):
"""Traverse from source GO down children."""
parent_id = goobj_parent.id
goids_seen.add(parent_id)
##A self.go2obj[parent_id] = goobj_parent
# Update goids_seen and go2obj with parent alt_ids
... | [
"def",
"_traverse_relationship_rev_objs",
"(",
"self",
",",
"rel2dst2srcs",
",",
"goobj_parent",
",",
"goids_seen",
")",
":",
"parent_id",
"=",
"goobj_parent",
".",
"id",
"goids_seen",
".",
"add",
"(",
"parent_id",
")",
"##A self.go2obj[parent_id] = goobj_parent",
"# ... | 54.526316 | 16.421053 |
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided accoun... | [
"def",
"add_member",
"(",
"self",
",",
"user_lookup_attribute_value",
")",
":",
"add_member",
"=",
"{",
"'member'",
":",
"(",
"MODIFY_ADD",
",",
"[",
"self",
".",
"_get_user_dn",
"(",
"user_lookup_attribute_value",
")",
"]",
")",
"}",
"self",
".",
"_attempt_mo... | 60.823529 | 40 |
def _to_tuple(self, _list):
""" Recursively converts lists to tuples """
result = list()
for l in _list:
if isinstance(l, list):
result.append(tuple(self._to_tuple(l)))
else:
result.append(l)
return tuple(result) | [
"def",
"_to_tuple",
"(",
"self",
",",
"_list",
")",
":",
"result",
"=",
"list",
"(",
")",
"for",
"l",
"in",
"_list",
":",
"if",
"isinstance",
"(",
"l",
",",
"list",
")",
":",
"result",
".",
"append",
"(",
"tuple",
"(",
"self",
".",
"_to_tuple",
"... | 32.444444 | 12.222222 |
def do_GET(self):
"""
Handle the retrieval of the code
"""
parsed_url = urlparse(self.path)
if parsed_url[2] == "/" + SERVER_REDIRECT_PATH: # 2 = Path
parsed_query = parse_qs(parsed_url[4]) # 4 = Query
if "code" not in parsed_query:
self.send_response(200)
self.send_header("Content-Type", "t... | [
"def",
"do_GET",
"(",
"self",
")",
":",
"parsed_url",
"=",
"urlparse",
"(",
"self",
".",
"path",
")",
"if",
"parsed_url",
"[",
"2",
"]",
"==",
"\"/\"",
"+",
"SERVER_REDIRECT_PATH",
":",
"# 2 = Path",
"parsed_query",
"=",
"parse_qs",
"(",
"parsed_url",
"[",... | 31.289474 | 21.289474 |
def _fill_empty_sessions(self, fill_subjects, fill_visits):
"""
Fill in tree with additional empty subjects and/or visits to
allow the study to pull its inputs from external repositories
"""
if fill_subjects is None:
fill_subjects = [s.id for s in self.subjects]
... | [
"def",
"_fill_empty_sessions",
"(",
"self",
",",
"fill_subjects",
",",
"fill_visits",
")",
":",
"if",
"fill_subjects",
"is",
"None",
":",
"fill_subjects",
"=",
"[",
"s",
".",
"id",
"for",
"s",
"in",
"self",
".",
"subjects",
"]",
"if",
"fill_visits",
"is",
... | 44.592593 | 12.814815 |
def create_intent(project_id, display_name, training_phrases_parts,
message_texts):
"""Create an intent of the given intent type."""
import dialogflow_v2 as dialogflow
intents_client = dialogflow.IntentsClient()
parent = intents_client.project_agent_path(project_id)
training_phras... | [
"def",
"create_intent",
"(",
"project_id",
",",
"display_name",
",",
"training_phrases_parts",
",",
"message_texts",
")",
":",
"import",
"dialogflow_v2",
"as",
"dialogflow",
"intents_client",
"=",
"dialogflow",
".",
"IntentsClient",
"(",
")",
"parent",
"=",
"intents... | 40 | 18.538462 |
def _cram_to_fastq_region(cram_file, work_dir, base_name, region, data):
"""Convert CRAM to fastq in a specified region.
"""
ref_file = tz.get_in(["reference", "fasta", "base"], data)
resources = config_utils.get_resources("bamtofastq", data["config"])
cores = tz.get_in(["config", "algorithm", "num_... | [
"def",
"_cram_to_fastq_region",
"(",
"cram_file",
",",
"work_dir",
",",
"base_name",
",",
"region",
",",
"data",
")",
":",
"ref_file",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"reference\"",
",",
"\"fasta\"",
",",
"\"base\"",
"]",
",",
"data",
")",
"resources... | 64.75 | 27.75 |
def unique_iter(src, key=None):
"""Yield unique elements from the iterable, *src*, based on *key*,
in the order in which they first appeared in *src*.
>>> repetitious = [1, 2, 3] * 10
>>> list(unique_iter(repetitious))
[1, 2, 3]
By default, *key* is the object itself, but *key* can either be a... | [
"def",
"unique_iter",
"(",
"src",
",",
"key",
"=",
"None",
")",
":",
"if",
"not",
"is_iterable",
"(",
"src",
")",
":",
"raise",
"TypeError",
"(",
"'expected an iterable, not %r'",
"%",
"type",
"(",
"src",
")",
")",
"if",
"key",
"is",
"None",
":",
"key_... | 32.823529 | 19.147059 |
def get_api_client(cls):
"""Get an API client (with configuration)."""
config = cloudsmith_api.Configuration()
client = cls()
client.config = config
client.api_client.rest_client = RestClient()
user_agent = getattr(config, "user_agent", None)
if user_agent:
client.api_client.user_ag... | [
"def",
"get_api_client",
"(",
"cls",
")",
":",
"config",
"=",
"cloudsmith_api",
".",
"Configuration",
"(",
")",
"client",
"=",
"cls",
"(",
")",
"client",
".",
"config",
"=",
"config",
"client",
".",
"api_client",
".",
"rest_client",
"=",
"RestClient",
"(",... | 29.529412 | 17.470588 |
def run(self):
"""Run git add and commit with message if provided."""
if os.system('git add .'):
sys.exit(1)
if self.message is not None:
os.system('git commit -a -m "' + self.message + '"')
else:
os.system('git commit -a') | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"os",
".",
"system",
"(",
"'git add .'",
")",
":",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"self",
".",
"message",
"is",
"not",
"None",
":",
"os",
".",
"system",
"(",
"'git commit -a -m \"'",
"+",
"self",... | 35.5 | 13.25 |
def _find_links(self):
processed = {}
links = []
body = re.search('<[^>]*body[^>]*>(.+?)</body>', self.text, re.S).group(1)
"""
The link follow by the span.t-mark-rev will contained c++xx information.
Consider the below case
<a href="LinkA">LinkA</a>
<... | [
"def",
"_find_links",
"(",
"self",
")",
":",
"processed",
"=",
"{",
"}",
"links",
"=",
"[",
"]",
"body",
"=",
"re",
".",
"search",
"(",
"'<[^>]*body[^>]*>(.+?)</body>'",
",",
"self",
".",
"text",
",",
"re",
".",
"S",
")",
".",
"group",
"(",
"1",
")... | 35.6 | 17.771429 |
def serve(content):
"""Write content to a temp file and serve it in browser"""
temp_folder = tempfile.gettempdir()
temp_file_name = tempfile.gettempprefix() + str(uuid.uuid4()) + ".html"
# Generate a file path with a random name in temporary dir
temp_file_path = os.path.join(temp_folder, temp_file_n... | [
"def",
"serve",
"(",
"content",
")",
":",
"temp_folder",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"temp_file_name",
"=",
"tempfile",
".",
"gettempprefix",
"(",
")",
"+",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"+",
"\".html\"",
"# Generate ... | 33.1 | 18 |
def parents(self) -> List[str]:
"""
Return the list of parents SHAs.
:return: List[str] parents
"""
parents = []
for p in self._c_object.parents:
parents.append(p.hexsha)
return parents | [
"def",
"parents",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"parents",
"=",
"[",
"]",
"for",
"p",
"in",
"self",
".",
"_c_object",
".",
"parents",
":",
"parents",
".",
"append",
"(",
"p",
".",
"hexsha",
")",
"return",
"parents"
] | 24.5 | 9.7 |
def _solve_k_from_mu(data, k_array, nll, *args):
"""
For given args, return k_agg from searching some k_range.
Parameters
----------
data : array
k_range : array
nll : function
args :
Returns
--------
:float
Minimum k_agg
"""
# TODO: See if a root finder l... | [
"def",
"_solve_k_from_mu",
"(",
"data",
",",
"k_array",
",",
"nll",
",",
"*",
"args",
")",
":",
"# TODO: See if a root finder like fminbound would work with Decimal used in",
"# logpmf method (will this work with arrays?)",
"nll_array",
"=",
"np",
".",
"zeros",
"(",
"len",
... | 20.241379 | 23.551724 |
def strip_flags(self, idx):
"""strip(1 byte) radiotap.flags
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
flags = collections.namedtuple(
'flags', ['cfp', 'preamble', 'wep', 'fragmentation', 'fcs',
'datapad', ... | [
"def",
"strip_flags",
"(",
"self",
",",
"idx",
")",
":",
"flags",
"=",
"collections",
".",
"namedtuple",
"(",
"'flags'",
",",
"[",
"'cfp'",
",",
"'preamble'",
",",
"'wep'",
",",
"'fragmentation'",
",",
"'fcs'",
",",
"'datapad'",
",",
"'badfcs'",
",",
"'s... | 35.142857 | 9.428571 |
def reload(module, exclude=['sys', 'os.path', '__builtin__', '__main__']):
"""Recursively reload all modules used in the given module. Optionally
takes a list of modules to exclude from reloading. The default exclude
list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
display, ex... | [
"def",
"reload",
"(",
"module",
",",
"exclude",
"=",
"[",
"'sys'",
",",
"'os.path'",
",",
"'__builtin__'",
",",
"'__main__'",
"]",
")",
":",
"global",
"found_now",
"for",
"i",
"in",
"exclude",
":",
"found_now",
"[",
"i",
"]",
"=",
"1",
"try",
":",
"w... | 37.266667 | 18.733333 |
def delete(self):
"""Delete the instance."""
if lib.EnvDeleteInstance(self._env, self._ist) != 1:
raise CLIPSError(self._env) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"lib",
".",
"EnvDeleteInstance",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_ist",
")",
"!=",
"1",
":",
"raise",
"CLIPSError",
"(",
"self",
".",
"_env",
")"
] | 37.5 | 11 |
def get(self, wheel=False):
"""Downloads the package from PyPI.
Returns:
Full path of the downloaded file.
Raises:
PermissionError if the save_dir is not writable.
"""
try:
url = get_url(self.client, self.name, self.version,
... | [
"def",
"get",
"(",
"self",
",",
"wheel",
"=",
"False",
")",
":",
"try",
":",
"url",
"=",
"get_url",
"(",
"self",
".",
"client",
",",
"self",
".",
"name",
",",
"self",
".",
"version",
",",
"wheel",
",",
"hashed_format",
"=",
"True",
")",
"[",
"0",... | 35.681818 | 16.227273 |
def format(args):
"""
%prog format infasta outfasta
Reformat FASTA file and also clean up names.
"""
sequential_choices = ("replace", "prefix", "suffix")
p = OptionParser(format.__doc__)
p.add_option("--pairs", default=False, action="store_true",
help="Add trailing /1 and /2 for... | [
"def",
"format",
"(",
"args",
")",
":",
"sequential_choices",
"=",
"(",
"\"replace\"",
",",
"\"prefix\"",
",",
"\"suffix\"",
")",
"p",
"=",
"OptionParser",
"(",
"format",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--pairs\"",
",",
"default",
"=",... | 40.537815 | 19.159664 |
def load_molecule_in_rdkit_smiles(self, molSize,kekulize=True,bonds=[],bond_color=None,atom_color = {}, size= {} ):
"""
Loads mol file in rdkit without the hydrogens - they do not have to appear in the final
figure. Once loaded, the molecule is converted to SMILES format which RDKit appears to
... | [
"def",
"load_molecule_in_rdkit_smiles",
"(",
"self",
",",
"molSize",
",",
"kekulize",
"=",
"True",
",",
"bonds",
"=",
"[",
"]",
",",
"bond_color",
"=",
"None",
",",
"atom_color",
"=",
"{",
"}",
",",
"size",
"=",
"{",
"}",
")",
":",
"mol_in_rdkit",
"=",... | 52.021277 | 28.06383 |
def send(self, obj_id):
"""
Send email to the assigned lists
:param obj_id: int
:return: dict|str
"""
response = self._client.session.post(
'{url}/{id}/send'.format(
url=self.endpoint_url, id=obj_id
)
)
return self.... | [
"def",
"send",
"(",
"self",
",",
"obj_id",
")",
":",
"response",
"=",
"self",
".",
"_client",
".",
"session",
".",
"post",
"(",
"'{url}/{id}/send'",
".",
"format",
"(",
"url",
"=",
"self",
".",
"endpoint_url",
",",
"id",
"=",
"obj_id",
")",
")",
"ret... | 25.692308 | 12.769231 |
def distance(self, physical_qubit1, physical_qubit2):
"""Returns the undirected distance between physical_qubit1 and physical_qubit2.
Args:
physical_qubit1 (int): A physical qubit
physical_qubit2 (int): Another physical qubit
Returns:
int: The undirected dis... | [
"def",
"distance",
"(",
"self",
",",
"physical_qubit1",
",",
"physical_qubit2",
")",
":",
"if",
"physical_qubit1",
"not",
"in",
"self",
".",
"physical_qubits",
":",
"raise",
"CouplingError",
"(",
"\"%s not in coupling graph\"",
"%",
"(",
"physical_qubit1",
",",
")... | 41.55 | 20.55 |
def induce(self, b, filestem='default',
examples=None,
pos=None,
neg=None,
cn2sd=True,
printOutput=False):
"""
Generate features and find subgroups.
:param filestem: The base name of this experiment.
... | [
"def",
"induce",
"(",
"self",
",",
"b",
",",
"filestem",
"=",
"'default'",
",",
"examples",
"=",
"None",
",",
"pos",
"=",
"None",
",",
"neg",
"=",
"None",
",",
"cn2sd",
"=",
"True",
",",
"printOutput",
"=",
"False",
")",
":",
"# Write the inputs",
"s... | 41.396552 | 20.258621 |
def precipitable_water(self, value=999.0):
"""Corresponds to IDD Field `precipitable_water`
Args:
value (float): value for IDD Field `precipitable_water`
Unit: mm
Missing value: 999.0
if `value` is None it will not be checked against the
... | [
"def",
"precipitable_water",
"(",
"self",
",",
"value",
"=",
"999.0",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of... | 33.086957 | 18.695652 |
def xmlFile(path, mode='r'):
"""lxml cannot parse XML files starting with a BOM
(see http://www.w3.org/TR/2000/REC-xml-20001006 in F.1.)
In case such XML file is used, we must skip these characters
So we open all XML files for read with 'xmlFile'.
TODO: File this issue to lxml ML or tracker (feature... | [
"def",
"xmlFile",
"(",
"path",
",",
"mode",
"=",
"'r'",
")",
":",
"fh",
"=",
"file",
"(",
"path",
",",
"mode",
")",
"while",
"fh",
".",
"read",
"(",
"1",
")",
"!=",
"'<'",
":",
"# Ignoring everything before '<?xml...'",
"pass",
"fh",
".",
"seek",
"("... | 36.466667 | 17.333333 |
def showMessageOverlay(self, pchText, pchCaption, pchButton0Text, pchButton1Text, pchButton2Text, pchButton3Text):
"""Show the message overlay. This will block and return you a result."""
fn = self.function_table.showMessageOverlay
result = fn(pchText, pchCaption, pchButton0Text, pchButton1Text... | [
"def",
"showMessageOverlay",
"(",
"self",
",",
"pchText",
",",
"pchCaption",
",",
"pchButton0Text",
",",
"pchButton1Text",
",",
"pchButton2Text",
",",
"pchButton3Text",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"showMessageOverlay",
"result",
"=",
... | 61.666667 | 34.666667 |
def _match_iter_generic(self, path_elements, start_at):
"""Implementation of match_iter for >1 self.elements"""
length = len(path_elements)
# If bound to start, we stop searching at the first element
if self.bound_start:
end = 1
else:
end = length - self.... | [
"def",
"_match_iter_generic",
"(",
"self",
",",
"path_elements",
",",
"start_at",
")",
":",
"length",
"=",
"len",
"(",
"path_elements",
")",
"# If bound to start, we stop searching at the first element",
"if",
"self",
".",
"bound_start",
":",
"end",
"=",
"1",
"else"... | 37.194444 | 18.166667 |
def user_has_permission(self, user, name):
""" verify user has permission """
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if not targetRecord:
return False
for group in targetRecord.groups:
if self.has_permission(group.role, name)... | [
"def",
"user_has_permission",
"(",
"self",
",",
"user",
",",
"name",
")",
":",
"targetRecord",
"=",
"AuthMembership",
".",
"objects",
"(",
"creator",
"=",
"self",
".",
"client",
",",
"user",
"=",
"user",
")",
".",
"first",
"(",
")",
"if",
"not",
"targe... | 40.222222 | 13.555556 |
def getPointsForInterpolation(self,EndOfPrdvP,aNrmNow):
'''
Finds interpolation points (c,m) for the consumption function.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
aNrmNow : np.array
Array of end-of-perio... | [
"def",
"getPointsForInterpolation",
"(",
"self",
",",
"EndOfPrdvP",
",",
"aNrmNow",
")",
":",
"cNrmNow",
"=",
"self",
".",
"uPinv",
"(",
"EndOfPrdvP",
")",
"mNrmNow",
"=",
"cNrmNow",
"+",
"aNrmNow",
"# Limiting consumption is zero as m approaches mNrmMin",
"c_for_inte... | 33.451613 | 20.870968 |
def get_ethernet_settings(self):
"""
Gets the Ethernet interconnect settings for the Logical Interconnect.
Returns:
dict: Ethernet Interconnect Settings
"""
uri = "{}/ethernetSettings".format(self.data["uri"])
return self._helper.do_get(uri) | [
"def",
"get_ethernet_settings",
"(",
"self",
")",
":",
"uri",
"=",
"\"{}/ethernetSettings\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"\"uri\"",
"]",
")",
"return",
"self",
".",
"_helper",
".",
"do_get",
"(",
"uri",
")"
] | 32.666667 | 15.333333 |
def _temporal_distance_pdf(self):
"""
Temporal distance probability density function.
Returns
-------
non_delta_peak_split_points: numpy.array
non_delta_peak_densities: numpy.array
len(density) == len(temporal_distance_split_points_ordered) -1
delta_p... | [
"def",
"_temporal_distance_pdf",
"(",
"self",
")",
":",
"temporal_distance_split_points_ordered",
",",
"norm_cdf",
"=",
"self",
".",
"_temporal_distance_cdf",
"(",
")",
"delta_peak_loc_to_probability_mass",
"=",
"{",
"}",
"non_delta_peak_split_points",
"=",
"[",
"temporal... | 47.206897 | 21.827586 |
def _JzStaeckelIntegrandSquared(v,E,Lz,I3V,delta,u0,cosh2u0,sinh2u0,
potu0pi2,pot):
#potu0pi2= potentialStaeckel(u0,nu.pi/2.,pot,delta)
"""The J_z integrand: p_v(v)/2/delta^2"""
sin2v= nu.sin(v)**2.
dV= cosh2u0*potu0pi2\
-(sinh2u0+sin2v)*potentialStaeckel(u0,v,pot... | [
"def",
"_JzStaeckelIntegrandSquared",
"(",
"v",
",",
"E",
",",
"Lz",
",",
"I3V",
",",
"delta",
",",
"u0",
",",
"cosh2u0",
",",
"sinh2u0",
",",
"potu0pi2",
",",
"pot",
")",
":",
"#potu0pi2= potentialStaeckel(u0,nu.pi/2.,pot,delta)",
"sin2v",
"=",
"nu",
".",
"... | 46.5 | 13.625 |
def run_one(self, set_title=False):
'''Get exactly one job, run it, and return.
Does nothing (but returns :const:`False`) if there is no work
to do. Ignores the global mode; this will do work even
if :func:`rejester.TaskMaster.get_mode` returns
:attr:`~rejester.TaskMaster.TERMI... | [
"def",
"run_one",
"(",
"self",
",",
"set_title",
"=",
"False",
")",
":",
"available_gb",
"=",
"MultiWorker",
".",
"available_gb",
"(",
")",
"unit",
"=",
"self",
".",
"task_master",
".",
"get_work",
"(",
"self",
".",
"worker_id",
",",
"available_gb",
",",
... | 42.545455 | 21.939394 |
def sigmaT2(self,R,z,nsigma=None,mc=False,nmc=10000,
gl=True,ngl=_DEFAULTNGL,**kwargs):
"""
NAME:
sigmaT2
PURPOSE:
calculate sigma_T^2 by marginalizing over velocity
INPUT:
R - radius at which to calculate this (can be Quantity)
... | [
"def",
"sigmaT2",
"(",
"self",
",",
"R",
",",
"z",
",",
"nsigma",
"=",
"None",
",",
"mc",
"=",
"False",
",",
"nmc",
"=",
"10000",
",",
"gl",
"=",
"True",
",",
"ngl",
"=",
"_DEFAULTNGL",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mc",
":",
"sur... | 41.025974 | 27.675325 |
def humanize(self):
"""
Humanize relative to now:
.. testsetup::
from datetime import timedelta
from delorean import Delorean
.. doctest::
>>> past = Delorean.utcnow() - timedelta(hours=1)
>>> past.humanize()
'an hour ago'
... | [
"def",
"humanize",
"(",
"self",
")",
":",
"now",
"=",
"self",
".",
"now",
"(",
"self",
".",
"timezone",
")",
"return",
"humanize",
".",
"naturaltime",
"(",
"now",
"-",
"self",
")"
] | 21.052632 | 19.157895 |
def draw_text(self, video_name, out, start, end, x, y, text,
color='0xFFFFFF', show_background=0,
background_color='0x000000', size=16):
"""
Draws text over a video
@param video_name : name of video input file
@param out : name of video output file
... | [
"def",
"draw_text",
"(",
"self",
",",
"video_name",
",",
"out",
",",
"start",
",",
"end",
",",
"x",
",",
"y",
",",
"text",
",",
"color",
"=",
"'0xFFFFFF'",
",",
"show_background",
"=",
"0",
",",
"background_color",
"=",
"'0x000000'",
",",
"size",
"=",
... | 42.55814 | 15.255814 |
def get_binom(base1, base2, estE, estH):
"""
return probability of base call
"""
prior_homo = (1. - estH) / 2.
prior_hete = estH
## calculate probs
bsum = base1 + base2
hetprob = scipy.misc.comb(bsum, base1)/(2. **(bsum))
homoa = scipy.stats.binom.pmf(base2, bsum, estE)... | [
"def",
"get_binom",
"(",
"base1",
",",
"base2",
",",
"estE",
",",
"estH",
")",
":",
"prior_homo",
"=",
"(",
"1.",
"-",
"estH",
")",
"/",
"2.",
"prior_hete",
"=",
"estH",
"## calculate probs",
"bsum",
"=",
"base1",
"+",
"base2",
"hetprob",
"=",
"scipy",... | 24.321429 | 17.75 |
def update_extent(self, extent):
# type: (int) -> None
'''
Update the extent for this CE record.
Parameters:
extent - The new extent for this CE record.
Returns:
Nothing.
'''
if not self._initialized:
raise pycdlibexception.PyCdlibIn... | [
"def",
"update_extent",
"(",
"self",
",",
"extent",
")",
":",
"# type: (int) -> None",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'CE record not yet initialized!'",
")",
"self",
".",
"bl_cont_area",
... | 27.714286 | 21.714286 |
def data_dtype(self):
"""Data type of the data block as determined from `header`.
If no header is available (i.e., before it has been initialized),
or the header entry ``'mode'`` is missing, the data type gained
from the ``dtype`` argument in the initializer is returned.
Otherwi... | [
"def",
"data_dtype",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"header",
":",
"return",
"self",
".",
"_init_data_dtype",
"try",
":",
"mode",
"=",
"int",
"(",
"self",
".",
"header",
"[",
"'mode'",
"]",
"[",
"'value'",
"]",
")",
"except",
"KeyEr... | 38.789474 | 17.736842 |
def remove_pattern(root, pat, verbose=True):
"""
Given a directory, and a pattern of files like "garbage.txt" or
"*pyc" inside it, remove them.
Try not to delete the whole OS while you're at it.
"""
print("removing pattern", root, pat)
combined = root + pat
print('combined', combined)
... | [
"def",
"remove_pattern",
"(",
"root",
",",
"pat",
",",
"verbose",
"=",
"True",
")",
":",
"print",
"(",
"\"removing pattern\"",
",",
"root",
",",
"pat",
")",
"combined",
"=",
"root",
"+",
"pat",
"print",
"(",
"'combined'",
",",
"combined",
")",
"items",
... | 31.555556 | 13.777778 |
def find_root_path(absolute_path, relative_path):
"""
Return the root path of a path relative to an absolute path.
Example:
@param absolute_path: an absolute path that is ended by the specified
relative path.
@param relative_path: a relative path that ends the specified absolute
p... | [
"def",
"find_root_path",
"(",
"absolute_path",
",",
"relative_path",
")",
":",
"_absolute_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"absolute_path",
")",
"_relative_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"relative_path",
")",
"index",
... | 32.363636 | 24.454545 |
def main(argv=None):
'''Command line options.'''
program_name = os.path.basename(sys.argv[0])
program_version = "v0.1"
program_build_date = "%s" % __updated__
program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
#program_usage = '''usage: spam two eggs''' # op... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"program_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"program_version",
"=",
"\"v0.1\"",
"program_build_date",
"=",
"\"%s\"",
"%",
"__updated__",
"program... | 38.584416 | 28.350649 |
def _param_to_list(self):
"""
Convert parameters defined in `self._param` to list
:return None
"""
for item in self._params:
self.__dict__[item] = list(self.__dict__[item]) | [
"def",
"_param_to_list",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"_params",
":",
"self",
".",
"__dict__",
"[",
"item",
"]",
"=",
"list",
"(",
"self",
".",
"__dict__",
"[",
"item",
"]",
")"
] | 27.25 | 15 |
def confusion(df, labels=['neg', 'pos']):
""" Binary classification confusion """
c = pd.DataFrame(np.zeros((2, 2)), dtype=int)
a, b = df.columns[:2] # labels[df.columns[:2]]
c.columns = sorted(set(df[a]))[:2]
c.columns.name = a
c.index = list(c.columns)
c.index.name = b
c1, c2 = c.colu... | [
"def",
"confusion",
"(",
"df",
",",
"labels",
"=",
"[",
"'neg'",
",",
"'pos'",
"]",
")",
":",
"c",
"=",
"pd",
".",
"DataFrame",
"(",
"np",
".",
"zeros",
"(",
"(",
"2",
",",
"2",
")",
")",
",",
"dtype",
"=",
"int",
")",
"a",
",",
"b",
"=",
... | 38.5 | 12.142857 |
def connect(self, datas=None):
"""
Connects ``Pipers`` in the order input -> output. See ``Piper.connect``.
According to the pipes (topology). If "datas" is given will connect the
input ``Pipers`` to the input data see: ``Dagger.connect_inputs``.
Argumensts:
... | [
"def",
"connect",
"(",
"self",
",",
"datas",
"=",
"None",
")",
":",
"# if data connect inputs",
"if",
"datas",
":",
"self",
".",
"connect_inputs",
"(",
"datas",
")",
"# connect the remaining pipers",
"postorder",
"=",
"self",
".",
"postorder",
"(",
")",
"self"... | 44.413793 | 18.551724 |
def _add_imports_to_env(self, raw_api):
"""
Scans raw parser output for import declarations. Checks if the imports
are valid, and then creates a reference to the namespace in the
environment.
Args:
raw_api (Tuple[Namespace, List[stone.stone.parser._Element]]):
... | [
"def",
"_add_imports_to_env",
"(",
"self",
",",
"raw_api",
")",
":",
"for",
"namespace",
",",
"desc",
"in",
"raw_api",
":",
"for",
"item",
"in",
"desc",
":",
"if",
"isinstance",
"(",
"item",
",",
"AstImport",
")",
":",
"if",
"namespace",
".",
"name",
"... | 50.59375 | 18.65625 |
def YiqToRgb(y, i, q):
'''Convert the color from YIQ coordinates to RGB.
Parameters:
:y:
Tte Y component value [0...1]
:i:
The I component value [0...1]
:q:
The Q component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
... | [
"def",
"YiqToRgb",
"(",
"y",
",",
"i",
",",
"q",
")",
":",
"r",
"=",
"y",
"+",
"(",
"i",
"*",
"0.9562",
")",
"+",
"(",
"q",
"*",
"0.6210",
")",
"g",
"=",
"y",
"-",
"(",
"i",
"*",
"0.2717",
")",
"-",
"(",
"q",
"*",
"0.6485",
")",
"b",
... | 23 | 21.4 |
def update(self, **kwargs):
"""Updates global configuration settings with given values.
First checks if given configuration values differ from current values.
If any of the configuration values changed, generates a change event.
Currently we generate change event for any configuration c... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Update inherited configurations",
"super",
"(",
"CommonConf",
",",
"self",
")",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"conf_changed",
"=",
"False",
"# Validate given configurations and ch... | 41.827586 | 20.517241 |
def UpdateSet(self, dataset):
"""Updates each hypothesis based on the dataset.
This is more efficient than calling Update repeatedly because
it waits until the end to Normalize.
Modifies the suite directly; if you want to keep the original, make
a copy.
dataset: a sequ... | [
"def",
"UpdateSet",
"(",
"self",
",",
"dataset",
")",
":",
"for",
"data",
"in",
"dataset",
":",
"for",
"hypo",
"in",
"self",
".",
"Values",
"(",
")",
":",
"like",
"=",
"self",
".",
"Likelihood",
"(",
"data",
",",
"hypo",
")",
"self",
".",
"Mult",
... | 31.055556 | 17 |
def is_vertex_coloring(G, coloring):
"""Determines whether the given coloring is a vertex coloring of graph G.
Parameters
----------
G : NetworkX graph
The graph on which the vertex coloring is applied.
coloring : dict
A coloring of the nodes of G. Should be a dict of the form
... | [
"def",
"is_vertex_coloring",
"(",
"G",
",",
"coloring",
")",
":",
"return",
"all",
"(",
"coloring",
"[",
"u",
"]",
"!=",
"coloring",
"[",
"v",
"]",
"for",
"u",
",",
"v",
"in",
"G",
".",
"edges",
")"
] | 31.571429 | 23.657143 |
def delete(self, path='', **params):
"""
Make a DELETE request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to URL parameters.
DELETE requests ask to delete the object represented by this URL.
"""
params = jsonify_p... | [
"def",
"delete",
"(",
"self",
",",
"path",
"=",
"''",
",",
"*",
"*",
"params",
")",
":",
"params",
"=",
"jsonify_parameters",
"(",
"params",
")",
"url",
"=",
"ensure_trailing_slash",
"(",
"self",
".",
"url",
"+",
"path",
".",
"lstrip",
"(",
"'/'",
")... | 37.916667 | 20.916667 |
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
creds = get_creds()
clc.v1.SetCredentials(... | [
"def",
"list_nodes_full",
"(",
"call",
"=",
"None",
",",
"for_output",
"=",
"True",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_full function must be called with -f or --function.'",
")",
"creds",
"=",
"get_cred... | 37.285714 | 19.857143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.