text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def cmd_set_homepos(self, args):
'''called when user selects "Set Home" on map'''
(lat, lon) = (self.click_position[0], self.click_position[1])
print("Setting home to: ", lat, lon)
self.master.mav.command_int_send(
self.settings.target_system, self.settings.target_component,
... | [
"def",
"cmd_set_homepos",
"(",
"self",
",",
"args",
")",
":",
"(",
"lat",
",",
"lon",
")",
"=",
"(",
"self",
".",
"click_position",
"[",
"0",
"]",
",",
"self",
".",
"click_position",
"[",
"1",
"]",
")",
"print",
"(",
"\"Setting home to: \"",
",",
"la... | 37.941176 | 15.235294 |
def next(self):
"""
Return all files in folder.
"""
# get depth of starting root directory
base_depth = self.__root.count(os.path.sep)
# walk files and folders
for root, subFolders, files in os.walk(self.__root):
# apply folder filter
if ... | [
"def",
"next",
"(",
"self",
")",
":",
"# get depth of starting root directory",
"base_depth",
"=",
"self",
".",
"__root",
".",
"count",
"(",
"os",
".",
"path",
".",
"sep",
")",
"# walk files and folders",
"for",
"root",
",",
"subFolders",
",",
"files",
"in",
... | 28.870968 | 16.225806 |
def page(request):
"""
Adds the current page to the template context and runs its
``set_helper`` method. This was previously part of
``PageMiddleware``, but moved to a context processor so that
we could assign these template context variables without
the middleware depending on Django's ``Templa... | [
"def",
"page",
"(",
"request",
")",
":",
"context",
"=",
"{",
"}",
"page",
"=",
"getattr",
"(",
"request",
",",
"\"page\"",
",",
"None",
")",
"if",
"isinstance",
"(",
"page",
",",
"Page",
")",
":",
"# set_helpers has always expected the current template contex... | 42.411765 | 17 |
def send_work(self):
'''Sends the query to the actor for it to start executing the
work.
It is possible to execute once again a future that has finished
if necessary (overwriting the results), but only one execution
at a time.
'''
if self.__set_running():
... | [
"def",
"send_work",
"(",
"self",
")",
":",
"if",
"self",
".",
"__set_running",
"(",
")",
":",
"# msg = FutureRequest(FUTURE, self.__method, self.__params,",
"# self.__channel, self.__target, self.__id)",
"msg",
"=",
"{",
"TYPE",
":",
"FUTURE",
",",
"ME... | 43.411765 | 24.117647 |
def str_repeat(arr, repeats):
"""
Duplicate each string in the Series or Index.
Parameters
----------
repeats : int or sequence of int
Same value for all (int) or different value per (sequence).
Returns
-------
Series or Index of object
Series or Index of repeated strin... | [
"def",
"str_repeat",
"(",
"arr",
",",
"repeats",
")",
":",
"if",
"is_scalar",
"(",
"repeats",
")",
":",
"def",
"scalar_rep",
"(",
"x",
")",
":",
"try",
":",
"return",
"bytes",
".",
"__mul__",
"(",
"x",
",",
"repeats",
")",
"except",
"TypeError",
":",... | 21.915254 | 21.711864 |
def _pretty_dump(self, label, data):
"""Print modbus/TCP frame ('[header]body')
or RTU ('body[CRC]') on stdout
:param label: modbus function code
:type label: str
:param data: modbus frame
:type data: str (Python2) or class bytes (Python3)
"""
# split dat... | [
"def",
"_pretty_dump",
"(",
"self",
",",
"label",
",",
"data",
")",
":",
"# split data string items to a list of hex value",
"dump",
"=",
"[",
"'%02X'",
"%",
"c",
"for",
"c",
"in",
"bytearray",
"(",
"data",
")",
"]",
"# format for TCP or RTU",
"if",
"self",
".... | 31.821429 | 11.571429 |
def reset(self):
"""Reset stacks and instruction pointer."""
self.data_stack = stack.Stack()
self.return_stack = stack.Stack()
self.instruction_pointer = 0
return self | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"data_stack",
"=",
"stack",
".",
"Stack",
"(",
")",
"self",
".",
"return_stack",
"=",
"stack",
".",
"Stack",
"(",
")",
"self",
".",
"instruction_pointer",
"=",
"0",
"return",
"self"
] | 33.666667 | 8.5 |
def compute_etag(self) -> Optional[str]:
"""Sets the ``Etag`` header based on static url version.
This allows efficient ``If-None-Match`` checks against cached
versions, and sends the correct ``Etag`` for a partial response
(i.e. the same ``Etag`` as the full file).
.. versiona... | [
"def",
"compute_etag",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"assert",
"self",
".",
"absolute_path",
"is",
"not",
"None",
"version_hash",
"=",
"self",
".",
"_get_cached_version",
"(",
"self",
".",
"absolute_path",
")",
"if",
"not",
"ver... | 38.285714 | 15.928571 |
def _fw_rule_create(self, drvr_name, data, cache):
"""Firewall Rule create routine.
This function updates its local cache with rule parameters.
It checks if local cache has information about the Policy
associated with the rule. If not, it means a restart has happened.
It retriev... | [
"def",
"_fw_rule_create",
"(",
"self",
",",
"drvr_name",
",",
"data",
",",
"cache",
")",
":",
"tenant_id",
"=",
"data",
".",
"get",
"(",
"'firewall_rule'",
")",
".",
"get",
"(",
"'tenant_id'",
")",
"fw_rule",
"=",
"data",
".",
"get",
"(",
"'firewall_rule... | 50.08 | 16.68 |
def temporary_chdir(new_dir):
"""
Like os.chdir(), but always restores the old working directory
For example, code like this...
old_curdir = os.getcwd()
os.chdir('stuff')
do_some_stuff()
os.chdir(old_curdir)
...leaves the current working directory unchanged if do_some_... | [
"def",
"temporary_chdir",
"(",
"new_dir",
")",
":",
"old_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"new_dir",
")",
"try",
":",
"yield",
"finally",
":",
"os",
".",
"chdir",
"(",
"old_dir",
")"
] | 22.8125 | 20.0625 |
def create_new_dispatch(self, dispatch):
"""
Create a new dispatch
:param dispatch:
is the new dispatch that the client wants to create
"""
self._validate_uuid(dispatch.dispatch_id)
# Create new dispatch
url = "/notification/v1/dispatch"
post_resp... | [
"def",
"create_new_dispatch",
"(",
"self",
",",
"dispatch",
")",
":",
"self",
".",
"_validate_uuid",
"(",
"dispatch",
".",
"dispatch_id",
")",
"# Create new dispatch",
"url",
"=",
"\"/notification/v1/dispatch\"",
"post_response",
"=",
"NWS_DAO",
"(",
")",
".",
"po... | 34.588235 | 12.705882 |
def _get_close_args(self, data):
""" this functions extracts the code, reason from the close body
if they exists, and if the self.on_close except three arguments """
# if the on_close callback is "old", just return empty list
if sys.version_info < (3, 0):
if not self.on_close... | [
"def",
"_get_close_args",
"(",
"self",
",",
"data",
")",
":",
"# if the on_close callback is \"old\", just return empty list",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"if",
"not",
"self",
".",
"on_close",
"or",
"len",
"(",
"inspect... | 43.176471 | 19.588235 |
def is_annual(self):
"""Check if an analysis period is annual."""
if (self.st_month, self.st_day, self.st_hour, self.end_month,
self.end_day, self.end_hour) == (1, 1, 0, 12, 31, 23):
return True
else:
return False | [
"def",
"is_annual",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"st_month",
",",
"self",
".",
"st_day",
",",
"self",
".",
"st_hour",
",",
"self",
".",
"end_month",
",",
"self",
".",
"end_day",
",",
"self",
".",
"end_hour",
")",
"==",
"(",
"1",
... | 39.857143 | 18.714286 |
def add_binary_content_type(application, content_type, pack, unpack):
"""
Add handler for a binary content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param pack: function that packs a dictionary to a byte string.
... | [
"def",
"add_binary_content_type",
"(",
"application",
",",
"content_type",
",",
"pack",
",",
"unpack",
")",
":",
"add_transcoder",
"(",
"application",
",",
"handlers",
".",
"BinaryContentHandler",
"(",
"content_type",
",",
"pack",
",",
"unpack",
")",
")"
] | 40.571429 | 19.285714 |
def makeEndOfPrdvFuncCond(self):
'''
Construct the end-of-period value function conditional on next period's
state. NOTE: It might be possible to eliminate this method and replace
it with ConsIndShockSolver.makeEndOfPrdvFunc, but the self.X_cond
variables must be renamed.
... | [
"def",
"makeEndOfPrdvFuncCond",
"(",
"self",
")",
":",
"VLvlNext",
"=",
"(",
"self",
".",
"PermShkVals_temp",
"**",
"(",
"1.0",
"-",
"self",
".",
"CRRA",
")",
"*",
"self",
".",
"PermGroFac",
"**",
"(",
"1.0",
"-",
"self",
".",
"CRRA",
")",
")",
"*",
... | 49.535714 | 29.75 |
def update(self, **kwargs):
''' validates the given data against this object's rules and then
updates '''
redis = type(self).get_redis()
errors = ValidationErrors()
for fieldname, field in self.proxy:
if not field.fillable:
continue
given... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"redis",
"=",
"type",
"(",
"self",
")",
".",
"get_redis",
"(",
")",
"errors",
"=",
"ValidationErrors",
"(",
")",
"for",
"fieldname",
",",
"field",
"in",
"self",
".",
"proxy",
":",
"if... | 23.935484 | 20.258065 |
def init(deb1, deb2=False):
"""Initialize DEBUG and DEBUGALL.
Allows other modules to set DEBUG and DEBUGALL, so their
call to dprint or dprintx generate output.
Args:
deb1 (bool): value of DEBUG to set
deb2 (bool): optional - value of DEBUGALL to set,
defaults to ... | [
"def",
"init",
"(",
"deb1",
",",
"deb2",
"=",
"False",
")",
":",
"global",
"DEBUG",
"# pylint: disable=global-statement",
"global",
"DEBUGALL",
"# pylint: disable=global-statement",
"DEBUG",
"=",
"deb1",
"DEBUGALL",
"=",
"deb2"
] | 29.6875 | 18.1875 |
def __get_labels(self):
"""
Read the label file of the documents and extract all the labels
Returns:
An array of labels.Label objects
"""
labels = []
try:
with self.fs.open(self.fs.join(self.path, self.LABEL_FILE),
... | [
"def",
"__get_labels",
"(",
"self",
")",
":",
"labels",
"=",
"[",
"]",
"try",
":",
"with",
"self",
".",
"fs",
".",
"open",
"(",
"self",
".",
"fs",
".",
"join",
"(",
"self",
".",
"path",
",",
"self",
".",
"LABEL_FILE",
")",
",",
"'r'",
")",
"as"... | 34.631579 | 17.789474 |
def parseconf (self, filename):
"""Parse clamav configuration from given file."""
with open(filename) as fd:
# yet another config format, sigh
for line in fd:
line = line.strip()
if not line or line.startswith("#"):
# ignore emp... | [
"def",
"parseconf",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fd",
":",
"# yet another config format, sigh",
"for",
"line",
"in",
"fd",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not",
"line",
"o... | 39.071429 | 7.714286 |
def ifusergroup(parser, token):
""" Check to see if the currently logged in user belongs to a specific
group. Requires the Django authentication contrib app and middleware.
Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or
{% ifusergroup Admins Clients Sellers %} ... {% else %} ... {%... | [
"def",
"ifusergroup",
"(",
"parser",
",",
"token",
")",
":",
"try",
":",
"tokensp",
"=",
"token",
".",
"split_contents",
"(",
")",
"groups",
"=",
"[",
"]",
"groups",
"+=",
"tokensp",
"[",
"1",
":",
"]",
"except",
"ValueError",
":",
"raise",
"template",... | 35.2 | 23.24 |
def create_checksum_object_from_iterator(
itr, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM
):
"""Calculate the checksum of an iterator.
Args:
itr: iterable
Object which supports the iterator protocol.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
... | [
"def",
"create_checksum_object_from_iterator",
"(",
"itr",
",",
"algorithm",
"=",
"d1_common",
".",
"const",
".",
"DEFAULT_CHECKSUM_ALGORITHM",
")",
":",
"checksum_str",
"=",
"calculate_checksum_on_iterator",
"(",
"itr",
",",
"algorithm",
")",
"checksum_pyxb",
"=",
"d... | 28.2 | 21.4 |
def subset_sum(x, R):
"""Subsetsum
:param x: table of non negative values
:param R: target value
:returns bool: True if a subset of x sums to R
:complexity: O(n*R)
"""
b = [False] * (R + 1)
b[0] = True
for xi in x:
for s in range(R, xi - 1, -1):
b[s] |= b[s - xi]... | [
"def",
"subset_sum",
"(",
"x",
",",
"R",
")",
":",
"b",
"=",
"[",
"False",
"]",
"*",
"(",
"R",
"+",
"1",
")",
"b",
"[",
"0",
"]",
"=",
"True",
"for",
"xi",
"in",
"x",
":",
"for",
"s",
"in",
"range",
"(",
"R",
",",
"xi",
"-",
"1",
",",
... | 23.071429 | 14.571429 |
def delete_certificate(ctx, slot, management_key, pin):
"""
Delete a certificate.
Delete a certificate from a slot on the YubiKey.
"""
controller = ctx.obj['controller']
_ensure_authenticated(ctx, controller, pin, management_key)
controller.delete_certificate(slot) | [
"def",
"delete_certificate",
"(",
"ctx",
",",
"slot",
",",
"management_key",
",",
"pin",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"_ensure_authenticated",
"(",
"ctx",
",",
"controller",
",",
"pin",
",",
"management_key",
")",... | 31.777778 | 12 |
def print_diskinfo(diskinfo, widelayout, incolor):
''' Disk information output function. '''
sep = ' '
if opts.relative:
import math
base = max([ disk.ocap for disk in diskinfo ])
for disk in diskinfo:
if disk.ismntd: ico = _diskico
else: ico = _unmnico... | [
"def",
"print_diskinfo",
"(",
"diskinfo",
",",
"widelayout",
",",
"incolor",
")",
":",
"sep",
"=",
"' '",
"if",
"opts",
".",
"relative",
":",
"import",
"math",
"base",
"=",
"max",
"(",
"[",
"disk",
".",
"ocap",
"for",
"disk",
"in",
"diskinfo",
"]",
"... | 34 | 19.52381 |
def read_config(conf_dir=DEFAULT_CONFIG_DIR):
"Find and read config file for a directory, return None if not found."
conf_path = os.path.expanduser(conf_dir)
if not os.path.exists(conf_path):
# only throw if not default
if conf_dir != DEFAULT_CONFIG_DIR:
raise IOError("Config di... | [
"def",
"read_config",
"(",
"conf_dir",
"=",
"DEFAULT_CONFIG_DIR",
")",
":",
"conf_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"conf_dir",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"conf_path",
")",
":",
"# only throw if not default"... | 41.9 | 19.5 |
def action_verify_checksum(self, ids):
"""Inactivate users."""
try:
count = 0
for file_id in ids:
f = FileInstance.query.filter_by(
id=uuid.UUID(file_id)).one_or_none()
if f is None:
raise ValueError(_("Canno... | [
"def",
"action_verify_checksum",
"(",
"self",
",",
"ids",
")",
":",
"try",
":",
"count",
"=",
"0",
"for",
"file_id",
"in",
"ids",
":",
"f",
"=",
"FileInstance",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"uuid",
".",
"UUID",
"(",
"file_id",
")",... | 39.684211 | 14.789474 |
def readLipd(usr_path=""):
"""
Read LiPD file(s).
Enter a file path, directory path, or leave args blank to trigger gui.
:param str usr_path: Path to file / directory (optional)
:return dict _d: Metadata
"""
global cwd, settings, files
if settings["verbose"]:
__disclaimer(opt="u... | [
"def",
"readLipd",
"(",
"usr_path",
"=",
"\"\"",
")",
":",
"global",
"cwd",
",",
"settings",
",",
"files",
"if",
"settings",
"[",
"\"verbose\"",
"]",
":",
"__disclaimer",
"(",
"opt",
"=",
"\"update\"",
")",
"start",
"=",
"clock",
"(",
")",
"files",
"["... | 28.388889 | 16.611111 |
def get(self,key,default=None):
"""Get a value from the dictionary.
Args:
key (str): The dictionary key.
default (any): The default to return if the key is not in the
dictionary. Defaults to None.
Returns:
str or any: The dictionary value or ... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"retval",
"=",
"self",
".",
"__getitem__",
"(",
"key",
")",
"if",
"not",
"retval",
":",
"retval",
"=",
"default",
"return",
"retval"
] | 27.444444 | 19.666667 |
def start(self):
''' doesn't work'''
thread = threading.Thread(target=reactor.run)
thread.start() | [
"def",
"start",
"(",
"self",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"reactor",
".",
"run",
")",
"thread",
".",
"start",
"(",
")"
] | 29.5 | 17 |
def hexadecimal(token):
"""
Convert a strip of hexadecimal numbers into binary data.
@type token: str
@param token: String to parse.
@rtype: str
@return: Parsed string value.
"""
token = ''.join([ c for c in token if c.isalnum() ])
if len(token... | [
"def",
"hexadecimal",
"(",
"token",
")",
":",
"token",
"=",
"''",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"token",
"if",
"c",
".",
"isalnum",
"(",
")",
"]",
")",
"if",
"len",
"(",
"token",
")",
"%",
"2",
"!=",
"0",
":",
"raise",
"ValueE... | 28.9 | 15.7 |
def get_gpg_home( appname, config_dir=None ):
"""
Get the GPG keyring directory for a particular application.
Return the path.
"""
assert is_valid_appname(appname)
config_dir = get_config_dir( config_dir )
path = os.path.join( config_dir, "gpgkeys", appname )
return path | [
"def",
"get_gpg_home",
"(",
"appname",
",",
"config_dir",
"=",
"None",
")",
":",
"assert",
"is_valid_appname",
"(",
"appname",
")",
"config_dir",
"=",
"get_config_dir",
"(",
"config_dir",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config_dir",
... | 32.777778 | 11 |
def add_member(self, user, state=MembershipState.ACTIVE):
"""Invite a user to a group.
:param user: User to be added as a group member.
:param state: MembershipState. Default: MembershipState.ACTIVE.
:returns: Membership object or None.
"""
return Membership.create(self,... | [
"def",
"add_member",
"(",
"self",
",",
"user",
",",
"state",
"=",
"MembershipState",
".",
"ACTIVE",
")",
":",
"return",
"Membership",
".",
"create",
"(",
"self",
",",
"user",
",",
"state",
")"
] | 40.75 | 14.875 |
def touch_project():
"""
Touches the project to trigger refreshing its cauldron.json state.
"""
r = Response()
project = cd.project.get_internal_project()
if project:
project.refresh()
else:
r.fail(
code='NO_PROJECT',
message='No open project to refre... | [
"def",
"touch_project",
"(",
")",
":",
"r",
"=",
"Response",
"(",
")",
"project",
"=",
"cd",
".",
"project",
".",
"get_internal_project",
"(",
")",
"if",
"project",
":",
"project",
".",
"refresh",
"(",
")",
"else",
":",
"r",
".",
"fail",
"(",
"code",... | 22.611111 | 19.166667 |
def max_width(self):
"""Get maximum width of progress bar
:rtype: int
:returns: Maximum column width of progress bar
"""
value, unit = float(self._width_str[:-1]), self._width_str[-1]
ensure(unit in ["c", "%"], ValueError,
"Width unit must be either 'c' o... | [
"def",
"max_width",
"(",
"self",
")",
":",
"value",
",",
"unit",
"=",
"float",
"(",
"self",
".",
"_width_str",
"[",
":",
"-",
"1",
"]",
")",
",",
"self",
".",
"_width_str",
"[",
"-",
"1",
"]",
"ensure",
"(",
"unit",
"in",
"[",
"\"c\"",
",",
"\"... | 34.73913 | 19.130435 |
def sleep(duration):
'''
Sleeps for duration seconds in increments of 0.5 seconds.
Use this so that the sleep can be interrupted by thread_raise().
'''
import time
start = time.time()
while True:
elapsed = time.time() - start
if elapsed >= duration:
break
... | [
"def",
"sleep",
"(",
"duration",
")",
":",
"import",
"time",
"start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"elapsed",
"=",
"time",
".",
"time",
"(",
")",
"-",
"start",
"if",
"elapsed",
">=",
"duration",
":",
"break",
"time",
".... | 26.846154 | 21.923077 |
def _FormatTypeCheck(type_):
"""Pretty format of type check."""
if isinstance(type_, tuple):
items = [_FormatTypeCheck(t) for t in type_]
return "(%s)" % ", ".join(items)
elif hasattr(type_, "__name__"):
return type_.__name__
else:
return repr(type_) | [
"def",
"_FormatTypeCheck",
"(",
"type_",
")",
":",
"if",
"isinstance",
"(",
"type_",
",",
"tuple",
")",
":",
"items",
"=",
"[",
"_FormatTypeCheck",
"(",
"t",
")",
"for",
"t",
"in",
"type_",
"]",
"return",
"\"(%s)\"",
"%",
"\", \"",
".",
"join",
"(",
... | 29.555556 | 11.777778 |
def printParams(paramDictionary, all=False, log=None):
"""
Print nicely the parameters from the dictionary.
"""
if log is not None:
def output(msg):
log.info(msg)
else:
def output(msg):
print(msg)
if not paramDictionary:
output('No parameters wer... | [
"def",
"printParams",
"(",
"paramDictionary",
",",
"all",
"=",
"False",
",",
"log",
"=",
"None",
")",
":",
"if",
"log",
"is",
"not",
"None",
":",
"def",
"output",
"(",
"msg",
")",
":",
"log",
".",
"info",
"(",
"msg",
")",
"else",
":",
"def",
"out... | 29.181818 | 17.636364 |
def add(self, operator, *args):
"""Adds a proximal operator to the list of operators"""
if isinstance(operator, str):
op = getattr(proxops, operator)(*args)
elif isinstance(operator, proxops.ProximalOperatorBaseClass):
op = operator
else:
raise ValueE... | [
"def",
"add",
"(",
"self",
",",
"operator",
",",
"*",
"args",
")",
":",
"if",
"isinstance",
"(",
"operator",
",",
"str",
")",
":",
"op",
"=",
"getattr",
"(",
"proxops",
",",
"operator",
")",
"(",
"*",
"args",
")",
"elif",
"isinstance",
"(",
"operat... | 35.916667 | 21 |
def xml_parser(self, scode, *args):
"""
args[0]: xpath
args[1]: text / html / xml
"""
allow_method = ('text', 'html', 'xml')
xpath_string, method = args
assert method in allow_method, 'method allow: %s' % allow_method
result = self.ensure_list(
... | [
"def",
"xml_parser",
"(",
"self",
",",
"scode",
",",
"*",
"args",
")",
":",
"allow_method",
"=",
"(",
"'text'",
",",
"'html'",
",",
"'xml'",
")",
"xpath_string",
",",
"method",
"=",
"args",
"assert",
"method",
"in",
"allow_method",
",",
"'method allow: %s'... | 32.388889 | 15.611111 |
async def _default_help_command(ctx, *commands : str):
"""Shows this message."""
bot = ctx.bot
destination = ctx.message.author if bot.pm_help else ctx.message.channel
def repl(obj):
return _mentions_transforms.get(obj.group(0), '')
# help by itself just lists our own commands.
if len(... | [
"async",
"def",
"_default_help_command",
"(",
"ctx",
",",
"*",
"commands",
":",
"str",
")",
":",
"bot",
"=",
"ctx",
".",
"bot",
"destination",
"=",
"ctx",
".",
"message",
".",
"author",
"if",
"bot",
".",
"pm_help",
"else",
"ctx",
".",
"message",
".",
... | 39.72 | 23.46 |
def get_preservation_data(self):
"""Returns a list of Preservation data
"""
for obj in self.get_preservations():
info = self.get_base_info(obj)
yield info | [
"def",
"get_preservation_data",
"(",
"self",
")",
":",
"for",
"obj",
"in",
"self",
".",
"get_preservations",
"(",
")",
":",
"info",
"=",
"self",
".",
"get_base_info",
"(",
"obj",
")",
"yield",
"info"
] | 32.833333 | 5.333333 |
def update_dimension(dimension,**kwargs):
"""
Update a dimension in the DB.
Raises and exception if the dimension does not exist.
The key is ALWAYS the name and the name itself is not modificable
"""
db_dimension = None
dimension = JSONObject(dimension)
try:
db_dimens... | [
"def",
"update_dimension",
"(",
"dimension",
",",
"*",
"*",
"kwargs",
")",
":",
"db_dimension",
"=",
"None",
"dimension",
"=",
"JSONObject",
"(",
"dimension",
")",
"try",
":",
"db_dimension",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Dimension",
")"... | 43.714286 | 26.952381 |
def _list_model(self, model_cls: Type[X]) -> List[X]:
"""List the models in this class."""
return self.session.query(model_cls).all() | [
"def",
"_list_model",
"(",
"self",
",",
"model_cls",
":",
"Type",
"[",
"X",
"]",
")",
"->",
"List",
"[",
"X",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"model_cls",
")",
".",
"all",
"(",
")"
] | 49 | 7.666667 |
def encode_list(data, encoding=None, errors='strict', keep=False,
preserve_dict_class=False, preserve_tuples=False):
'''
Encode all string values to bytes
'''
rv = []
for item in data:
if isinstance(item, list):
item = encode_list(item, encoding, errors, keep,
... | [
"def",
"encode_list",
"(",
"data",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"keep",
"=",
"False",
",",
"preserve_dict_class",
"=",
"False",
",",
"preserve_tuples",
"=",
"False",
")",
":",
"rv",
"=",
"[",
"]",
"for",
"item",
"i... | 41.125 | 21.5 |
def read_config(self, path):
"""Read configuration file."""
PYVLXLOG.info('Reading config file: %s', path)
try:
with open(path, 'r') as filehandle:
doc = yaml.safe_load(filehandle)
self.test_configuration(doc, path)
self.host = doc['con... | [
"def",
"read_config",
"(",
"self",
",",
"path",
")",
":",
"PYVLXLOG",
".",
"info",
"(",
"'Reading config file: %s'",
",",
"path",
")",
"try",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"filehandle",
":",
"doc",
"=",
"yaml",
".",
"safe_loa... | 45.307692 | 11.769231 |
def _indent_line(self, line, stripspace=''):
"""indent the given line according to the current indent level.
stripspace is a string of space that will be truncated from the
start of the line before indenting."""
return re.sub(r"^%s" % stripspace, self.indentstring
... | [
"def",
"_indent_line",
"(",
"self",
",",
"line",
",",
"stripspace",
"=",
"''",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r\"^%s\"",
"%",
"stripspace",
",",
"self",
".",
"indentstring",
"*",
"self",
".",
"indent",
",",
"line",
")"
] | 41.75 | 17.125 |
def _get_init_args(self, skip=4):
"""Get all arguments of current layer for saving the graph."""
stack = inspect.stack()
if len(stack) < skip + 1:
raise ValueError("The length of the inspection stack is shorter than the requested start position.")
args, _, _, values = inspe... | [
"def",
"_get_init_args",
"(",
"self",
",",
"skip",
"=",
"4",
")",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"if",
"len",
"(",
"stack",
")",
"<",
"skip",
"+",
"1",
":",
"raise",
"ValueError",
"(",
"\"The length of the inspection stack is shorter... | 37.137931 | 26.448276 |
def get_attachment(self, ticket_id, attachment_id):
""" Get attachment.
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment for obtain
:returns: Attachment as dictionary with these keys:
* Transaction
* ContentType
... | [
"def",
"get_attachment",
"(",
"self",
",",
"ticket_id",
",",
"attachment_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/attachments/{}'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
"str",
"(",
"attachment_id",
")",
")",
"... | 43.47191 | 18.955056 |
def compute_eigen(self, n_comps=15, sym=None, sort='decrease'):
"""Compute eigen decomposition of transition matrix.
Parameters
----------
n_comps : `int`
Number of eigenvalues/vectors to be computed, set `n_comps = 0` if
you need all eigenvectors.
sym : ... | [
"def",
"compute_eigen",
"(",
"self",
",",
"n_comps",
"=",
"15",
",",
"sym",
"=",
"None",
",",
"sort",
"=",
"'decrease'",
")",
":",
"np",
".",
"set_printoptions",
"(",
"precision",
"=",
"10",
")",
"if",
"self",
".",
"_transitions_sym",
"is",
"None",
":"... | 45.351852 | 20.518519 |
def show_ntp_output_node_active_server_rbridge_id_out(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_ntp = ET.Element("show_ntp")
config = show_ntp
output = ET.SubElement(show_ntp, "output")
node_active_server = ET.SubElement(output... | [
"def",
"show_ntp_output_node_active_server_rbridge_id_out",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_ntp",
"=",
"ET",
".",
"Element",
"(",
"\"show_ntp\"",
")",
"config",
"=",
"show_ntp",... | 42.923077 | 16.230769 |
def load_config(self, config):
"""Load outdated parameter in the global section of the configuration file."""
global_section = 'global'
if (hasattr(config, 'has_section') and
config.has_section(global_section)):
self.args.disable_check_update = config.get_value(globa... | [
"def",
"load_config",
"(",
"self",
",",
"config",
")",
":",
"global_section",
"=",
"'global'",
"if",
"(",
"hasattr",
"(",
"config",
",",
"'has_section'",
")",
"and",
"config",
".",
"has_section",
"(",
"global_section",
")",
")",
":",
"self",
".",
"args",
... | 42.833333 | 25.833333 |
def estimate_optim(data, testfile, ipyclient):
"""
Estimate a reasonable optim value by grabbing a chunk of sequences,
decompressing and counting them, to estimate the full file size.
"""
## count the len of one file and assume all others are similar len
insize = os.path.getsize(testfile)
... | [
"def",
"estimate_optim",
"(",
"data",
",",
"testfile",
",",
"ipyclient",
")",
":",
"## count the len of one file and assume all others are similar len",
"insize",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"testfile",
")",
"tmp_file_name",
"=",
"os",
".",
"path",
... | 37.833333 | 19.133333 |
def save_data(self,session, exp_id, content):
'''save data will obtain the current subid from the session, and save it
depending on the database type.'''
from expfactory.database.models import (
Participant,
Result
)
subid = session.get('subid')
bot.info('Saving data for subi... | [
"def",
"save_data",
"(",
"self",
",",
"session",
",",
"exp_id",
",",
"content",
")",
":",
"from",
"expfactory",
".",
"database",
".",
"models",
"import",
"(",
"Participant",
",",
"Result",
")",
"subid",
"=",
"session",
".",
"get",
"(",
"'subid'",
")",
... | 34.833333 | 18.633333 |
def connect(self):
"""
Starts up an authentication session for the client using cookie
authentication if necessary.
"""
if self.r_session:
self.session_logout()
if self.admin_party:
self._use_iam = False
self.r_session = ClientSession(... | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"r_session",
":",
"self",
".",
"session_logout",
"(",
")",
"if",
"self",
".",
"admin_party",
":",
"self",
".",
"_use_iam",
"=",
"False",
"self",
".",
"r_session",
"=",
"ClientSession",
"(",
"t... | 34.12 | 14.72 |
def factory(self, data, manager=None):
"""Factory func for filters.
data - policy config for filters
manager - resource type manager (ec2, s3, etc)
"""
# Make the syntax a little nicer for common cases.
if isinstance(data, dict) and len(data) == 1 and 'type' not in data... | [
"def",
"factory",
"(",
"self",
",",
"data",
",",
"manager",
"=",
"None",
")",
":",
"# Make the syntax a little nicer for common cases.",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
"and",
"len",
"(",
"data",
")",
"==",
"1",
"and",
"'type'",
"not",
"... | 36.545455 | 10.212121 |
def add_done_callback(self, fn):
"""Adds a callback to be completed once future is done
:parm fn: A callable that takes no arguments. Note that is different
than concurrent.futures.Future.add_done_callback that requires
a single argument for the future.
"""
# The... | [
"def",
"add_done_callback",
"(",
"self",
",",
"fn",
")",
":",
"# The done callback for concurrent.futures.Future will always pass a",
"# the future in as the only argument. So we need to create the",
"# proper signature wrapper that will invoke the callback provided.",
"def",
"done_callback"... | 49.923077 | 20.461538 |
def event_return(events):
'''
Send the events to a mattermost room.
:param events: List of events
:return: Boolean if messages were sent successfully.
'''
_options = _get_options()
api_url = _options.get('api_url')
channel = _options.get('channel')
username = _optio... | [
"def",
"event_return",
"(",
"events",
")",
":",
"_options",
"=",
"_get_options",
"(",
")",
"api_url",
"=",
"_options",
".",
"get",
"(",
"'api_url'",
")",
"channel",
"=",
"_options",
".",
"get",
"(",
"'channel'",
")",
"username",
"=",
"_options",
".",
"ge... | 30 | 15.466667 |
def get_average_of_timeseries( image, idx=None ):
"""Average the timeseries into a dimension-1 image.
image: input time series image
idx: indices over which to average
"""
imagedim = image.dimension
if idx is None:
idx = range( image.shape[ imagedim - 1 ] )
i0 = utils.slice_image( i... | [
"def",
"get_average_of_timeseries",
"(",
"image",
",",
"idx",
"=",
"None",
")",
":",
"imagedim",
"=",
"image",
".",
"dimension",
"if",
"idx",
"is",
"None",
":",
"idx",
"=",
"range",
"(",
"image",
".",
"shape",
"[",
"imagedim",
"-",
"1",
"]",
")",
"i0... | 38.153846 | 14.923077 |
def main(self):
"""Search and sieve query names."""
# TODO: Break up, too complex
primary_bool = True
no_records = True
nsearch = 1
search_terms = self.terms
original_names = []
while True:
if primary_bool:
self.logger.info('Sea... | [
"def",
"main",
"(",
"self",
")",
":",
"# TODO: Break up, too complex",
"primary_bool",
"=",
"True",
"no_records",
"=",
"True",
"nsearch",
"=",
"1",
"search_terms",
"=",
"self",
".",
"terms",
"original_names",
"=",
"[",
"]",
"while",
"True",
":",
"if",
"prima... | 39.630435 | 13.73913 |
def create_translated_fields_serializer(shared_model, meta=None, related_name=None, **fields):
"""
Create a Rest Framework serializer class for a translated fields model.
:param shared_model: The shared model.
:type shared_model: :class:`parler.models.TranslatableModel`
"""
if not related_name:... | [
"def",
"create_translated_fields_serializer",
"(",
"shared_model",
",",
"meta",
"=",
"None",
",",
"related_name",
"=",
"None",
",",
"*",
"*",
"fields",
")",
":",
"if",
"not",
"related_name",
":",
"translated_model",
"=",
"shared_model",
".",
"_parler_meta",
".",... | 36.6 | 24.2 |
def calc_avgstrlen_pathstextnodes(pars_tnodes, dbg=False):
"""In the effort of not using external libraries (like scipy, numpy, etc),
I've written some harmless code for basic statistical calculations
"""
ttl = 0
for _, tnodes in pars_tnodes:
ttl += tnodes[3] # index #3 holds th... | [
"def",
"calc_avgstrlen_pathstextnodes",
"(",
"pars_tnodes",
",",
"dbg",
"=",
"False",
")",
":",
"ttl",
"=",
"0",
"for",
"_",
",",
"tnodes",
"in",
"pars_tnodes",
":",
"ttl",
"+=",
"tnodes",
"[",
"3",
"]",
"# index #3 holds the avg strlen\r",
"crd",
"=",
"len"... | 33.142857 | 17.928571 |
def N(u,i,p,knots):
"""Compute Spline Basis
Evaluates the spline basis of order p defined by knots
at knot i and point u.
"""
if p == 0:
if knots[i] < u and u <=knots[i+1]:
return 1.0
else:
return 0.0
else:
try:
k = (( float((u-kn... | [
"def",
"N",
"(",
"u",
",",
"i",
",",
"p",
",",
"knots",
")",
":",
"if",
"p",
"==",
"0",
":",
"if",
"knots",
"[",
"i",
"]",
"<",
"u",
"and",
"u",
"<=",
"knots",
"[",
"i",
"+",
"1",
"]",
":",
"return",
"1.0",
"else",
":",
"return",
"0.0",
... | 28.434783 | 17.826087 |
def input_chat(self):
"""
This :tl:`InputPeer` is the input version of the chat where the
message was sent. Similarly to `input_sender`, this doesn't have
things like username or similar, but still useful in some cases.
Note that this might not be available if the library doesn'... | [
"def",
"input_chat",
"(",
"self",
")",
":",
"if",
"self",
".",
"_input_chat",
"is",
"None",
"and",
"self",
".",
"_chat_peer",
":",
"try",
":",
"self",
".",
"_input_chat",
"=",
"self",
".",
"_client",
".",
"_entity_cache",
"[",
"self",
".",
"_chat_peer",
... | 37.3125 | 21.4375 |
def _known_stale(self):
"""
The commit is known to be from a file (and therefore stale) if a
SHA is supplied by git archive and doesn't match the parsed commit.
"""
if self._output_from_file() is None:
commit = None
else:
commit = self.commit
... | [
"def",
"_known_stale",
"(",
"self",
")",
":",
"if",
"self",
".",
"_output_from_file",
"(",
")",
"is",
"None",
":",
"commit",
"=",
"None",
"else",
":",
"commit",
"=",
"self",
".",
"commit",
"known_stale",
"=",
"(",
"self",
".",
"archive_commit",
"is",
"... | 37.6 | 17.6 |
def write_chisq(page, injList, grbtag):
"""
Write injection chisq plots to markup.page object page
"""
if injList:
th = ['']+injList + ['OFFSOURCE']
else:
th= ['','OFFSOURCE']
injList = ['OFFSOURCE']
td = []
plots = ['bank_veto','auto_veto','chi_square', 'mchir... | [
"def",
"write_chisq",
"(",
"page",
",",
"injList",
",",
"grbtag",
")",
":",
"if",
"injList",
":",
"th",
"=",
"[",
"''",
"]",
"+",
"injList",
"+",
"[",
"'OFFSOURCE'",
"]",
"else",
":",
"th",
"=",
"[",
"''",
",",
"'OFFSOURCE'",
"]",
"injList",
"=",
... | 26.0625 | 20.8125 |
def sandbox(cls, path):
'''Ensures path exists before yielding, cleans up after'''
# Ensure the path exists and is clean
try:
os.makedirs(path)
logger.debug('Making %s' % path)
except OSError:
if not os.path.isdir(path):
raise
f... | [
"def",
"sandbox",
"(",
"cls",
",",
"path",
")",
":",
"# Ensure the path exists and is clean",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"logger",
".",
"debug",
"(",
"'Making %s'",
"%",
"path",
")",
"except",
"OSError",
":",
"if",
"not",
"os",
... | 30.5625 | 17.8125 |
def cursor_up(self, stats):
"""Set the cursor to position N-1 in the list."""
if 0 <= self.cursor_position - 1:
self.cursor_position -= 1
else:
if self._current_page - 1 < 0 :
self._current_page = self._page_max - 1
self.cursor_position = (... | [
"def",
"cursor_up",
"(",
"self",
",",
"stats",
")",
":",
"if",
"0",
"<=",
"self",
".",
"cursor_position",
"-",
"1",
":",
"self",
".",
"cursor_position",
"-=",
"1",
"else",
":",
"if",
"self",
".",
"_current_page",
"-",
"1",
"<",
"0",
":",
"self",
".... | 42.818182 | 13.454545 |
def list_images(profile, location_id=None, **libcloud_kwargs):
'''
Return a list of images for this cloud
:param profile: The profile key
:type profile: ``str``
:param location_id: The location key, from list_locations
:type location_id: ``str``
:param libcloud_kwargs: Extra arguments f... | [
"def",
"list_images",
"(",
"profile",
",",
"location_id",
"=",
"None",
",",
"*",
"*",
"libcloud_kwargs",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"libcloud_kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwarg... | 28.354839 | 23.516129 |
def with_metaclass(meta, *bases):
"""
Create a base class with a metaclass.
For example, if you have the metaclass
>>> class Meta(type):
... pass
Use this as the metaclass by doing
>>> from symengine.compatibility import with_metaclass
>>> class MyClass(with_metaclass(Meta, objec... | [
"def",
"with_metaclass",
"(",
"meta",
",",
"*",
"bases",
")",
":",
"class",
"metaclass",
"(",
"meta",
")",
":",
"__call__",
"=",
"type",
".",
"__call__",
"__init__",
"=",
"type",
".",
"__init__",
"def",
"__new__",
"(",
"cls",
",",
"name",
",",
"this_ba... | 25.348837 | 19.302326 |
def getone(self, key):
"""
Get one value matching the key, raising a KeyError if multiple
values were found.
"""
v = self.getall(key)
if not v:
raise KeyError('Key not found: %r' % key)
if len(v) > 1:
raise KeyError('Multiple values match %... | [
"def",
"getone",
"(",
"self",
",",
"key",
")",
":",
"v",
"=",
"self",
".",
"getall",
"(",
"key",
")",
"if",
"not",
"v",
":",
"raise",
"KeyError",
"(",
"'Key not found: %r'",
"%",
"key",
")",
"if",
"len",
"(",
"v",
")",
">",
"1",
":",
"raise",
"... | 31.636364 | 16.181818 |
def diff_node_cache(prov_dir, node, new_data, opts):
'''
Check new node data against current cache. If data differ, fire an event
which consists of the new node data.
This function will only run if configured to do so in the main Salt Cloud
configuration file (normally /etc/salt/cloud).
.. cod... | [
"def",
"diff_node_cache",
"(",
"prov_dir",
",",
"node",
",",
"new_data",
",",
"opts",
")",
":",
"if",
"'diff_cache_events'",
"not",
"in",
"opts",
"or",
"not",
"opts",
"[",
"'diff_cache_events'",
"]",
":",
"return",
"if",
"node",
"is",
"None",
":",
"return"... | 32.306452 | 22.145161 |
def _provision_network(self, port_id, net_uuid, network_type,
physical_network, segmentation_id):
"""Provision the network with the received information."""
LOG.info("Provisioning network %s", net_uuid)
vswitch_name = self._get_vswitch_name(network_type, physical_netw... | [
"def",
"_provision_network",
"(",
"self",
",",
"port_id",
",",
"net_uuid",
",",
"network_type",
",",
"physical_network",
",",
"segmentation_id",
")",
":",
"LOG",
".",
"info",
"(",
"\"Provisioning network %s\"",
",",
"net_uuid",
")",
"vswitch_name",
"=",
"self",
... | 45.333333 | 15.5 |
def find_exception_by_code(code):
"""Find name of exception by WebDriver defined error code.
Args:
code(str): Error code defined in protocol.
Returns:
The error name defined in protocol.
"""
errorName = None
for error in WebDriverError:
if error.value.code == code:
... | [
"def",
"find_exception_by_code",
"(",
"code",
")",
":",
"errorName",
"=",
"None",
"for",
"error",
"in",
"WebDriverError",
":",
"if",
"error",
".",
"value",
".",
"code",
"==",
"code",
":",
"errorName",
"=",
"error",
"break",
"return",
"errorName"
] | 24.666667 | 16.333333 |
def add_sequence(self, words):
"""Add each of the tuple words[i:i+n], using a sliding window.
Prefix some copies of the empty word, '', to make the start work."""
n = self.n
words = ['',] * (n-1) + words
for i in range(len(words)-n):
self.add(tuple(words[i:i+n])) | [
"def",
"add_sequence",
"(",
"self",
",",
"words",
")",
":",
"n",
"=",
"self",
".",
"n",
"words",
"=",
"[",
"''",
",",
"]",
"*",
"(",
"n",
"-",
"1",
")",
"+",
"words",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"words",
")",
"-",
"n",
")",
... | 44.142857 | 5.571429 |
def __get_is_revertible(self):
"""Return a boolean representing whether this Action is revertible
or not"""
# If it was already reverted
if self.reverted:
return False
errors = []
inst = self.timemachine
if inst.fields != inst.presently.fiel... | [
"def",
"__get_is_revertible",
"(",
"self",
")",
":",
"# If it was already reverted",
"if",
"self",
".",
"reverted",
":",
"return",
"False",
"errors",
"=",
"[",
"]",
"inst",
"=",
"self",
".",
"timemachine",
"if",
"inst",
".",
"fields",
"!=",
"inst",
".",
"p... | 42.661972 | 16.309859 |
def infer_id(self, ident, diagnostic=None):
"""
Infer type from an ID!
- check if ID is declarated in the scope
- if no ID is polymorphic type
"""
# check if ID is declared
#defined = self.type_node.get_by_symbol_name(ident)
defined = self.infer_node.scope... | [
"def",
"infer_id",
"(",
"self",
",",
"ident",
",",
"diagnostic",
"=",
"None",
")",
":",
"# check if ID is declared",
"#defined = self.type_node.get_by_symbol_name(ident)",
"defined",
"=",
"self",
".",
"infer_node",
".",
"scope_node",
".",
"get_by_symbol_name",
"(",
"i... | 35.473684 | 11.052632 |
def sample_hidden_from_visible(self, visible):
"""Sample the hidden units from the visible units.
This is the Positive phase of the Contrastive Divergence algorithm.
:param visible: activations of the visible units
:return: tuple(hidden probabilities, hidden binary states)
"""
... | [
"def",
"sample_hidden_from_visible",
"(",
"self",
",",
"visible",
")",
":",
"hprobs",
"=",
"tf",
".",
"nn",
".",
"sigmoid",
"(",
"tf",
".",
"add",
"(",
"tf",
".",
"matmul",
"(",
"visible",
",",
"self",
".",
"W",
")",
",",
"self",
".",
"bh_",
")",
... | 39.75 | 22.333333 |
def filter(self, record):
"""If request_id is set in flask.g, add it to log record."""
if g and hasattr(g, 'request_id'):
record.request_id = g.request_id
return True | [
"def",
"filter",
"(",
"self",
",",
"record",
")",
":",
"if",
"g",
"and",
"hasattr",
"(",
"g",
",",
"'request_id'",
")",
":",
"record",
".",
"request_id",
"=",
"g",
".",
"request_id",
"return",
"True"
] | 39.6 | 8.4 |
def _update_table(data):
"""Add new jobs to the priority table and update the build system if required.
data - it is a list of dictionaries that describe a job type
returns the number of new, failed and updated jobs
"""
jp_index, priority, expiration_date = _initialize_values()
total_jobs = le... | [
"def",
"_update_table",
"(",
"data",
")",
":",
"jp_index",
",",
"priority",
",",
"expiration_date",
"=",
"_initialize_values",
"(",
")",
"total_jobs",
"=",
"len",
"(",
"data",
")",
"new_jobs",
",",
"failed_changes",
",",
"updated_jobs",
"=",
"0",
",",
"0",
... | 44.436364 | 21.872727 |
def get_atlas_summary_df(self):
"""Create a single data frame which summarizes all genes per row.
Returns:
DataFrame: Pandas DataFrame of the results
"""
all_info = []
for g in self.reference_gempro.genes_with_a_representative_sequence:
info = {}
... | [
"def",
"get_atlas_summary_df",
"(",
"self",
")",
":",
"all_info",
"=",
"[",
"]",
"for",
"g",
"in",
"self",
".",
"reference_gempro",
".",
"genes_with_a_representative_sequence",
":",
"info",
"=",
"{",
"}",
"info",
"[",
"'Gene_ID'",
"]",
"=",
"g",
".",
"id",... | 53.818182 | 28.766234 |
def render(self):
"""Runs the render until thread flag is set.
Returns
-------
self
"""
while not self._stop_spinner.is_set():
self._render_frame()
time.sleep(0.001 * self._interval)
return self | [
"def",
"render",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"_stop_spinner",
".",
"is_set",
"(",
")",
":",
"self",
".",
"_render_frame",
"(",
")",
"time",
".",
"sleep",
"(",
"0.001",
"*",
"self",
".",
"_interval",
")",
"return",
"self"
] | 24.090909 | 16.545455 |
def run(self):
'''Define the job of each process to run.
'''
if self.verbose:
pbar = tqdm(total=100)
while True:
task_remain = self._task_queue.qsize()
task_finished = int((float(self.total_task - task_remain) /
float(s... | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"verbose",
":",
"pbar",
"=",
"tqdm",
"(",
"total",
"=",
"100",
")",
"while",
"True",
":",
"task_remain",
"=",
"self",
".",
"_task_queue",
".",
"qsize",
"(",
")",
"task_finished",
"=",
"int",
"... | 41.941176 | 17.235294 |
def raise_exception_if_baseline_file_is_unstaged(filename):
"""We want to make sure that if there are changes to the baseline
file, they will be included in the commit. This way, we can keep
our baselines up-to-date.
:raises: ValueError
"""
try:
files_changed_but_not_staged = subprocess... | [
"def",
"raise_exception_if_baseline_file_is_unstaged",
"(",
"filename",
")",
":",
"try",
":",
"files_changed_but_not_staged",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'git'",
",",
"'diff'",
",",
"'--name-only'",
",",
"]",
",",
")",
".",
"split",
"(",
"... | 28.965517 | 19.862069 |
def Chen_Edelstein(m, x, D, rhol, rhog, mul, mug, kl, Cpl, Hvap, sigma,
dPsat, Te):
r'''Calculates heat transfer coefficient for film boiling of saturated
fluid in any orientation of flow. Correlation
is developed in [1]_ and [2]_, and reviewed in [3]_. This model is one of
the most... | [
"def",
"Chen_Edelstein",
"(",
"m",
",",
"x",
",",
"D",
",",
"rhol",
",",
"rhog",
",",
"mul",
",",
"mug",
",",
"kl",
",",
"Cpl",
",",
"Hvap",
",",
"sigma",
",",
"dPsat",
",",
"Te",
")",
":",
"G",
"=",
"m",
"/",
"(",
"pi",
"/",
"4",
"*",
"D... | 35.280374 | 23.616822 |
def load(data_path):
"""
Extract data from provided file and return it as a string.
"""
with open(data_path, "r") as data_file:
raw_data = data_file.read()
data_file.close()
return raw_data | [
"def",
"load",
"(",
"data_path",
")",
":",
"with",
"open",
"(",
"data_path",
",",
"\"r\"",
")",
"as",
"data_file",
":",
"raw_data",
"=",
"data_file",
".",
"read",
"(",
")",
"data_file",
".",
"close",
"(",
")",
"return",
"raw_data"
] | 26.888889 | 14 |
def _check_std(self, paths, cmd_pieces):
"""
Run `cmd` as a check on `paths`.
"""
cmd_pieces.extend(paths)
process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE)
out, err = process.communicate()
lines = out.strip().splitlines() + err.strip().splitlines()
re... | [
"def",
"_check_std",
"(",
"self",
",",
"paths",
",",
"cmd_pieces",
")",
":",
"cmd_pieces",
".",
"extend",
"(",
"paths",
")",
"process",
"=",
"Popen",
"(",
"cmd_pieces",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
")",
"out",
",",
"err",
"... | 36.172414 | 12.862069 |
def _load_plain_yaml(cls, _yaml: YamlDocument) -> Any:
"""
Will just load the yaml without executing any extensions. You will get the plain dictionary
without augmentation. It is equivalent to just perform `yaml.safe_load`. Besides that you
can specify a stream, a file or just a string t... | [
"def",
"_load_plain_yaml",
"(",
"cls",
",",
"_yaml",
":",
"YamlDocument",
")",
"->",
"Any",
":",
"if",
"Validator",
".",
"is_stream",
"(",
"yaml_",
"=",
"_yaml",
")",
":",
"return",
"yaml",
".",
"safe_load",
"(",
"_yaml",
")",
"if",
"Validator",
".",
"... | 42.857143 | 22.857143 |
def info_gain_nominal(x, y, separate_max):
"""
Function calculates information gain for discrete features. If feature is continuous it is firstly discretized.
x: numpy array - numerical or discrete feature
y: numpy array - labels
ft: string - feature type ("c" - continuous, "d" - discrete)
spli... | [
"def",
"info_gain_nominal",
"(",
"x",
",",
"y",
",",
"separate_max",
")",
":",
"x_vals",
"=",
"np",
".",
"unique",
"(",
"x",
")",
"# unique values",
"if",
"len",
"(",
"x_vals",
")",
"<",
"3",
":",
"# if there is just one unique value",
"return",
"None",
"y... | 47.363636 | 27.227273 |
def start_drag_opperation(self, evt):
"Event handler for drag&drop functionality"
# get the control
ctrl = self.menu_ctrl_map[evt.GetToolId()]
# create our own data format and use it in a custom data object
ldata = wx.CustomDataObject("gui")
ldata.SetData(ctrl._meta... | [
"def",
"start_drag_opperation",
"(",
"self",
",",
"evt",
")",
":",
"# get the control",
"ctrl",
"=",
"self",
".",
"menu_ctrl_map",
"[",
"evt",
".",
"GetToolId",
"(",
")",
"]",
"# create our own data format and use it in a custom data object",
"ldata",
"=",
"wx",
"."... | 35.774194 | 17.258065 |
def _process_loaded_object(self, path):
"""process the :paramref:`path`.
:param str path: the path to load an svg from
"""
file_name = os.path.basename(path)
name = os.path.splitext(file_name)[0]
with open(path) as file:
string = file.read()
self.... | [
"def",
"_process_loaded_object",
"(",
"self",
",",
"path",
")",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"[",
"0",
"]",
"with",
"open",
"(",
... | 35.9 | 10.2 |
def get_field_key(self, key, using_name=True):
"""Given a field key or name, return it's field key.
"""
try:
if using_name:
return self.f_name[key].key
else:
return self.f[key].key
except KeyError:
raise ValueError("'%s'... | [
"def",
"get_field_key",
"(",
"self",
",",
"key",
",",
"using_name",
"=",
"True",
")",
":",
"try",
":",
"if",
"using_name",
":",
"return",
"self",
".",
"f_name",
"[",
"key",
"]",
".",
"key",
"else",
":",
"return",
"self",
".",
"f",
"[",
"key",
"]",
... | 33.4 | 10.9 |
def encode(self):
"""This method encodes the data into a binary string using
the appropriate algorithm specified by the mode.
"""
if self.mode == tables.modes['alphanumeric']:
encoded = self.encode_alphanumeric()
elif self.mode == tables.modes['numeric']:
... | [
"def",
"encode",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"==",
"tables",
".",
"modes",
"[",
"'alphanumeric'",
"]",
":",
"encoded",
"=",
"self",
".",
"encode_alphanumeric",
"(",
")",
"elif",
"self",
".",
"mode",
"==",
"tables",
".",
"modes",
... | 41.923077 | 8.461538 |
def p_unit_list(self, p):
""" unit_list : unit_list unit
| unit
"""
if isinstance(p[1], list):
if len(p) >= 3:
if isinstance(p[2], list):
p[1].extend(p[2])
else:
... | [
"def",
"p_unit_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"isinstance",
"(",
"p",
"[",
"1",
"]",
",",
"list",
")",
":",
"if",
"len",
"(",
"p",
")",
">=",
"3",
":",
"if",
"isinstance",
"(",
"p",
"[",
"2",
"]",
",",
"list",
")",
":",
"p",
... | 29.769231 | 9.769231 |
def make_synthetic(self,
srd=0,
v_repl_seismic=2000,
v_repl_log=2000,
f=50,
dt=0.001):
"""
Early hack. Use with extreme caution.
Hands-free. There'll be a more granualr version in ... | [
"def",
"make_synthetic",
"(",
"self",
",",
"srd",
"=",
"0",
",",
"v_repl_seismic",
"=",
"2000",
",",
"v_repl_log",
"=",
"2000",
",",
"f",
"=",
"50",
",",
"dt",
"=",
"0.001",
")",
":",
"kb",
"=",
"getattr",
"(",
"self",
".",
"location",
",",
"'kb'",... | 30.192982 | 18.894737 |
def get_overs_summary(self, match_key):
"""
Calling Overs Summary API
Arg:
match_key: key of the match
Return:
json data
"""
overs_summary_url = self.api_path + "match/" + match_key + "/overs_summary/"
response = self.get_response(overs_summ... | [
"def",
"get_overs_summary",
"(",
"self",
",",
"match_key",
")",
":",
"overs_summary_url",
"=",
"self",
".",
"api_path",
"+",
"\"match/\"",
"+",
"match_key",
"+",
"\"/overs_summary/\"",
"response",
"=",
"self",
".",
"get_response",
"(",
"overs_summary_url",
")",
... | 28.416667 | 16.583333 |
def page(self, end_date=values.unset, event_type=values.unset,
minutes=values.unset, reservation_sid=values.unset,
start_date=values.unset, task_queue_sid=values.unset,
task_sid=values.unset, worker_sid=values.unset,
workflow_sid=values.unset, task_channel=values.unse... | [
"def",
"page",
"(",
"self",
",",
"end_date",
"=",
"values",
".",
"unset",
",",
"event_type",
"=",
"values",
".",
"unset",
",",
"minutes",
"=",
"values",
".",
"unset",
",",
"reservation_sid",
"=",
"values",
".",
"unset",
",",
"start_date",
"=",
"values",
... | 48.962264 | 23.415094 |
def postURL(self, url, headers, body):
"""
Implement post using a get call
"""
new_url = url
if body is not None:
new_url = FileSea.convert_body(url, body)
return self.getURL(new_url, headers) | [
"def",
"postURL",
"(",
"self",
",",
"url",
",",
"headers",
",",
"body",
")",
":",
"new_url",
"=",
"url",
"if",
"body",
"is",
"not",
"None",
":",
"new_url",
"=",
"FileSea",
".",
"convert_body",
"(",
"url",
",",
"body",
")",
"return",
"self",
".",
"g... | 30.625 | 6.375 |
def link_docstring(modules, docstring:str, overwrite:bool=False)->str:
"Search `docstring` for backticks and attempt to link those functions to respective documentation."
mods = listify(modules)
for mod in mods: _modvars.update(mod.__dict__) # concat all module definitions
return re.sub(BT_REGEX, replac... | [
"def",
"link_docstring",
"(",
"modules",
",",
"docstring",
":",
"str",
",",
"overwrite",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"mods",
"=",
"listify",
"(",
"modules",
")",
"for",
"mod",
"in",
"mods",
":",
"_modvars",
".",
"update",
"(",
"... | 66.8 | 32 |
def write_config(configfile, content):
"""
Write dict to a file in yaml format
"""
with open(configfile, 'w+') as ymlfile:
yaml.dump(
content,
ymlfile,
default_flow_style=False,
) | [
"def",
"write_config",
"(",
"configfile",
",",
"content",
")",
":",
"with",
"open",
"(",
"configfile",
",",
"'w+'",
")",
"as",
"ymlfile",
":",
"yaml",
".",
"dump",
"(",
"content",
",",
"ymlfile",
",",
"default_flow_style",
"=",
"False",
",",
")"
] | 23.8 | 10.2 |
def get_comics(self, *args, **kwargs):
"""
Returns a full ComicDataWrapper object for this creator.
/creators/{creatorId}/comics
:returns: ComicDataWrapper -- A new request to API. Contains full results set.
"""
from .comic import Comic, ComicDataWrappe... | [
"def",
"get_comics",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"comic",
"import",
"Comic",
",",
"ComicDataWrapper",
"return",
"self",
".",
"get_related_resource",
"(",
"Comic",
",",
"ComicDataWrapper",
",",
"args",
",",... | 39.2 | 19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.