text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_listed_projects():
"""Find the projects listed in the Home Documentation's
index.md file
Returns:
set(str): projects' names, with the '/' in their beginings
"""
index_path = Path().resolve() / "docs" / "index.md"
with open(index_path, "r") as index_file:
lines = index_fi... | [
"def",
"get_listed_projects",
"(",
")",
":",
"index_path",
"=",
"Path",
"(",
")",
".",
"resolve",
"(",
")",
"/",
"\"docs\"",
"/",
"\"index.md\"",
"with",
"open",
"(",
"index_path",
",",
"\"r\"",
")",
"as",
"index_file",
":",
"lines",
"=",
"index_file",
"... | 37.21875 | 15.71875 |
def signalflow(self, token, endpoint=None, timeout=None, compress=None):
"""Obtain a SignalFlow API client."""
from . import signalflow
compress = compress if compress is not None else self._compress
return signalflow.SignalFlowClient(
token=token,
endpoint=endpoi... | [
"def",
"signalflow",
"(",
"self",
",",
"token",
",",
"endpoint",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"compress",
"=",
"None",
")",
":",
"from",
".",
"import",
"signalflow",
"compress",
"=",
"compress",
"if",
"compress",
"is",
"not",
"None",
... | 46.333333 | 13.333333 |
def settings(**kwargs):
"""Modifier decorator to update a patch's settings.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
kwargs
Sett... | [
"def",
"settings",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"wrapped",
")",
":",
"data",
"=",
"get_decorator_data",
"(",
"_get_base",
"(",
"wrapped",
")",
",",
"set_default",
"=",
"True",
")",
"data",
".",
"override",
".",
"setdefault"... | 27.478261 | 23.826087 |
def do_directory_repo(self, repo):
'''
[Re]define REPO as directory package repository.
directory_repo REPO
'''
self.abort_on_missing_effective_repo_name(repo, 'directory_repo')
repo_name = self.get_effective_repo_name(repo)
try:
self.network.set(repo... | [
"def",
"do_directory_repo",
"(",
"self",
",",
"repo",
")",
":",
"self",
".",
"abort_on_missing_effective_repo_name",
"(",
"repo",
",",
"'directory_repo'",
")",
"repo_name",
"=",
"self",
".",
"get_effective_repo_name",
"(",
"repo",
")",
"try",
":",
"self",
".",
... | 37 | 20.538462 |
def assert_condition_md5(self):
"""If the ``Content-MD5`` request header is present in the request
it's verified against the MD5 hash of the request body. If they don't
match, a 400 HTTP response is returned.
:raises: :class:`webob.exceptions.ResponseException` of status 400 if
... | [
"def",
"assert_condition_md5",
"(",
"self",
")",
":",
"if",
"'Content-MD5'",
"in",
"self",
".",
"request",
".",
"headers",
":",
"body_md5",
"=",
"hashlib",
".",
"md5",
"(",
"self",
".",
"request",
".",
"body",
")",
".",
"hexdigest",
"(",
")",
"if",
"bo... | 51.833333 | 19.583333 |
def _make_random_string(length):
"""Returns a random lowercase, uppercase, alphanumerical string.
:param int length: The length in bytes of the string to generate.
"""
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
return ''.join(random.choice(chars) for x in range(length)) | [
"def",
"_make_random_string",
"(",
"length",
")",
":",
"chars",
"=",
"string",
".",
"ascii_lowercase",
"+",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"digits",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"chars",
")",
"for",... | 44.857143 | 19.285714 |
def reset_counter(self):
""" reset the failed connection counters
"""
self._cnt_retries = 0
for i in self._url_counter:
self._url_counter[i] = 0 | [
"def",
"reset_counter",
"(",
"self",
")",
":",
"self",
".",
"_cnt_retries",
"=",
"0",
"for",
"i",
"in",
"self",
".",
"_url_counter",
":",
"self",
".",
"_url_counter",
"[",
"i",
"]",
"=",
"0"
] | 30.5 | 6 |
def _gen_figure(nxplot=1, nyplot=1, figargs=None, projection=None,
sharex='none', joinx=False, sharey='none', joiny=False,
x=None, nxlabel=None, xlabels=None, nxdecimal=None, xmin=None, xmax=None,
y=None, nylabel=None, ylabels=None, nydecimal=None, ymin=None, ymax=None,
... | [
"def",
"_gen_figure",
"(",
"nxplot",
"=",
"1",
",",
"nyplot",
"=",
"1",
",",
"figargs",
"=",
"None",
",",
"projection",
"=",
"None",
",",
"sharex",
"=",
"'none'",
",",
"joinx",
"=",
"False",
",",
"sharey",
"=",
"'none'",
",",
"joiny",
"=",
"False",
... | 47.791045 | 20.507463 |
def configure_containers(self, current_options):
""" Configures the container dict """
containers = [
("default", "Default container. For Bash and Python 2 tasks"),
("cpp", "Contains gcc and g++ for compiling C++"),
("java7", "Contains Java 7"),
("java8sca... | [
"def",
"configure_containers",
"(",
"self",
",",
"current_options",
")",
":",
"containers",
"=",
"[",
"(",
"\"default\"",
",",
"\"Default container. For Bash and Python 2 tasks\"",
")",
",",
"(",
"\"cpp\"",
",",
"\"Contains gcc and g++ for compiling C++\"",
")",
",",
"(... | 48.973684 | 28.842105 |
def finditer(self, string, pos=0, endpos=sys.maxint):
"""Return a list of all non-overlapping matches of pattern in string."""
scanner = self.scanner(string, pos, endpos)
return iter(scanner.search, None) | [
"def",
"finditer",
"(",
"self",
",",
"string",
",",
"pos",
"=",
"0",
",",
"endpos",
"=",
"sys",
".",
"maxint",
")",
":",
"scanner",
"=",
"self",
".",
"scanner",
"(",
"string",
",",
"pos",
",",
"endpos",
")",
"return",
"iter",
"(",
"scanner",
".",
... | 56.25 | 6.25 |
def set_nsxcontroller_ip(self, **kwargs):
"""
Set nsx-controller IP
Args:
IP (str): IPV4 address.
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
... | [
"def",
"set_nsxcontroller_ip",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
")",
"ip_addr",
"=",
"str",
"(",
"(",
"kwargs",
".",
"pop",
"(",
"'ip_addr'",
",",
"None",
")",
")",
")",
"nsxipaddress",... | 31.642857 | 16.857143 |
def start_span(self,
operation_name=None,
child_of=None,
references=None,
tags=None,
start_time=None,
ignore_active_span=False):
"""Starts and returns a new :class:`Span` representing a unit of work... | [
"def",
"start_span",
"(",
"self",
",",
"operation_name",
"=",
"None",
",",
"child_of",
"=",
"None",
",",
"references",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"start_time",
"=",
"None",
",",
"ignore_active_span",
"=",
"False",
")",
":",
"return",
"se... | 34.918033 | 24.278689 |
def get_memory_info(self) -> str:
'''Show device memory information.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'cat', '/proc/meminfo')
return output | [
"def",
"get_memory_info",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'cat'",
",",
"'/proc/meminfo'",
")",
"return",
"output"
] | 39.8 | 12.6 |
def appendRecords(self, records, progressCB=None):
"""
Saves multiple records in the underlying storage.
:param records: array of records as in
:meth:`~.FileRecordStream.appendRecord`
:param progressCB: (function) callback to report progress
"""
for record in records:
... | [
"def",
"appendRecords",
"(",
"self",
",",
"records",
",",
"progressCB",
"=",
"None",
")",
":",
"for",
"record",
"in",
"records",
":",
"self",
".",
"appendRecord",
"(",
"record",
")",
"if",
"progressCB",
"is",
"not",
"None",
":",
"progressCB",
"(",
")"
] | 29.846154 | 15.076923 |
def pong(self, payload):
"""
send pong data.
payload: data payload to send server.
"""
if isinstance(payload, six.text_type):
payload = payload.encode("utf-8")
self.send(payload, ABNF.OPCODE_PONG) | [
"def",
"pong",
"(",
"self",
",",
"payload",
")",
":",
"if",
"isinstance",
"(",
"payload",
",",
"six",
".",
"text_type",
")",
":",
"payload",
"=",
"payload",
".",
"encode",
"(",
"\"utf-8\"",
")",
"self",
".",
"send",
"(",
"payload",
",",
"ABNF",
".",
... | 27.666667 | 10.333333 |
def addCompletedJob(self, job, wallTime):
"""
Adds the shape of a completed job to the queue, allowing the scalar to use the last N
completed jobs in factoring how many nodes are required in the cluster.
:param toil.job.JobNode job: The memory, core and disk requirements of the completed... | [
"def",
"addCompletedJob",
"(",
"self",
",",
"job",
",",
"wallTime",
")",
":",
"#Adjust average runtimes to include this job.",
"if",
"job",
".",
"jobName",
"in",
"self",
".",
"jobNameToAvgRuntime",
":",
"prevAvg",
"=",
"self",
".",
"jobNameToAvgRuntime",
"[",
"job... | 53.190476 | 26.52381 |
def MI_invokeMethod(self, env, objectName, metaMethod, inputParams):
# pylint: disable=invalid-name
"""Invoke an extrinsic method.
Implements the InvokeMethod WBEM operation by calling the
method on a derived class called cim_method_<method_name>,
where <method_name> is the name... | [
"def",
"MI_invokeMethod",
"(",
"self",
",",
"env",
",",
"objectName",
",",
"metaMethod",
",",
"inputParams",
")",
":",
"# pylint: disable=invalid-name",
"logger",
"=",
"env",
".",
"get_logger",
"(",
")",
"logger",
".",
"log_debug",
"(",
"'CIMProvider MI_invokeMeth... | 43.185714 | 20.371429 |
def Get(self, project_id):
"""Returns an existing emulator instance for the provided project_id.
If an emulator instance doesn't yet exist, it creates one.
Args:
project_id: project ID
Returns:
a DatastoreEmulator
"""
if project_id in self._emulators:
return self._emulators[... | [
"def",
"Get",
"(",
"self",
",",
"project_id",
")",
":",
"if",
"project_id",
"in",
"self",
".",
"_emulators",
":",
"return",
"self",
".",
"_emulators",
"[",
"project_id",
"]",
"emulator",
"=",
"self",
".",
"Create",
"(",
"project_id",
")",
"self",
".",
... | 24.588235 | 18.235294 |
def clone(self):
"""
Return an independent copy of this layout with a completely separate
color_list and no drivers.
"""
args = {k: getattr(self, k) for k in self.CLONE_ATTRS}
args['color_list'] = copy.copy(self.color_list)
return self.__class__([], **args) | [
"def",
"clone",
"(",
"self",
")",
":",
"args",
"=",
"{",
"k",
":",
"getattr",
"(",
"self",
",",
"k",
")",
"for",
"k",
"in",
"self",
".",
"CLONE_ATTRS",
"}",
"args",
"[",
"'color_list'",
"]",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"color_list... | 38.25 | 13 |
def _set_auto_watering(self, zoneid, value):
"""Private method to set auto_watering program."""
if not isinstance(value, bool):
return None
ddata = self.preupdate()
attr = 'zone{}_program_toggle'.format(zoneid)
try:
if not value:
ddata.pop... | [
"def",
"_set_auto_watering",
"(",
"self",
",",
"zoneid",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"None",
"ddata",
"=",
"self",
".",
"preupdate",
"(",
")",
"attr",
"=",
"'zone{}_program_toggle'",
"... | 28.75 | 14.5 |
def exec_command(self, domain, function, operator, value=None):
"""
Write a command to the receiver and read the value it returns.
"""
if operator in CMDS[domain][function]['supported_operators']:
if operator is '=' and value is None:
raise ValueError('No valu... | [
"def",
"exec_command",
"(",
"self",
",",
"domain",
",",
"function",
",",
"operator",
",",
"value",
"=",
"None",
")",
":",
"if",
"operator",
"in",
"CMDS",
"[",
"domain",
"]",
"[",
"function",
"]",
"[",
"'supported_operators'",
"]",
":",
"if",
"operator",
... | 41.521739 | 23.565217 |
def get_mixcloud_data(url):
"""
Scrapes a Mixcloud page for a track's important information.
Returns:
dict: containing audio data
"""
data = {}
request = requests.get(url)
preview_mp3_url = request.text.split('m-preview="')[1].split('" m-preview-light')[0]
song_uuid = request.... | [
"def",
"get_mixcloud_data",
"(",
"url",
")",
":",
"data",
"=",
"{",
"}",
"request",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"preview_mp3_url",
"=",
"request",
".",
"text",
".",
"split",
"(",
"'m-preview=\"'",
")",
"[",
"1",
"]",
".",
"split",
"... | 37.292683 | 27.878049 |
def forget(self, key):
"""
Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool
"""
if key in self._storage:
del self._storage[key]
return True
return False | [
"def",
"forget",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"_storage",
":",
"del",
"self",
".",
"_storage",
"[",
"key",
"]",
"return",
"True",
"return",
"False"
] | 17.733333 | 18.4 |
def group_reads_by_allele(allele_reads):
"""
Returns dictionary mapping each allele's nucleotide sequence to a list of
supporting AlleleRead objects.
"""
allele_to_reads_dict = defaultdict(list)
for allele_read in allele_reads:
allele_to_reads_dict[allele_read.allele].append(allele_read)... | [
"def",
"group_reads_by_allele",
"(",
"allele_reads",
")",
":",
"allele_to_reads_dict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"allele_read",
"in",
"allele_reads",
":",
"allele_to_reads_dict",
"[",
"allele_read",
".",
"allele",
"]",
".",
"append",
"(",
"allel... | 38.222222 | 9.777778 |
def get_netspeed(self, ip):
''' Get netspeed '''
rec = self.get_all(ip)
return rec and rec.netspeed | [
"def",
"get_netspeed",
"(",
"self",
",",
"ip",
")",
":",
"rec",
"=",
"self",
".",
"get_all",
"(",
"ip",
")",
"return",
"rec",
"and",
"rec",
".",
"netspeed"
] | 30 | 10 |
def get_env_variable(var_name, default=None):
"""Get the environment variable or return exception."""
try:
return os.environ[var_name]
except KeyError:
if default is None:
error_msg = "Set the %s environment variable" % var_name
raise ImproperlyConfigured(error_msg)
... | [
"def",
"get_env_variable",
"(",
"var_name",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"os",
".",
"environ",
"[",
"var_name",
"]",
"except",
"KeyError",
":",
"if",
"default",
"is",
"None",
":",
"error_msg",
"=",
"\"Set the %s environment va... | 35 | 15.3 |
def construct_routes(self):
""" Gets modules routes.py and converts to module imports """
modules = self.evernode_app.get_modules()
for module_name in modules:
with self.app.app_context():
module = importlib.import_module(
'modules.%s.routes'... | [
"def",
"construct_routes",
"(",
"self",
")",
":",
"modules",
"=",
"self",
".",
"evernode_app",
".",
"get_modules",
"(",
")",
"for",
"module_name",
"in",
"modules",
":",
"with",
"self",
".",
"app",
".",
"app_context",
"(",
")",
":",
"module",
"=",
"import... | 47.666667 | 8.333333 |
def get_nameid(self):
"""
Gets the NameID provided by the SAML Response from the IdP
:returns: NameID (value)
:rtype: string|None
"""
nameid_value = None
nameid_data = self.get_nameid_data()
if nameid_data and 'Value' in nameid_data.keys():
na... | [
"def",
"get_nameid",
"(",
"self",
")",
":",
"nameid_value",
"=",
"None",
"nameid_data",
"=",
"self",
".",
"get_nameid_data",
"(",
")",
"if",
"nameid_data",
"and",
"'Value'",
"in",
"nameid_data",
".",
"keys",
"(",
")",
":",
"nameid_value",
"=",
"nameid_data",... | 30.833333 | 13.333333 |
def environ_setting(name, default=None, required=True):
"""
Fetch setting from the environment. The bahavior of the setting if it
is not in environment is as follows:
1. If it is required and the default is None, raise Exception
2. If it is requried and a default exists, return default
... | [
"def",
"environ_setting",
"(",
"name",
",",
"default",
"=",
"None",
",",
"required",
"=",
"True",
")",
":",
"if",
"name",
"not",
"in",
"os",
".",
"environ",
"and",
"default",
"is",
"None",
":",
"message",
"=",
"\"The {0} ENVVAR is not set.\"",
".",
"format... | 40.777778 | 18.555556 |
def main():
"""
NAME
pmag_results_extract.py
DESCRIPTION
make a tab delimited output file from pmag_results table
SYNTAX
pmag_results_extract.py [command line options]
OPTIONS
-h prints help message and quits
-f RFILE, specify pmag_results table; default ... | [
"def",
"main",
"(",
")",
":",
"do_help",
"=",
"pmag",
".",
"get_flag_arg_from_sys",
"(",
"'-h'",
")",
"if",
"do_help",
":",
"print",
"(",
"main",
".",
"__doc__",
")",
"return",
"False",
"res_file",
"=",
"pmag",
".",
"get_named_arg",
"(",
"'-f'",
",",
"... | 37.28125 | 20.15625 |
def _get_mean(self, C, rup, dists, sites):
"""
Returns the mean value of ground motion - noting that in this case
the style-of-faulting term is neglected
"""
return (self._get_magnitude_scaling_term(C, rup.mag) +
self._get_distance_scaling_term(C, dists.rjb, rup.m... | [
"def",
"_get_mean",
"(",
"self",
",",
"C",
",",
"rup",
",",
"dists",
",",
"sites",
")",
":",
"return",
"(",
"self",
".",
"_get_magnitude_scaling_term",
"(",
"C",
",",
"rup",
".",
"mag",
")",
"+",
"self",
".",
"_get_distance_scaling_term",
"(",
"C",
","... | 48 | 15.25 |
def detect_spans(self, tokens):
"""Return (abbr_span, long_span) pair for each abbreviation definition.
abbr_span and long_span are (int, int) spans defining token ranges.
"""
candidates = self._get_candidates(tokens)
results = self._filter_candidates(tokens, candidates)
... | [
"def",
"detect_spans",
"(",
"self",
",",
"tokens",
")",
":",
"candidates",
"=",
"self",
".",
"_get_candidates",
"(",
"tokens",
")",
"results",
"=",
"self",
".",
"_filter_candidates",
"(",
"tokens",
",",
"candidates",
")",
"return",
"results"
] | 41 | 16.5 |
def import_generated_autoboto_module(self, name):
"""
Imports a module from the generated autoboto package in the build directory (not target_dir).
For example, to import autoboto.services.s3.shapes, call:
botogen.import_generated_autoboto_module("services.s3.shapes")
"""
... | [
"def",
"import_generated_autoboto_module",
"(",
"self",
",",
"name",
")",
":",
"if",
"str",
"(",
"self",
".",
"config",
".",
"build_dir",
")",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"append",
"(",
"str",
"(",
"self",
".",
"con... | 45.272727 | 25.090909 |
def DetermineType(value):
"""Determines the type of val, returning a "full path" string.
For example:
DetermineType(5) -> __builtin__.int
DetermineType(Foo()) -> com.google.bar.Foo
Args:
value: Any value, the value is irrelevant as only the type metadata
is checked
Returns:
Type path stri... | [
"def",
"DetermineType",
"(",
"value",
")",
":",
"object_type",
"=",
"type",
"(",
"value",
")",
"if",
"not",
"hasattr",
"(",
"object_type",
",",
"'__name__'",
")",
":",
"return",
"None",
"type_string",
"=",
"getattr",
"(",
"object_type",
",",
"'__module__'",
... | 23.44 | 21.72 |
def settle_timeout(self) -> int:
""" Returns the channels settle_timeout. """
# There is no way to get the settle timeout after the channel has been closed as
# we're saving gas. Therefore get the ChannelOpened event and get the timeout there.
filter_args = get_filter_args_for_specific_... | [
"def",
"settle_timeout",
"(",
"self",
")",
"->",
"int",
":",
"# There is no way to get the settle timeout after the channel has been closed as",
"# we're saving gas. Therefore get the ChannelOpened event and get the timeout there.",
"filter_args",
"=",
"get_filter_args_for_specific_event_fro... | 45.952381 | 26.142857 |
def from_zone(zone):
'''Build a GeoID from a given zone'''
validity = zone.validity.start if zone.validity else None
return build(zone.level, zone.code, validity) | [
"def",
"from_zone",
"(",
"zone",
")",
":",
"validity",
"=",
"zone",
".",
"validity",
".",
"start",
"if",
"zone",
".",
"validity",
"else",
"None",
"return",
"build",
"(",
"zone",
".",
"level",
",",
"zone",
".",
"code",
",",
"validity",
")"
] | 42.75 | 12.75 |
def move_examples(root, lib_dir):
"""find examples not under lib dir, and move into ``examples``"""
all_pde = files_multi_pattern(root, INO_PATTERNS)
lib_pde = files_multi_pattern(lib_dir, INO_PATTERNS)
stray_pde = all_pde.difference(lib_pde)
if len(stray_pde) and not len(lib_pde):
log.debug... | [
"def",
"move_examples",
"(",
"root",
",",
"lib_dir",
")",
":",
"all_pde",
"=",
"files_multi_pattern",
"(",
"root",
",",
"INO_PATTERNS",
")",
"lib_pde",
"=",
"files_multi_pattern",
"(",
"lib_dir",
",",
"INO_PATTERNS",
")",
"stray_pde",
"=",
"all_pde",
".",
"dif... | 40.071429 | 11.714286 |
def showEvent(self, event):
"""When this widget is shown it has an effect of putting
other widgets in the parent widget into different editing modes, emits
signal to notify other widgets. Restores the previous selection the last
time this widget was visible"""
selected = self.par... | [
"def",
"showEvent",
"(",
"self",
",",
"event",
")",
":",
"selected",
"=",
"self",
".",
"paramList",
".",
"selectedIndexes",
"(",
")",
"model",
"=",
"self",
".",
"paramList",
".",
"model",
"(",
")",
"self",
".",
"visibilityChanged",
".",
"emit",
"(",
"1... | 56.714286 | 26.095238 |
def write_force_constants_to_hdf5(force_constants,
filename='force_constants.hdf5',
p2s_map=None,
physical_unit=None,
compression=None):
"""Write force constants in hdf5 format.
... | [
"def",
"write_force_constants_to_hdf5",
"(",
"force_constants",
",",
"filename",
"=",
"'force_constants.hdf5'",
",",
"p2s_map",
"=",
"None",
",",
"physical_unit",
"=",
"None",
",",
"compression",
"=",
"None",
")",
":",
"try",
":",
"import",
"h5py",
"except",
"Im... | 35.642857 | 18.857143 |
def surface_tessellate(v1, v2, v3, v4, vidx, tidx, trim_curves, tessellate_args):
""" Triangular tessellation algorithm for surfaces with no trims.
This function can be directly used as an input to :func:`.make_triangle_mesh` using ``tessellate_func`` keyword
argument.
:param v1: vertex 1
:type v1... | [
"def",
"surface_tessellate",
"(",
"v1",
",",
"v2",
",",
"v3",
",",
"v4",
",",
"vidx",
",",
"tidx",
",",
"trim_curves",
",",
"tessellate_args",
")",
":",
"# Triangulate vertices",
"tris",
"=",
"polygon_triangulate",
"(",
"tidx",
",",
"v1",
",",
"v2",
",",
... | 32.133333 | 20.933333 |
def create_config_drive(network_interface_info, os_version):
"""Generate config driver for zVM guest vm.
:param dict network_interface_info: Required keys:
ip_addr - (str) IP address
nic_vdev - (str) VDEV of the nic
gateway_v4 - IPV4 gateway
broadcast_v4 - IPV4 broadcast address... | [
"def",
"create_config_drive",
"(",
"network_interface_info",
",",
"os_version",
")",
":",
"temp_path",
"=",
"CONF",
".",
"guest",
".",
"temp_path",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"temp_path",
")",
":",
"os",
".",
"mkdir",
"(",
"temp_pa... | 37.02439 | 14.731707 |
def _build_ref_data_names(self, project, build_system):
'''
We want all reference data names for every task that runs on a specific project.
For example:
* Buildbot - "Windows 8 64-bit mozilla-inbound debug test web-platform-tests-1"
* TaskCluster = "test-linux64/opt-moc... | [
"def",
"_build_ref_data_names",
"(",
"self",
",",
"project",
",",
"build_system",
")",
":",
"ignored_jobs",
"=",
"[",
"]",
"ref_data_names",
"=",
"{",
"}",
"runnable_jobs",
"=",
"list_runnable_jobs",
"(",
"project",
")",
"for",
"job",
"in",
"runnable_jobs",
":... | 35.785714 | 21.97619 |
def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs):
"""
This method adds enterprise-specific metadata for each course.
We are adding following field in all the courses.
tpa_hint: a string for identifying Identity Provider.
... | [
"def",
"update_enterprise_courses",
"(",
"self",
",",
"enterprise_customer",
",",
"course_container_key",
"=",
"'results'",
",",
"*",
"*",
"kwargs",
")",
":",
"enterprise_context",
"=",
"{",
"'tpa_hint'",
":",
"enterprise_customer",
"and",
"enterprise_customer",
".",
... | 47.28 | 29.04 |
def distributedConnectionMap(names: List[str]) -> OrderedDict:
"""
Create a map where every node is connected every other node.
Assume each key in the returned dictionary to be connected to each item in
its value(list).
:param names: a list of node names
:return: a dictionary of name -> list(na... | [
"def",
"distributedConnectionMap",
"(",
"names",
":",
"List",
"[",
"str",
"]",
")",
"->",
"OrderedDict",
":",
"names",
".",
"sort",
"(",
")",
"combos",
"=",
"list",
"(",
"itertools",
".",
"combinations",
"(",
"names",
",",
"2",
")",
")",
"maxPer",
"=",... | 34.5 | 15 |
def versus_summaries(turns=2, sims_to_average=2, async_results_q=None):
"""Return summaries of the likely resutls of each available action..
Arguments:
- turns: how many turns to simulate.
- in 2013, 1 is fast (seconds), 2 is slow (seconds), 3 who knows
- sims_to_average: how many times to run ... | [
"def",
"versus_summaries",
"(",
"turns",
"=",
"2",
",",
"sims_to_average",
"=",
"2",
",",
"async_results_q",
"=",
"None",
")",
":",
"board",
",",
"player",
",",
"opponent",
",",
"extra_actions",
"=",
"_state_investigator",
".",
"get_versus",
"(",
")",
"if",
... | 51.346939 | 18.673469 |
def _validate_units(self, has_units, key, value):
"""Validate fields with `units` key in schema set to True.
The rule's arguments are validated against this schema:
{'type': 'boolean'}
"""
if has_units:
if isinstance(self.test.units, dict):
required_u... | [
"def",
"_validate_units",
"(",
"self",
",",
"has_units",
",",
"key",
",",
"value",
")",
":",
"if",
"has_units",
":",
"if",
"isinstance",
"(",
"self",
".",
"test",
".",
"units",
",",
"dict",
")",
":",
"required_units",
"=",
"self",
".",
"test",
".",
"... | 46.857143 | 16.809524 |
def decode_osgi_props(input_props):
# type: (Dict[str, Any]) -> Dict[str, Any]
"""
Decodes the OSGi properties of the given endpoint properties
"""
result_props = {}
intfs = decode_list(input_props, OBJECTCLASS)
result_props[OBJECTCLASS] = intfs
for intf in intfs:
package_key = E... | [
"def",
"decode_osgi_props",
"(",
"input_props",
")",
":",
"# type: (Dict[str, Any]) -> Dict[str, Any]",
"result_props",
"=",
"{",
"}",
"intfs",
"=",
"decode_list",
"(",
"input_props",
",",
"OBJECTCLASS",
")",
"result_props",
"[",
"OBJECTCLASS",
"]",
"=",
"intfs",
"f... | 44.896552 | 18.068966 |
def propose_live(self):
"""Propose a live point/axes to be used by other sampling methods."""
i = self.rstate.randint(self.nlive)
u = self.live_u[i, :]
ax = np.identity(self.npdim) * self.radfriends.radius
return u, ax | [
"def",
"propose_live",
"(",
"self",
")",
":",
"i",
"=",
"self",
".",
"rstate",
".",
"randint",
"(",
"self",
".",
"nlive",
")",
"u",
"=",
"self",
".",
"live_u",
"[",
"i",
",",
":",
"]",
"ax",
"=",
"np",
".",
"identity",
"(",
"self",
".",
"npdim"... | 31.625 | 19 |
def _get_events(self):
"""Get the list of events."""
events, changed_container_ids = self.docker_util.get_events()
if not self._disable_net_metrics:
self._invalidate_network_mapping_cache(events)
if changed_container_ids and self._service_discovery:
get_sd_backend... | [
"def",
"_get_events",
"(",
"self",
")",
":",
"events",
",",
"changed_container_ids",
"=",
"self",
".",
"docker_util",
".",
"get_events",
"(",
")",
"if",
"not",
"self",
".",
"_disable_net_metrics",
":",
"self",
".",
"_invalidate_network_mapping_cache",
"(",
"even... | 48.3 | 17.4 |
def _get_cibpath():
'''
Get the path to the directory on the minion where CIB's are saved
'''
cibpath = os.path.join(__opts__['cachedir'], 'pcs', __env__)
log.trace('cibpath: %s', cibpath)
return cibpath | [
"def",
"_get_cibpath",
"(",
")",
":",
"cibpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'pcs'",
",",
"__env__",
")",
"log",
".",
"trace",
"(",
"'cibpath: %s'",
",",
"cibpath",
")",
"return",
"cibpath"
] | 31.571429 | 23.571429 |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(IPMISensorCollector, self).get_default_config()
config.update({
'bin': '/usr/bin/ipmitool',
'use_sudo': False,
'sudo_cmd': ... | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"IPMISensorCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'bin'",
":",
"'/usr/bin/ipmitool'",
",",
"'use_sudo'",
":",
"Fa... | 34.214286 | 10.642857 |
def lessThanOrEqual(self, value):
"""
Sets the operator type to Query.Op.LessThanOrEqual and sets
the value to the inputted value.
:param value <variant>
:return <Query>
:sa lessThanOrEqual
:usage |>... | [
"def",
"lessThanOrEqual",
"(",
"self",
",",
"value",
")",
":",
"newq",
"=",
"self",
".",
"copy",
"(",
")",
"newq",
".",
"setOp",
"(",
"Query",
".",
"Op",
".",
"LessThanOrEqual",
")",
"newq",
".",
"setValue",
"(",
"value",
")",
"return",
"newq"
] | 30.45 | 13.75 |
def export_event_params(filename, params, count=None, density=None):
"""Write event analysis data to CSV."""
heading_row_1 = ['Segment index',
'Start time',
'End time',
'Stitches',
'Stage',
'Cycle',
... | [
"def",
"export_event_params",
"(",
"filename",
",",
"params",
",",
"count",
"=",
"None",
",",
"density",
"=",
"None",
")",
":",
"heading_row_1",
"=",
"[",
"'Segment index'",
",",
"'Start time'",
",",
"'End time'",
",",
"'Stitches'",
",",
"'Stage'",
",",
"'Cy... | 39.266129 | 18.483871 |
def parse(self, uri, defaults=None):
"""Parse the URI.
uri is the uri to parse.
defaults is a scheme-dependent list of values to use if there
is no value for that part in the supplied URI.
The return value is a tuple of scheme-dependent length.
"""
return tuple(... | [
"def",
"parse",
"(",
"self",
",",
"uri",
",",
"defaults",
"=",
"None",
")",
":",
"return",
"tuple",
"(",
"[",
"self",
".",
"scheme_of",
"(",
"uri",
")",
"]",
"+",
"list",
"(",
"self",
".",
"parser_for",
"(",
"uri",
")",
"(",
"defaults",
")",
".",... | 38.3 | 21.1 |
def setNodeCount(self, nodeType, numNodes, preemptable=False, force=False):
"""
Attempt to grow or shrink the number of preemptable or non-preemptable worker nodes in
the cluster to the given value, or as close a value as possible, and, after performing
the necessary additions or removal... | [
"def",
"setNodeCount",
"(",
"self",
",",
"nodeType",
",",
"numNodes",
",",
"preemptable",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"for",
"attempt",
"in",
"retry",
"(",
"predicate",
"=",
"self",
".",
"provisioner",
".",
"retryPredicate",
")",
... | 66.757576 | 37.484848 |
def _get_a(self, _type):
""" Gets an instance implementing type <_type> """
tmp = self._get_all(_type)
ret = pick(tmp)
if len(tmp) != 1:
self.l.warn(("get_a: %s all implement %s; " +
"picking %s") % (tmp, _type, ret))
return ret | [
"def",
"_get_a",
"(",
"self",
",",
"_type",
")",
":",
"tmp",
"=",
"self",
".",
"_get_all",
"(",
"_type",
")",
"ret",
"=",
"pick",
"(",
"tmp",
")",
"if",
"len",
"(",
"tmp",
")",
"!=",
"1",
":",
"self",
".",
"l",
".",
"warn",
"(",
"(",
"\"get_a... | 37.25 | 14 |
def make_function3_annotate(self, node, is_lambda, nested=1,
code_node=None, annotate_last=-1):
"""
Dump function defintion, doc string, and function
body. This code is specialized for Python 3"""
def build_param(ast, name, default):
"""build parameters:
... | [
"def",
"make_function3_annotate",
"(",
"self",
",",
"node",
",",
"is_lambda",
",",
"nested",
"=",
"1",
",",
"code_node",
"=",
"None",
",",
"annotate_last",
"=",
"-",
"1",
")",
":",
"def",
"build_param",
"(",
"ast",
",",
"name",
",",
"default",
")",
":"... | 32.004065 | 15.662602 |
def load( filename ):
"""
Loads the profile from the inputed filename.
:param filename | <str>
"""
try:
f = open(filename, 'r')
except IOError:
logger.exception('Could not load the file: %s' % filename)
return... | [
"def",
"load",
"(",
"filename",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"except",
"IOError",
":",
"logger",
".",
"exception",
"(",
"'Could not load the file: %s'",
"%",
"filename",
")",
"return",
"False",
"strdata",
"=",
... | 24.764706 | 17.588235 |
def add_dict_to_cookiejar(cj, cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
"""
for k, v in cookie_dict.items():
cookie = cookielib.Cookie(
version... | [
"def",
"add_dict_to_cookiejar",
"(",
"cj",
",",
"cookie_dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"cookie_dict",
".",
"items",
"(",
")",
":",
"cookie",
"=",
"cookielib",
".",
"Cookie",
"(",
"version",
"=",
"0",
",",
"name",
"=",
"k",
",",
"value",... | 25.090909 | 16.727273 |
def next_instruction_in_row(self):
"""The instruction after this one or None.
:return: the instruction in :attr:`row_instructions` after this or
:obj:`None` if this is the last
:rtype: knittingpattern.Instruction.InstructionInRow
This can be used to traverse the instructions.... | [
"def",
"next_instruction_in_row",
"(",
"self",
")",
":",
"index",
"=",
"self",
".",
"index_in_row",
"+",
"1",
"if",
"index",
">=",
"len",
"(",
"self",
".",
"row_instructions",
")",
":",
"return",
"None",
"return",
"self",
".",
"row_instructions",
"[",
"ind... | 35.333333 | 16.066667 |
def get_file_list(opts):
"""
Returns a list containing file paths of requested files to be parsed
using AnchorHub options.
:param opts: Namespace containing AnchorHub options, usually created from
command line arguments
:return: a list of absolute string file paths of files that should be
... | [
"def",
"get_file_list",
"(",
"opts",
")",
":",
"if",
"opts",
".",
"is_dir",
":",
"# Input is a directory, get a list of files",
"return",
"get_files",
"(",
"opts",
".",
"abs_input",
",",
"opts",
".",
"extensions",
",",
"exclude",
"=",
"[",
"opts",
".",
"abs_ou... | 35.3 | 18.7 |
def get_sentence(start=None, depth=7):
''' follow the grammatical patterns to generate a random sentence '''
if not GRAMMAR:
return 'Please set a GRAMMAR file'
start = start if start else GRAMMAR.start()
if isinstance(start, Nonterminal):
productions = GRAMMAR.productions(start)
... | [
"def",
"get_sentence",
"(",
"start",
"=",
"None",
",",
"depth",
"=",
"7",
")",
":",
"if",
"not",
"GRAMMAR",
":",
"return",
"'Please set a GRAMMAR file'",
"start",
"=",
"start",
"if",
"start",
"else",
"GRAMMAR",
".",
"start",
"(",
")",
"if",
"isinstance",
... | 33.681818 | 17.863636 |
def metrics(ty, query, query_type, **kwargs):
"""
Outputs runtime metrics collected from cocaine-runtime and its services.
This command shows runtime metrics collected from cocaine-runtime and its services during their
lifetime.
There are four kind of metrics available: gauges, counters, meters and... | [
"def",
"metrics",
"(",
"ty",
",",
"query",
",",
"query_type",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'metrics'",
",",
"*",
"*",
"{",
"'metrics'",
":",
"ctx",
".",
... | 45.970149 | 29.850746 |
def param_names(self):
"""The param_names vector is a list each parameter's analysis_path, and is used for *GetDist* visualization.
The parameter names are determined from the class instance names of the model_mapper. Latex tags are \
properties of each model class."""
return [self.nam... | [
"def",
"param_names",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"name_for_prior",
"(",
"prior",
")",
"for",
"prior",
"in",
"sorted",
"(",
"self",
".",
"priors",
",",
"key",
"=",
"lambda",
"prior",
":",
"prior",
".",
"id",
")",
"]"
] | 56.285714 | 33.142857 |
def any2i(self, pkt, x):
# type: (Optional[packet.Packet], Union[None, str, int]) -> Optional[int] # noqa: E501
"""
A "x" value as a string is parsed as a binary encoding of a UVarInt. An int is considered an internal value. # noqa: E501
None is returned as is.
@param pack... | [
"def",
"any2i",
"(",
"self",
",",
"pkt",
",",
"x",
")",
":",
"# type: (Optional[packet.Packet], Union[None, str, int]) -> Optional[int] # noqa: E501",
"if",
"isinstance",
"(",
"x",
",",
"type",
"(",
"None",
")",
")",
":",
"return",
"x",
"if",
"isinstance",
"(",
... | 44.130435 | 21 |
def regular(u):
'''
Equation matrix generation for the regular (cubic) lattice.
The order of constants is as follows:
.. math::
C_{11}, C_{12}, C_{44}
:param u: vector of deformations:
[ :math:`u_{xx}, u_{yy}, u_{zz}, u_{yz}, u_{xz}, u_{xy}` ]
:returns: Symmetry defined stress-... | [
"def",
"regular",
"(",
"u",
")",
":",
"uxx",
",",
"uyy",
",",
"uzz",
",",
"uyz",
",",
"uxz",
",",
"uxy",
"=",
"u",
"[",
"0",
"]",
",",
"u",
"[",
"1",
"]",
",",
"u",
"[",
"2",
"]",
",",
"u",
"[",
"3",
"]",
",",
"u",
"[",
"4",
"]",
",... | 33.095238 | 19.285714 |
def TriToBin(self, x, y, z):
'''
Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the correspo... | [
"def",
"TriToBin",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"if",
"(",
"z",
">=",
"0",
")",
":",
"if",
"(",
"x",
"+",
"y",
"+",
"z",
"==",
"0",
")",
":",
"return",
"(",
"0",
",",
"0",
")",
"else",
":",
"Sum",
"=",
"x",
"+"... | 32.375 | 14.375 |
def save_hdf5(X, y, path):
"""Save data as a HDF5 file.
Args:
X (numpy or scipy sparse matrix): Data matrix
y (numpy array): Target vector.
path (str): Path to the HDF5 file to save data.
"""
with h5py.File(path, 'w') as f:
is_sparse = 1 if sparse.issparse(X) else 0
... | [
"def",
"save_hdf5",
"(",
"X",
",",
"y",
",",
"path",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"is_sparse",
"=",
"1",
"if",
"sparse",
".",
"issparse",
"(",
"X",
")",
"else",
"0",
"f",
"[",
"'issparse'"... | 26.5 | 15.458333 |
def status(directory: str) -> Tuple[RepositoryLocation, Branch, Commit]:
"""
Gets the status of the subrepo that has been cloned into the given directory.
:param directory: the directory containing the subrepo
:return: a tuple consisting of the URL the subrepo is tracking, the branch that has been check... | [
"def",
"status",
"(",
"directory",
":",
"str",
")",
"->",
"Tuple",
"[",
"RepositoryLocation",
",",
"Branch",
",",
"Commit",
"]",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"raise",
"ValueError",
"(",
"f\"No subrepo fo... | 46.461538 | 26.538462 |
def facet_raw(self, **kw):
"""
Return a new S instance with raw facet args combined with
existing set.
"""
items = kw.items()
if six.PY3:
items = list(items)
return self._clone(next_step=('facet_raw', items)) | [
"def",
"facet_raw",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"items",
"=",
"kw",
".",
"items",
"(",
")",
"if",
"six",
".",
"PY3",
":",
"items",
"=",
"list",
"(",
"items",
")",
"return",
"self",
".",
"_clone",
"(",
"next_step",
"=",
"(",
"'fa... | 29.777778 | 13.333333 |
def model_to_dict(instance, **options):
"Takes a model instance and converts it into a dict."
options = _defaults(options)
attrs = {}
if options['prehook']:
if isinstance(options['prehook'], collections.Callable):
instance = options['prehook'](instance)
if instance is N... | [
"def",
"model_to_dict",
"(",
"instance",
",",
"*",
"*",
"options",
")",
":",
"options",
"=",
"_defaults",
"(",
"options",
")",
"attrs",
"=",
"{",
"}",
"if",
"options",
"[",
"'prehook'",
"]",
":",
"if",
"isinstance",
"(",
"options",
"[",
"'prehook'",
"]... | 36.969697 | 21.363636 |
def format_date(self, value, format_):
"""
Format the date using Babel
"""
date_ = make_date(value)
return dates.format_date(date_, format_, locale=self.lang) | [
"def",
"format_date",
"(",
"self",
",",
"value",
",",
"format_",
")",
":",
"date_",
"=",
"make_date",
"(",
"value",
")",
"return",
"dates",
".",
"format_date",
"(",
"date_",
",",
"format_",
",",
"locale",
"=",
"self",
".",
"lang",
")"
] | 32.166667 | 6.833333 |
def overlapping(self, other):
"""Do these variants overlap in the reference"""
return (
other.start in self.ref_range) or (
self.start in other.ref_range) | [
"def",
"overlapping",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"other",
".",
"start",
"in",
"self",
".",
"ref_range",
")",
"or",
"(",
"self",
".",
"start",
"in",
"other",
".",
"ref_range",
")"
] | 38 | 8.8 |
def assertFileNameRegex(self, filename, expected_regex, msg=None):
'''Fail unless ``filename`` matches ``expected_regex``.
Parameters
----------
filename : str, bytes, file-like
expected_regex : str, bytes
msg : str
If not provided, the :mod:`marbles.mixins` ... | [
"def",
"assertFileNameRegex",
"(",
"self",
",",
"filename",
",",
"expected_regex",
",",
"msg",
"=",
"None",
")",
":",
"fname",
"=",
"self",
".",
"_get_file_name",
"(",
"filename",
")",
"self",
".",
"assertRegex",
"(",
"fname",
",",
"expected_regex",
",",
"... | 32.526316 | 21.368421 |
def generate_output_list(self, source, key, val, line='2', hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output RDAP list results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required)... | [
"def",
"generate_output_list",
"(",
"self",
",",
"source",
",",
"key",
",",
"val",
",",
"line",
"=",
"'2'",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"output",
"=",
"generate_output",
"(",
"line",
... | 38.022727 | 19.75 |
def handle_error(self, error, req, schema, error_status_code, error_headers):
"""Handles errors during parsing. Aborts the current request with a
400 error.
"""
status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS
raise bottle.HTTPError(
status=status_cod... | [
"def",
"handle_error",
"(",
"self",
",",
"error",
",",
"req",
",",
"schema",
",",
"error_status_code",
",",
"error_headers",
")",
":",
"status_code",
"=",
"error_status_code",
"or",
"self",
".",
"DEFAULT_VALIDATION_STATUS",
"raise",
"bottle",
".",
"HTTPError",
"... | 38.090909 | 15.181818 |
def main(args=sys.argv[1:]):
"""
Command-line interface for nestagg
"""
parser = argparse.ArgumentParser(description="""Aggregate results of
nestly runs""")
subparsers = parser.add_subparsers()
delim_parser = subparsers.add_parser('delim', help="""Combine control files
wi... | [
"def",
"main",
"(",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"\"\"Aggregate results of\n nestly runs\"\"\"",
")",
"subparsers",
"=",
"parser",
".",
"a... | 52.459459 | 9.27027 |
def propagate_lithology_cols(self):
"""
Propagate any data from lithologies, geologic_types, or geologic_classes
from the sites table to the samples and specimens table.
In the samples/specimens tables, null or "Not Specified" values
will be overwritten based on the data from the... | [
"def",
"propagate_lithology_cols",
"(",
"self",
")",
":",
"cols",
"=",
"[",
"'lithologies'",
",",
"'geologic_types'",
",",
"'geologic_classes'",
"]",
"#for table in ['specimens', 'samples']:",
"# convert \"Not Specified\" to blank",
"#self.tables[table].df.replace(\"^[Nn]ot [Ss]pec... | 52 | 17.92 |
def __prepare_resource(data):
"""Prepare the resourcepart of the JID.
:Parameters:
- `data`: Resourcepart of the JID
:raise JIDError: if the resource name is too long.
:raise pyxmpp.xmppstringprep.StringprepError: if the
resourcepart fails Resourceprep preparati... | [
"def",
"__prepare_resource",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"None",
"data",
"=",
"unicode",
"(",
"data",
")",
"try",
":",
"resource",
"=",
"RESOURCEPREP",
".",
"prepare",
"(",
"data",
")",
"except",
"StringprepError",
",",
"er... | 35.526316 | 16.157895 |
def histogram(data, *args, **kwargs):
"""
Create and fill a one-dimensional histogram.
The same arguments as the ``Hist`` class are expected.
If the number of bins and the ranges are not specified they are
automatically deduced with the ``autobinning`` function using the method
specified by the... | [
"def",
"histogram",
"(",
"data",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"autobinning",
"import",
"autobinning",
"dim",
"=",
"kwargs",
".",
"pop",
"(",
"'dim'",
",",
"1",
")",
"if",
"dim",
"!=",
"1",
":",
"raise",
"NotImpl... | 34.809524 | 15.095238 |
def concat_nd_pickles(self, mv_grid_districts):
"""
Read multiple pickles, join nd objects and save to file
Parameters
----------
mv_grid_districts : list
Ints describing MV grid districts
"""
pickle_name = cfg_ding0.get('output', 'nd_pickle')
# self.nd = self.read_pickles_from... | [
"def",
"concat_nd_pickles",
"(",
"self",
",",
"mv_grid_districts",
")",
":",
"pickle_name",
"=",
"cfg_ding0",
".",
"get",
"(",
"'output'",
",",
"'nd_pickle'",
")",
"# self.nd = self.read_pickles_from_files(pickle_name)",
"# TODO: instead of passing a list of mvgd's, pass list o... | 34.23913 | 16.891304 |
def extract_actions_from_class(record_class):
"""Extract actions from class."""
for name in dir(record_class):
method = getattr(record_class, name, None)
if method and getattr(method, '__deposit_action__', False):
yield method.__name__ | [
"def",
"extract_actions_from_class",
"(",
"record_class",
")",
":",
"for",
"name",
"in",
"dir",
"(",
"record_class",
")",
":",
"method",
"=",
"getattr",
"(",
"record_class",
",",
"name",
",",
"None",
")",
"if",
"method",
"and",
"getattr",
"(",
"method",
",... | 44.333333 | 9.166667 |
def file_handle(fnh, mode="rU"):
"""
Takes either a file path or an open file handle, checks validity and returns an open
file handle or raises an appropriate Exception.
:type fnh: str
:param fnh: It is the full path to a file, or open file handle
:type mode: str
:param mode: The way in wh... | [
"def",
"file_handle",
"(",
"fnh",
",",
"mode",
"=",
"\"rU\"",
")",
":",
"handle",
"=",
"None",
"if",
"isinstance",
"(",
"fnh",
",",
"file",
")",
":",
"if",
"fnh",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"Input file is closed.\"",
")",
"handle",... | 31.347826 | 22.391304 |
def send_and_wait_for_sent(self, stanza):
"""
Send the given `stanza` over the given :class:`StanzaStream` `stream`.
.. deprecated:: 0.8
This method will be removed in 1.0. Use :meth:`send` instead.
"""
warnings.warn(
r"send_and_wait_for_sent is deprecate... | [
"def",
"send_and_wait_for_sent",
"(",
"self",
",",
"stanza",
")",
":",
"warnings",
".",
"warn",
"(",
"r\"send_and_wait_for_sent is deprecated and will be removed in 1.0\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"1",
",",
")",
"yield",
"from",
"self",
".",... | 31.857143 | 19.714286 |
def settings_view_for_block(block_wrapper, settings_view_factory):
"""
Returns the settings view for an arbitrary block.
Args:
block_wrapper (BlockWrapper): The block for which a settings
view is to be returned
settings_view_factory (SettingsViewFactory):... | [
"def",
"settings_view_for_block",
"(",
"block_wrapper",
",",
"settings_view_factory",
")",
":",
"state_root_hash",
"=",
"block_wrapper",
".",
"state_root_hash",
"if",
"block_wrapper",
"is",
"not",
"None",
"else",
"None",
"return",
"settings_view_factory",
".",
"create_s... | 37.277778 | 21.166667 |
def _gaussian_function(self, datalength: int, values: np.ndarray,
height: int, index: int) -> np.ndarray:
"""
i'th Regression Model Gaussian
:param: len(x)
:param: x values
:param: height of gaussian
:param: position of gaussian
:retur... | [
"def",
"_gaussian_function",
"(",
"self",
",",
"datalength",
":",
"int",
",",
"values",
":",
"np",
".",
"ndarray",
",",
"height",
":",
"int",
",",
"index",
":",
"int",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"height",
"*",
"np",
".",
"exp",
... | 36.857143 | 19 |
def GetEntries(self, parser_mediator, top_level=None, **unused_kwargs):
"""Simple method to exact date values from a Plist.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
top_level (dict[str, object]): plist t... | [
"def",
"GetEntries",
"(",
"self",
",",
"parser_mediator",
",",
"top_level",
"=",
"None",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"for",
"root",
",",
"key",
",",
"datetime_value",
"in",
"interface",
".",
"RecurseKey",
"(",
"top_level",
")",
":",
"if",
"... | 39.894737 | 22 |
def parse_zip(fp):
"""
Parse the zip file headers at fp
:param fp: the file pointer from which to parse the zip file
:return: A tuple of local files, directory headers, and end of central directory
The local files are dictionary where the keys are the local file offset and the
... | [
"def",
"parse_zip",
"(",
"fp",
")",
":",
"local_files",
"=",
"{",
"}",
"dir_files",
"=",
"{",
"}",
"eocd",
"=",
"None",
"fp",
".",
"seek",
"(",
"0",
")",
"while",
"True",
":",
"pos",
"=",
"fp",
".",
"tell",
"(",
")",
"signature",
"=",
"struct",
... | 40.666667 | 19.964912 |
def report_down(self, service, port):
"""
Reports the given service's present node as down by deleting the
node's znode in Zookeeper if the znode is present.
Waits for the Zookeeper connection to be established before further
action is taken.
"""
wait_on_any(self... | [
"def",
"report_down",
"(",
"self",
",",
"service",
",",
"port",
")",
":",
"wait_on_any",
"(",
"self",
".",
"connected",
",",
"self",
".",
"shutdown",
")",
"node",
"=",
"Node",
".",
"current",
"(",
"service",
",",
"port",
")",
"path",
"=",
"self",
"."... | 32.111111 | 17.222222 |
def is_url_for(cls, _action, _endpoint=None, _app=None, _external=None, **paramattrs):
"""
View decorator that registers the view as a :meth:`url_for` target.
"""
def decorator(f):
if 'url_for_endpoints' not in cls.__dict__:
cls.url_for_endpoints = {None: {}} ... | [
"def",
"is_url_for",
"(",
"cls",
",",
"_action",
",",
"_endpoint",
"=",
"None",
",",
"_app",
"=",
"None",
",",
"_external",
"=",
"None",
",",
"*",
"*",
"paramattrs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"if",
"'url_for_endpoints'",
"not",
... | 51.733333 | 28 |
def _open_all_rings(self):
"""
Having already generated all unique fragments that did not require ring opening,
now we want to also obtain fragments that do require opening. We achieve this by
looping through all unique fragments and opening each bond present in any ring
we find.... | [
"def",
"_open_all_rings",
"(",
"self",
")",
":",
"self",
".",
"unique_fragments",
".",
"insert",
"(",
"0",
",",
"self",
".",
"mol_graph",
")",
"for",
"fragment",
"in",
"self",
".",
"unique_fragments",
":",
"ring_edges",
"=",
"fragment",
".",
"find_rings",
... | 52.708333 | 19.041667 |
def plot_pseudodepths(configs, nr_electrodes, spacing=1, grid=None,
ctypes=None, dd_merge=False, **kwargs):
"""Plot pseudodepths for the measurements. If grid is given, then the
actual electrode positions are used, and the parameter 'spacing' is
ignored'
Parameters
----------
... | [
"def",
"plot_pseudodepths",
"(",
"configs",
",",
"nr_electrodes",
",",
"spacing",
"=",
"1",
",",
"grid",
"=",
"None",
",",
"ctypes",
"=",
"None",
",",
"dd_merge",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# for each configuration type we have different... | 32.461538 | 19.230769 |
def local_lru(obj):
""" Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
..
class Foo(object):
def __init__(self, cache_size=5000):
self._cache = OrderedDict()
... | [
"def",
"local_lru",
"(",
"obj",
")",
":",
"@",
"wraps",
"(",
"obj",
")",
"def",
"memoizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"args",
"[",
"0",
"]",
"lru_size",
"=",
"instance",
".",
"_cache_size",
"if",
"lru_siz... | 29.727273 | 13.242424 |
def get_message(self, message_id):
"""Get a message by its persistent id.
Args:
message_id (int): The id of the message that we're looking for
"""
for message in self.messages:
if message.id == message_id:
return message
raise ArgumentEr... | [
"def",
"get_message",
"(",
"self",
",",
"message_id",
")",
":",
"for",
"message",
"in",
"self",
".",
"messages",
":",
"if",
"message",
".",
"id",
"==",
"message_id",
":",
"return",
"message",
"raise",
"ArgumentError",
"(",
"\"Message ID not found\"",
",",
"m... | 29.916667 | 19.5 |
def get_subscriptions_by_channel_id_and_person_id(
self, channel_id, person_id):
"""
Search for all subscriptions by a given channel and person
"""
return self.search_subscriptions(
channel_id=channel_id, person_id=person_id) | [
"def",
"get_subscriptions_by_channel_id_and_person_id",
"(",
"self",
",",
"channel_id",
",",
"person_id",
")",
":",
"return",
"self",
".",
"search_subscriptions",
"(",
"channel_id",
"=",
"channel_id",
",",
"person_id",
"=",
"person_id",
")"
] | 39.285714 | 7.571429 |
def process(self, processor:PreProcessors=None):
"Apply `processor` or `self.processor` to `self`."
if processor is not None: self.processor = processor
self.processor = listify(self.processor)
for p in self.processor: p.process(self)
return self | [
"def",
"process",
"(",
"self",
",",
"processor",
":",
"PreProcessors",
"=",
"None",
")",
":",
"if",
"processor",
"is",
"not",
"None",
":",
"self",
".",
"processor",
"=",
"processor",
"self",
".",
"processor",
"=",
"listify",
"(",
"self",
".",
"processor"... | 46.833333 | 13.833333 |
def oneImageNLF(img, img2=None, signal=None):
'''
Estimate the NLF from one or two images of the same kind
'''
x, y, weights, signal = calcNLF(img, img2, signal)
_, fn, _ = _evaluate(x, y, weights)
return fn, signal | [
"def",
"oneImageNLF",
"(",
"img",
",",
"img2",
"=",
"None",
",",
"signal",
"=",
"None",
")",
":",
"x",
",",
"y",
",",
"weights",
",",
"signal",
"=",
"calcNLF",
"(",
"img",
",",
"img2",
",",
"signal",
")",
"_",
",",
"fn",
",",
"_",
"=",
"_evalua... | 34.142857 | 17.857143 |
def export_graph(checkpoint_path, output_nodes):
"""
Export a graph stored in a checkpoint as a *.pb file.
:param checkpoint_path: The checkpoint path which should be frozen.
:param output_nodes: The output nodes you care about as a list of strings (their names).
:return:
"""
if not tf.gfile... | [
"def",
"export_graph",
"(",
"checkpoint_path",
",",
"output_nodes",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"checkpoint_path",
")",
":",
"raise",
"AssertionError",
"(",
"\"Export directory doesn't exists. Please specify an export \"",
"\"directory... | 42.829787 | 25.765957 |
def torus_knot(t, p=3, q=4, scale=1.0, radius=2.0):
""" A tight (small inner crossings) (p,q) torus knot parametric curve
Source (for trefoil): https://en.wikipedia.org/wiki/Trefoil_knot
"""
return ['{scale}*(sin({t}) + ({radius})*sin({p}*({t})))'.format(t=t, p=p, scale=scale, radius=radius),
... | [
"def",
"torus_knot",
"(",
"t",
",",
"p",
"=",
"3",
",",
"q",
"=",
"4",
",",
"scale",
"=",
"1.0",
",",
"radius",
"=",
"2.0",
")",
":",
"return",
"[",
"'{scale}*(sin({t}) + ({radius})*sin({p}*({t})))'",
".",
"format",
"(",
"t",
"=",
"t",
",",
"p",
"=",... | 53.444444 | 31.222222 |
def expand(self, local_search=False):
'''Create successors.'''
new_nodes = []
for action in self.problem.actions(self.state):
new_state = self.problem.result(self.state, action)
cost = self.problem.cost(self.state,
action,
... | [
"def",
"expand",
"(",
"self",
",",
"local_search",
"=",
"False",
")",
":",
"new_nodes",
"=",
"[",
"]",
"for",
"action",
"in",
"self",
".",
"problem",
".",
"actions",
"(",
"self",
".",
"state",
")",
":",
"new_state",
"=",
"self",
".",
"problem",
".",
... | 49.4375 | 15.0625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.