text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def lookup_tag(name):
"""Look up a tag based on its key. Returns a DmapTag."""
return next((_TAGS[t] for t in _TAGS if t == name),
DmapTag(_read_unknown, 'unknown tag')) | [
"def",
"lookup_tag",
"(",
"name",
")",
":",
"return",
"next",
"(",
"(",
"_TAGS",
"[",
"t",
"]",
"for",
"t",
"in",
"_TAGS",
"if",
"t",
"==",
"name",
")",
",",
"DmapTag",
"(",
"_read_unknown",
",",
"'unknown tag'",
")",
")"
] | 47.5 | 12 |
def value(self):
# type: () -> bytes
"""Binary value content."""
v = self.file
return v.open("rb").read() if v is not None else v | [
"def",
"value",
"(",
"self",
")",
":",
"# type: () -> bytes",
"v",
"=",
"self",
".",
"file",
"return",
"v",
".",
"open",
"(",
"\"rb\"",
")",
".",
"read",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"else",
"v"
] | 31.4 | 14.8 |
def download(self, job_id, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES):
"""
Downloads all screenshots for given job_id to `destination` folder.
If `destination` is None, then screenshots will be saved in current directory.
"""
self._retries_num = 0
... | [
"def",
"download",
"(",
"self",
",",
"job_id",
",",
"destination",
"=",
"None",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
"retries",
"=",
"DEFAULT_RETRIES",
")",
":",
"self",
".",
"_retries_num",
"=",
"0",
"sleep",
"(",
"timeout",
")",
"self",
".",
"s... | 46.222222 | 22.222222 |
def format_camel_case(text):
"""
Example::
ThisIsVeryGood
**中文文档**
将文本格式化为各单词首字母大写, 拼接而成的长变量名。
"""
text = text.strip()
if len(text) == 0: # if empty string, return it
raise ValueError("can not be empty string!")
else:
text = text.lower() # lower all char
... | [
"def",
"format_camel_case",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"text",
")",
"==",
"0",
":",
"# if empty string, return it",
"raise",
"ValueError",
"(",
"\"can not be empty string!\"",
")",
"else",
":",
"text... | 25.1 | 16.566667 |
def __get_base_path(self):
"""Return the file's directory and file name, with the
suffix stripped."""
entry = self.get()
return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(entry.get_path())[0],
entry.name + "_base") | [
"def",
"__get_base_path",
"(",
"self",
")",
":",
"entry",
"=",
"self",
".",
"get",
"(",
")",
"return",
"SCons",
".",
"Subst",
".",
"SpecialAttrWrapper",
"(",
"SCons",
".",
"Util",
".",
"splitext",
"(",
"entry",
".",
"get_path",
"(",
")",
")",
"[",
"0... | 49 | 16.833333 |
def handle_oauth1_response(self, args):
"""Handles an oauth1 authorization response."""
client = self.make_client()
client.verifier = args.get('oauth_verifier')
tup = session.get('%s_oauthtok' % self.name)
if not tup:
raise OAuthException(
'Token not f... | [
"def",
"handle_oauth1_response",
"(",
"self",
",",
"args",
")",
":",
"client",
"=",
"self",
".",
"make_client",
"(",
")",
"client",
".",
"verifier",
"=",
"args",
".",
"get",
"(",
"'oauth_verifier'",
")",
"tup",
"=",
"session",
".",
"get",
"(",
"'%s_oauth... | 36.1 | 13 |
def connected_to(self, vertex_id):
"""
Parameters
-----------
vertex_id : int
Get what `vertex_id` is connected to.
Returns
-----------
int|None, the vertex id connected to the
input `vertex_id` in this edge, as long as `vertex_id` is
... | [
"def",
"connected_to",
"(",
"self",
",",
"vertex_id",
")",
":",
"if",
"vertex_id",
"not",
"in",
"self",
".",
"edge",
":",
"return",
"None",
"connected_to",
"=",
"(",
"self",
".",
"edge",
"[",
"1",
"]",
"if",
"self",
".",
"edge",
"[",
"0",
"]",
"=="... | 31.111111 | 14.777778 |
def predict_expectation(self, X):
"""
Compute the expected lifetime, E[T], using covariates X.
Parameters
----------
X: a (n,d) covariate numpy array or DataFrame
If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
... | [
"def",
"predict_expectation",
"(",
"self",
",",
"X",
")",
":",
"index",
"=",
"_get_index",
"(",
"X",
")",
"t",
"=",
"self",
".",
"_index",
"return",
"pd",
".",
"DataFrame",
"(",
"trapz",
"(",
"self",
".",
"predict_survival_function",
"(",
"X",
")",
"["... | 35.6875 | 19.8125 |
def check_address(cls, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> (typing.Union[str, int], typing.Union[str, int]):
"""
In all storage's methods chat or user is always required.
If one of them is not pro... | [
"def",
"check_address",
"(",
"cls",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
")",... | 38 | 24.380952 |
def call_external_subprocess(command_list,
stdin_filename=None, stdout_filename=None, stderr_filename=None,
env=None):
"""Run the command and arguments in the command_list. Will search the system
PATH for commands to execute, but no shell is started. Redirects any... | [
"def",
"call_external_subprocess",
"(",
"command_list",
",",
"stdin_filename",
"=",
"None",
",",
"stdout_filename",
"=",
"None",
",",
"stderr_filename",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"if",
"stdin_filename",
":",
"stdin",
"=",
"open",
"(",
"... | 42.642857 | 20.25 |
def two_way_information_gain(X, Y, Z, base=2):
"""Calculates the two-way information gain between three variables, I(X;Y;Z), in the given base
IG(X;Y;Z) indicates the information gained about variable Z by the joint variable X_Y, after removing
the information that X and Y have about Z individually. Thus, ... | [
"def",
"two_way_information_gain",
"(",
"X",
",",
"Y",
",",
"Z",
",",
"base",
"=",
"2",
")",
":",
"X_Y",
"=",
"[",
"'{}{}'",
".",
"format",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"X",
",",
"Y",
")",
"]",
"return",
... | 43.607143 | 25.607143 |
def main():
""" main function """
# get options and arguments
(parser, options, args) = init_parser()
# initialize result variable
result = None
# check for values which are always needed
if not options.user:
parser.error("No user given.")
if not options.secret:
parser.... | [
"def",
"main",
"(",
")",
":",
"# get options and arguments",
"(",
"parser",
",",
"options",
",",
"args",
")",
"=",
"init_parser",
"(",
")",
"# initialize result variable",
"result",
"=",
"None",
"# check for values which are always needed",
"if",
"not",
"options",
"... | 31.902439 | 18.658537 |
def filter_all_contents(value: ecore.EPackage, type_):
"""Returns `eAllContents(type_)`."""
return (c for c in value.eAllContents() if isinstance(c, type_)) | [
"def",
"filter_all_contents",
"(",
"value",
":",
"ecore",
".",
"EPackage",
",",
"type_",
")",
":",
"return",
"(",
"c",
"for",
"c",
"in",
"value",
".",
"eAllContents",
"(",
")",
"if",
"isinstance",
"(",
"c",
",",
"type_",
")",
")"
] | 56.666667 | 15.333333 |
def print_debug(self, text, indent=0):
"""Only prints debug info on screen when self.debug == True."""
if self.debug:
if indent > 0:
print(" "*self.debug, text)
self.debug += indent
if indent <= 0:
print(" "*self.debug, text) | [
"def",
"print_debug",
"(",
"self",
",",
"text",
",",
"indent",
"=",
"0",
")",
":",
"if",
"self",
".",
"debug",
":",
"if",
"indent",
">",
"0",
":",
"print",
"(",
"\" \"",
"*",
"self",
".",
"debug",
",",
"text",
")",
"self",
".",
"debug",
"+=",
"... | 37.75 | 7.625 |
def enqueue(self, message, *, delay=None):
"""Enqueue a message.
Parameters:
message(Message): The message to enqueue.
delay(int): The minimum amount of time, in milliseconds, to
delay the message by.
Raises:
QueueNotFound: If the queue the message is ... | [
"def",
"enqueue",
"(",
"self",
",",
"message",
",",
"*",
",",
"delay",
"=",
"None",
")",
":",
"queue_name",
"=",
"message",
".",
"queue_name",
"if",
"delay",
"is",
"not",
"None",
":",
"queue_name",
"=",
"dq_name",
"(",
"queue_name",
")",
"message_eta",
... | 31.833333 | 15.1 |
def FindLiteral(self, pattern, data):
"""Search the data for a hit."""
pattern = utils.Xor(pattern, self.xor_in_key)
offset = 0
while 1:
# We assume here that data.find does not make a copy of pattern.
offset = data.find(pattern, offset)
if offset < 0:
break
yield (off... | [
"def",
"FindLiteral",
"(",
"self",
",",
"pattern",
",",
"data",
")",
":",
"pattern",
"=",
"utils",
".",
"Xor",
"(",
"pattern",
",",
"self",
".",
"xor_in_key",
")",
"offset",
"=",
"0",
"while",
"1",
":",
"# We assume here that data.find does not make a copy of ... | 23.466667 | 22 |
def check_pause(self):
"""
Call at regular intervals within long running tasks to add pause breakpoints.
:return: time that the task was paused for, always 0.0 if it didn't pause
:rtype: float
"""
# todo task_runner vs model
pause_time = 0.0
sleep_time =... | [
"def",
"check_pause",
"(",
"self",
")",
":",
"# todo task_runner vs model",
"pause_time",
"=",
"0.0",
"sleep_time",
"=",
"0.1",
"if",
"self",
".",
"model",
".",
"tasks_paused",
":",
"while",
"self",
".",
"model",
".",
"tasks_paused",
":",
"sleep",
"(",
"paus... | 30.5625 | 16.8125 |
def __stringify_body(self, request_or_response):
''' this method reference from httprunner '''
headers = self.__track_info['{}_headers'.format(request_or_response)]
body = self.__track_info.get('{}_body'.format(request_or_response))
if isinstance(body, CaseInsensitiveDict):
... | [
"def",
"__stringify_body",
"(",
"self",
",",
"request_or_response",
")",
":",
"headers",
"=",
"self",
".",
"__track_info",
"[",
"'{}_headers'",
".",
"format",
"(",
"request_or_response",
")",
"]",
"body",
"=",
"self",
".",
"__track_info",
".",
"get",
"(",
"'... | 42.866667 | 20.6 |
def make_split(self, split_name, val_indices=None, train_pct=0.8, field_name=None):
""" Splits the dataset into train and test according
to the given attribute.
The split is saved with the dataset for future access.
Parameters
----------
split_name : str
name... | [
"def",
"make_split",
"(",
"self",
",",
"split_name",
",",
"val_indices",
"=",
"None",
",",
"train_pct",
"=",
"0.8",
",",
"field_name",
"=",
"None",
")",
":",
"# check train percentage",
"if",
"train_pct",
"<",
"0",
"or",
"train_pct",
">",
"1",
":",
"raise"... | 39.778761 | 17.345133 |
def check_configuration_string(
self,
config_string,
is_job=True,
external_name=False
):
"""
Check whether the given job or task configuration string
is well-formed (if ``is_bstring`` is ``True``)
and it has all the required parameters.... | [
"def",
"check_configuration_string",
"(",
"self",
",",
"config_string",
",",
"is_job",
"=",
"True",
",",
"external_name",
"=",
"False",
")",
":",
"if",
"is_job",
":",
"self",
".",
"log",
"(",
"u\"Checking job configuration string\"",
")",
"else",
":",
"self",
... | 44.976744 | 20.604651 |
def add_prefix(self, name, stmt):
"""Return `name` prepended with correct prefix.
If the name is already prefixed, the prefix may be translated
to the value obtained from `self.module_prefixes`. Unmodified
`name` is returned if we are inside a global grouping.
"""
if se... | [
"def",
"add_prefix",
"(",
"self",
",",
"name",
",",
"stmt",
")",
":",
"if",
"self",
".",
"gg_level",
":",
"return",
"name",
"pref",
",",
"colon",
",",
"local",
"=",
"name",
".",
"partition",
"(",
"\":\"",
")",
"if",
"colon",
":",
"return",
"(",
"se... | 41.214286 | 17.357143 |
def add_group_members(self, members):
"""Add a new group member to the groups list
:param members: member name
:type members: str
:return: None
"""
if not isinstance(members, list):
members = [members]
if not getattr(self, 'group_members', None):
... | [
"def",
"add_group_members",
"(",
"self",
",",
"members",
")",
":",
"if",
"not",
"isinstance",
"(",
"members",
",",
"list",
")",
":",
"members",
"=",
"[",
"members",
"]",
"if",
"not",
"getattr",
"(",
"self",
",",
"'group_members'",
",",
"None",
")",
":"... | 28.928571 | 12.571429 |
def filterAll(self, **kwargs):
'''
filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children.
Results must match ALL the filter criteria. for ANY, use the *Or methods
For just the nodes in this collection, use "filter" or... | [
"def",
"filterAll",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"canFilterTags",
"is",
"False",
":",
"raise",
"NotImplementedError",
"(",
"'filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust \"find\" method, ... | 44.884615 | 37.576923 |
def _get_3000_galaxies_needing_metadata(
self):
""" get 3000 galaxies needing metadata
**Return:**
- ``len(self.theseIds)`` -- the number of NED IDs returned
.. todo ::
- update key arguments values and definitions with defaults
- update return ... | [
"def",
"_get_3000_galaxies_needing_metadata",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_get_3000_galaxies_needing_metadata`` method'",
")",
"tableName",
"=",
"self",
".",
"dbTableName",
"# SELECT THE DATA FROM NED TABLE",
"self",
".",
... | 33.025 | 20.125 |
def _set_trap(self, v, load=False):
"""
Setter method for trap, mapped from YANG variable /snmp_server/enable/trap (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_trap is considered as a private
method. Backends looking to populate this variable should
... | [
"def",
"_set_trap",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 70.954545 | 33 |
def _load_yaml_config(cls, config_data, filename="(unknown)"):
"""Load a yaml config file."""
try:
config = yaml.safe_load(config_data)
except yaml.YAMLError as err:
if hasattr(err, 'problem_mark'):
mark = err.problem_mark
errmsg = ("Inval... | [
"def",
"_load_yaml_config",
"(",
"cls",
",",
"config_data",
",",
"filename",
"=",
"\"(unknown)\"",
")",
":",
"try",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"config_data",
")",
"except",
"yaml",
".",
"YAMLError",
"as",
"err",
":",
"if",
"hasattr"... | 39.363636 | 16.636364 |
def get(map_name):
"""Get an instance of a map by name. Errors if the map doesn't exist."""
if isinstance(map_name, Map):
return map_name
# Get the list of maps. This isn't at module scope to avoid problems of maps
# being defined after this module is imported.
maps = get_maps()
map_class = maps.get(ma... | [
"def",
"get",
"(",
"map_name",
")",
":",
"if",
"isinstance",
"(",
"map_name",
",",
"Map",
")",
":",
"return",
"map_name",
"# Get the list of maps. This isn't at module scope to avoid problems of maps",
"# being defined after this module is imported.",
"maps",
"=",
"get_maps",... | 34.5 | 19 |
def originalTextFor(expr, asString=True):
"""Helper to return the original, untokenized text for a given
expression. Useful to restore the parsed fields of an HTML start
tag into the raw tag text itself, or to revert separate tokens with
intervening whitespace back to the original matching input text. ... | [
"def",
"originalTextFor",
"(",
"expr",
",",
"asString",
"=",
"True",
")",
":",
"locMarker",
"=",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"lambda",
"s",
",",
"loc",
",",
"t",
":",
"loc",
")",
"endlocMarker",
"=",
"locMarker",
".",
"copy",
"(",
... | 41.829268 | 20.487805 |
def _from_json_list(cls, response_raw, wrapper=None):
"""
:type response_raw: client.BunqResponseRaw
:type wrapper: str|None
:rtype: client.BunqResponse[list[cls]]
"""
json = response_raw.body_bytes.decode()
obj = converter.json_to_class(dict, json)
arra... | [
"def",
"_from_json_list",
"(",
"cls",
",",
"response_raw",
",",
"wrapper",
"=",
"None",
")",
":",
"json",
"=",
"response_raw",
".",
"body_bytes",
".",
"decode",
"(",
")",
"obj",
"=",
"converter",
".",
"json_to_class",
"(",
"dict",
",",
"json",
")",
"arra... | 36.913043 | 19.608696 |
def power_up(self):
""" Changes all settings to guarantee the motors will be used at their maximum power. """
for m in self.motors:
m.compliant = False
m.moving_speed = 0
m.torque_limit = 100.0 | [
"def",
"power_up",
"(",
"self",
")",
":",
"for",
"m",
"in",
"self",
".",
"motors",
":",
"m",
".",
"compliant",
"=",
"False",
"m",
".",
"moving_speed",
"=",
"0",
"m",
".",
"torque_limit",
"=",
"100.0"
] | 40 | 9.5 |
def typecasted(func):
"""Decorator that converts arguments via annotations."""
signature = inspect.signature(func).parameters.items()
@wraps(func)
def wrapper(*args, **kwargs):
args = list(args)
new_args = []
new_kwargs = {}
for _, param in signature:
convert... | [
"def",
"typecasted",
"(",
"func",
")",
":",
"signature",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
".",
"parameters",
".",
"items",
"(",
")",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"... | 36.153846 | 12.230769 |
def _parse(self, fname, code):
"""Parse RiveScript code into memory.
:param str fname: The arbitrary file name used for syntax reporting.
:param []str code: Lines of RiveScript source code to parse.
"""
# Get the "abstract syntax tree"
ast = self._parser.parse(fname, co... | [
"def",
"_parse",
"(",
"self",
",",
"fname",
",",
"code",
")",
":",
"# Get the \"abstract syntax tree\"",
"ast",
"=",
"self",
".",
"_parser",
".",
"parse",
"(",
"fname",
",",
"code",
")",
"# Get all of the \"begin\" type variables: global, var, sub, person, ...",
"for"... | 42.904762 | 17.761905 |
def init_logging(
log_dir=tempfile.gettempdir(),
format="[%(asctime)s][%(levelname)s] %(name)s:%(lineno)s - %(message)s",
level=logging.INFO,
):
"""Configures logging to output to the provided log_dir.
Will use a nested directory whose name is the current timestamp.
:param log_dir: The directo... | [
"def",
"init_logging",
"(",
"log_dir",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"format",
"=",
"\"[%(asctime)s][%(levelname)s] %(name)s:%(lineno)s - %(message)s\"",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
")",
":",
"if",
"not",
"Meta",
".",
"lo... | 33.642857 | 20.666667 |
def getPID(self):
""" Returns the PID for the associated app
(or -1, if no app is associated or the app is not running)
"""
if self._pid is not None:
if not PlatformManager.isPIDValid(self._pid):
self._pid = -1
return self._pid
return -1 | [
"def",
"getPID",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pid",
"is",
"not",
"None",
":",
"if",
"not",
"PlatformManager",
".",
"isPIDValid",
"(",
"self",
".",
"_pid",
")",
":",
"self",
".",
"_pid",
"=",
"-",
"1",
"return",
"self",
".",
"_pid",
... | 34.333333 | 13.111111 |
def CreateDataTypeMapByType(cls, data_type_definition):
"""Creates a specific data type map by type indicator.
Args:
data_type_definition (DataTypeDefinition): data type definition.
Returns:
DataTypeMap: data type map or None if the date type definition
is not available.
"""
... | [
"def",
"CreateDataTypeMapByType",
"(",
"cls",
",",
"data_type_definition",
")",
":",
"data_type_map_class",
"=",
"cls",
".",
"_MAP_PER_DEFINITION",
".",
"get",
"(",
"data_type_definition",
".",
"TYPE_INDICATOR",
",",
"None",
")",
"if",
"not",
"data_type_map_class",
... | 31.875 | 20.8125 |
def get_related_fields(model_class, field_name, path=""):
""" Get fields for a given model """
if field_name:
field, model, direct, m2m = _get_field_by_name(model_class, field_name)
if direct:
# Direct field
try:
new_model = _get_remote_field(field).parent... | [
"def",
"get_related_fields",
"(",
"model_class",
",",
"field_name",
",",
"path",
"=",
"\"\"",
")",
":",
"if",
"field_name",
":",
"field",
",",
"model",
",",
"direct",
",",
"m2m",
"=",
"_get_field_by_name",
"(",
"model_class",
",",
"field_name",
")",
"if",
... | 33.5 | 19.423077 |
def mark_module_skipped(self, module_name):
"""Skip reloading the named module in the future"""
try:
del self.modules[module_name]
except KeyError:
pass
self.skip_modules[module_name] = True | [
"def",
"mark_module_skipped",
"(",
"self",
",",
"module_name",
")",
":",
"try",
":",
"del",
"self",
".",
"modules",
"[",
"module_name",
"]",
"except",
"KeyError",
":",
"pass",
"self",
".",
"skip_modules",
"[",
"module_name",
"]",
"=",
"True"
] | 34.285714 | 11 |
def encode_id_header(resource):
"""
Generate a header for a newly created resource.
Assume `id` attribute convention.
"""
if not hasattr(resource, "id"):
return {}
return {
"X-{}-Id".format(
camelize(name_for(resource))
): str(resource.id),
} | [
"def",
"encode_id_header",
"(",
"resource",
")",
":",
"if",
"not",
"hasattr",
"(",
"resource",
",",
"\"id\"",
")",
":",
"return",
"{",
"}",
"return",
"{",
"\"X-{}-Id\"",
".",
"format",
"(",
"camelize",
"(",
"name_for",
"(",
"resource",
")",
")",
")",
"... | 19.666667 | 17.4 |
def represent_list(self, data):
"""If a list has less than 4 items, represent it in inline style
(i.e. comma separated, within square brackets).
"""
node = super(Dumper, self).represent_list(data)
length = len(data)
if self.default_flow_style is None and length < 4:
... | [
"def",
"represent_list",
"(",
"self",
",",
"data",
")",
":",
"node",
"=",
"super",
"(",
"Dumper",
",",
"self",
")",
".",
"represent_list",
"(",
"data",
")",
"length",
"=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"default_flow_style",
"is",
"None",
... | 40.090909 | 9.818182 |
def _get_field(instance, field):
"""
This is here to support ``MarkupField``. It's a little ugly to
have that support baked-in; other option would be to have a
generic way (via setting?) to override how attribute values are
fetched from content model instances.
"""
value = getattr(inst... | [
"def",
"_get_field",
"(",
"instance",
",",
"field",
")",
":",
"value",
"=",
"getattr",
"(",
"instance",
",",
"field",
")",
"if",
"hasattr",
"(",
"value",
",",
"'raw'",
")",
":",
"value",
"=",
"value",
".",
"raw",
"return",
"value"
] | 30.230769 | 16.538462 |
def _FormatExpression(self, frame, expression):
"""Evaluates a single watched expression and formats it into a string form.
If expression evaluation fails, returns error message string.
Args:
frame: Python stack frame in which the expression is evaluated.
expression: string expression to evalu... | [
"def",
"_FormatExpression",
"(",
"self",
",",
"frame",
",",
"expression",
")",
":",
"rc",
",",
"value",
"=",
"_EvaluateExpression",
"(",
"frame",
",",
"expression",
")",
"if",
"not",
"rc",
":",
"message",
"=",
"_FormatMessage",
"(",
"value",
"[",
"'descrip... | 35.368421 | 22.210526 |
def _dist_version_url(self, dist):
"""
Get version and homepage for a pkg_resources.Distribution
:param dist: the pkg_resources.Distribution to get information for
:returns: 2-tuple of (version, homepage URL)
:rtype: tuple
"""
ver = str(dist.version)
url ... | [
"def",
"_dist_version_url",
"(",
"self",
",",
"dist",
")",
":",
"ver",
"=",
"str",
"(",
"dist",
".",
"version",
")",
"url",
"=",
"None",
"for",
"line",
"in",
"dist",
".",
"get_metadata_lines",
"(",
"dist",
".",
"PKG_INFO",
")",
":",
"line",
"=",
"lin... | 32.722222 | 14.055556 |
def wait(self, pattern, timeout=10.0, safe=False, **match_kwargs):
"""Wait till pattern is found or time is out (default: 10s)."""
t = time.time() + timeout
while time.time() < t:
ret = self.exists(pattern, **match_kwargs)
if ret:
return ret
ti... | [
"def",
"wait",
"(",
"self",
",",
"pattern",
",",
"timeout",
"=",
"10.0",
",",
"safe",
"=",
"False",
",",
"*",
"*",
"match_kwargs",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"while",
"time",
".",
"time",
"(",
")",
"<",
"... | 42.3 | 16.2 |
def _init_client(self, from_archive=False):
"""Init client"""
return MattermostClient(self.url, self.api_token,
max_items=self.max_items,
sleep_for_rate=self.sleep_for_rate,
min_rate_to_sleep=self.min_rate_t... | [
"def",
"_init_client",
"(",
"self",
",",
"from_archive",
"=",
"False",
")",
":",
"return",
"MattermostClient",
"(",
"self",
".",
"url",
",",
"self",
".",
"api_token",
",",
"max_items",
"=",
"self",
".",
"max_items",
",",
"sleep_for_rate",
"=",
"self",
".",... | 51.222222 | 21.777778 |
def diff(self, order=1):
"""Differentiate a B-spline `order` number of times.
Parameters:
order:
int, >= 0
Returns:
**lambda** `x`: ... that evaluates the `order`-th derivative of `B` at the point `x`.
The returned function internally uses __call__, which is 'memoized' for ... | [
"def",
"diff",
"(",
"self",
",",
"order",
"=",
"1",
")",
":",
"order",
"=",
"int",
"(",
"order",
")",
"if",
"order",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"order must be >= 0, got %d\"",
"%",
"(",
"order",
")",
")",
"if",
"order",
"==",
"0",
... | 39.447368 | 29.526316 |
def set_initial_state(self, initial_state, initial_frames):
"""Sets the state that will be used on next reset."""
self._initial_state = initial_state
self._initial_frames = initial_frames[:, -1, ...]
self._should_preprocess_on_reset = False | [
"def",
"set_initial_state",
"(",
"self",
",",
"initial_state",
",",
"initial_frames",
")",
":",
"self",
".",
"_initial_state",
"=",
"initial_state",
"self",
".",
"_initial_frames",
"=",
"initial_frames",
"[",
":",
",",
"-",
"1",
",",
"...",
"]",
"self",
".",... | 50.4 | 7.4 |
def statisticalInefficiencyMultiple(A_kn, fast=False, return_correlation_function=False):
"""Estimate the statistical inefficiency from multiple stationary timeseries (of potentially differing lengths).
Parameters
----------
A_kn : list of np.ndarrays
A_kn[k] is the kth timeseries, and A_kn[k][... | [
"def",
"statisticalInefficiencyMultiple",
"(",
"A_kn",
",",
"fast",
"=",
"False",
",",
"return_correlation_function",
"=",
"False",
")",
":",
"# Convert A_kn into a list of arrays if it is not in this form already.",
"if",
"(",
"type",
"(",
"A_kn",
")",
"==",
"np",
".",... | 36.832258 | 28.464516 |
def _fetchAllChildren(self):
""" Gets all sub directories and files within the current directory.
Does not fetch hidden files.
"""
childItems = []
fileNames = os.listdir(self._fileName)
absFileNames = [os.path.join(self._fileName, fn) for fn in fileNames]
# A... | [
"def",
"_fetchAllChildren",
"(",
"self",
")",
":",
"childItems",
"=",
"[",
"]",
"fileNames",
"=",
"os",
".",
"listdir",
"(",
"self",
".",
"_fileName",
")",
"absFileNames",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_fileName",
",",
... | 42.9 | 21.45 |
def clear(self):
"""Clears all the axes to start fresh."""
for ax in self.flat_grid:
for im_h in ax.findobj(AxesImage):
im_h.remove() | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"ax",
"in",
"self",
".",
"flat_grid",
":",
"for",
"im_h",
"in",
"ax",
".",
"findobj",
"(",
"AxesImage",
")",
":",
"im_h",
".",
"remove",
"(",
")"
] | 28.833333 | 14.666667 |
def create_tab_header_label(tab_name, icons):
"""Create the tab header labels for notebook tabs. If USE_ICONS_AS_TAB_LABELS is set to True in the gui_config,
icons are used as headers. Otherwise, the titles of the tabs are rotated by 90 degrees.
:param tab_name: The label text of the tab, written in small ... | [
"def",
"create_tab_header_label",
"(",
"tab_name",
",",
"icons",
")",
":",
"tooltip_event_box",
"=",
"Gtk",
".",
"EventBox",
"(",
")",
"tooltip_event_box",
".",
"set_tooltip_text",
"(",
"tab_name",
")",
"tab_label",
"=",
"Gtk",
".",
"Label",
"(",
")",
"if",
... | 48.208333 | 18.375 |
def write(self, data):
"""Writes json data to the output directory."""
cnpj, data = data
path = os.path.join(self.output, '%s.json' % cnpj)
with open(path, 'w') as f:
json.dump(data, f, encoding='utf-8') | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"cnpj",
",",
"data",
"=",
"data",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"output",
",",
"'%s.json'",
"%",
"cnpj",
")",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as... | 34.571429 | 15 |
def _parse_operation_bytes(unpacker):
"""Returns a protobuf message representing the next operation as read from
the byte stream in unpacker
"""
# Check for and parse optional source account field
source_account = None
if unpacker.unpack_bool():
source_account = unpacker.unpack_fopaque(... | [
"def",
"_parse_operation_bytes",
"(",
"unpacker",
")",
":",
"# Check for and parse optional source account field",
"source_account",
"=",
"None",
"if",
"unpacker",
".",
"unpack_bool",
"(",
")",
":",
"source_account",
"=",
"unpacker",
".",
"unpack_fopaque",
"(",
"32",
... | 31.930818 | 18.100629 |
def pack_ip_addr(addr):
"""Given an IP address tuple like ('1.2.3.4', 47808) return the six-octet string
useful for a BACnet address."""
addr, port = addr
return socket.inet_aton(addr) + struct.pack('!H', port & _short_mask) | [
"def",
"pack_ip_addr",
"(",
"addr",
")",
":",
"addr",
",",
"port",
"=",
"addr",
"return",
"socket",
".",
"inet_aton",
"(",
"addr",
")",
"+",
"struct",
".",
"pack",
"(",
"'!H'",
",",
"port",
"&",
"_short_mask",
")"
] | 47.2 | 13.8 |
def set_scan_target_progress(
self, scan_id, target, host, progress):
""" Sets host's progress which is part of target. """
self.scan_collection.set_target_progress(
scan_id, target, host, progress) | [
"def",
"set_scan_target_progress",
"(",
"self",
",",
"scan_id",
",",
"target",
",",
"host",
",",
"progress",
")",
":",
"self",
".",
"scan_collection",
".",
"set_target_progress",
"(",
"scan_id",
",",
"target",
",",
"host",
",",
"progress",
")"
] | 46.8 | 7 |
def create_states_geo_zone(cls, states_geo_zone, **kwargs):
"""Create StatesGeoZone
Create a new StatesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_states_geo_zone(states_geo... | [
"def",
"create_states_geo_zone",
"(",
"cls",
",",
"states_geo_zone",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_create_states_g... | 43.666667 | 21.761905 |
def _charInfo(self, point, padding):
"""
Displays character info.
"""
print('{0:0>4X} '.format(point).rjust(padding), ud.name(chr(point), '<code point {0:0>4X}>'.format(point))) | [
"def",
"_charInfo",
"(",
"self",
",",
"point",
",",
"padding",
")",
":",
"print",
"(",
"'{0:0>4X} '",
".",
"format",
"(",
"point",
")",
".",
"rjust",
"(",
"padding",
")",
",",
"ud",
".",
"name",
"(",
"chr",
"(",
"point",
")",
",",
"'<code point {0:0>... | 41 | 17.4 |
def quote_js(text):
'''Quotes text to be used as JavaScript string in HTML templates. The
result doesn't contain surrounding quotes.'''
if isinstance(text, six.binary_type):
text = text.decode('utf-8') # for Jinja2 Markup
text = text.replace('\\', '\\\\');
text = text.replace('\n', '\\n');
... | [
"def",
"quote_js",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"six",
".",
"binary_type",
")",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
"# for Jinja2 Markup",
"text",
"=",
"text",
".",
"replace",
"(",
"'\\\\'",
","... | 40.909091 | 14 |
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
type = msg.get_type()
if type == "STATUSTEXT":
# say some statustext values
if msg.text.startswith("Tuning: "):
self.say(msg.text[8:]) | [
"def",
"mavlink_packet",
"(",
"self",
",",
"msg",
")",
":",
"type",
"=",
"msg",
".",
"get_type",
"(",
")",
"if",
"type",
"==",
"\"STATUSTEXT\"",
":",
"# say some statustext values",
"if",
"msg",
".",
"text",
".",
"startswith",
"(",
"\"Tuning: \"",
")",
":"... | 37.571429 | 6.428571 |
def atlasdb_reset_zonefile_tried_storage( con=None, path=None ):
"""
For zonefiles that we don't have, re-attempt to fetch them from storage.
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "UPDATE zonefiles SET tried_storage = ? WHERE present = ?;"
args = (0, 0)
cur ... | [
"def",
"atlasdb_reset_zonefile_tried_storage",
"(",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"sql",
"=",
"\"UPDATE zonefiles SET tried_storage = ? ... | 27.733333 | 23.333333 |
def put(self, destination):
""" Copy the referenced directory to this path
Note:
This ignores anything not in the desired directory, given by ``self.dirname``.
Args:
destination (str): path to put this directory (which must NOT already exist)
References:
... | [
"def",
"put",
"(",
"self",
",",
"destination",
")",
":",
"target",
"=",
"get_target_path",
"(",
"destination",
",",
"self",
".",
"dirname",
")",
"valid_paths",
"=",
"(",
"self",
".",
"dirname",
",",
"'./%s'",
"%",
"self",
".",
"dirname",
")",
"with",
"... | 38.878788 | 23.151515 |
def get_motor_position(self, motor_name):
""" Gets the motor current position. """
return self.call_remote_api('simxGetJointPosition',
self.get_object_handle(motor_name),
streaming=True) | [
"def",
"get_motor_position",
"(",
"self",
",",
"motor_name",
")",
":",
"return",
"self",
".",
"call_remote_api",
"(",
"'simxGetJointPosition'",
",",
"self",
".",
"get_object_handle",
"(",
"motor_name",
")",
",",
"streaming",
"=",
"True",
")"
] | 54 | 12.4 |
def zone_compare(timezone):
'''
Compares the given timezone name with the system timezone name.
Checks the hash sum between the given timezone, and the one set in
/etc/localtime. Returns True if names and hash sums match, and False if not.
Mostly useful for running state checks.
.. versionchang... | [
"def",
"zone_compare",
"(",
"timezone",
")",
":",
"if",
"'Solaris'",
"in",
"__grains__",
"[",
"'os_family'",
"]",
"or",
"'AIX'",
"in",
"__grains__",
"[",
"'os_family'",
"]",
":",
"return",
"timezone",
"==",
"get_zone",
"(",
")",
"if",
"'FreeBSD'",
"in",
"_... | 31.434783 | 22.478261 |
def _read_ssh_config(ssh_host,
ssh_config_file,
ssh_username=None,
ssh_pkey=None,
ssh_port=None,
ssh_proxy=None,
compression=None,
logger=None):
... | [
"def",
"_read_ssh_config",
"(",
"ssh_host",
",",
"ssh_config_file",
",",
"ssh_username",
"=",
"None",
",",
"ssh_pkey",
"=",
"None",
",",
"ssh_port",
"=",
"None",
",",
"ssh_proxy",
"=",
"None",
",",
"compression",
"=",
"None",
",",
"logger",
"=",
"None",
")... | 41.338983 | 15.745763 |
def create_screenshot(self, app_id, filename, position=1):
"""Add a screenshot to the web app identified by by ``app_id``.
Screenshots are ordered by ``position``.
:returns: HttpResponse:
* status_code (int) 201 is successful
* content (dict) containing screenshot data
... | [
"def",
"create_screenshot",
"(",
"self",
",",
"app_id",
",",
"filename",
",",
"position",
"=",
"1",
")",
":",
"# prepare file for upload",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"s_file",
":",
"s_content",
"=",
"s_file",
".",
"read",
"(",... | 36.863636 | 11.863636 |
def transform(self, X, lenscale=None):
"""
Apply the RBF to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar or ndarray, optional
scal... | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"lenscale",
"=",
"None",
")",
":",
"N",
",",
"d",
"=",
"X",
".",
"shape",
"lenscale",
"=",
"self",
".",
"_check_dim",
"(",
"d",
",",
"lenscale",
")",
"den",
"=",
"(",
"2",
"*",
"lenscale",
"**",
"... | 31.291667 | 20.708333 |
def get_apps(exclude=(), append=(), current={'apps': INSTALLED_APPS}):
"""
Returns INSTALLED_APPS without the apps listed in exclude and with the apps
listed in append.
The use of a mutable dict is intentional, in order to preserve the state of
the INSTALLED_APPS tuple across multiple settings file... | [
"def",
"get_apps",
"(",
"exclude",
"=",
"(",
")",
",",
"append",
"=",
"(",
")",
",",
"current",
"=",
"{",
"'apps'",
":",
"INSTALLED_APPS",
"}",
")",
":",
"current",
"[",
"'apps'",
"]",
"=",
"tuple",
"(",
"[",
"a",
"for",
"a",
"in",
"current",
"["... | 34.923077 | 22.153846 |
def store(self, data, key=None, *args, **kwargs):
""" Cache the list
:param list data: List of objects to cache
"""
list.__init__(self, data)
self._store_items(self._cache_key(key)) | [
"def",
"store",
"(",
"self",
",",
"data",
",",
"key",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"list",
".",
"__init__",
"(",
"self",
",",
"data",
")",
"self",
".",
"_store_items",
"(",
"self",
".",
"_cache_key",
"(",
"key... | 31.428571 | 11 |
def _bsecurate_cli_component_file_refs(args):
'''Handles the component-file-refs subcommand'''
data = curate.component_file_refs(args.files)
s = ''
for cfile, cdata in data.items():
s += cfile + '\n'
rows = []
for el, refs in cdata:
rows.append((' ' + el, ' '.joi... | [
"def",
"_bsecurate_cli_component_file_refs",
"(",
"args",
")",
":",
"data",
"=",
"curate",
".",
"component_file_refs",
"(",
"args",
".",
"files",
")",
"s",
"=",
"''",
"for",
"cfile",
",",
"cdata",
"in",
"data",
".",
"items",
"(",
")",
":",
"s",
"+=",
"... | 27.428571 | 20.142857 |
def _complete_path(path=None):
"""Perform completion of filesystem path.
https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input
"""
if not path:
return _listdir('.')
dirname, rest = os.path.split(path)
tmp = dirname if dirname else '.'
res = [p for p ... | [
"def",
"_complete_path",
"(",
"path",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"return",
"_listdir",
"(",
"'.'",
")",
"dirname",
",",
"rest",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"tmp",
"=",
"dirname",
"if",
"dirname",
"e... | 41.529412 | 14.235294 |
def _document_by_attribute(self, kind, condition=None):
"""
Helper method to return the document only if it has an attribute
that's an instance of the given kind, and passes the condition.
"""
doc = self.document
if doc:
for attr in doc.attributes:
... | [
"def",
"_document_by_attribute",
"(",
"self",
",",
"kind",
",",
"condition",
"=",
"None",
")",
":",
"doc",
"=",
"self",
".",
"document",
"if",
"doc",
":",
"for",
"attr",
"in",
"doc",
".",
"attributes",
":",
"if",
"isinstance",
"(",
"attr",
",",
"kind",... | 38.666667 | 12.5 |
def fit(self, X, y=None, init=None):
"""
Computes the position of the points in the embedding space
Parameters
----------
X : array, shape=[n_samples, n_features], or [n_samples, n_samples] \
if dissimilarity='precomputed'
Input data.
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"init",
"=",
"None",
")",
":",
"self",
".",
"fit_transform",
"(",
"X",
",",
"init",
"=",
"init",
")",
"return",
"self"
] | 36.0625 | 19.5625 |
def pages_siblings_menu(context, page, url='/'):
"""Get the parent page of the given page and render a nested list of its
child pages. Good for rendering a secondary menu.
:param page: the page where to start the menu from.
:param url: not used anymore.
"""
lang = context.get('lang', pages_sett... | [
"def",
"pages_siblings_menu",
"(",
"context",
",",
"page",
",",
"url",
"=",
"'/'",
")",
":",
"lang",
"=",
"context",
".",
"get",
"(",
"'lang'",
",",
"pages_settings",
".",
"PAGE_DEFAULT_LANGUAGE",
")",
"page",
"=",
"get_page_from_string_or_id",
"(",
"page",
... | 36.411765 | 16 |
def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None,
gateway_id=None, instance_id=None, interface_id=None, tags=None,
region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None):
'''
Checks if a route exists.
.. versiona... | [
"def",
"route_exists",
"(",
"destination_cidr_block",
",",
"route_table_name",
"=",
"None",
",",
"route_table_id",
"=",
"None",
",",
"gateway_id",
"=",
"None",
",",
"instance_id",
"=",
"None",
",",
"interface_id",
"=",
"None",
",",
"tags",
"=",
"None",
",",
... | 41.878788 | 30.69697 |
def deploy(target):
"""Deploys the package and documentation.
Proceeds in the following steps:
1. Ensures proper environment variables are set and checks that we are on Circle CI
2. Tags the repository with the new version
3. Creates a standard distribution and a wheel
4. Updates version.py to... | [
"def",
"deploy",
"(",
"target",
")",
":",
"# Ensure proper environment",
"if",
"not",
"os",
".",
"getenv",
"(",
"CIRCLECI_ENV_VAR",
")",
":",
"# pragma: no cover",
"raise",
"EnvironmentError",
"(",
"'Must be on CircleCI to run this script'",
")",
"current_branch",
"=",
... | 39.768293 | 24.060976 |
def imsave(path, img, channel_first=False, as_uint16=False, auto_scale=True):
"""
Save image by pypng module.
Args:
path (str): output filename
img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) by default.
channel_first:
This... | [
"def",
"imsave",
"(",
"path",
",",
"img",
",",
"channel_first",
"=",
"False",
",",
"as_uint16",
"=",
"False",
",",
"auto_scale",
"=",
"True",
")",
":",
"img",
"=",
"_imsave_before",
"(",
"img",
",",
"channel_first",
",",
"auto_scale",
")",
"if",
"auto_sc... | 45.277778 | 28.944444 |
def assign_moving_mean_variance(
mean_var, variance_var, value, decay, name=None):
"""Compute exponentially weighted moving {mean,variance} of a streaming value.
The `value` updated exponentially weighted moving `mean_var` and
`variance_var` are given by the following recurrence relations:
```python
var... | [
"def",
"assign_moving_mean_variance",
"(",
"mean_var",
",",
"variance_var",
",",
"value",
",",
"decay",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"assign_moving_mean_variance\"",
",",
"... | 44.4125 | 22.25 |
def p_deploy_sentence(self, t):
"""deploy_sentence : DEPLOY VAR NUMBER
| DEPLOY VAR NUMBER VAR"""
if len(t) == 4:
t[0] = deploy(t[2], t[3], line=t.lineno(1))
else:
t[0] = deploy(t[2], t[3], t[4], line=t.lineno(1)) | [
"def",
"p_deploy_sentence",
"(",
"self",
",",
"t",
")",
":",
"if",
"len",
"(",
"t",
")",
"==",
"4",
":",
"t",
"[",
"0",
"]",
"=",
"deploy",
"(",
"t",
"[",
"2",
"]",
",",
"t",
"[",
"3",
"]",
",",
"line",
"=",
"t",
".",
"lineno",
"(",
"1",
... | 35.25 | 16.125 |
def following_key(key):
"""
Returns the key immediately following the input key - based on the Java implementation found in
org.apache.accumulo.core.data.Key, function followingKey(PartialKey part)
:param key: the key to be followed
:return: a key that immediately follows the input key
"""
i... | [
"def",
"following_key",
"(",
"key",
")",
":",
"if",
"key",
".",
"timestamp",
"is",
"not",
"None",
":",
"key",
".",
"timestamp",
"-=",
"1",
"elif",
"key",
".",
"colVisibility",
"is",
"not",
"None",
":",
"key",
".",
"colVisibility",
"=",
"following_array",... | 41.111111 | 14.222222 |
def get_portchannel_info_by_intf_output_lacp_actor_max_deskew(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf")
config = get_portchannel_info_by_intf
output = ET.SubElement(g... | [
"def",
"get_portchannel_info_by_intf_output_lacp_actor_max_deskew",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_portchannel_info_by_intf",
"=",
"ET",
".",
"Element",
"(",
"\"get_portchannel_info_by_... | 47.076923 | 18.076923 |
def check(
state,
unused=False,
style=False,
ignore=None,
args=None,
**kwargs
):
"""Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile."""
from ..core import do_check
do_check(
three=state.three,
python=state.python,
system=st... | [
"def",
"check",
"(",
"state",
",",
"unused",
"=",
"False",
",",
"style",
"=",
"False",
",",
"ignore",
"=",
"None",
",",
"args",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"core",
"import",
"do_check",
"do_check",
"(",
"three"... | 21.1 | 21.6 |
def delete_certificate_issuer(self, certificate_issuer_id, **kwargs): # noqa: E501
"""Delete certificate issuer. # noqa: E501
Delete a certificate issuer by ID. <br> **Example usage:** ``` curl -X DELETE \\ -H 'authorization: <valid access token>' \\ https://api.us-east-1.mbedcloud.com/v3/certificat... | [
"def",
"delete_certificate_issuer",
"(",
"self",
",",
"certificate_issuer_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
... | 62.619048 | 38.714286 |
def _ensure_sliding_windows(self, assets, dts, field,
is_perspective_after):
"""
Ensure that there is a Float64Multiply window for each asset that can
provide data for the given parameters.
If the corresponding window for the (assets, len(dts), field) does... | [
"def",
"_ensure_sliding_windows",
"(",
"self",
",",
"assets",
",",
"dts",
",",
"field",
",",
"is_perspective_after",
")",
":",
"end",
"=",
"dts",
"[",
"-",
"1",
"]",
"size",
"=",
"len",
"(",
"dts",
")",
"asset_windows",
"=",
"{",
"}",
"needed_assets",
... | 38.59434 | 17.990566 |
def flip_ctrlpts_u(ctrlpts, size_u, size_v):
""" Flips a list of 1-dimensional control points from u-row order to v-row order.
**u-row order**: each row corresponds to a list of u values
**v-row order**: each row corresponds to a list of v values
:param ctrlpts: control points in u-row order
:typ... | [
"def",
"flip_ctrlpts_u",
"(",
"ctrlpts",
",",
"size_u",
",",
"size_v",
")",
":",
"new_ctrlpts",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size_u",
")",
":",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"size_v",
")",
":",
"temp",
"="... | 31.434783 | 16.478261 |
def getNeighbors(trainingSet, testInstance, k, considerDimensions=None):
"""
collect the k most similar instances in the trainingSet for a given test
instance
:param trainingSet: A list of data instances
:param testInstance: a single data instance
:param k: number of neighbors
:param considerDimensions: a... | [
"def",
"getNeighbors",
"(",
"trainingSet",
",",
"testInstance",
",",
"k",
",",
"considerDimensions",
"=",
"None",
")",
":",
"if",
"considerDimensions",
"is",
"None",
":",
"considerDimensions",
"=",
"len",
"(",
"testInstance",
")",
"-",
"1",
"neighborList",
"="... | 32.769231 | 17.230769 |
def connect(self, host, port):
'''
Connect to a host and port.
'''
# Clear the connect state immediately since we're no longer connected
# at this point.
self._connected = False
# Only after the socket has connected do we clear this state; closed
# must b... | [
"def",
"connect",
"(",
"self",
",",
"host",
",",
"port",
")",
":",
"# Clear the connect state immediately since we're no longer connected",
"# at this point.",
"self",
".",
"_connected",
"=",
"False",
"# Only after the socket has connected do we clear this state; closed",
"# must... | 49.632653 | 25.346939 |
def cli(ctx, feature_id, old_db, old_accession, new_db, new_accession, organism="", sequence=""):
"""Delete a dbxref from a feature
Output:
A standard apollo feature dictionary ({"features": [{...}]})
"""
return ctx.gi.annotations.update_dbxref(feature_id, old_db, old_accession, new_db, new_accession,... | [
"def",
"cli",
"(",
"ctx",
",",
"feature_id",
",",
"old_db",
",",
"old_accession",
",",
"new_db",
",",
"new_accession",
",",
"organism",
"=",
"\"\"",
",",
"sequence",
"=",
"\"\"",
")",
":",
"return",
"ctx",
".",
"gi",
".",
"annotations",
".",
"update_dbxr... | 43.875 | 36.625 |
def optimize(initial_memory):
""" This will remove useless instructions
"""
global BLOCKS
global PROC_COUNTER
LABELS.clear()
JUMP_LABELS.clear()
del MEMORY[:]
PROC_COUNTER = 0
cleanupmem(initial_memory)
if OPTIONS.optimization.value <= 2:
return '\n'.join(x for x in ini... | [
"def",
"optimize",
"(",
"initial_memory",
")",
":",
"global",
"BLOCKS",
"global",
"PROC_COUNTER",
"LABELS",
".",
"clear",
"(",
")",
"JUMP_LABELS",
".",
"clear",
"(",
")",
"del",
"MEMORY",
"[",
":",
"]",
"PROC_COUNTER",
"=",
"0",
"cleanupmem",
"(",
"initial... | 29.090909 | 23.954545 |
def is_published(self):
"""Check fields 980 and 773 to see if the record has already been published.
:return: True is published, else False
"""
field773 = record_get_field_instances(self.record, '773')
for f773 in field773:
if 'c' in field_get_subfields(f773):
... | [
"def",
"is_published",
"(",
"self",
")",
":",
"field773",
"=",
"record_get_field_instances",
"(",
"self",
".",
"record",
",",
"'773'",
")",
"for",
"f773",
"in",
"field773",
":",
"if",
"'c'",
"in",
"field_get_subfields",
"(",
"f773",
")",
":",
"return",
"Tr... | 35.3 | 14 |
def input_fn(self,
mode,
hparams,
data_dir=None,
params=None,
config=None,
force_repeat=False,
prevent_repeat=False,
dataset_kwargs=None):
"""Builds input pipeline for problem.
Args:
mo... | [
"def",
"input_fn",
"(",
"self",
",",
"mode",
",",
"hparams",
",",
"data_dir",
"=",
"None",
",",
"params",
"=",
"None",
",",
"config",
"=",
"None",
",",
"force_repeat",
"=",
"False",
",",
"prevent_repeat",
"=",
"False",
",",
"dataset_kwargs",
"=",
"None",... | 34.877193 | 16.245614 |
def store(self, extractions: List[Extraction], attribute: str, group_by_tags: bool = True) -> None:
"""
Records extractions in the container, and for each individual extraction inserts a
ProvenanceRecord to record where the extraction is stored.
Records the "output_segment" in the proven... | [
"def",
"store",
"(",
"self",
",",
"extractions",
":",
"List",
"[",
"Extraction",
"]",
",",
"attribute",
":",
"str",
",",
"group_by_tags",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_value",
",",
"d... | 54.894737 | 31.026316 |
def read_tx_opreturn(vout: dict) -> bytes:
'''Decode OP_RETURN message from vout[1]'''
asm = vout['scriptPubKey']['asm']
n = asm.find('OP_RETURN')
if n == -1:
raise InvalidNulldataOutput({'error': 'OP_RETURN not found.'})
else:
# add 10 because 'OP_RETURN ' is 10 characters
... | [
"def",
"read_tx_opreturn",
"(",
"vout",
":",
"dict",
")",
"->",
"bytes",
":",
"asm",
"=",
"vout",
"[",
"'scriptPubKey'",
"]",
"[",
"'asm'",
"]",
"n",
"=",
"asm",
".",
"find",
"(",
"'OP_RETURN'",
")",
"if",
"n",
"==",
"-",
"1",
":",
"raise",
"Invali... | 31.529412 | 17.058824 |
def get(self):
"""
Fetches the current state of the alarm from the API and updates the
object.
"""
new_alarm = self.entity.get_alarm(self)
if new_alarm:
self._add_details(new_alarm._info) | [
"def",
"get",
"(",
"self",
")",
":",
"new_alarm",
"=",
"self",
".",
"entity",
".",
"get_alarm",
"(",
"self",
")",
"if",
"new_alarm",
":",
"self",
".",
"_add_details",
"(",
"new_alarm",
".",
"_info",
")"
] | 30 | 14.75 |
def generalize(self,
sr,
geometries,
maxDeviation,
deviationUnit):
"""
The generalize operation is performed on a geometry service resource.
The generalize operation simplifies the input geometries using the
Do... | [
"def",
"generalize",
"(",
"self",
",",
"sr",
",",
"geometries",
",",
"maxDeviation",
",",
"deviationUnit",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/generalize\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"sr\"",
":",
"sr",
",",
"... | 49.117647 | 22.941176 |
def create_or_update_resource(resource_name, identifier_fields, data, diff=None, profile='pagerduty', subdomain=None, api_key=None):
'''
create or update any pagerduty resource
Helper method for present().
Determining if two resources are the same is different for different PD resource, so this method ... | [
"def",
"create_or_update_resource",
"(",
"resource_name",
",",
"identifier_fields",
",",
"data",
",",
"diff",
"=",
"None",
",",
"profile",
"=",
"'pagerduty'",
",",
"subdomain",
"=",
"None",
",",
"api_key",
"=",
"None",
")",
":",
"# try to locate the resource by an... | 48.763636 | 30.218182 |
def url(self):
"""
Returns the URL for the current transformation, which can be used
to retrieve the file. If security is enabled, signature and policy parameters will
be included
*returns* [String]
```python
transform = client.upload(filepath='/path/to/file')
... | [
"def",
"url",
"(",
"self",
")",
":",
"return",
"utils",
".",
"get_transform_url",
"(",
"self",
".",
"_transformation_tasks",
",",
"external_url",
"=",
"self",
".",
"external_url",
",",
"handle",
"=",
"self",
".",
"handle",
",",
"security",
"=",
"self",
"."... | 34 | 24.111111 |
def get_function_from_settings(settings_key):
"""Gets a function from the string path defined in a settings file.
Example:
# my_app/my_file.py
def some_function():
# do something
pass
# settings.py
SOME_FUNCTION = 'my_app.my_file.some_function'
> get_function_from_setting... | [
"def",
"get_function_from_settings",
"(",
"settings_key",
")",
":",
"renderer_func_str",
"=",
"getattr",
"(",
"settings",
",",
"settings_key",
",",
"None",
")",
"if",
"not",
"renderer_func_str",
":",
"return",
"None",
"module_str",
",",
"renderer_func_name",
"=",
... | 24.892857 | 21.678571 |
def cut_off_drivers_of(dstSignal, statements):
"""
Cut off drivers from statements
"""
separated = []
stm_filter = []
for stm in statements:
stm._clean_signal_meta()
d = stm._cut_off_drivers_of(dstSignal)
if d is not None:
separated.append(d)
f = d is... | [
"def",
"cut_off_drivers_of",
"(",
"dstSignal",
",",
"statements",
")",
":",
"separated",
"=",
"[",
"]",
"stm_filter",
"=",
"[",
"]",
"for",
"stm",
"in",
"statements",
":",
"stm",
".",
"_clean_signal_meta",
"(",
")",
"d",
"=",
"stm",
".",
"_cut_off_drivers_... | 25.25 | 14.625 |
def fill(self, paths):
"""
Initialise the tree.
paths is a list of strings where each string is the relative path to some
file.
"""
for path in paths:
tree = self.tree
parts = tuple(path.split('/'))
dir_parts = parts[:-1]
b... | [
"def",
"fill",
"(",
"self",
",",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"tree",
"=",
"self",
".",
"tree",
"parts",
"=",
"tuple",
"(",
"path",
".",
"split",
"(",
"'/'",
")",
")",
"dir_parts",
"=",
"parts",
"[",
":",
"-",
"1",
"]",... | 33.090909 | 15.818182 |
def autodoc_module(module):
"""Add a short summary of all implemented members to a modules docstring.
"""
doc = getattr(module, '__doc__')
if doc is None:
doc = ''
members = []
for name, member in inspect.getmembers(module):
if ((not name.startswith('_')) and
(ins... | [
"def",
"autodoc_module",
"(",
"module",
")",
":",
"doc",
"=",
"getattr",
"(",
"module",
",",
"'__doc__'",
")",
"if",
"doc",
"is",
"None",
":",
"doc",
"=",
"''",
"members",
"=",
"[",
"]",
"for",
"name",
",",
"member",
"in",
"inspect",
".",
"getmembers... | 38.615385 | 12.538462 |
def _to_dict(self, node, fast_access=True, short_names=False, nested=False,
copy=True, with_links=True):
""" Returns a dictionary with pairings of (full) names as keys and instances as values.
:param fast_access:
If true parameter or result values are returned instead of t... | [
"def",
"_to_dict",
"(",
"self",
",",
"node",
",",
"fast_access",
"=",
"True",
",",
"short_names",
"=",
"False",
",",
"nested",
"=",
"False",
",",
"copy",
"=",
"True",
",",
"with_links",
"=",
"True",
")",
":",
"if",
"(",
"fast_access",
"or",
"short_name... | 33.512821 | 23.717949 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.