text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def read_text_from_conll_file( file_name, layer_name=LAYER_CONLL, **kwargs ):
''' Reads the CONLL format syntactic analysis from given file, and returns as
a Text object.
The Text object has been tokenized for paragraphs, sentences, words, and it
contains syntactic analyses aligne... | [
"def",
"read_text_from_conll_file",
"(",
"file_name",
",",
"layer_name",
"=",
"LAYER_CONLL",
",",
"*",
"*",
"kwargs",
")",
":",
"# 1) Load conll analysed text from file",
"conll_lines",
"=",
"[",
"]",
"in_f",
"=",
"codecs",
".",
"open",
"(",
"file_name",
",",
"m... | 40.012658 | 20.924051 |
def create_groups(orientations, *groups, **kwargs):
"""
Create groups of an orientation measurement dataset
"""
grouped = []
# Copy all datasets to be safe (this could be bad for
# memory usage, so can be disabled).
if kwargs.pop('copy', True):
orientations = [copy(o) for o in orient... | [
"def",
"create_groups",
"(",
"orientations",
",",
"*",
"groups",
",",
"*",
"*",
"kwargs",
")",
":",
"grouped",
"=",
"[",
"]",
"# Copy all datasets to be safe (this could be bad for",
"# memory usage, so can be disabled).",
"if",
"kwargs",
".",
"pop",
"(",
"'copy'",
... | 31.189189 | 16.594595 |
def _SkipFieldContents(tokenizer):
"""Skips over contents (value or message) of a field.
Args:
tokenizer: A tokenizer to parse the field name and values.
"""
# Try to guess the type of this field.
# If this field is not a message, there should be a ":" between the
# field name and the field value and a... | [
"def",
"_SkipFieldContents",
"(",
"tokenizer",
")",
":",
"# Try to guess the type of this field.",
"# If this field is not a message, there should be a \":\" between the",
"# field name and the field value and also the field value should not",
"# start with \"{\" or \"<\" which indicates the begin... | 41.647059 | 18.117647 |
def bulk_modify(self, *filters_or_records, **kwargs):
"""Shortcut to bulk modify records
.. versionadded:: 2.17.0
Args:
*filters_or_records (tuple) or (Record): Either a list of Records, or a list of filters.
Keyword Args:
values (dict): Diction... | [
"def",
"bulk_modify",
"(",
"self",
",",
"*",
"filters_or_records",
",",
"*",
"*",
"kwargs",
")",
":",
"values",
"=",
"kwargs",
".",
"pop",
"(",
"'values'",
",",
"None",
")",
"if",
"kwargs",
":",
"raise",
"ValueError",
"(",
"'Unexpected arguments: {}'",
"."... | 36.910714 | 24.4375 |
def create_parser(self):
"""Create the CLI parser."""
parser = argparse.ArgumentParser(
description=PROGRAM_DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent(PROGRAM_EPILOG))
parser.add_argument(
'filename',... | [
"def",
"create_parser",
"(",
"self",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"PROGRAM_DESCRIPTION",
",",
"formatter_class",
"=",
"argparse",
".",
"RawDescriptionHelpFormatter",
",",
"epilog",
"=",
"textwrap",
".",
"dede... | 40.606897 | 19.668966 |
def get_pseudo_salt(length, *args):
"""
generate a pseudo salt (used, if user is wrong)
"""
temp = "".join([arg for arg in args])
return hash_hexdigest(temp)[:length] | [
"def",
"get_pseudo_salt",
"(",
"length",
",",
"*",
"args",
")",
":",
"temp",
"=",
"\"\"",
".",
"join",
"(",
"[",
"arg",
"for",
"arg",
"in",
"args",
"]",
")",
"return",
"hash_hexdigest",
"(",
"temp",
")",
"[",
":",
"length",
"]"
] | 30.166667 | 2.833333 |
def _peer_bfd_tx(self, **kwargs):
"""Return the BFD minimum transmit interval XML.
You should not use this method.
You probably want `BGP.bfd`.
Args:
peer_ip (str): Peer IPv4 address for BFD setting.
min_tx (str): BFD transmit interval in milliseconds (300, 500,... | [
"def",
"_peer_bfd_tx",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"method_name",
"=",
"'rbridge_id_router_router_bgp_router_bgp_attributes_'",
"'neighbor_neighbor_ips_neighbor_addr_bfd_interval_min_tx'",
"bfd_tx",
"=",
"getattr",
"(",
"self",
".",
"_rbridge",
",",
"m... | 34.56 | 21 |
def put(self, source, rel_path, metadata=None):
'''Copy a file to the repository
Args:
source: Absolute path to the source file, or a file-like object
rel_path: path relative to the root of the repository
'''
# This case should probably be deprecated.
i... | [
"def",
"put",
"(",
"self",
",",
"source",
",",
"rel_path",
",",
"metadata",
"=",
"None",
")",
":",
"# This case should probably be deprecated.",
"if",
"not",
"isinstance",
"(",
"rel_path",
",",
"basestring",
")",
":",
"rel_path",
"=",
"rel_path",
".",
"cache_k... | 28.769231 | 21 |
def reorder_image(dst_order, src_arr, src_order):
"""Reorder src_arr, with order of color planes in src_order, as
dst_order.
"""
depth = src_arr.shape[2]
if depth != len(src_order):
raise ValueError("src_order (%s) does not match array depth (%d)" % (
src_order, depth))
band... | [
"def",
"reorder_image",
"(",
"dst_order",
",",
"src_arr",
",",
"src_order",
")",
":",
"depth",
"=",
"src_arr",
".",
"shape",
"[",
"2",
"]",
"if",
"depth",
"!=",
"len",
"(",
"src_order",
")",
":",
"raise",
"ValueError",
"(",
"\"src_order (%s) does not match a... | 37.896552 | 18.655172 |
def draw_lines():
"""
Draws a line between a set of random values
"""
r = numpy.random.randn(200)
fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.plot(r)
ax.grid(True)
pyplot.savefig(lines_filename) | [
"def",
"draw_lines",
"(",
")",
":",
"r",
"=",
"numpy",
".",
"random",
".",
"randn",
"(",
"200",
")",
"fig",
"=",
"pyplot",
".",
"figure",
"(",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"111",
")",
"ax",
".",
"plot",
"(",
"r",
")",
"ax",
... | 19 | 16.666667 |
def decrypt_filedata(data, keys):
'''Decrypts a file from Send'''
# The last 16 bytes / 128 bits of data is the GCM tag
# https://www.w3.org/TR/WebCryptoAPI/#aes-gcm-operations :-
# 7. Let ciphertext be equal to C | T, where '|' denotes concatenation.
data.seek(-16, 2)
tag = data.read()
# n... | [
"def",
"decrypt_filedata",
"(",
"data",
",",
"keys",
")",
":",
"# The last 16 bytes / 128 bits of data is the GCM tag",
"# https://www.w3.org/TR/WebCryptoAPI/#aes-gcm-operations :-",
"# 7. Let ciphertext be equal to C | T, where '|' denotes concatenation.",
"data",
".",
"seek",
"(",
"-... | 30.6 | 23.8 |
def decode(cls, phrase):
"""Calculate hexadecimal representation of the phrase.
"""
phrase = phrase.split(" ")
out = ""
for i in range(len(phrase) // 3):
word1, word2, word3 = phrase[3*i:3*i+3]
w1 = cls.word_list.index(word1)
w2 = cls.word_list... | [
"def",
"decode",
"(",
"cls",
",",
"phrase",
")",
":",
"phrase",
"=",
"phrase",
".",
"split",
"(",
"\" \"",
")",
"out",
"=",
"\"\"",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"phrase",
")",
"//",
"3",
")",
":",
"word1",
",",
"word2",
",",
"wor... | 40.692308 | 11.692308 |
def _setup_user_dir(self):
"""Returns user config dir, create it when it doesn't exist."""
user_dir = self._get_user_dir_path()
rules_dir = user_dir.joinpath('rules')
if not rules_dir.is_dir():
rules_dir.mkdir(parents=True)
self.user_dir = user_dir | [
"def",
"_setup_user_dir",
"(",
"self",
")",
":",
"user_dir",
"=",
"self",
".",
"_get_user_dir_path",
"(",
")",
"rules_dir",
"=",
"user_dir",
".",
"joinpath",
"(",
"'rules'",
")",
"if",
"not",
"rules_dir",
".",
"is_dir",
"(",
")",
":",
"rules_dir",
".",
"... | 36.75 | 9.875 |
def write(self, data):
'''
Write some bytes to the transport.
'''
# MUST use a lock here else gevent could raise an exception if 2
# greenlets try to write at the same time. I was hoping that
# sendall() would do that blocking for me, but I guess not. May
# requir... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"# MUST use a lock here else gevent could raise an exception if 2",
"# greenlets try to write at the same time. I was hoping that",
"# sendall() would do that blocking for me, but I guess not. May",
"# require an eventsocket-like buffer to sp... | 40.692308 | 21.615385 |
def _parse_packet(rawdata):
""" Returns a tupel (opcode, minusconf-data). opcode is None if this isn't a -conf packet."""
if (len(rawdata) < len(_MAGIC) + 1) or (_MAGIC != rawdata[:len(_MAGIC)]):
# Wrong protocol
return (None, None)
opcode = rawdata[len(_MAGIC):len(_MAGIC)+1]
payload =... | [
"def",
"_parse_packet",
"(",
"rawdata",
")",
":",
"if",
"(",
"len",
"(",
"rawdata",
")",
"<",
"len",
"(",
"_MAGIC",
")",
"+",
"1",
")",
"or",
"(",
"_MAGIC",
"!=",
"rawdata",
"[",
":",
"len",
"(",
"_MAGIC",
")",
"]",
")",
":",
"# Wrong protocol",
... | 33.090909 | 20.090909 |
def comment (self, s, **args):
"""Write CSV comment."""
self.writeln(s=u"# %s" % s, **args) | [
"def",
"comment",
"(",
"self",
",",
"s",
",",
"*",
"*",
"args",
")",
":",
"self",
".",
"writeln",
"(",
"s",
"=",
"u\"# %s\"",
"%",
"s",
",",
"*",
"*",
"args",
")"
] | 35 | 4.333333 |
def alignment_to_partials(alignment, missing_data=None):
""" Generate a partials dictionary from a treeCl.Alignment """
partials_dict = {}
for (name, sequence) in alignment.get_sequences():
datatype = 'dna' if alignment.is_dna() else 'protein'
partials_dict[name] = seq_to_partials(sequence, ... | [
"def",
"alignment_to_partials",
"(",
"alignment",
",",
"missing_data",
"=",
"None",
")",
":",
"partials_dict",
"=",
"{",
"}",
"for",
"(",
"name",
",",
"sequence",
")",
"in",
"alignment",
".",
"get_sequences",
"(",
")",
":",
"datatype",
"=",
"'dna'",
"if",
... | 42.307692 | 16.153846 |
def __substitute_replace_pairs(self):
"""
Substitutes all replace pairs in the source of the stored routine.
"""
self._set_magic_constants()
routine_source = []
i = 0
for line in self._routine_source_code_lines:
self._replace['__LINE__'] = "'%d'" % (i... | [
"def",
"__substitute_replace_pairs",
"(",
"self",
")",
":",
"self",
".",
"_set_magic_constants",
"(",
")",
"routine_source",
"=",
"[",
"]",
"i",
"=",
"0",
"for",
"line",
"in",
"self",
".",
"_routine_source_code_lines",
":",
"self",
".",
"_replace",
"[",
"'__... | 35.055556 | 16.944444 |
def _name_with_flags(self, include_restricted, title=None):
"""Generate the name with flags."""
name = "Special: " if self.special else ""
name += self.name
if title:
name += " - {}".format(title)
if include_restricted and self.restricted:
name += " (R)"
... | [
"def",
"_name_with_flags",
"(",
"self",
",",
"include_restricted",
",",
"title",
"=",
"None",
")",
":",
"name",
"=",
"\"Special: \"",
"if",
"self",
".",
"special",
"else",
"\"\"",
"name",
"+=",
"self",
".",
"name",
"if",
"title",
":",
"name",
"+=",
"\" -... | 40.846154 | 11.846154 |
def classify_intersection(intersection, edge_nodes1, edge_nodes2):
r"""Determine which curve is on the "inside of the intersection".
.. note::
This is a helper used only by :meth:`.Surface.intersect`.
This is intended to be a helper for forming a :class:`.CurvedPolygon`
from the edge intersect... | [
"def",
"classify_intersection",
"(",
"intersection",
",",
"edge_nodes1",
",",
"edge_nodes2",
")",
":",
"if",
"intersection",
".",
"s",
"==",
"1.0",
"or",
"intersection",
".",
"t",
"==",
"1.0",
":",
"raise",
"ValueError",
"(",
"\"Intersection occurs at the end of a... | 34.821803 | 19.098532 |
def _create_clause_based_dep_links( orig_text, layer=LAYER_CONLL ):
''' Rewrites dependency links in the text from sentence-based linking to clause-
based linking:
*) words which have their parent outside-the-clause will become root
nodes (will obtain link value -1), and
... | [
"def",
"_create_clause_based_dep_links",
"(",
"orig_text",
",",
"layer",
"=",
"LAYER_CONLL",
")",
":",
"sent_start_index",
"=",
"0",
"for",
"sent_text",
"in",
"orig_text",
".",
"split_by",
"(",
"SENTENCES",
")",
":",
"# 1) Create a mapping: from sentence-based dependenc... | 48.608696 | 19.478261 |
def element(self):
"""
:return: the :class:`Element` that contains these attributes.
"""
return self.adapter.wrap_node(
self.impl_element, self.adapter.impl_document, self.adapter) | [
"def",
"element",
"(",
"self",
")",
":",
"return",
"self",
".",
"adapter",
".",
"wrap_node",
"(",
"self",
".",
"impl_element",
",",
"self",
".",
"adapter",
".",
"impl_document",
",",
"self",
".",
"adapter",
")"
] | 36.5 | 14.166667 |
def list_data_type(type_list):
"""This function takes a list of format specifiers and returns a list of data
types represented by the format specifiers."""
data_type = []
for item in type_list:
match = re.match(r"(\d+)(.+)", item)
if not match:
reps = 1
if item[0]... | [
"def",
"list_data_type",
"(",
"type_list",
")",
":",
"data_type",
"=",
"[",
"]",
"for",
"item",
"in",
"type_list",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r\"(\\d+)(.+)\"",
",",
"item",
")",
"if",
"not",
"match",
":",
"reps",
"=",
"1",
"if",
"it... | 34.785714 | 9.178571 |
def build_result(data):
"""Create a dictionary with the contents of result.json"""
more = {}
for key, value in data.items():
if key != 'elements':
newnode = value
else:
newnode = {}
for el in value:
nkey, nvalue = process_node(el)
... | [
"def",
"build_result",
"(",
"data",
")",
":",
"more",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"key",
"!=",
"'elements'",
":",
"newnode",
"=",
"value",
"else",
":",
"newnode",
"=",
"{",
"}",
"for... | 25.466667 | 16.933333 |
def minion_mods(
opts,
context=None,
utils=None,
whitelist=None,
initial_load=False,
loaded_base_name=None,
notify=False,
static_modules=None,
proxy=None):
'''
Load execution modules
Returns a dictionary of execution modules appropriat... | [
"def",
"minion_mods",
"(",
"opts",
",",
"context",
"=",
"None",
",",
"utils",
"=",
"None",
",",
"whitelist",
"=",
"None",
",",
"initial_load",
"=",
"False",
",",
"loaded_base_name",
"=",
"None",
",",
"notify",
"=",
"False",
",",
"static_modules",
"=",
"N... | 35.698795 | 22.277108 |
def start(self):
'''
Start the actual master.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
'''
super(SaltAPI, self).start()
if check_user(self.config['user']):
... | [
"def",
"start",
"(",
"self",
")",
":",
"super",
"(",
"SaltAPI",
",",
"self",
")",
".",
"start",
"(",
")",
"if",
"check_user",
"(",
"self",
".",
"config",
"[",
"'user'",
"]",
")",
":",
"log",
".",
"info",
"(",
"'The salt-api is starting up'",
")",
"se... | 27.5 | 20.071429 |
def sign(self, cert, pkey, digest_type=None, data=None, flags=Flags.BINARY):
"""
Adds another signer to already signed message
@param cert - signer's certificate
@param pkey - signer's private key
@param digest_type - message digest to use as DigestType object
... | [
"def",
"sign",
"(",
"self",
",",
"cert",
",",
"pkey",
",",
"digest_type",
"=",
"None",
",",
"data",
"=",
"None",
",",
"flags",
"=",
"Flags",
".",
"BINARY",
")",
":",
"if",
"not",
"pkey",
".",
"cansign",
":",
"raise",
"ValueError",
"(",
"\"Specified k... | 47 | 15.888889 |
def deprecated_for(replace_message):
"""
Decorate a deprecated function, with info about what to use instead, like:
@deprecated_for("toBytes()")
def toAscii(arg):
...
"""
def decorator(to_wrap):
@functools.wraps(to_wrap)
def wrapper(*args, **kwargs):
warnings... | [
"def",
"deprecated_for",
"(",
"replace_message",
")",
":",
"def",
"decorator",
"(",
"to_wrap",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"to_wrap",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn"... | 31.166667 | 15.5 |
def setup(self, app):
'''
Setup properties from parent app on the command
'''
self.logger = app.logger
self.shell.logger = self.logger
if not self.command_name:
raise EmptyCommandNameException()
self.app = app
self.arguments_declaration = sel... | [
"def",
"setup",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"logger",
"=",
"app",
".",
"logger",
"self",
".",
"shell",
".",
"logger",
"=",
"self",
".",
"logger",
"if",
"not",
"self",
".",
"command_name",
":",
"raise",
"EmptyCommandNameException",
"... | 26.222222 | 17.333333 |
def solution(events, slots, objective_function=None, solver=None, **kwargs):
"""Compute a schedule in solution form
Parameters
----------
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` instances
solver : pulp.s... | [
"def",
"solution",
"(",
"events",
",",
"slots",
",",
"objective_function",
"=",
"None",
",",
"solver",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"shape",
"=",
"Shape",
"(",
"len",
"(",
"events",
")",
",",
"len",
"(",
"slots",
")",
")",
"probl... | 28.962963 | 18.425926 |
def strong(node):
"""
A bolded section
"""
o = nodes.strong()
for n in MarkDown(node):
o += n
return o | [
"def",
"strong",
"(",
"node",
")",
":",
"o",
"=",
"nodes",
".",
"strong",
"(",
")",
"for",
"n",
"in",
"MarkDown",
"(",
"node",
")",
":",
"o",
"+=",
"n",
"return",
"o"
] | 15.875 | 15.875 |
def explore(args):
"""Create mapping of sequences of two clusters
"""
logger.info("reading sequeces")
data = load_data(args.json)
logger.info("get sequences from json")
#get_sequences_from_cluster()
c1, c2 = args.names.split(",")
seqs, names = get_sequences_from_cluster(c1, c2, data[0])
... | [
"def",
"explore",
"(",
"args",
")",
":",
"logger",
".",
"info",
"(",
"\"reading sequeces\"",
")",
"data",
"=",
"load_data",
"(",
"args",
".",
"json",
")",
"logger",
".",
"info",
"(",
"\"get sequences from json\"",
")",
"#get_sequences_from_cluster()",
"c1",
",... | 37.777778 | 11.833333 |
def get_rng(obj=None):
"""
Get a good RNG seeded with time, pid and the object.
Args:
obj: some object to use to generate random seed.
Returns:
np.random.RandomState: the RNG.
"""
seed = (id(obj) + os.getpid() +
int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 42949... | [
"def",
"get_rng",
"(",
"obj",
"=",
"None",
")",
":",
"seed",
"=",
"(",
"id",
"(",
"obj",
")",
"+",
"os",
".",
"getpid",
"(",
")",
"+",
"int",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y%m%d%H%M%S%f\"",
")",
")",
")",
"%",... | 29 | 15.428571 |
def chunked_join(iterable, int1, int2, str1, str2, func):
"""Chunk and join."""
chunks = list(chunked(iterable, int1))
logging.debug(chunks)
groups = [list(chunked(chunk, int2)) for chunk in chunks]
logging.debug(groups)
return str1.join([
str2.join([func(''.join(chunk)) for chunk in chu... | [
"def",
"chunked_join",
"(",
"iterable",
",",
"int1",
",",
"int2",
",",
"str1",
",",
"str2",
",",
"func",
")",
":",
"chunks",
"=",
"list",
"(",
"chunked",
"(",
"iterable",
",",
"int1",
")",
")",
"logging",
".",
"debug",
"(",
"chunks",
")",
"groups",
... | 35.2 | 15.5 |
def get_files(path, ext=[], include=True):
"""遍历提供的文件夹的所有子文件夹,饭后生成器对象。
:param str path: 待处理的文件夹。
:param list ext: 扩展名列表。
:param bool include: 若值为 True,代表 ext 提供的是包含列表;
否则是排除列表。
:returns: 一个生成器对象。
"""
has_ext = len(ext)>0
for p, d, fs in os.walk(path):
... | [
"def",
"get_files",
"(",
"path",
",",
"ext",
"=",
"[",
"]",
",",
"include",
"=",
"True",
")",
":",
"has_ext",
"=",
"len",
"(",
"ext",
")",
">",
"0",
"for",
"p",
",",
"d",
",",
"fs",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"f"... | 29.416667 | 11.083333 |
def iter_logical_lines(self, blob):
"""Returns an iterator of (start_line, stop_line, indent) for logical lines """
indent_stack = []
contents = []
line_number_start = None
for token in self.iter_tokens(blob):
token_type, token_text, token_start = token[0:3]
if token_type == tokenize.IND... | [
"def",
"iter_logical_lines",
"(",
"self",
",",
"blob",
")",
":",
"indent_stack",
"=",
"[",
"]",
"contents",
"=",
"[",
"]",
"line_number_start",
"=",
"None",
"for",
"token",
"in",
"self",
".",
"iter_tokens",
"(",
"blob",
")",
":",
"token_type",
",",
"toke... | 38.92 | 10.32 |
def payload_body(req):
"""
A generator that will include the sha256 signature of the request's body
in the JWT payload. This is only done if the request could have a body:
if the method is POST or PUT.
>>> auth = JWTAuth('secret')
>>> auth.add_field('body', payload_body)
"""
to_hash = ... | [
"def",
"payload_body",
"(",
"req",
")",
":",
"to_hash",
"=",
"req",
".",
"body",
"if",
"type",
"(",
"req",
".",
"body",
")",
"is",
"bytes",
"else",
"req",
".",
"body",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"req",
".",
"method",
"in",
"(",
"'P... | 33.625 | 19.125 |
def unparse(self, indent_step = 4, max_linelen = 72) :
"returns an XML string description of this Introspection tree."
out = io.StringIO()
def to_string(obj, indent) :
tag_name = obj.tag_name
attrs = []
for attrname in obj.tag_attrs :
attr = ... | [
"def",
"unparse",
"(",
"self",
",",
"indent_step",
"=",
"4",
",",
"max_linelen",
"=",
"72",
")",
":",
"out",
"=",
"io",
".",
"StringIO",
"(",
")",
"def",
"to_string",
"(",
"obj",
",",
"indent",
")",
":",
"tag_name",
"=",
"obj",
".",
"tag_name",
"at... | 34.478723 | 15.946809 |
def collapse_all(self):
"""collapse all messages in thread"""
for MT in self.messagetrees():
MT.collapse(MT.root)
self.focus_selected_message() | [
"def",
"collapse_all",
"(",
"self",
")",
":",
"for",
"MT",
"in",
"self",
".",
"messagetrees",
"(",
")",
":",
"MT",
".",
"collapse",
"(",
"MT",
".",
"root",
")",
"self",
".",
"focus_selected_message",
"(",
")"
] | 35 | 6 |
def from_ini(cls, folder, ini_file='fpp.ini', ichrone='mist', recalc=False,
refit_trap=False, **kwargs):
"""
To enable simple usage, initializes a FPPCalculation from a .ini file
By default, a file called ``fpp.ini`` will be looked for in the
current folder. Also presen... | [
"def",
"from_ini",
"(",
"cls",
",",
"folder",
",",
"ini_file",
"=",
"'fpp.ini'",
",",
"ichrone",
"=",
"'mist'",
",",
"recalc",
"=",
"False",
",",
"refit_trap",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Check if all starmodel fits are done.",
"# If ... | 38.691057 | 22.186992 |
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 get_stacked_rnn(config: RNNConfig, prefix: str,
parallel_inputs: bool = False,
layers: Optional[Iterable[int]] = None) -> mx.rnn.SequentialRNNCell:
"""
Returns (stacked) RNN cell given parameters.
:param config: rnn configuration.
:param prefix: Symbol prefix... | [
"def",
"get_stacked_rnn",
"(",
"config",
":",
"RNNConfig",
",",
"prefix",
":",
"str",
",",
"parallel_inputs",
":",
"bool",
"=",
"False",
",",
"layers",
":",
"Optional",
"[",
"Iterable",
"[",
"int",
"]",
"]",
"=",
"None",
")",
"->",
"mx",
".",
"rnn",
... | 50.913793 | 29.258621 |
def _derX(self,x,y):
'''
Returns the first derivative of the function with respect to X at each
value in (x,y). Only called internally by HARKinterpolator2D._derX.
'''
m = len(x)
temp = np.zeros((m,self.funcCount))
for j in range(self.funcCount):
temp... | [
"def",
"_derX",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"m",
"=",
"len",
"(",
"x",
")",
"temp",
"=",
"np",
".",
"zeros",
"(",
"(",
"m",
",",
"self",
".",
"funcCount",
")",
")",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"funcCount",
")... | 36.625 | 16.5 |
def run(self, args):
"""Flashes the device connected to the J-Link.
Args:
self (FlashCommand): the ``FlashCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
kwargs = {}
kwargs['path'] = args.... | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"kwargs",
"=",
"{",
"}",
"kwargs",
"[",
"'path'",
"]",
"=",
"args",
".",
"file",
"[",
"0",
"]",
"kwargs",
"[",
"'addr'",
"]",
"=",
"args",
".",
"addr",
"kwargs",
"[",
"'on_progress'",
"]",
"=",
... | 29.944444 | 18.111111 |
def create_app(settings):
"""Create a new Flask application"""
app = Flask(__name__)
# Import settings from file
for name in dir(settings):
value = getattr(settings, name)
if not (name.startswith('_') or isinstance(value, ModuleType)
or isinstance(value, FunctionType)):
... | [
"def",
"create_app",
"(",
"settings",
")",
":",
"app",
"=",
"Flask",
"(",
"__name__",
")",
"# Import settings from file",
"for",
"name",
"in",
"dir",
"(",
"settings",
")",
":",
"value",
"=",
"getattr",
"(",
"settings",
",",
"name",
")",
"if",
"not",
"(",... | 27.875 | 17.725 |
def start(self, threaded=True):
"""Start the data feed.
:param threaded: If True, run in a separate thread.
"""
self.running = True
if threaded:
self._thread = Thread(target=self._run)
self._thread.start()
else:
self._run() | [
"def",
"start",
"(",
"self",
",",
"threaded",
"=",
"True",
")",
":",
"self",
".",
"running",
"=",
"True",
"if",
"threaded",
":",
"self",
".",
"_thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_run",
")",
"self",
".",
"_thread",
".",
"star... | 27.090909 | 14.909091 |
def with_color_stripped(f):
"""
A function decorator for applying to `len` or imitators thereof that strips
ANSI color sequences from a string before passing it on. If any color
sequences are not followed by a reset sequence, an `UnterminatedColorError`
is raised.
"""
@wraps(f)
def colo... | [
"def",
"with_color_stripped",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"colored_len",
"(",
"s",
")",
":",
"s2",
"=",
"re",
".",
"sub",
"(",
"COLOR_BEGIN_RGX",
"+",
"'(.*?)'",
"+",
"COLOR_END_RGX",
",",
"lambda",
"m",
":",
"re",
".",
... | 35.333333 | 18.777778 |
def check_longitude(self, ds):
'''
Check variable(s) that define longitude and are defined correctly according to CF.
CF §4.2 Variables representing longitude must always explicitly include
the units attribute; there is no default value. The recommended unit
of longitude is deg... | [
"def",
"check_longitude",
"(",
"self",
",",
"ds",
")",
":",
"# TODO we already have a check_latitude... I'm sure we can make DRYer",
"ret_val",
"=",
"[",
"]",
"allowed_lon_units",
"=",
"[",
"'degrees_east'",
",",
"'degree_east'",
",",
"'degree_e'",
",",
"'degrees_e'",
"... | 49.1875 | 26.625 |
def get_mac_address_table_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_mac_address_table = ET.Element("get_mac_address_table")
config = get_mac_address_table
output = ET.SubElement(get_mac_address_table, "output")
h... | [
"def",
"get_mac_address_table_output_has_more",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_mac_address_table",
"=",
"ET",
".",
"Element",
"(",
"\"get_mac_address_table\"",
")",
"config",
"=",... | 40.833333 | 13.083333 |
def search_extension(self, limit=100, offset=0, **kw):
"""Search the list of available extensions."""
response = self.request(E.searchExtensionRequest(
E.limit(limit),
E.offset(offset),
E.withDescription(int(kw.get('with_description', 0))),
E.withPrice(in... | [
"def",
"search_extension",
"(",
"self",
",",
"limit",
"=",
"100",
",",
"offset",
"=",
"0",
",",
"*",
"*",
"kw",
")",
":",
"response",
"=",
"self",
".",
"request",
"(",
"E",
".",
"searchExtensionRequest",
"(",
"E",
".",
"limit",
"(",
"limit",
")",
"... | 41.818182 | 17.636364 |
def message_to_dict(msg):
"""Convert an email message into a dictionary.
This function transforms an `email.message.Message` object
into a dictionary. Headers are stored as key:value pairs
while the body of the message is stored inside `body` key.
Body may have two other keys inside, 'plain', for p... | [
"def",
"message_to_dict",
"(",
"msg",
")",
":",
"def",
"parse_headers",
"(",
"msg",
")",
":",
"headers",
"=",
"{",
"}",
"for",
"header",
",",
"value",
"in",
"msg",
".",
"items",
"(",
")",
":",
"hv",
"=",
"[",
"]",
"for",
"text",
",",
"charset",
"... | 34.247059 | 21.129412 |
def Start(self):
"""Issue a request to list the directory."""
self.CallClient(
server_stubs.PlistQuery,
request=self.args.request,
next_state="Receive") | [
"def",
"Start",
"(",
"self",
")",
":",
"self",
".",
"CallClient",
"(",
"server_stubs",
".",
"PlistQuery",
",",
"request",
"=",
"self",
".",
"args",
".",
"request",
",",
"next_state",
"=",
"\"Receive\"",
")"
] | 29.833333 | 11.5 |
def on_key_press(self, symbol, modifiers):
"""
Pyglet specific key press callback.
Forwards and translates the events to the example
"""
self.example.key_event(symbol, self.keys.ACTION_PRESS) | [
"def",
"on_key_press",
"(",
"self",
",",
"symbol",
",",
"modifiers",
")",
":",
"self",
".",
"example",
".",
"key_event",
"(",
"symbol",
",",
"self",
".",
"keys",
".",
"ACTION_PRESS",
")"
] | 38.5 | 7.833333 |
def are_diphtong(tokenA, tokenB):
"""
Check (naively) whether the two tokens can form a diphtong. This would be a
sequence of vowels of which no more than one is syllabic. Vowel sequences
connected with a tie bar would already be handled in tokenise_word, so are
not checked for here.
Users who want more sophisti... | [
"def",
"are_diphtong",
"(",
"tokenA",
",",
"tokenB",
")",
":",
"is_short",
"=",
"lambda",
"token",
":",
"'◌̯'[1]",
" ",
"i",
"n",
"to",
"en",
"subtokens",
"=",
"[",
"]",
"for",
"char",
"in",
"tokenA",
"+",
"tokenB",
":",
"if",
"ipa",
".",
"is_vowel",... | 26.15625 | 23.09375 |
def find_modules(import_path, include_packages=False, recursive=False):
"""Finds all the modules below a package. This can be useful to
automatically import all views / controllers so that their metaclasses /
function decorators have a chance to register themselves on the
application.
Packages are... | [
"def",
"find_modules",
"(",
"import_path",
",",
"include_packages",
"=",
"False",
",",
"recursive",
"=",
"False",
")",
":",
"module",
"=",
"import_string",
"(",
"import_path",
")",
"path",
"=",
"getattr",
"(",
"module",
",",
"\"__path__\"",
",",
"None",
")",... | 43.266667 | 20.766667 |
def f_preset_parameter(self, param_name, *args, **kwargs):
"""Presets parameter value before a parameter is added.
Can be called before parameters are added to the Trajectory in order to change the
values that are stored into the parameter on creation.
After creation of a parameter, th... | [
"def",
"f_preset_parameter",
"(",
"self",
",",
"param_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"param_name",
".",
"startswith",
"(",
"'parameters.'",
")",
":",
"param_name",
"=",
"'parameters.'",
"+",
"param_name",
"self",
"... | 32.894737 | 28.842105 |
def clone(self, **kwargs):
'''
Clone this context, and return the ChildContextDict
'''
child = ChildContextDict(parent=self, threadsafe=self._threadsafe, overrides=kwargs)
return child | [
"def",
"clone",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"child",
"=",
"ChildContextDict",
"(",
"parent",
"=",
"self",
",",
"threadsafe",
"=",
"self",
".",
"_threadsafe",
",",
"overrides",
"=",
"kwargs",
")",
"return",
"child"
] | 36.5 | 27.166667 |
def add_docs(self, docs):
"""docs is a list of fields that are a dictionary of name:value for a record."""
return self.query(
'solr',
'<add>{}</add>'.format(
''.join([self._format_add(fields) for fields in docs])
),
do_post=True,
) | [
"def",
"add_docs",
"(",
"self",
",",
"docs",
")",
":",
"return",
"self",
".",
"query",
"(",
"'solr'",
",",
"'<add>{}</add>'",
".",
"format",
"(",
"''",
".",
"join",
"(",
"[",
"self",
".",
"_format_add",
"(",
"fields",
")",
"for",
"fields",
"in",
"doc... | 34.555556 | 17.444444 |
def create_auto_scaling_group(AutoScalingGroupName=None, LaunchConfigurationName=None, InstanceId=None, MinSize=None, MaxSize=None, DesiredCapacity=None, DefaultCooldown=None, AvailabilityZones=None, LoadBalancerNames=None, TargetGroupARNs=None, HealthCheckType=None, HealthCheckGracePeriod=None, PlacementGroup=None, VP... | [
"def",
"create_auto_scaling_group",
"(",
"AutoScalingGroupName",
"=",
"None",
",",
"LaunchConfigurationName",
"=",
"None",
",",
"InstanceId",
"=",
"None",
",",
"MinSize",
"=",
"None",
",",
"MaxSize",
"=",
"None",
",",
"DesiredCapacity",
"=",
"None",
",",
"Defaul... | 48.980519 | 38.967532 |
def _mask_feature_data(feature_data, mask, mask_type):
""" Masks values of data feature with a given mask of given mask type. The masking is done by assigning
`numpy.nan` value.
:param feature_data: Data array which will be masked
:type feature_data: numpy.ndarray
:param mask: M... | [
"def",
"_mask_feature_data",
"(",
"feature_data",
",",
"mask",
",",
"mask_type",
")",
":",
"if",
"mask_type",
".",
"is_spatial",
"(",
")",
"and",
"feature_data",
".",
"shape",
"[",
"1",
":",
"3",
"]",
"!=",
"mask",
".",
"shape",
"[",
"-",
"3",
":",
"... | 42.315789 | 21.894737 |
def set_cognitive_process(self, grade_id):
"""Sets the cognitive process.
arg: grade_id (osid.id.Id): the new cognitive process
raise: InvalidArgument - ``grade_id`` is invalid
raise: NoAccess - ``grade_id`` cannot be modified
raise: NullArgument - ``grade_id`` is ``null``... | [
"def",
"set_cognitive_process",
"(",
"self",
",",
"grade_id",
")",
":",
"# Implemented from template for osid.resource.ResourceForm.set_avatar_template",
"if",
"self",
".",
"get_cognitive_process_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
":",
"raise",
"errors",
... | 45 | 17.5625 |
def _no_auto_update_getter(self):
""":class:`bool`. Boolean controlling whether the :meth:`start_update`
method is automatically called by the :meth:`update` method
Examples
--------
You can disable the automatic update via
>>> with data.no_auto_update:
... data.update(time=1)... | [
"def",
"_no_auto_update_getter",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'_no_auto_update'",
",",
"None",
")",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_no_auto_update",
"else",
":",
"self",
".",
"_no_auto_update",
"=",
"utils",
... | 31.608696 | 17.565217 |
def _get_all_volumes_paths(conn):
'''
Extract the path and backing stores path of all volumes.
:param conn: libvirt connection to use
'''
volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l]
return {vol.path(): [path.text for path in ElementTree.fro... | [
"def",
"_get_all_volumes_paths",
"(",
"conn",
")",
":",
"volumes",
"=",
"[",
"vol",
"for",
"l",
"in",
"[",
"obj",
".",
"listAllVolumes",
"(",
")",
"for",
"obj",
"in",
"conn",
".",
"listAllStoragePools",
"(",
")",
"]",
"for",
"vol",
"in",
"l",
"]",
"r... | 47.111111 | 32.222222 |
def command(self, func):
"""
Decorator to add a command function to the registry.
:param func: command function.
"""
command = Command(func)
self._commands[func.__name__] = command
return func | [
"def",
"command",
"(",
"self",
",",
"func",
")",
":",
"command",
"=",
"Command",
"(",
"func",
")",
"self",
".",
"_commands",
"[",
"func",
".",
"__name__",
"]",
"=",
"command",
"return",
"func"
] | 24.1 | 15.5 |
def recompute(self, quiet=False, **kwargs):
"""
Re-compute a previously computed model. You might want to do this if
the kernel parameters change and the kernel is labeled as ``dirty``.
:param quiet: (optional)
If ``True``, return false when the computation fails. Otherwise,... | [
"def",
"recompute",
"(",
"self",
",",
"quiet",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"computed",
":",
"if",
"not",
"(",
"hasattr",
"(",
"self",
",",
"\"_x\"",
")",
"and",
"hasattr",
"(",
"self",
",",
"\"_yerr2\"... | 41.318182 | 20.863636 |
def __intermediate_htmode(self, radio):
"""
only for mac80211 driver
"""
protocol = radio.pop('protocol')
channel_width = radio.pop('channel_width')
# allow overriding htmode
if 'htmode' in radio:
return radio['htmode']
if protocol == '802.11n'... | [
"def",
"__intermediate_htmode",
"(",
"self",
",",
"radio",
")",
":",
"protocol",
"=",
"radio",
".",
"pop",
"(",
"'protocol'",
")",
"channel_width",
"=",
"radio",
".",
"pop",
"(",
"'channel_width'",
")",
"# allow overriding htmode",
"if",
"'htmode'",
"in",
"rad... | 32.4 | 7.333333 |
def get_repos(self, since=github.GithubObject.NotSet):
"""
:calls: `GET /repositories <http://developer.github.com/v3/repos/#list-all-public-repositories>`_
:param since: integer
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
"""
... | [
"def",
"get_repos",
"(",
"self",
",",
"since",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
")",
":",
"assert",
"since",
"is",
"github",
".",
"GithubObject",
".",
"NotSet",
"or",
"isinstance",
"(",
"since",
",",
"(",
"int",
",",
"long",
")",
")",... | 44.3125 | 18.9375 |
def _series_col_letter(self, series):
"""
The letter of the Excel worksheet column in which the data for a
series appears.
"""
column_number = 1 + series.categories.depth + series.index
return self._column_reference(column_number) | [
"def",
"_series_col_letter",
"(",
"self",
",",
"series",
")",
":",
"column_number",
"=",
"1",
"+",
"series",
".",
"categories",
".",
"depth",
"+",
"series",
".",
"index",
"return",
"self",
".",
"_column_reference",
"(",
"column_number",
")"
] | 38.857143 | 12.857143 |
def table(contents, heading=True, colw=None, cwunit='dxa', tblw=0,
twunit='auto', borders={}, celstyle=None):
"""
Return a table element based on specified parameters
@param list contents: A list of lists describing contents. Every item in
the list can be a string or a v... | [
"def",
"table",
"(",
"contents",
",",
"heading",
"=",
"True",
",",
"colw",
"=",
"None",
",",
"cwunit",
"=",
"'dxa'",
",",
"tblw",
"=",
"0",
",",
"twunit",
"=",
"'auto'",
",",
"borders",
"=",
"{",
"}",
",",
"celstyle",
"=",
"None",
")",
":",
"tabl... | 44.296296 | 16.311111 |
def CheckForCopyright(filename, lines, error):
"""Logs an error if no Copyright message appears at the top of the file."""
# We'll say it should occur by line 10. Don't forget there's a
# dummy line at the front.
for line in range(1, min(len(lines), 11)):
if re.search(r'Copyright', lines[line], re.I): brea... | [
"def",
"CheckForCopyright",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"# We'll say it should occur by line 10. Don't forget there's a",
"# dummy line at the front.",
"for",
"line",
"in",
"range",
"(",
"1",
",",
"min",
"(",
"len",
"(",
"lines",
")",
",",... | 48.909091 | 15 |
def load_labware_by_name(self, name: str) -> Labware:
""" Specify the presence of a piece of labware on the module.
:param name: The name of the labware object.
:returns: The initialized and loaded labware object.
"""
lw = load(name, self._geometry.location)
return self.... | [
"def",
"load_labware_by_name",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Labware",
":",
"lw",
"=",
"load",
"(",
"name",
",",
"self",
".",
"_geometry",
".",
"location",
")",
"return",
"self",
".",
"load_labware",
"(",
"lw",
")"
] | 41.125 | 12.125 |
def read(self, filename):
'''
Read a file content.
:param string filename: The storage root-relative filename
:raises FileNotFound: If the file does not exists
'''
if not self.backend.exists(filename):
raise FileNotFound(filename)
return self.backend.... | [
"def",
"read",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"self",
".",
"backend",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"FileNotFound",
"(",
"filename",
")",
"return",
"self",
".",
"backend",
".",
"read",
"(",
"filename",
")"
] | 32.5 | 17.5 |
def build(self, construct):
"""Build a single construct in CLIPS.
The Python equivalent of the CLIPS build command.
"""
if lib.EnvBuild(self._env, construct.encode()) != 1:
raise CLIPSError(self._env) | [
"def",
"build",
"(",
"self",
",",
"construct",
")",
":",
"if",
"lib",
".",
"EnvBuild",
"(",
"self",
".",
"_env",
",",
"construct",
".",
"encode",
"(",
")",
")",
"!=",
"1",
":",
"raise",
"CLIPSError",
"(",
"self",
".",
"_env",
")"
] | 29.875 | 16.375 |
def diff_parameters(old_params, new_params):
"""Compares the old vs. new parameters and returns a "diff"
If there are no changes, we return an empty list.
Args:
old_params(dict): old paramters
new_params(dict): new parameters
Returns:
list: A list of differences
"""
[c... | [
"def",
"diff_parameters",
"(",
"old_params",
",",
"new_params",
")",
":",
"[",
"changes",
",",
"diff",
"]",
"=",
"diff_dictionaries",
"(",
"old_params",
",",
"new_params",
")",
"if",
"changes",
"==",
"0",
":",
"return",
"[",
"]",
"return",
"diff"
] | 26.0625 | 18.3125 |
def reload_module(self, module_name):
"""Reloads the specified module without changing its ordering.
1. Calls stop(reloading=True) on the module
2. Reloads the Module object into .loaded_modules
3. Calls start(reloading=True) on the new object
If called with a module na... | [
"def",
"reload_module",
"(",
"self",
",",
"module_name",
")",
":",
"module",
"=",
"self",
".",
"loaded_modules",
".",
"get",
"(",
"module_name",
")",
"if",
"module",
":",
"module",
".",
"stop",
"(",
"reloading",
"=",
"True",
")",
"else",
":",
"_log",
"... | 40.285714 | 19.892857 |
def _split_addr(addr):
"""
Splits a str of IP address and port pair into (host, port).
Example::
>>> _split_addr('127.0.0.1:6653')
('127.0.0.1', 6653)
>>> _split_addr('[::1]:6653')
('::1', 6653)
Raises ValueError if invalid format.
:param addr: A pair of IP addres... | [
"def",
"_split_addr",
"(",
"addr",
")",
":",
"e",
"=",
"ValueError",
"(",
"'Invalid IP address and port pair: \"%s\"'",
"%",
"addr",
")",
"pair",
"=",
"addr",
".",
"rsplit",
"(",
"':'",
",",
"1",
")",
"if",
"len",
"(",
"pair",
")",
"!=",
"2",
":",
"rai... | 24.566667 | 18.033333 |
def is_tracking_shield_displayed(self):
"""Tracking Protection shield.
Returns:
bool: True or False if the Tracking Shield is displayed.
"""
with self.selenium.context(self.selenium.CONTEXT_CHROME):
if self.window.firefox_version >= 63: # Bug 1471713, 1476218
... | [
"def",
"is_tracking_shield_displayed",
"(",
"self",
")",
":",
"with",
"self",
".",
"selenium",
".",
"context",
"(",
"self",
".",
"selenium",
".",
"CONTEXT_CHROME",
")",
":",
"if",
"self",
".",
"window",
".",
"firefox_version",
">=",
"63",
":",
"# Bug 1471713... | 44.692308 | 23.230769 |
def parse_entry(self, name):
"""
Parse query entry name, just like:
{
'User[]:user'
}
'User[]:user' is an entry name.
:param name:
:return:
"""
# calculate schema mode
# if ':name' or '' or '[]:name' or '[]' found, it'll be t... | [
"def",
"parse_entry",
"(",
"self",
",",
"name",
")",
":",
"# calculate schema mode",
"# if ':name' or '' or '[]:name' or '[]' found, it'll be treat as multiple Schema query",
"alias",
"=",
"name",
"if",
"':'",
"in",
"name",
":",
"name",
",",
"alias",
"=",
"name",
".",
... | 24.375 | 17.958333 |
def convert_to_one_hot(y):
"""
converts y into one hot reprsentation.
Parameters
----------
y : list
A list containing continous integer values.
Returns
-------
one_hot : numpy.ndarray
A numpy.ndarray object, which is one-hot representation of y.
"""
max_value ... | [
"def",
"convert_to_one_hot",
"(",
"y",
")",
":",
"max_value",
"=",
"max",
"(",
"y",
")",
"min_value",
"=",
"min",
"(",
"y",
")",
"length",
"=",
"len",
"(",
"y",
")",
"one_hot",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"length",
",",
"(",
"max_value",
... | 22.666667 | 20.47619 |
def _validatePullParams(MaxObjectCount, context):
"""
Validate the input paramaters for the PullInstances,
PullInstancesWithPath, and PullInstancePaths requests.
MaxObjectCount: Must be integer type and ge 0
context: Must be not None and length ge 2
"""
if (not isinstance(M... | [
"def",
"_validatePullParams",
"(",
"MaxObjectCount",
",",
"context",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"MaxObjectCount",
",",
"six",
".",
"integer_types",
")",
"or",
"MaxObjectCount",
"<",
"0",
")",
":",
"raise",
"ValueError",
"(",
"_format",
"(... | 38.611111 | 16.611111 |
def parse(self, fo):
"""
Convert Improbizer output to motifs
Parameters
----------
fo : file-like
File object containing Improbizer output.
Returns
-------
motifs : list
List of Motif instances.
"""
motifs ... | [
"def",
"parse",
"(",
"self",
",",
"fo",
")",
":",
"motifs",
"=",
"[",
"]",
"p",
"=",
"re",
".",
"compile",
"(",
"r'\\d+\\s+@\\s+\\d+\\.\\d+\\s+sd\\s+\\d+\\.\\d+\\s+(\\w+)$'",
")",
"line",
"=",
"fo",
".",
"readline",
"(",
")",
"while",
"line",
"and",
"line"... | 31.242424 | 18.757576 |
def format_field(self, value, format_spec):
"""Override :meth:`string.Formatter.format_field` to have our
default format_spec for :class:`datetime.Datetime` objects, and to
let None yield an empty string rather than ``None``."""
if isinstance(value, datetime) and not format_spec:
... | [
"def",
"format_field",
"(",
"self",
",",
"value",
",",
"format_spec",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
")",
"and",
"not",
"format_spec",
":",
"return",
"super",
"(",
")",
".",
"format_field",
"(",
"value",
",",
"'%Y-%m-%d_%H-%M-... | 53.111111 | 14.777778 |
def check_cache(self, vts, counter):
"""Manually checks the artifact cache (usually immediately before compilation.)
Returns true if the cache was hit successfully, indicating that no compilation is necessary.
"""
if not self.artifact_cache_reads_enabled():
return False
cached_vts, _, _ = sel... | [
"def",
"check_cache",
"(",
"self",
",",
"vts",
",",
"counter",
")",
":",
"if",
"not",
"self",
".",
"artifact_cache_reads_enabled",
"(",
")",
":",
"return",
"False",
"cached_vts",
",",
"_",
",",
"_",
"=",
"self",
".",
"check_artifact_cache",
"(",
"[",
"vt... | 40.666667 | 22.333333 |
def parse_darknet_ann_list_to_cls_box(annotations):
"""Parse darknet annotation format into two lists for class and bounding box.
Input list of [[class, x, y, w, h], ...], return two list of [class ...] and [[x, y, w, h], ...].
Parameters
------------
annotations : list of list
A list of c... | [
"def",
"parse_darknet_ann_list_to_cls_box",
"(",
"annotations",
")",
":",
"class_list",
"=",
"[",
"]",
"bbox_list",
"=",
"[",
"]",
"for",
"ann",
"in",
"annotations",
":",
"class_list",
".",
"append",
"(",
"ann",
"[",
"0",
"]",
")",
"bbox_list",
".",
"appen... | 26.8 | 22.8 |
def from_global_moment_and_saxis(cls, global_moment, saxis):
"""
Convenience method to initialize Magmom from a given global
magnetic moment, i.e. magnetic moment with saxis=(0,0,1), and
provided saxis.
Method is useful if you do not know the components of your
m... | [
"def",
"from_global_moment_and_saxis",
"(",
"cls",
",",
"global_moment",
",",
"saxis",
")",
":",
"magmom",
"=",
"Magmom",
"(",
"global_moment",
")",
"return",
"cls",
"(",
"magmom",
".",
"get_moment",
"(",
"saxis",
"=",
"saxis",
")",
",",
"saxis",
"=",
"sax... | 37.4 | 17.4 |
def subseq(self, start_offset=0, end_offset=None):
"""
Return a subset of the sequence
starting at start_offset (defaulting to the beginning)
ending at end_offset (None representing the end, whih is the default)
Raises ValueError if duration_64 is missing on any element
"... | [
"def",
"subseq",
"(",
"self",
",",
"start_offset",
"=",
"0",
",",
"end_offset",
"=",
"None",
")",
":",
"from",
"sebastian",
".",
"core",
"import",
"DURATION_64",
"def",
"subseq_iter",
"(",
"start_offset",
",",
"end_offset",
")",
":",
"cur_offset",
"=",
"0"... | 41.346154 | 16.730769 |
def ok_for_running(self, cmd_obj, name, nargs):
"""We separate some of the common debugger command checks here:
whether it makes sense to run the command in this execution state,
if the command has the right number of arguments and so on.
"""
if hasattr(cmd_obj, 'execution_set'):... | [
"def",
"ok_for_running",
"(",
"self",
",",
"cmd_obj",
",",
"name",
",",
"nargs",
")",
":",
"if",
"hasattr",
"(",
"cmd_obj",
",",
"'execution_set'",
")",
":",
"if",
"not",
"(",
"self",
".",
"core",
".",
"execution_status",
"in",
"cmd_obj",
".",
"execution... | 49.333333 | 17.533333 |
def _add_step(self, step):
"""Add a step to the workflow.
Args:
step (Step): a step from the steps library.
"""
self._closed()
self.has_workflow_step = self.has_workflow_step or step.is_workflow
self.wf_steps[step.name_in_workflow] = step | [
"def",
"_add_step",
"(",
"self",
",",
"step",
")",
":",
"self",
".",
"_closed",
"(",
")",
"self",
".",
"has_workflow_step",
"=",
"self",
".",
"has_workflow_step",
"or",
"step",
".",
"is_workflow",
"self",
".",
"wf_steps",
"[",
"step",
".",
"name_in_workflo... | 29.1 | 20 |
def linkify(self, timeperiods, contacts, services, hosts):
"""Create link between objects::
* escalation -> host
* escalation -> service
* escalation -> timeperiods
* escalation -> contact
:param timeperiods: timeperiods to link
:type timeperiods: alignak.ob... | [
"def",
"linkify",
"(",
"self",
",",
"timeperiods",
",",
"contacts",
",",
"services",
",",
"hosts",
")",
":",
"self",
".",
"linkify_with_timeperiods",
"(",
"timeperiods",
",",
"'escalation_period'",
")",
"self",
".",
"linkify_with_contacts",
"(",
"contacts",
")",... | 37.954545 | 12.181818 |
def LAHF(cpu):
"""
Loads status flags into AH register.
Moves the low byte of the EFLAGS register (which includes status flags
SF, ZF, AF, PF, and CF) to the AH register. Reserved bits 1, 3, and 5
of the EFLAGS register are set in the AH register::
AH = EFLAGS... | [
"def",
"LAHF",
"(",
"cpu",
")",
":",
"used_regs",
"=",
"(",
"cpu",
".",
"SF",
",",
"cpu",
".",
"ZF",
",",
"cpu",
".",
"AF",
",",
"cpu",
".",
"PF",
",",
"cpu",
".",
"CF",
")",
"is_expression",
"=",
"any",
"(",
"issymbolic",
"(",
"x",
")",
"for... | 35.515152 | 15.333333 |
def verify_pss_padding(hash_algorithm, salt_length, key_length, message, signature):
"""
Verifies the PSS padding on an encoded message
:param hash_algorithm:
The string name of the hash algorithm to use: "sha1", "sha224",
"sha256", "sha384", "sha512"
:param salt_length:
The le... | [
"def",
"verify_pss_padding",
"(",
"hash_algorithm",
",",
"salt_length",
",",
"key_length",
",",
"message",
",",
"signature",
")",
":",
"if",
"_backend",
"!=",
"'winlegacy'",
"and",
"sys",
".",
"platform",
"!=",
"'darwin'",
":",
"raise",
"SystemError",
"(",
"pr... | 28.173228 | 21.527559 |
def setup_logging():
"""Function to configure log hadlers.
.. important::
Configuration, if needed, should be applied before invoking this
decorator, as starting the subscriber process for logging will
configure the root logger for the child process based on the
state of :obj:`... | [
"def",
"setup_logging",
"(",
")",
":",
"logging_configs",
"=",
"DEFAULT_LOGGING_CONFIG",
"new_logging_configs",
"=",
"bigchaindb",
".",
"config",
"[",
"'log'",
"]",
"if",
"'file'",
"in",
"new_logging_configs",
":",
"filename",
"=",
"new_logging_configs",
"[",
"'file... | 37.413793 | 22.482759 |
def ignore_failed_logs_action(self, request, queryset):
"""Set FAILED trigger logs in queryset to IGNORED."""
count = _ignore_failed_logs(queryset)
self.message_user(
request,
_('{count} failed trigger logs marked as ignored.').format(count=count),
) | [
"def",
"ignore_failed_logs_action",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"count",
"=",
"_ignore_failed_logs",
"(",
"queryset",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"_",
"(",
"'{count} failed trigger logs marked as ignored.'",
")"... | 42.857143 | 18.428571 |
def parse_option(self, option, block_name, *values):
""" Parse app path values for option.
"""
# treat arguments as part of the program name (support spaces in name)
values = [x.replace(' ', '\\ ') if not x.startswith(os.sep) else x
for x in [str(v) for v in values... | [
"def",
"parse_option",
"(",
"self",
",",
"option",
",",
"block_name",
",",
"*",
"values",
")",
":",
"# treat arguments as part of the program name (support spaces in name)",
"values",
"=",
"[",
"x",
".",
"replace",
"(",
"' '",
",",
"'\\\\ '",
")",
"if",
"not",
"... | 37.153846 | 19.615385 |
def __check_looks_like_uri(self, uri):
"""Checks the URI looks like a RAW uri in github:
- 'https://raw.githubusercontent.com/github/hubot/master/README.md'
- 'https://github.com/github/hubot/raw/master/README.md'
:param uri: uri of the file
"""
if uri.split('/')[2] == ... | [
"def",
"__check_looks_like_uri",
"(",
"self",
",",
"uri",
")",
":",
"if",
"uri",
".",
"split",
"(",
"'/'",
")",
"[",
"2",
"]",
"==",
"'raw.githubusercontent.com'",
":",
"return",
"True",
"elif",
"uri",
".",
"split",
"(",
"'/'",
")",
"[",
"2",
"]",
"=... | 39.2 | 19.2 |
def market_value(self):
"""
[float] 市值
"""
return sum(account.market_value for account in six.itervalues(self._accounts)) | [
"def",
"market_value",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"account",
".",
"market_value",
"for",
"account",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"_accounts",
")",
")"
] | 29.8 | 17 |
def js_to_url_function(converter):
"""Get the JavaScript converter function from a rule."""
if hasattr(converter, 'js_to_url_function'):
data = converter.js_to_url_function()
else:
for cls in getmro(type(converter)):
if cls in js_to_url_functions:
data = js_to_url... | [
"def",
"js_to_url_function",
"(",
"converter",
")",
":",
"if",
"hasattr",
"(",
"converter",
",",
"'js_to_url_function'",
")",
":",
"data",
"=",
"converter",
".",
"js_to_url_function",
"(",
")",
"else",
":",
"for",
"cls",
"in",
"getmro",
"(",
"type",
"(",
"... | 38 | 10.333333 |
def walk_code(co, _prefix=''):
"""
Traverse a code object, finding all consts which are also code objects.
Yields pairs of (name, code object).
"""
name = _prefix + co.co_name
yield name, co
yield from chain.from_iterable(
walk_code(c, _prefix=_extend_name(name, co))
for c i... | [
"def",
"walk_code",
"(",
"co",
",",
"_prefix",
"=",
"''",
")",
":",
"name",
"=",
"_prefix",
"+",
"co",
".",
"co_name",
"yield",
"name",
",",
"co",
"yield",
"from",
"chain",
".",
"from_iterable",
"(",
"walk_code",
"(",
"c",
",",
"_prefix",
"=",
"_exte... | 27.923077 | 14.230769 |
def d_acquisition_function(self, x):
"""
Returns the gradient of the acquisition function at x.
"""
x = np.atleast_2d(x)
if self.transform=='softplus':
fval = -self.acq.acquisition_function(x)[:,0]
scale = 1./(np.log1p(np.exp(fval))*(1.+np.exp(-fval)))
... | [
"def",
"d_acquisition_function",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"np",
".",
"atleast_2d",
"(",
"x",
")",
"if",
"self",
".",
"transform",
"==",
"'softplus'",
":",
"fval",
"=",
"-",
"self",
".",
"acq",
".",
"acquisition_function",
"(",
"x",
... | 37.761905 | 19.571429 |
def plot(x, y, z, ax=None, **kwargs):
r"""
Plot iso-probability mass function, converted to sigmas.
Parameters
----------
x, y, z : numpy arrays
Same as arguments to :func:`matplotlib.pyplot.contour`
ax: axes object, optional
:class:`matplotlib.axes._subplots.AxesSubplot` to pl... | [
"def",
"plot",
"(",
"x",
",",
"y",
",",
"z",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"matplotlib",
".",
"pyplot",
".",
"gca",
"(",
")",
"# Get inputs",
"colors",
"=",
"kwargs",
".",
... | 32.62 | 21.43 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.