text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def set_commit(self, commit, logmsg=None):
"""As set_object, but restricts the type of object to be a Commit
:raise ValueError: If commit is not a Commit object or doesn't point to
a commit
:return: self"""
# check the type - assume the best if it is a base-string
in... | [
"def",
"set_commit",
"(",
"self",
",",
"commit",
",",
"logmsg",
"=",
"None",
")",
":",
"# check the type - assume the best if it is a base-string",
"invalid_type",
"=",
"False",
"if",
"isinstance",
"(",
"commit",
",",
"Object",
")",
":",
"invalid_type",
"=",
"comm... | 36.642857 | 18.75 |
def parse(cls, parser, text, pos): # pylint: disable=W0613
"""Match simple values excluding some Keywords like 'and' and 'or'"""
if not text.strip():
return text, SyntaxError("Invalid value")
class Rule(object):
grammar = attr('value', SpiresSimpleValue), omit(re.compil... | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"text",
",",
"pos",
")",
":",
"# pylint: disable=W0613",
"if",
"not",
"text",
".",
"strip",
"(",
")",
":",
"return",
"text",
",",
"SyntaxError",
"(",
"\"Invalid value\"",
")",
"class",
"Rule",
"(",
"object"... | 35.210526 | 21.684211 |
def get_ilx2superclass(self, clean:bool=True):
''' clean: for list of literals only '''
ilx2superclass = defaultdict(list)
header = ['Index'] + list(self.fetch_superclasses().columns)
for row in self.fetch_superclasses().itertuples():
row = {header[i]:val for i, val in enumer... | [
"def",
"get_ilx2superclass",
"(",
"self",
",",
"clean",
":",
"bool",
"=",
"True",
")",
":",
"ilx2superclass",
"=",
"defaultdict",
"(",
"list",
")",
"header",
"=",
"[",
"'Index'",
"]",
"+",
"list",
"(",
"self",
".",
"fetch_superclasses",
"(",
")",
".",
... | 44.733333 | 14.866667 |
def count_of_assigned_jobs(self):
"Number of fields that have attrib['JobAssigned'] set to true."
assigned = len([x.attrib['JobAssigned'] for x in self.fields
if x.attrib['JobAssigned'] == 'true'])
return assigned | [
"def",
"count_of_assigned_jobs",
"(",
"self",
")",
":",
"assigned",
"=",
"len",
"(",
"[",
"x",
".",
"attrib",
"[",
"'JobAssigned'",
"]",
"for",
"x",
"in",
"self",
".",
"fields",
"if",
"x",
".",
"attrib",
"[",
"'JobAssigned'",
"]",
"==",
"'true'",
"]",
... | 52.2 | 21.8 |
def library_exists(self, library):
"""
Check whether a given library exists.
Parameters
----------
library : `str`
The name of the library. e.g. 'library' or 'user.library'
Returns
-------
`bool`
True if the library with the given... | [
"def",
"library_exists",
"(",
"self",
",",
"library",
")",
":",
"exists",
"=",
"False",
"try",
":",
"# This forces auth errors, and to fall back to the slower \"list_collections\"",
"ArcticLibraryBinding",
"(",
"self",
",",
"library",
")",
".",
"get_library_type",
"(",
... | 33.269231 | 21.5 |
def convert_sent_to_conll(sent_ls: List[Extraction]):
"""
Given a list of extractions for a single sentence -
convert it to conll representation.
"""
# Sanity check - make sure all extractions are on the same sentence
assert(len(set([ex.sent for ex in sent_ls])) == 1)
toks = sent_ls[0].sent.... | [
"def",
"convert_sent_to_conll",
"(",
"sent_ls",
":",
"List",
"[",
"Extraction",
"]",
")",
":",
"# Sanity check - make sure all extractions are on the same sentence",
"assert",
"(",
"len",
"(",
"set",
"(",
"[",
"ex",
".",
"sent",
"for",
"ex",
"in",
"sent_ls",
"]",
... | 36.692308 | 10.076923 |
def per_chat_id_in(s, types='all'):
"""
:param s:
a list or set of chat id
:param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``)
:return:
a seeder function that returns the chat id only if the chat id is in ``s``
and chat type is in ``types... | [
"def",
"per_chat_id_in",
"(",
"s",
",",
"types",
"=",
"'all'",
")",
":",
"return",
"_wrap_none",
"(",
"lambda",
"msg",
":",
"msg",
"[",
"'chat'",
"]",
"[",
"'id'",
"]",
"if",
"(",
"types",
"==",
"'all'",
"or",
"msg",
"[",
"'chat'",
"]",
"[",
"'type... | 33.5 | 20.625 |
def set_max_string_length(self, length=None):
"""stub"""
if self.get_max_string_length_metadata().is_read_only():
raise NoAccess()
if not self.my_osid_object_form._is_valid_cardinal(
length,
self.get_max_string_length_metadata()):
raise Inv... | [
"def",
"set_max_string_length",
"(",
"self",
",",
"length",
"=",
"None",
")",
":",
"if",
"self",
".",
"get_max_string_length_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
":",
"raise",
"NoAccess",
"(",
")",
"if",
"not",
"self",
".",
"my_osid_object_for... | 47.153846 | 14.846154 |
def kill_process(process_name):
""" method is called to kill a running process """
try:
sys.stdout.write('killing: {0} {{ \n'.format(process_name))
pid = get_process_pid(process_name)
if pid is not None and psutil.pid_exists(int(pid)):
p = psutil.Process(pid)
p.ki... | [
"def",
"kill_process",
"(",
"process_name",
")",
":",
"try",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'killing: {0} {{ \\n'",
".",
"format",
"(",
"process_name",
")",
")",
"pid",
"=",
"get_process_pid",
"(",
"process_name",
")",
"if",
"pid",
"is",
"n... | 37.857143 | 16.714286 |
def sg_sum(tensor, opt):
r"""Computes the sum of elements across axis of a tensor.
See `tf.reduce_sum()` in tensorflow.
Args:
tensor: A `Tensor` with zero-padding (automatically given by chain).
opt:
axis: A tuple/list of integers or an integer. The axis to reduce.
keep_dim... | [
"def",
"sg_sum",
"(",
"tensor",
",",
"opt",
")",
":",
"return",
"tf",
".",
"reduce_sum",
"(",
"tensor",
",",
"axis",
"=",
"opt",
".",
"axis",
",",
"keep_dims",
"=",
"opt",
".",
"keep_dims",
",",
"name",
"=",
"opt",
".",
"name",
")"
] | 34.125 | 25.125 |
def alias_list(self, args: argparse.Namespace) -> None:
"""List some or all aliases"""
if args.name:
for cur_name in utils.remove_duplicates(args.name):
if cur_name in self.aliases:
self.poutput("alias create {} {}".format(cur_name, self.aliases[cur_name])... | [
"def",
"alias_list",
"(",
"self",
",",
"args",
":",
"argparse",
".",
"Namespace",
")",
"->",
"None",
":",
"if",
"args",
".",
"name",
":",
"for",
"cur_name",
"in",
"utils",
".",
"remove_duplicates",
"(",
"args",
".",
"name",
")",
":",
"if",
"cur_name",
... | 53.833333 | 24.833333 |
def notify(title,
message,
auth_token,
source=None,
url=None,
url_title=None,
image=None,
ttl=None,
important=False,
silent=False,
retcode=None):
"""
Required parameters:
* ``auth_token``
O... | [
"def",
"notify",
"(",
"title",
",",
"message",
",",
"auth_token",
",",
"source",
"=",
"None",
",",
"url",
"=",
"None",
",",
"url_title",
"=",
"None",
",",
"image",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
"important",
"=",
"False",
",",
"silent",
... | 21.510204 | 18.571429 |
def set_volume(self, volume):
"""Set volume level of the device. Accepts integer values 0-200."""
if 0 <= volume <= 200:
volume = format(volume, "02x") # Convert to hex
self._send(self.CMD_VOLUME + volume) | [
"def",
"set_volume",
"(",
"self",
",",
"volume",
")",
":",
"if",
"0",
"<=",
"volume",
"<=",
"200",
":",
"volume",
"=",
"format",
"(",
"volume",
",",
"\"02x\"",
")",
"# Convert to hex",
"self",
".",
"_send",
"(",
"self",
".",
"CMD_VOLUME",
"+",
"volume"... | 48.4 | 9.8 |
def confidence_interval_noiseID(x, dev, af, dev_type="adev", data_type="phase", ci=ONE_SIGMA_CI):
""" returns confidence interval (dev_min, dev_max)
for a given deviation dev = Xdev( x, tau = af*(1/rate) )
steps:
1) identify noise type
2) compute EDF
3) compute conf... | [
"def",
"confidence_interval_noiseID",
"(",
"x",
",",
"dev",
",",
"af",
",",
"dev_type",
"=",
"\"adev\"",
",",
"data_type",
"=",
"\"phase\"",
",",
"ci",
"=",
"ONE_SIGMA_CI",
")",
":",
"# 1) noise ID",
"dmax",
"=",
"2",
"if",
"(",
"dev_type",
"is",
"\"hdev\"... | 35.907407 | 24.388889 |
def Approval(self, username, approval_id):
"""Returns a reference to an approval."""
return ClientApprovalRef(
client_id=self.client_id,
username=username,
approval_id=approval_id,
context=self._context) | [
"def",
"Approval",
"(",
"self",
",",
"username",
",",
"approval_id",
")",
":",
"return",
"ClientApprovalRef",
"(",
"client_id",
"=",
"self",
".",
"client_id",
",",
"username",
"=",
"username",
",",
"approval_id",
"=",
"approval_id",
",",
"context",
"=",
"sel... | 29.625 | 11.5 |
def retry(max_retries=1):
""" Retry a function `max_retries` times. """
def retry_func(func):
@wraps(func)
def wrapper(*args, **kwargs):
num_retries = 0
while num_retries <= max_retries:
try:
ret = func(*args, **kwargs)
... | [
"def",
"retry",
"(",
"max_retries",
"=",
"1",
")",
":",
"def",
"retry_func",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"num_retries",
"=",
"0",
"while",
"num_retrie... | 26.952381 | 15.571429 |
def as_json(self, validate=True):
"""Return JSON serialization.
Will raise IIIFInfoError if insufficient parameters are present to
have a valid info.json response (unless validate is False).
"""
if (validate):
self.validate()
json_dict = {}
if (self.a... | [
"def",
"as_json",
"(",
"self",
",",
"validate",
"=",
"True",
")",
":",
"if",
"(",
"validate",
")",
":",
"self",
".",
"validate",
"(",
")",
"json_dict",
"=",
"{",
"}",
"if",
"(",
"self",
".",
"api_version",
">",
"'1.0'",
")",
":",
"json_dict",
"[",
... | 42.166667 | 12.214286 |
def get_traffic(self, subreddit):
"""Return the json dictionary containing traffic stats for a subreddit.
:param subreddit: The subreddit whose /about/traffic page we will
collect.
"""
url = self.config['subreddit_traffic'].format(
subreddit=six.text_type(subred... | [
"def",
"get_traffic",
"(",
"self",
",",
"subreddit",
")",
":",
"url",
"=",
"self",
".",
"config",
"[",
"'subreddit_traffic'",
"]",
".",
"format",
"(",
"subreddit",
"=",
"six",
".",
"text_type",
"(",
"subreddit",
")",
")",
"return",
"self",
".",
"request_... | 35.4 | 16.4 |
def draw(self):
"""Draw the Onshape flocculator model based off of this object."""
from onshapepy import Part
CAD = Part(
'https://cad.onshape.com/documents/b4cfd328713460beeb3125ac/w/3928b5c91bb0a0be7858d99e/e/6f2eeada21e494cebb49515f'
)
CAD.params = {
'c... | [
"def",
"draw",
"(",
"self",
")",
":",
"from",
"onshapepy",
"import",
"Part",
"CAD",
"=",
"Part",
"(",
"'https://cad.onshape.com/documents/b4cfd328713460beeb3125ac/w/3928b5c91bb0a0be7858d99e/e/6f2eeada21e494cebb49515f'",
")",
"CAD",
".",
"params",
"=",
"{",
"'channel_L'",
... | 39.615385 | 17.615385 |
def rgb2gray(image_rgb_array):
"""!
@brief Returns image as 1-dimension (gray colored) matrix, where one element of list describes pixel.
@details Luma coding is used for transformation and that is calculated directly from gamma-compressed primary intensities as a weighted sum:
\f[Y = 0.2989R ... | [
"def",
"rgb2gray",
"(",
"image_rgb_array",
")",
":",
"image_gray_array",
"=",
"[",
"0.0",
"]",
"*",
"len",
"(",
"image_rgb_array",
")",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"image_rgb_array",
")",
",",
"1",
")",
":",
"image_gray_arra... | 39.08 | 31.68 |
def get_field(self, field):
'''A :class:`Q` performs a series of operations and ultimately
generate of set of matched elements ``ids``. If on the other hand, a
different field is required, it can be specified with the :meth:`get_field`
method. For example, lets say a model has a field called ``object_id``
... | [
"def",
"get_field",
"(",
"self",
",",
"field",
")",
":",
"if",
"field",
"!=",
"self",
".",
"_get_field",
":",
"if",
"field",
"not",
"in",
"self",
".",
"_meta",
".",
"dfields",
":",
"raise",
"QuerySetError",
"(",
"'Model \"{0}\" has no field \"{1}\".'",
".",
... | 40.48 | 22.64 |
def flag_based_complete(self, text: str, line: str, begidx: int, endidx: int,
flag_dict: Dict[str, Union[Iterable, Callable]],
all_else: Union[None, Iterable, Callable] = None) -> List[str]:
"""
Tab completes based on a particular flag preceding th... | [
"def",
"flag_based_complete",
"(",
"self",
",",
"text",
":",
"str",
",",
"line",
":",
"str",
",",
"begidx",
":",
"int",
",",
"endidx",
":",
"int",
",",
"flag_dict",
":",
"Dict",
"[",
"str",
",",
"Union",
"[",
"Iterable",
",",
"Callable",
"]",
"]",
... | 52.341463 | 28.04878 |
def p_operation_definition7(self, p):
"""
operation_definition : operation_type directives selection_set
"""
p[0] = self.operation_cls(p[1])(
selections=p[3],
directives=p[2],
) | [
"def",
"p_operation_definition7",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"operation_cls",
"(",
"p",
"[",
"1",
"]",
")",
"(",
"selections",
"=",
"p",
"[",
"3",
"]",
",",
"directives",
"=",
"p",
"[",
"2",
"]",
",",... | 29.25 | 11 |
def extract_arguments(args, defaults):
"""Extract a set of arguments from a large dictionary
Parameters
----------
args : dict
Dictionary with the arguments values to use
defaults : dict
Dictionary with all the argument to extract, and default values for each
Returns
----... | [
"def",
"extract_arguments",
"(",
"args",
",",
"defaults",
")",
":",
"out_dict",
"=",
"convert_option_dict_to_dict",
"(",
"defaults",
")",
"for",
"key",
"in",
"defaults",
".",
"keys",
"(",
")",
":",
"mapped_val",
"=",
"args",
".",
"get",
"(",
"key",
",",
... | 23.296296 | 21.814815 |
def _build_prior(self, unconstrained_tensor, constrained_tensor):
"""
Build a tensorflow representation of the prior density.
The log Jacobian is included.
"""
if not misc.is_tensor(unconstrained_tensor):
raise GPflowError("Unconstrained input must be a tensor.")
... | [
"def",
"_build_prior",
"(",
"self",
",",
"unconstrained_tensor",
",",
"constrained_tensor",
")",
":",
"if",
"not",
"misc",
".",
"is_tensor",
"(",
"unconstrained_tensor",
")",
":",
"raise",
"GPflowError",
"(",
"\"Unconstrained input must be a tensor.\"",
")",
"if",
"... | 40.263158 | 22.789474 |
def get_email_templates(self, params=None):
"""
Get all e-mail templates
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""... | [
"def",
"get_email_templates",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"self",
".",
"get_email_templates_per_page",
",",
"resource",
"=",
"EM... | 40.307692 | 20.923077 |
def is_http_log_entry(self, string):
"""
Determines if a log entry is an HTTP-formatted log string or not.
"""
# Debug event filter
if 'Zappa Event' in string:
return False
# IP address filter
for token in string.replace('\t', ' ').split(' '):
... | [
"def",
"is_http_log_entry",
"(",
"self",
",",
"string",
")",
":",
"# Debug event filter",
"if",
"'Zappa Event'",
"in",
"string",
":",
"return",
"False",
"# IP address filter",
"for",
"token",
"in",
"string",
".",
"replace",
"(",
"'\\t'",
",",
"' '",
")",
".",
... | 30.588235 | 17.882353 |
def dump(fc, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the community object as dictionary.
:param fc: Community featuring to be dumped.
:type fc: `invenio_communities.models.FeaturedCommunity [Invenio2.x]`
:returns: Community serialized to dictionary.
:rtype: dict
"""
... | [
"def",
"dump",
"(",
"fc",
",",
"from_date",
",",
"with_json",
"=",
"True",
",",
"latest_only",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"dict",
"(",
"id",
"=",
"fc",
".",
"id",
",",
"id_community",
"=",
"fc",
".",
"id_community",
... | 39.272727 | 16 |
def machines(self, machine_type=None, name=None, dataset=None, state=None,
memory=None, tombstone=None, tags=None, credentials=False,
paged=False, limit=None, offset=None):
"""
::
GET /:login/machines
Query for machines in the current DataC... | [
"def",
"machines",
"(",
"self",
",",
"machine_type",
"=",
"None",
",",
"name",
"=",
"None",
",",
"dataset",
"=",
"None",
",",
"state",
"=",
"None",
",",
"memory",
"=",
"None",
",",
"tombstone",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"credentials... | 36.447917 | 18.989583 |
def _color(self, msg, color):
"""Internal helper method to add colors to input"""
kwargs = {'fg': color}
return click.style(msg, **kwargs) if self.colorize else msg | [
"def",
"_color",
"(",
"self",
",",
"msg",
",",
"color",
")",
":",
"kwargs",
"=",
"{",
"'fg'",
":",
"color",
"}",
"return",
"click",
".",
"style",
"(",
"msg",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"colorize",
"else",
"msg"
] | 46.25 | 12 |
def generate_seviri_file(seviri, platform_name):
"""Generate the pyspectral internal common format relative response
function file for one SEVIRI
"""
import h5py
filename = os.path.join(seviri.output_dir,
"rsr_seviri_{0}.h5".format(platform_name))
sat_name = platfor... | [
"def",
"generate_seviri_file",
"(",
"seviri",
",",
"platform_name",
")",
":",
"import",
"h5py",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"seviri",
".",
"output_dir",
",",
"\"rsr_seviri_{0}.h5\"",
".",
"format",
"(",
"platform_name",
")",
")",
"s... | 38.263158 | 17.631579 |
def dict_remove_value(d, v):
"""
Recursively remove keys with a certain value from a dict
:param d: the dictionary
:param v: value which should be removed
:return: formatted dictionary
"""
dd = dict()
for key, value in d.items():
if not value == v:
if isinstance(value... | [
"def",
"dict_remove_value",
"(",
"d",
",",
"v",
")",
":",
"dd",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"not",
"value",
"==",
"v",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",... | 31.705882 | 11.823529 |
def validate_single_matching_uri(all_blockchain_uris: List[str], w3: Web3) -> str:
"""
Return a single block URI after validating that it is the *only* URI in
all_blockchain_uris that matches the w3 instance.
"""
matching_uris = [
uri for uri in all_blockchain_uris if check_if_chain_matches_... | [
"def",
"validate_single_matching_uri",
"(",
"all_blockchain_uris",
":",
"List",
"[",
"str",
"]",
",",
"w3",
":",
"Web3",
")",
"->",
"str",
":",
"matching_uris",
"=",
"[",
"uri",
"for",
"uri",
"in",
"all_blockchain_uris",
"if",
"check_if_chain_matches_chain_uri",
... | 38.875 | 24.25 |
def get_images(self, obj):
"""Object of images serialized by tag name."""
return {str(i.tag): i.image.url for i in obj.images.all()} | [
"def",
"get_images",
"(",
"self",
",",
"obj",
")",
":",
"return",
"{",
"str",
"(",
"i",
".",
"tag",
")",
":",
"i",
".",
"image",
".",
"url",
"for",
"i",
"in",
"obj",
".",
"images",
".",
"all",
"(",
")",
"}"
] | 48.666667 | 13.333333 |
def setEnv(self, name, value=None):
"""
Set an environment variable for the worker process before it is launched. The worker
process will typically inherit the environment of the machine it is running on but this
method makes it possible to override specific variables in that inherited e... | [
"def",
"setEnv",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"try",
":",
"value",
"=",
"os",
".",
"environ",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"RuntimeError",
"(",
"\"%s does no... | 54.551724 | 34.344828 |
def get_detail(self):
"""Get general stats information.
Includes:
- size_total: total size on disk
- num_folder_total: how many subfolders
- num_file_total: how many files
- size_current: total size of files on this folder. file in subfolders
... | [
"def",
"get_detail",
"(",
"self",
")",
":",
"self",
".",
"size_total",
"=",
"0",
"self",
".",
"num_folder_total",
"=",
"0",
"self",
".",
"num_file_total",
"=",
"0",
"self",
".",
"size_current",
"=",
"0",
"self",
".",
"num_folder_current",
"=",
"0",
"self... | 39.84375 | 17.90625 |
def relativize(self, origin):
"""If self is a subdomain of origin, return a new name which is self
relative to origin. Otherwise return self.
@rtype: dns.name.Name object
"""
if not origin is None and self.is_subdomain(origin):
return Name(self[: -len(origin)])
... | [
"def",
"relativize",
"(",
"self",
",",
"origin",
")",
":",
"if",
"not",
"origin",
"is",
"None",
"and",
"self",
".",
"is_subdomain",
"(",
"origin",
")",
":",
"return",
"Name",
"(",
"self",
"[",
":",
"-",
"len",
"(",
"origin",
")",
"]",
")",
"else",
... | 34.4 | 13.5 |
def find_module(self, name, path=None):
"""
Called when an import is made. If there are hooks waiting for this
module to be imported then we stop the normal import process and
manually load the module.
@param name: The name of the module being imported.
@param path The r... | [
"def",
"find_module",
"(",
"self",
",",
"name",
",",
"path",
"=",
"None",
")",
":",
"if",
"name",
"in",
"self",
".",
"loaded_modules",
":",
"return",
"None",
"hooks",
"=",
"self",
".",
"post_load_hooks",
".",
"get",
"(",
"name",
",",
"None",
")",
"if... | 39 | 21.631579 |
def update_stack(self, name, working_bucket, wait=False, update_only=False, disable_progress=False):
"""
Update or create the CF stack managed by Zappa.
"""
capabilities = []
template = name + '-template-' + str(int(time.time())) + '.json'
with open(template, 'wb') as ou... | [
"def",
"update_stack",
"(",
"self",
",",
"name",
",",
"working_bucket",
",",
"wait",
"=",
"False",
",",
"update_only",
"=",
"False",
",",
"disable_progress",
"=",
"False",
")",
":",
"capabilities",
"=",
"[",
"]",
"template",
"=",
"name",
"+",
"'-template-'... | 45.760417 | 25.427083 |
def merge_true_table():
"""Merge all true table into single excel file.
"""
writer = pd.ExcelWriter("True Table.xlsx")
for p in Path(__file__).parent.select_by_ext(".csv"):
df = pd.read_csv(p.abspath, index_col=0)
df.to_excel(writer, p.fname, index=True)
writer.save() | [
"def",
"merge_true_table",
"(",
")",
":",
"writer",
"=",
"pd",
".",
"ExcelWriter",
"(",
"\"True Table.xlsx\"",
")",
"for",
"p",
"in",
"Path",
"(",
"__file__",
")",
".",
"parent",
".",
"select_by_ext",
"(",
"\".csv\"",
")",
":",
"df",
"=",
"pd",
".",
"r... | 37.125 | 9.875 |
def _complete_multipart_upload(self, bucket_name, object_name,
upload_id, uploaded_parts):
"""
Complete an active multipart upload request.
:param bucket_name: Bucket name of the multipart request.
:param object_name: Object name of the multipart reque... | [
"def",
"_complete_multipart_upload",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"upload_id",
",",
"uploaded_parts",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"is_non_empty_string",
"(",
"object_name",
")",
"is_non_empty_string",
"(",
"u... | 40.527778 | 19.361111 |
def V_from_h(self, h, method='full'):
r'''Method to calculate the volume of liquid in a fully defined tank
given a specified height `h`. `h` must be under the maximum height.
If the method is 'chebyshev', and the coefficients have not yet been
calculated, they are created by calling `se... | [
"def",
"V_from_h",
"(",
"self",
",",
"h",
",",
"method",
"=",
"'full'",
")",
":",
"if",
"method",
"==",
"'full'",
":",
"return",
"V_from_h",
"(",
"h",
",",
"self",
".",
"D",
",",
"self",
".",
"L",
",",
"self",
".",
"horizontal",
",",
"self",
".",... | 37.90625 | 23.59375 |
def list_shares(self, prefix=None, marker=None, num_results=None,
include_metadata=False, timeout=None):
'''
Returns a generator to list the shares under the specified account.
The generator will lazily follow the continuation tokens returned by
the service and stop ... | [
"def",
"list_shares",
"(",
"self",
",",
"prefix",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"num_results",
"=",
"None",
",",
"include_metadata",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"include",
"=",
"'metadata'",
"if",
"include_metadata"... | 51.916667 | 26.583333 |
def _custom_token_stream(self):
""" A wrapper for the BaseEnamlLexer's make_token_stream which allows
the stream to be customized by adding "token_stream_processors".
A token_stream_processor is a generator function which takes the
token_stream as it's single input argument and yields each process... | [
"def",
"_custom_token_stream",
"(",
"self",
")",
":",
"token_stream",
"=",
"default_make_token_stream",
"(",
"self",
")",
"for",
"processor",
"in",
"_token_stream_processors",
":",
"token_stream",
"=",
"processor",
"(",
"token_stream",
")",
"return",
"token_stream"
] | 44.076923 | 19.153846 |
def columns(self):
"""List[:class:`~.external_config.BigtableColumn`]: Lists of columns
that should be exposed as individual fields.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions.(key).bigtableOptions.columnFamilies.columns
... | [
"def",
"columns",
"(",
"self",
")",
":",
"prop",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"\"columns\"",
",",
"[",
"]",
")",
"return",
"[",
"BigtableColumn",
".",
"from_api_repr",
"(",
"col",
")",
"for",
"col",
"in",
"prop",
"]"
] | 57.1 | 34.6 |
def _get_env_bin_path(env_path):
"""Return the bin path for a virtualenv
This provides a fallback for a situation in which you're trying
to use the script and create a virtualenv from within
a virtualenv in which virtualenv isn't installed and so
is not importable.
"""
if IS_VIRTUALENV_INST... | [
"def",
"_get_env_bin_path",
"(",
"env_path",
")",
":",
"if",
"IS_VIRTUALENV_INSTALLED",
":",
"path",
"=",
"virtualenv",
".",
"path_locations",
"(",
"env_path",
")",
"[",
"3",
"]",
"else",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"env_path",
... | 36.846154 | 17 |
def get(self, *args, **kwargs):
"""
Get a single object.
This is a convenience wrapper for the search method that checks that
only one object was returned, and returns that single object instead
of a list. This method takes the exact same arguments as search.
"""
... | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"self",
".",
"search",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"num_results",
"=",
"len",
"(",
"results",
")",
"if",
"num_results",
"==",
"1",... | 36 | 14.933333 |
def intercept(work_db):
"""Look for WorkItems in `work_db` that should not be mutated due to spor metadata.
For each WorkItem, find anchors for the item's file/line/columns. If an
anchor exists with metadata containing `{mutate: False}` then the WorkItem
is marked as SKIPPED.
"""
@lru_cache()
... | [
"def",
"intercept",
"(",
"work_db",
")",
":",
"@",
"lru_cache",
"(",
")",
"def",
"file_contents",
"(",
"file_path",
")",
":",
"\"A simple cache of file contents.\"",
"with",
"file_path",
".",
"open",
"(",
"mode",
"=",
"\"rt\"",
")",
"as",
"handle",
":",
"ret... | 33.06 | 16.3 |
def compile_args(args, kwargs, sep, prefix):
""" takes args and kwargs, as they were passed into the command instance
being executed with __call__, and compose them into a flat list that
will eventually be fed into exec. example:
with this call:
sh.ls("-l", "/tmp", color="never")
this fu... | [
"def",
"compile_args",
"(",
"args",
",",
"kwargs",
",",
"sep",
",",
"prefix",
")",
":",
"processed_args",
"=",
"[",
"]",
"encode",
"=",
"encode_to_py3bytes_or_py2str",
"# aggregate positional args",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"ar... | 27.769231 | 19.538462 |
def delete_account(self, account):
""" Account was deleted. """
try:
luser = self._get_account(account.username)
groups = luser['groups'].load(database=self._database)
for group in groups:
changes = changeset(group, {})
changes = group.... | [
"def",
"delete_account",
"(",
"self",
",",
"account",
")",
":",
"try",
":",
"luser",
"=",
"self",
".",
"_get_account",
"(",
"account",
".",
"username",
")",
"groups",
"=",
"luser",
"[",
"'groups'",
"]",
".",
"load",
"(",
"database",
"=",
"self",
".",
... | 39.071429 | 15.357143 |
def get_config(self):
"""Get the combined configuration of all curriculums in this
MetaCurriculum.
Returns:
A dict from parameter to value.
"""
config = {}
for _, curriculum in self.brains_to_curriculums.items():
curr_config = curriculum.get_conf... | [
"def",
"get_config",
"(",
"self",
")",
":",
"config",
"=",
"{",
"}",
"for",
"_",
",",
"curriculum",
"in",
"self",
".",
"brains_to_curriculums",
".",
"items",
"(",
")",
":",
"curr_config",
"=",
"curriculum",
".",
"get_config",
"(",
")",
"config",
".",
"... | 26.642857 | 18.428571 |
def logpdf(self, mu):
"""
Log PDF for Truncated Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
... | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"if",
"mu",
"<",
"self",
".",
"lower",
"and",
"self",
".",
"lower",
"is",
"not",
"... | 28.952381 | 19.047619 |
def fromwgs84(lat, lng, pkm=False):
"""
Convert coordintes from WGS84 to TWD97
pkm true for Penghu, Kinmen and Matsu area
The latitude and longitude can be in the following formats:
[+/-]DDD°MMM'SSS.SSSS" (unicode)
[+/-]DDD°MMM.MMMM' (unicode)
[+/-]DDD.DDDDD (string, unicode or ... | [
"def",
"fromwgs84",
"(",
"lat",
",",
"lng",
",",
"pkm",
"=",
"False",
")",
":",
"_lng0",
"=",
"lng0pkm",
"if",
"pkm",
"else",
"lng0",
"lat",
"=",
"radians",
"(",
"todegdec",
"(",
"lat",
")",
")",
"lng",
"=",
"radians",
"(",
"todegdec",
"(",
"lng",
... | 37.172414 | 19.241379 |
def get_rate_limit(self):
"""
Rate limit status for different resources (core/search/graphql).
:calls: `GET /rate_limit <http://developer.github.com/v3/rate_limit>`_
:rtype: :class:`github.RateLimit.RateLimit`
"""
headers, data = self.__requester.requestJsonAndCheck(
... | [
"def",
"get_rate_limit",
"(",
"self",
")",
":",
"headers",
",",
"data",
"=",
"self",
".",
"__requester",
".",
"requestJsonAndCheck",
"(",
"'GET'",
",",
"'/rate_limit'",
")",
"return",
"RateLimit",
".",
"RateLimit",
"(",
"self",
".",
"__requester",
",",
"head... | 37.25 | 22.583333 |
def load(cls, cache_file, backend=None):
"""Instantiate AsyncResult from dumped `cache_file`.
This is the inverse of :meth:`dump`.
Parameters
----------
cache_file: str
Name of file from which the run should be read.
backend: clusterjob.backen... | [
"def",
"load",
"(",
"cls",
",",
"cache_file",
",",
"backend",
"=",
"None",
")",
":",
"with",
"open",
"(",
"cache_file",
",",
"'rb'",
")",
"as",
"pickle_fh",
":",
"(",
"remote",
",",
"backend_name",
",",
"max_sleep_interval",
",",
"job_id",
",",
"status",... | 38.884615 | 21.346154 |
def build_plugins(cls, plugins_conf):
"""Create an instance of the named plugin and return it
:param plugins_conf: dict of {alias: dict(plugin builder params) }
:type plugins_conf: dict
:rtype: dict[str, AbstractPlugin]
:return: dict of alias: plugin instance
"""
... | [
"def",
"build_plugins",
"(",
"cls",
",",
"plugins_conf",
")",
":",
"plugins",
"=",
"{",
"}",
"for",
"alias",
",",
"params_dict",
"in",
"plugins_conf",
".",
"items",
"(",
")",
":",
"plugin_config",
"=",
"PluginConfig",
"(",
"*",
"*",
"(",
"params_dict",
"... | 48.75 | 17.416667 |
def buffer_leave(self, filename):
"""User is changing of buffer."""
self.log.debug('buffer_leave: %s', filename)
# TODO: This is questionable, and we should use location list for
# single-file errors.
self.editor.clean_errors() | [
"def",
"buffer_leave",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'buffer_leave: %s'",
",",
"filename",
")",
"# TODO: This is questionable, and we should use location list for",
"# single-file errors.",
"self",
".",
"editor",
".",
... | 43.666667 | 11.5 |
def create_network_interface(self, subnet_id, private_ip_address=None,
description=None, groups=None):
"""
Creates a network interface in the specified subnet.
:type subnet_id: str
:param subnet_id: The ID of the subnet to associate with the
... | [
"def",
"create_network_interface",
"(",
"self",
",",
"subnet_id",
",",
"private_ip_address",
"=",
"None",
",",
"description",
"=",
"None",
",",
"groups",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'SubnetId'",
":",
"subnet_id",
"}",
"if",
"private_ip_address"... | 39.725 | 19.575 |
def publish(self, topic, data, defer=None, block=True, timeout=None,
raise_error=True):
"""Publish a message to the given topic.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in milliseconds to defer before publish... | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"data",
",",
"defer",
"=",
"None",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"raise_error",
"=",
"True",
")",
":",
"result",
"=",
"AsyncResult",
"(",
")",
"conn",
"=",
"self",
"."... | 36.222222 | 23.638889 |
def get_authors(self):
"""
Returns:
list: Authors represented as :class:`.Person` objects.
"""
authors = self._parse_persons("100", "a")
authors += self._parse_persons("600", "a")
authors += self._parse_persons("700", "a")
authors += self._parse_person... | [
"def",
"get_authors",
"(",
"self",
")",
":",
"authors",
"=",
"self",
".",
"_parse_persons",
"(",
"\"100\"",
",",
"\"a\"",
")",
"authors",
"+=",
"self",
".",
"_parse_persons",
"(",
"\"600\"",
",",
"\"a\"",
")",
"authors",
"+=",
"self",
".",
"_parse_persons"... | 31.545455 | 15 |
def elem_add(self, idx=None, name=None, **kwargs):
"""overloading elem_add function of a JIT class"""
self.jit_load()
if self.loaded:
return self.system.__dict__[self.name].elem_add(
idx, name, **kwargs) | [
"def",
"elem_add",
"(",
"self",
",",
"idx",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"jit_load",
"(",
")",
"if",
"self",
".",
"loaded",
":",
"return",
"self",
".",
"system",
".",
"__dict__",
"[",
"sel... | 41.666667 | 11.333333 |
def select_neighbors_by_layer(docgraph, node, layer, data=False):
"""
Get all neighboring nodes belonging to (any of) the given layer(s),
A neighboring node is a node that the given node connects to with an
outgoing edge.
Parameters
----------
docgraph : DiscourseDocumentGraph
docum... | [
"def",
"select_neighbors_by_layer",
"(",
"docgraph",
",",
"node",
",",
"layer",
",",
"data",
"=",
"False",
")",
":",
"for",
"node_id",
"in",
"docgraph",
".",
"neighbors_iter",
"(",
"node",
")",
":",
"node_layers",
"=",
"docgraph",
".",
"node",
"[",
"node_i... | 37.83871 | 20.225806 |
def _read_tal(rawbytes):
"""Read TAL (Time-stamped Annotations Lists) using regex
Parameters
----------
rawbytes : bytes
raw information from file
Returns
-------
annotation : list of dict
where each dict contains onset, duration, and list with the annotations
"""
a... | [
"def",
"_read_tal",
"(",
"rawbytes",
")",
":",
"annotations",
"=",
"[",
"]",
"for",
"m",
"in",
"finditer",
"(",
"PATTERN",
",",
"rawbytes",
")",
":",
"d",
"=",
"m",
".",
"groupdict",
"(",
")",
"annot",
"=",
"{",
"'onset'",
":",
"float",
"(",
"decod... | 27.461538 | 22.653846 |
def _get_by_index(self, index):
"""Returns a volume,disk tuple for the specified index"""
volume_or_disk = self.parser.get_by_index(index)
volume, disk = (volume_or_disk, None) if not isinstance(volume_or_disk, Disk) else (None, volume_or_disk)
return volume, disk | [
"def",
"_get_by_index",
"(",
"self",
",",
"index",
")",
":",
"volume_or_disk",
"=",
"self",
".",
"parser",
".",
"get_by_index",
"(",
"index",
")",
"volume",
",",
"disk",
"=",
"(",
"volume_or_disk",
",",
"None",
")",
"if",
"not",
"isinstance",
"(",
"volum... | 58.4 | 22.2 |
def run_kmeans(self, X, K):
"""Runs k-means and returns the labels assigned to the data."""
wX = vq.whiten(X)
means, dist = vq.kmeans(wX, K, iter=100)
labels, dist = vq.vq(wX, means)
return means, labels | [
"def",
"run_kmeans",
"(",
"self",
",",
"X",
",",
"K",
")",
":",
"wX",
"=",
"vq",
".",
"whiten",
"(",
"X",
")",
"means",
",",
"dist",
"=",
"vq",
".",
"kmeans",
"(",
"wX",
",",
"K",
",",
"iter",
"=",
"100",
")",
"labels",
",",
"dist",
"=",
"v... | 39.666667 | 8.166667 |
def barplot(df, column='Adjusted P-value', title="", cutoff=0.05, top_term=10,
figsize=(6.5,6), color='salmon', ofname=None, **kwargs):
"""Visualize enrichr results.
:param df: GSEApy DataFrame results.
:param column: which column of DataFrame to show. Default: Adjusted P-value
:param title... | [
"def",
"barplot",
"(",
"df",
",",
"column",
"=",
"'Adjusted P-value'",
",",
"title",
"=",
"\"\"",
",",
"cutoff",
"=",
"0.05",
",",
"top_term",
"=",
"10",
",",
"figsize",
"=",
"(",
"6.5",
",",
"6",
")",
",",
"color",
"=",
"'salmon'",
",",
"ofname",
... | 38.90566 | 18.226415 |
def f_get(self, *args):
"""Returns items handled by the result.
If only a single name is given, a single data item is returned. If several names are
given, a list is returned. For integer inputs the result returns `resultname_X`.
If the result contains only a single entry you can ca... | [
"def",
"f_get",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"if",
"len",
"(",
"self",
".",
"_data",
")",
"==",
"1",
":",
"return",
"list",
"(",
"self",
".",
"_data",
".",
"values",
"(",
")",
")",
... | 37.821429 | 25.5 |
def _pip_list(self, stdout, stderr, prefix=None):
"""Callback for `pip_list`."""
result = stdout # A dict
linked = self.linked(prefix)
pip_only = []
linked_names = [self.split_canonical_name(l)[0] for l in linked]
for pkg in result:
name = self.split_canon... | [
"def",
"_pip_list",
"(",
"self",
",",
"stdout",
",",
"stderr",
",",
"prefix",
"=",
"None",
")",
":",
"result",
"=",
"stdout",
"# A dict",
"linked",
"=",
"self",
".",
"linked",
"(",
"prefix",
")",
"pip_only",
"=",
"[",
"]",
"linked_names",
"=",
"[",
"... | 34.8 | 13.92 |
def shapefiles(fname, f_tooltip=None, color=None, linewidth=3, shape_type='full'):
"""
Load and draws shapefiles
:param fname: full path to the shapefile
:param f_tooltip: function to generate a tooltip on mouseover
:param color: color
:param linewidth: line width
:param shape_type: either ... | [
"def",
"shapefiles",
"(",
"fname",
",",
"f_tooltip",
"=",
"None",
",",
"color",
"=",
"None",
",",
"linewidth",
"=",
"3",
",",
"shape_type",
"=",
"'full'",
")",
":",
"from",
"geoplotlib",
".",
"layers",
"import",
"ShapefileLayer",
"_global_config",
".",
"la... | 39.583333 | 17.75 |
def parse_marker(cls, line):
"""
Returns a pair (prepend, leader) iff the line has a valid leader.
"""
match_obj = cls.pattern.match(line)
if match_obj is None:
return None # no valid leader
leader = match_obj.group(1)
content = match_obj.group(... | [
"def",
"parse_marker",
"(",
"cls",
",",
"line",
")",
":",
"match_obj",
"=",
"cls",
".",
"pattern",
".",
"match",
"(",
"line",
")",
"if",
"match_obj",
"is",
"None",
":",
"return",
"None",
"# no valid leader",
"leader",
"=",
"match_obj",
".",
"group",
"(",... | 38.136364 | 9.681818 |
def _get_tls(self):
"""Get an SMTP session with TLS."""
session = smtplib.SMTP(self.server, self.port)
session.ehlo()
session.starttls(context=ssl.create_default_context())
session.ehlo()
return session | [
"def",
"_get_tls",
"(",
"self",
")",
":",
"session",
"=",
"smtplib",
".",
"SMTP",
"(",
"self",
".",
"server",
",",
"self",
".",
"port",
")",
"session",
".",
"ehlo",
"(",
")",
"session",
".",
"starttls",
"(",
"context",
"=",
"ssl",
".",
"create_defaul... | 34.857143 | 15.857143 |
def remove_object(self, file_path):
"""Remove an existing file or directory.
Args:
file_path: The path to the file relative to self.
Raises:
IOError: if file_path does not correspond to an existing file, or
if part of the path refers to something other t... | [
"def",
"remove_object",
"(",
"self",
",",
"file_path",
")",
":",
"file_path",
"=",
"self",
".",
"absnormpath",
"(",
"self",
".",
"_original_path",
"(",
"file_path",
")",
")",
"if",
"self",
".",
"_is_root_path",
"(",
"file_path",
")",
":",
"self",
".",
"r... | 41.318182 | 19.636364 |
def symbols(self):
"""List of the coded symbols as strings, with special characters included."""
def _iter_symbols(symbol_values):
# The initial charset doesn't matter, as the start codes have the same symbol values in all charsets.
charset = 'A'
shift_charset = None... | [
"def",
"symbols",
"(",
"self",
")",
":",
"def",
"_iter_symbols",
"(",
"symbol_values",
")",
":",
"# The initial charset doesn't matter, as the start codes have the same symbol values in all charsets.",
"charset",
"=",
"'A'",
"shift_charset",
"=",
"None",
"for",
"symbol_value"... | 42.214286 | 19.607143 |
def _divide_and_round(a, b):
"""divide a by b and round result to the nearest integer
When the ratio is exactly half-way between two integers,
the even integer is returned.
"""
# Based on the reference implementation for divmod_near
# in Objects/longobject.c.
q, r = divmod(a, b)
# round... | [
"def",
"_divide_and_round",
"(",
"a",
",",
"b",
")",
":",
"# Based on the reference implementation for divmod_near",
"# in Objects/longobject.c.",
"q",
",",
"r",
"=",
"divmod",
"(",
"a",
",",
"b",
")",
"# round up if either r / b > 0.5, or r / b == 0.5 and q is odd.",
"# Th... | 33.833333 | 17.888889 |
def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`.
LoggingDatastore logs the access.
'''
self.logger.info('%s: query %s' % (self, query))
return super(LoggingDatastore, self).query(query) | [
"def",
"query",
"(",
"self",
",",
"query",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'%s: query %s'",
"%",
"(",
"self",
",",
"query",
")",
")",
"return",
"super",
"(",
"LoggingDatastore",
",",
"self",
")",
".",
"query",
"(",
"query",
")"
] | 42 | 18.666667 |
def _build_bank_hier(bank, redis_pipe):
'''
Build the bank hierarchy from the root of the tree.
If already exists, it won't rewrite.
It's using the Redis pipeline,
so there will be only one interaction with the remote server.
'''
bank_list = bank.split('/')
parent_bank_path = bank_list[0... | [
"def",
"_build_bank_hier",
"(",
"bank",
",",
"redis_pipe",
")",
":",
"bank_list",
"=",
"bank",
".",
"split",
"(",
"'/'",
")",
"parent_bank_path",
"=",
"bank_list",
"[",
"0",
"]",
"for",
"bank_name",
"in",
"bank_list",
"[",
"1",
":",
"]",
":",
"prev_bank_... | 40.611111 | 14.722222 |
def _is_yaw_flip(lat, delta=10):
"""Determine whether the satellite is yaw-flipped ('upside down')"""
logger.debug('Computing yaw flip flag')
# In case of yaw-flip the data and coordinates in the netCDF files are
# also flipped. Just check whether the latitude increases or decrases
... | [
"def",
"_is_yaw_flip",
"(",
"lat",
",",
"delta",
"=",
"10",
")",
":",
"logger",
".",
"debug",
"(",
"'Computing yaw flip flag'",
")",
"# In case of yaw-flip the data and coordinates in the netCDF files are",
"# also flipped. Just check whether the latitude increases or decrases",
... | 56.625 | 16.375 |
def recall(Ntp, Nref, eps=numpy.spacing(1)):
"""Recall.
Wikipedia entry https://en.wikipedia.org/wiki/Precision_and_recall
Parameters
----------
Ntp : int >=0
Number of true positives.
Nref : int >=0
Amount of reference.
eps : float
eps.
Default value nump... | [
"def",
"recall",
"(",
"Ntp",
",",
"Nref",
",",
"eps",
"=",
"numpy",
".",
"spacing",
"(",
"1",
")",
")",
":",
"if",
"Nref",
"==",
"0",
":",
"return",
"numpy",
".",
"nan",
"else",
":",
"return",
"float",
"(",
"Ntp",
"/",
"float",
"(",
"Nref",
")"... | 16.642857 | 23.678571 |
def _append_html_fetching_plain_text(self, html, before_prompt=False):
""" Appends HTML, then returns the plain text version of it.
"""
return self._append_custom(self._insert_html_fetching_plain_text,
html, before_prompt) | [
"def",
"_append_html_fetching_plain_text",
"(",
"self",
",",
"html",
",",
"before_prompt",
"=",
"False",
")",
":",
"return",
"self",
".",
"_append_custom",
"(",
"self",
".",
"_insert_html_fetching_plain_text",
",",
"html",
",",
"before_prompt",
")"
] | 55.4 | 15.6 |
def set_ion_type(self, ion_type):
"""Sets context to the given IonType."""
if ion_type is self.ion_type:
return self
self.ion_type = ion_type
self.line_comment = False
return self | [
"def",
"set_ion_type",
"(",
"self",
",",
"ion_type",
")",
":",
"if",
"ion_type",
"is",
"self",
".",
"ion_type",
":",
"return",
"self",
"self",
".",
"ion_type",
"=",
"ion_type",
"self",
".",
"line_comment",
"=",
"False",
"return",
"self"
] | 32.142857 | 9 |
def django_admin(request):
'''
Adds additional information to the context:
``django_admin`` - boolean variable indicating whether the current
page is part of the django admin or not.
``ADMIN_URL`` - normalized version of settings.ADMIN_URL; starts with a slash, ends without a slash
NOTE: do no... | [
"def",
"django_admin",
"(",
"request",
")",
":",
"# ensure that adminurl always starts with a '/' but never ends with a '/'",
"if",
"settings",
".",
"ADMIN_URL",
".",
"endswith",
"(",
"'/'",
")",
":",
"admin_url",
"=",
"settings",
".",
"ADMIN_URL",
"[",
":",
"-",
"1... | 34.857143 | 23.5 |
def concat_batch_variantcalls(items, region_block=True, skip_jointcheck=False):
"""CWL entry point: combine variant calls from regions into single VCF.
"""
items = [utils.to_single_data(x) for x in items]
batch_name = _get_batch_name(items, skip_jointcheck)
variantcaller = _get_batch_variantcaller(i... | [
"def",
"concat_batch_variantcalls",
"(",
"items",
",",
"region_block",
"=",
"True",
",",
"skip_jointcheck",
"=",
"False",
")",
":",
"items",
"=",
"[",
"utils",
".",
"to_single_data",
"(",
"x",
")",
"for",
"x",
"in",
"items",
"]",
"batch_name",
"=",
"_get_b... | 55.210526 | 21.631579 |
def node_from_elem(elem, nodefactory=Node, lazy=()):
"""
Convert (recursively) an ElementTree object into a Node object.
"""
children = list(elem)
lineno = getattr(elem, 'lineno', None)
if not children:
return nodefactory(elem.tag, dict(elem.attrib), elem.text,
... | [
"def",
"node_from_elem",
"(",
"elem",
",",
"nodefactory",
"=",
"Node",
",",
"lazy",
"=",
"(",
")",
")",
":",
"children",
"=",
"list",
"(",
"elem",
")",
"lineno",
"=",
"getattr",
"(",
"elem",
",",
"'lineno'",
",",
"None",
")",
"if",
"not",
"children",... | 42.642857 | 17.642857 |
def like(self, **kwargs):
'''
When provided with keyword arguments of the form ``col=pattern``, this
will limit the entities returned to those that include the provided
pattern. Note that 'like' queries require that the ``prefix=True``
option must have been provided as part of th... | [
"def",
"like",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"new",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"v",
"=",
"self",
".",
"_check",
"(",
"k",
",",
"v",
",",
"'like'",
")",
"new",
".",
"... | 45.058824 | 26.529412 |
def iter_hostnames(self):
"""
Yields a list of tuples of the form (ip, hostname).
"""
from burlap.common import get_hosts_retriever
if self.env.use_retriever:
self.vprint('using retriever')
self.vprint('hosts:', self.genv.hosts)
retriever = get... | [
"def",
"iter_hostnames",
"(",
"self",
")",
":",
"from",
"burlap",
".",
"common",
"import",
"get_hosts_retriever",
"if",
"self",
".",
"env",
".",
"use_retriever",
":",
"self",
".",
"vprint",
"(",
"'using retriever'",
")",
"self",
".",
"vprint",
"(",
"'hosts:'... | 42.515152 | 13.787879 |
def match(self, sampling_req):
"""
Determines whether or not this sampling rule applies to the incoming
request based on some of the request's parameters.
Any ``None`` parameter provided will be considered an implicit match.
"""
if sampling_req is None:
return... | [
"def",
"match",
"(",
"self",
",",
"sampling_req",
")",
":",
"if",
"sampling_req",
"is",
"None",
":",
"return",
"False",
"host",
"=",
"sampling_req",
".",
"get",
"(",
"'host'",
",",
"None",
")",
"method",
"=",
"sampling_req",
".",
"get",
"(",
"'method'",
... | 46.3 | 20.6 |
def wiki_2x2_base():
"""Set of architectural experiments - language model on wikipedia on a 2x2.
1 epoch = ~180k steps at batch size 32 - we may never finish an epoch!
Returns:
a hparams
"""
hparams = mtf_transformer.mtf_transformer_base_lm()
hparams.shared_embedding_and_softmax_weights = False
# no... | [
"def",
"wiki_2x2_base",
"(",
")",
":",
"hparams",
"=",
"mtf_transformer",
".",
"mtf_transformer_base_lm",
"(",
")",
"hparams",
".",
"shared_embedding_and_softmax_weights",
"=",
"False",
"# no dropout - dataset is big enough to avoid overfitting.",
"hparams",
".",
"attention_d... | 31.861111 | 17.861111 |
def call_at(
self, when: float, callback: Callable[..., None], *args: Any, **kwargs: Any
) -> object:
"""Runs the ``callback`` at the absolute time designated by ``when``.
``when`` must be a number using the same reference point as
`IOLoop.time`.
Returns an opaque handle th... | [
"def",
"call_at",
"(",
"self",
",",
"when",
":",
"float",
",",
"callback",
":",
"Callable",
"[",
"...",
",",
"None",
"]",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"object",
":",
"return",
"self",
".",
"add_tim... | 39 | 26.882353 |
def _init_compile_patterns(optional_attrs):
"""Compile search patterns for optional attributes if needed."""
attr2cmp = {}
if optional_attrs is None:
return attr2cmp
# "peptidase inhibitor complex" EXACT [GOC:bf, GOC:pr]
# "blood vessel formation from pre-existing blo... | [
"def",
"_init_compile_patterns",
"(",
"optional_attrs",
")",
":",
"attr2cmp",
"=",
"{",
"}",
"if",
"optional_attrs",
"is",
"None",
":",
"return",
"attr2cmp",
"# \"peptidase inhibitor complex\" EXACT [GOC:bf, GOC:pr]",
"# \"blood vessel formation from pre-existing blood vessels\" ... | 56 | 22.588235 |
def normalize(self):
"""Make sure the probabilities of all values sum to 1.
Returns the normalized distribution.
Raises a ZeroDivisionError if the sum of the values is 0.
>>> P = ProbDist('Flip'); P['H'], P['T'] = 35, 65
>>> P = P.normalize()
>>> print '%5.3f %5.3f' % (P.... | [
"def",
"normalize",
"(",
"self",
")",
":",
"total",
"=",
"float",
"(",
"sum",
"(",
"self",
".",
"prob",
".",
"values",
"(",
")",
")",
")",
"if",
"not",
"(",
"1.0",
"-",
"epsilon",
"<",
"total",
"<",
"1.0",
"+",
"epsilon",
")",
":",
"for",
"val"... | 39.642857 | 11.714286 |
def dmag_magic(in_file="measurements.txt", dir_path=".", input_dir_path="",
spec_file="specimens.txt", samp_file="samples.txt",
site_file="sites.txt", loc_file="locations.txt",
plot_by="loc", LT="AF", norm=True, XLP="",
save_plots=True, fmt="svg"):
"""
plots intensity decay ... | [
"def",
"dmag_magic",
"(",
"in_file",
"=",
"\"measurements.txt\"",
",",
"dir_path",
"=",
"\".\"",
",",
"input_dir_path",
"=",
"\"\"",
",",
"spec_file",
"=",
"\"specimens.txt\"",
",",
"samp_file",
"=",
"\"samples.txt\"",
",",
"site_file",
"=",
"\"sites.txt\"",
",",
... | 40.023256 | 19.255814 |
def solver(AA, N_max, symNx = 2, throw_out_modes=False):
""" Constructs the matrix A and the vector b from a timeseries of toy
action-angles AA to solve for the vector x = (J_0,J_1,J_2,S...) where
x contains all Fourier components of the generating function with |n|<N_max """
# Find all integer compone... | [
"def",
"solver",
"(",
"AA",
",",
"N_max",
",",
"symNx",
"=",
"2",
",",
"throw_out_modes",
"=",
"False",
")",
":",
"# Find all integer component n_vectors which lie within sphere of radius N_max",
"# Here we have assumed that the potential is symmetric x->-x, y->-y, z->-z",
"# Thi... | 43.659091 | 27.204545 |
def size(self):
"""Total number of coefficients in the ScalarCoefs structure.
Example::
>>> sz = c.size
>>> N = c.nmax + 1
>>> L = N+ c.mmax * (2 * N - c.mmax - 1);
>>> assert sz == L
"""
N = self.nmax + 1;
NC = N + se... | [
"def",
"size",
"(",
"self",
")",
":",
"N",
"=",
"self",
".",
"nmax",
"+",
"1",
"NC",
"=",
"N",
"+",
"self",
".",
"mmax",
"*",
"(",
"2",
"*",
"N",
"-",
"self",
".",
"mmax",
"-",
"1",
")",
"assert",
"NC",
"==",
"len",
"(",
"self",
".",
"_ve... | 28.357143 | 15.785714 |
def hitail(E: np.ndarray, diffnumflux: np.ndarray, isimE0: np.ndarray, E0: np.ndarray,
Bhf: np.ndarray, bh: float, verbose: int = 0):
"""
strickland 1993 said 0.2, but 0.145 gives better match to peak flux at 2500 = E0
"""
Bh = np.empty_like(E0)
for iE0 in np.arange(E0.size):
Bh[i... | [
"def",
"hitail",
"(",
"E",
":",
"np",
".",
"ndarray",
",",
"diffnumflux",
":",
"np",
".",
"ndarray",
",",
"isimE0",
":",
"np",
".",
"ndarray",
",",
"E0",
":",
"np",
".",
"ndarray",
",",
"Bhf",
":",
"np",
".",
"ndarray",
",",
"bh",
":",
"float",
... | 40.357143 | 17.642857 |
def taylor(f, n=2, **kwargs):
"""
Taylor/Mclaurin polynomial aproximation for the given function.
The ``n`` (default 2) is the amount of aproximation terms for ``f``. Other
arguments are keyword-only and will be passed to the ``f.series`` method.
"""
return sum(Stream(f.series(n=None, **kwargs)).limit(n)) | [
"def",
"taylor",
"(",
"f",
",",
"n",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"sum",
"(",
"Stream",
"(",
"f",
".",
"series",
"(",
"n",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
")",
".",
"limit",
"(",
"n",
")",
")"
] | 44.571429 | 17.714286 |
def _get_result(self, idx, timeout=None):
"""Called by the CollectorIterator object to retrieve the
result's values one after another, in the order the results have
become available.
\param idx The index of the result we want, wrt collector's order
\param timeout integer telling ... | [
"def",
"_get_result",
"(",
"self",
",",
"idx",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_cond",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"idx",
">=",
"self",
".",
"_expected",
":",
"raise",
"IndexError",
"elif",
"idx",
"<",
"len",
"(... | 40.592593 | 13.925926 |
def calculate_v(nfs):
"""Calculates V(n+1/n) values. Useful for establishing the quality of
your normalization regime. See Vandesompele 2002 for advice on
interpretation.
:param DataFrame nfs: A matrix of all normalization factors, produced by
`calculate_all_nfs`.
:return: a Series of values... | [
"def",
"calculate_v",
"(",
"nfs",
")",
":",
"v",
"=",
"[",
"]",
"if",
"(",
"nfs",
".",
"columns",
"!=",
"range",
"(",
"1",
",",
"nfs",
".",
"columns",
"[",
"-",
"1",
"]",
"+",
"1",
")",
")",
".",
"any",
"(",
")",
":",
"raise",
"ValueError",
... | 40.666667 | 18.4 |
def list_tables(self,includePrivate=None,namespace=None,atype=None,verbose=None):
"""
Returns a list of the table SUIDs associated with the passed network parameter.
:param includePrivate (string, optional): A boolean value determining wheth
er to return private as well as public ta... | [
"def",
"list_tables",
"(",
"self",
",",
"includePrivate",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"atype",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"PARAMS",
"=",
"set_param",
"(",
"[",
"'includePrivate'",
",",
"'namespace'",
",",
"'t... | 57.3125 | 28.0625 |
def get_objective_bank_record_types(self):
"""Gets the objective bank types available in Handcar.
arg: None
return: (osid.type.TypeList) - list of objective bank types
raise: NotFound - objectiveBankTypes is not found
raise: OperationFailed - unable to complete request
... | [
"def",
"get_objective_bank_record_types",
"(",
"self",
")",
":",
"try",
":",
"url_path",
"=",
"construct_url",
"(",
"'objective_bank_types'",
")",
"objective_bank_types",
"=",
"typeObjects",
".",
"TypeList",
"(",
"self",
".",
"_get_request",
"(",
"url_path",
")",
... | 42.0625 | 18.875 |
def get_keys_charset(keys, bid):
""" Use set of keys as selector for character superset
Note this isn't optimal, its probabilistic on the keyset char population.
"""
# use the keys found to sample possible chars
chars = set()
for k in keys:
chars.update(k[:4])
remainder = chars
... | [
"def",
"get_keys_charset",
"(",
"keys",
",",
"bid",
")",
":",
"# use the keys found to sample possible chars",
"chars",
"=",
"set",
"(",
")",
"for",
"k",
"in",
"keys",
":",
"chars",
".",
"update",
"(",
"k",
"[",
":",
"4",
"]",
")",
"remainder",
"=",
"cha... | 27.631579 | 18.131579 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.