text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def com_adobe_fonts_check_cff2_call_depth(ttFont):
"""Is the CFF2 subr/gsubr call depth > 10?"""
any_failures = False
cff = ttFont['CFF2'].cff
for top_dict in cff.topDictIndex:
for fd_index, font_dict in enumerate(top_dict.FDArray):
if hasattr(font_dict, 'Private'):
... | [
"def",
"com_adobe_fonts_check_cff2_call_depth",
"(",
"ttFont",
")",
":",
"any_failures",
"=",
"False",
"cff",
"=",
"ttFont",
"[",
"'CFF2'",
"]",
".",
"cff",
"for",
"top_dict",
"in",
"cff",
".",
"topDictIndex",
":",
"for",
"fd_index",
",",
"font_dict",
"in",
... | 36.647059 | 15.176471 |
def __view_to_intervals(self, data_and_metadata: DataAndMetadata.DataAndMetadata, intervals: typing.List[typing.Tuple[float, float]]) -> None:
"""Change the view to encompass the channels and data represented by the given intervals."""
left = None
right = None
for interval in intervals:
... | [
"def",
"__view_to_intervals",
"(",
"self",
",",
"data_and_metadata",
":",
"DataAndMetadata",
".",
"DataAndMetadata",
",",
"intervals",
":",
"typing",
".",
"List",
"[",
"typing",
".",
"Tuple",
"[",
"float",
",",
"float",
"]",
"]",
")",
"->",
"None",
":",
"l... | 60.296296 | 28.148148 |
def opt_width(self, width):
""" Set width of output ('auto' will auto-detect terminal width) """
if width != "auto":
width = int(width)
self.conf["width"] = width | [
"def",
"opt_width",
"(",
"self",
",",
"width",
")",
":",
"if",
"width",
"!=",
"\"auto\"",
":",
"width",
"=",
"int",
"(",
"width",
")",
"self",
".",
"conf",
"[",
"\"width\"",
"]",
"=",
"width"
] | 38.8 | 8.4 |
def get_i_text(node):
"""
Get the text for an Indicator node.
:param node: Indicator node.
:return:
"""
if node.tag != 'Indicator':
raise IOCParseError('Invalid tag: {}'.format(node.tag))
s = node.get('operator').upper()
return s | [
"def",
"get_i_text",
"(",
"node",
")",
":",
"if",
"node",
".",
"tag",
"!=",
"'Indicator'",
":",
"raise",
"IOCParseError",
"(",
"'Invalid tag: {}'",
".",
"format",
"(",
"node",
".",
"tag",
")",
")",
"s",
"=",
"node",
".",
"get",
"(",
"'operator'",
")",
... | 26.909091 | 13.272727 |
def get_program(self, program_path, controller=None):
"""
Find the program within this manifest. If key is found, and it contains
a list, iterate over the list and return the program that matches
the controller tag. NOTICE: program_path must have a leading slash.
"""
if n... | [
"def",
"get_program",
"(",
"self",
",",
"program_path",
",",
"controller",
"=",
"None",
")",
":",
"if",
"not",
"program_path",
"or",
"program_path",
"[",
"0",
"]",
"!=",
"'/'",
":",
"raise",
"ValueError",
"(",
"\"program_path must be a full path with leading slash... | 37.459459 | 18.432432 |
def upload(import_path, verbose=False, skip_subfolders=False, number_threads=None, max_attempts=None, video_import_path=None, dry_run=False,api_version=1.0):
'''
Upload local images to Mapillary
Args:
import_path: Directory path to where the images are stored.
verbose: Print extra warnings a... | [
"def",
"upload",
"(",
"import_path",
",",
"verbose",
"=",
"False",
",",
"skip_subfolders",
"=",
"False",
",",
"number_threads",
"=",
"None",
",",
"max_attempts",
"=",
"None",
",",
"video_import_path",
"=",
"None",
",",
"dry_run",
"=",
"False",
",",
"api_vers... | 47.680672 | 22.201681 |
def _set_network(self, v, load=False):
"""
Setter method for network, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/default_vrf/network (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_network is considered as a private
... | [
"def",
"_set_network",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",... | 126 | 61.909091 |
def __deserialize_file(self, response):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
:param response: RESTResponse.
:return: file path.
"""
fd, path = t... | [
"def",
"__deserialize_file",
"(",
"self",
",",
"response",
")",
":",
"fd",
",",
"path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"dir",
"=",
"self",
".",
"configuration",
".",
"temp_folder_path",
")",
"os",
".",
"close",
"(",
"fd",
")",
"os",
".",
"remove... | 34.565217 | 21.478261 |
def point_data_to_cell_data(dataset, pass_point_data=False):
"""Transforms point data (i.e., data specified per node) into cell data
(i.e., data specified within cells).
Optionally, the input point data can be passed through to the output.
See aslo: :func:`vtki.DataSetFilters.cell_data_... | [
"def",
"point_data_to_cell_data",
"(",
"dataset",
",",
"pass_point_data",
"=",
"False",
")",
":",
"alg",
"=",
"vtk",
".",
"vtkPointDataToCellData",
"(",
")",
"alg",
".",
"SetInputDataObject",
"(",
"dataset",
")",
"alg",
".",
"SetPassPointData",
"(",
"pass_point_... | 40.941176 | 18.588235 |
def assert_200(response, max_len=500):
""" Check that a HTTP response returned 200. """
if response.status_code == 200:
return
raise ValueError(
"Response was {}, not 200:\n{}\n{}".format(
response.status_code,
json.dumps(dict(response.headers), indent=2),
response.content... | [
"def",
"assert_200",
"(",
"response",
",",
"max_len",
"=",
"500",
")",
":",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"raise",
"ValueError",
"(",
"\"Response was {}, not 200:\\n{}\\n{}\"",
".",
"format",
"(",
"response",
".",
"status_code... | 32.3 | 13.5 |
def sim(self, src, tar):
"""Return the Ratcliff-Obershelp similarity of two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Ratcliff-Ob... | [
"def",
"sim",
"(",
"self",
",",
"src",
",",
"tar",
")",
":",
"def",
"_lcsstr_stl",
"(",
"src",
",",
"tar",
")",
":",
"\"\"\"Return start positions & length for Ratcliff-Obershelp.\n\n Parameters\n ----------\n src : str\n Source str... | 31.038835 | 18.718447 |
def process_columns(self, columns):
"""
Handle provided columns and if necessary, convert columns to a list for
internal strage.
:columns: A sequence of columns for the table. Can be list, comma
-delimited string, or IntEnum.
"""
if type(columns) == list:
... | [
"def",
"process_columns",
"(",
"self",
",",
"columns",
")",
":",
"if",
"type",
"(",
"columns",
")",
"==",
"list",
":",
"self",
".",
"columns",
"=",
"columns",
"elif",
"type",
"(",
"columns",
")",
"==",
"str",
":",
"self",
".",
"columns",
"=",
"[",
... | 37.8125 | 15 |
def _process_key(evt):
"""Helper to convert from wx keycode to vispy keycode"""
key = evt.GetKeyCode()
if key in KEYMAP:
return KEYMAP[key], ''
if 97 <= key <= 122:
key -= 32
if key >= 32 and key <= 127:
return keys.Key(chr(key)), chr(key)
else:
return None, None | [
"def",
"_process_key",
"(",
"evt",
")",
":",
"key",
"=",
"evt",
".",
"GetKeyCode",
"(",
")",
"if",
"key",
"in",
"KEYMAP",
":",
"return",
"KEYMAP",
"[",
"key",
"]",
",",
"''",
"if",
"97",
"<=",
"key",
"<=",
"122",
":",
"key",
"-=",
"32",
"if",
"... | 28.090909 | 14.272727 |
def is_ratio_different(min_ratio, study_go, study_n, pop_go, pop_n):
"""
check if the ratio go /n is different between the study group and
the population
"""
if min_ratio is None:
return True
stu_ratio = float(study_go) / study_n
pop_ratio = float(pop_go) / pop_n
if stu_ratio == ... | [
"def",
"is_ratio_different",
"(",
"min_ratio",
",",
"study_go",
",",
"study_n",
",",
"pop_go",
",",
"pop_n",
")",
":",
"if",
"min_ratio",
"is",
"None",
":",
"return",
"True",
"stu_ratio",
"=",
"float",
"(",
"study_go",
")",
"/",
"study_n",
"pop_ratio",
"="... | 32.375 | 12.25 |
def comments(self, issue):
"""Return all comments for this issue/pull request
"""
commit = self.as_id(issue)
return self.get_list(url='%s/%s/comments' % (self, commit)) | [
"def",
"comments",
"(",
"self",
",",
"issue",
")",
":",
"commit",
"=",
"self",
".",
"as_id",
"(",
"issue",
")",
"return",
"self",
".",
"get_list",
"(",
"url",
"=",
"'%s/%s/comments'",
"%",
"(",
"self",
",",
"commit",
")",
")"
] | 39.2 | 9.4 |
def _parse_splits(patch, splits):
"""
Parse splits string to get list of all associated subset strings.
Parameters
----------
patch : obj
Patch object containing data to subset
splits : str
Specifies how a column of a dataset should be split. See Notes.
Returns
-------
... | [
"def",
"_parse_splits",
"(",
"patch",
",",
"splits",
")",
":",
"split_list",
"=",
"splits",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"split",
"(",
"';'",
")",
"subset_list",
"=",
"[",
"]",
"# List of all subset strings",
"for",
"split",
"in",
"sp... | 27.697674 | 23.139535 |
def main(args):
"""Command-line tool to transform html style to inline css
Usage::
$ echo '<style>h1 { color:red; }</style><h1>Title</h1>' | \
python -m premailer
<h1 style="color:red"></h1>
$ cat newsletter.html | python -m premailer
"""
parser = argparse.ArgumentPars... | [
"def",
"main",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"usage",
"=",
"\"python -m premailer [options]\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-f\"",
",",
"\"--file\"",
",",
"nargs",
"=",
"\"?\"",
",",
"type",
"="... | 27.520231 | 21.745665 |
def transmissions(self, status="all"):
"""Get transmissions sent along this Vector.
Status can be "all" (the default), "pending", or "received".
"""
if status not in ["all", "pending", "received"]:
raise(ValueError("You cannot get {} transmissions."
... | [
"def",
"transmissions",
"(",
"self",
",",
"status",
"=",
"\"all\"",
")",
":",
"if",
"status",
"not",
"in",
"[",
"\"all\"",
",",
"\"pending\"",
",",
"\"received\"",
"]",
":",
"raise",
"(",
"ValueError",
"(",
"\"You cannot get {} transmissions.\"",
".",
"format"... | 35.521739 | 14.347826 |
def load(self, file=CONFIG_FILE):
"""
load a configuration file. loads default config if file is not found
"""
if not os.path.exists(file):
print("Config file was not found under %s. Default file has been created" % CONFIG_FILE)
self._settings = yaml.load(DEFAULT_... | [
"def",
"load",
"(",
"self",
",",
"file",
"=",
"CONFIG_FILE",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file",
")",
":",
"print",
"(",
"\"Config file was not found under %s. Default file has been created\"",
"%",
"CONFIG_FILE",
")",
"self",
... | 44.454545 | 18.454545 |
def _sort_lambda(sortedby='cpu_percent',
sortedby_secondary='memory_percent'):
"""Return a sort lambda function for the sortedbykey"""
ret = None
if sortedby == 'io_counters':
ret = _sort_io_counters
elif sortedby == 'cpu_times':
ret = _sort_cpu_times
return ret | [
"def",
"_sort_lambda",
"(",
"sortedby",
"=",
"'cpu_percent'",
",",
"sortedby_secondary",
"=",
"'memory_percent'",
")",
":",
"ret",
"=",
"None",
"if",
"sortedby",
"==",
"'io_counters'",
":",
"ret",
"=",
"_sort_io_counters",
"elif",
"sortedby",
"==",
"'cpu_times'",
... | 34.111111 | 11.111111 |
def validate_training_data_stats(training_data_stats):
"""
Method to validate the structure of training data stats
"""
stat_keys = list(training_data_stats.keys())
valid_stat_keys = ["means", "mins", "maxs", "stds", "feature_values", "feature_frequencies"]
missing_key... | [
"def",
"validate_training_data_stats",
"(",
"training_data_stats",
")",
":",
"stat_keys",
"=",
"list",
"(",
"training_data_stats",
".",
"keys",
"(",
")",
")",
"valid_stat_keys",
"=",
"[",
"\"means\"",
",",
"\"mins\"",
",",
"\"maxs\"",
",",
"\"stds\"",
",",
"\"fe... | 54.111111 | 22.111111 |
def package(input_dir, output_dir, meta_path=None, create_meta=False, force=False):
"""
Generate Python package for model data, including meta and required
installation files. A new directory will be created in the specified
output directory, and model data will be copied over. If --create-meta is
s... | [
"def",
"package",
"(",
"input_dir",
",",
"output_dir",
",",
"meta_path",
"=",
"None",
",",
"create_meta",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"msg",
"=",
"Printer",
"(",
")",
"input_path",
"=",
"util",
".",
"ensure_path",
"(",
"input_dir"... | 47.192982 | 19.789474 |
def to_datetime(timestamp):
"""Return datetime object from timestamp."""
return dt.fromtimestamp(time.mktime(
time.localtime(int(str(timestamp)[:10])))) | [
"def",
"to_datetime",
"(",
"timestamp",
")",
":",
"return",
"dt",
".",
"fromtimestamp",
"(",
"time",
".",
"mktime",
"(",
"time",
".",
"localtime",
"(",
"int",
"(",
"str",
"(",
"timestamp",
")",
"[",
":",
"10",
"]",
")",
")",
")",
")"
] | 41.25 | 5.75 |
def freeze(self):
"""
Freeze (disable) all settings
"""
for fields in zip(self.xsll, self.xsul, self.xslr, self.xsur,
self.ys, self.nx, self.ny):
for field in fields:
field.disable()
self.nquad.disable()
self.xbin.disa... | [
"def",
"freeze",
"(",
"self",
")",
":",
"for",
"fields",
"in",
"zip",
"(",
"self",
".",
"xsll",
",",
"self",
".",
"xsul",
",",
"self",
".",
"xslr",
",",
"self",
".",
"xsur",
",",
"self",
".",
"ys",
",",
"self",
".",
"nx",
",",
"self",
".",
"n... | 30.538462 | 11.461538 |
def _init_jupyter(run):
"""Asks for user input to configure the machine if it isn't already and creates a new run.
Log pushing and system stats don't start until `wandb.monitor()` is called.
"""
from wandb import jupyter
# TODO: Should we log to jupyter?
# global logging had to be disabled becau... | [
"def",
"_init_jupyter",
"(",
"run",
")",
":",
"from",
"wandb",
"import",
"jupyter",
"# TODO: Should we log to jupyter?",
"# global logging had to be disabled because it set the level to debug",
"# I also disabled run logging because we're rairly using it.",
"# try_to_set_up_global_logging(... | 38.906977 | 16.837209 |
def _set_show_raslog(self, v, load=False):
"""
Setter method for show_raslog, mapped from YANG variable /brocade_ras_ext_rpc/show_raslog (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_raslog is considered as a private
method. Backends looking to populate ... | [
"def",
"_set_show_raslog",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"ba... | 67.333333 | 32.541667 |
def singledispatch(*, nargs=None, nouts=None, ndefs=None):
"""
singledispatch decorate of both functools.singledispatch and func
"""
def wrapper(f):
return wraps(f)(SingleDispatchFunction(f, nargs=nargs, nouts=nouts, ndefs=ndefs))
return wrapper | [
"def",
"singledispatch",
"(",
"*",
",",
"nargs",
"=",
"None",
",",
"nouts",
"=",
"None",
",",
"ndefs",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"return",
"wraps",
"(",
"f",
")",
"(",
"SingleDispatchFunction",
"(",
"f",
",",
"nar... | 30.111111 | 24.777778 |
def monkey_patch_override_instance_method(instance):
"""
Override an instance method with a new version of the same name. The
original method implementation is made available within the override method
as `_original_<METHOD_NAME>`.
"""
def perform_override(override_fn):
fn_name = overrid... | [
"def",
"monkey_patch_override_instance_method",
"(",
"instance",
")",
":",
"def",
"perform_override",
"(",
"override_fn",
")",
":",
"fn_name",
"=",
"override_fn",
".",
"__name__",
"original_fn_name",
"=",
"'_original_'",
"+",
"fn_name",
"# Override instance method, if it ... | 46.8125 | 13.9375 |
def to_sky(self, wcs, mode='all'):
"""
Convert the aperture to a `SkyCircularAperture` object defined
in celestial coordinates.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wc... | [
"def",
"to_sky",
"(",
"self",
",",
"wcs",
",",
"mode",
"=",
"'all'",
")",
":",
"sky_params",
"=",
"self",
".",
"_to_sky_params",
"(",
"wcs",
",",
"mode",
"=",
"mode",
")",
"return",
"SkyCircularAperture",
"(",
"*",
"*",
"sky_params",
")"
] | 31.782609 | 18.391304 |
def _extract_email(gh):
"""Get user email from github."""
return next(
(x.email for x in gh.emails() if x.verified and x.primary), None) | [
"def",
"_extract_email",
"(",
"gh",
")",
":",
"return",
"next",
"(",
"(",
"x",
".",
"email",
"for",
"x",
"in",
"gh",
".",
"emails",
"(",
")",
"if",
"x",
".",
"verified",
"and",
"x",
".",
"primary",
")",
",",
"None",
")"
] | 37.25 | 18.5 |
def add_section(self, section):
"""You can add section inside a Element, the section must be a
subclass of SubSection. You can use this class to represent a tree.
"""
if not issubclass(section.__class__, SubSection):
raise TypeError("Argument should be a subclass of SubSecti... | [
"def",
"add_section",
"(",
"self",
",",
"section",
")",
":",
"if",
"not",
"issubclass",
"(",
"section",
".",
"__class__",
",",
"SubSection",
")",
":",
"raise",
"TypeError",
"(",
"\"Argument should be a subclass of SubSection, \\\n not :\"",
"... | 44.7 | 18 |
def create_function_from_request_pdu(pdu):
""" Return function instance, based on request PDU.
:param pdu: Array of bytes.
:return: Instance of a function.
"""
function_code = get_function_code_from_request_pdu(pdu)
try:
function_class = function_code_to_function_map[function_code]
... | [
"def",
"create_function_from_request_pdu",
"(",
"pdu",
")",
":",
"function_code",
"=",
"get_function_code_from_request_pdu",
"(",
"pdu",
")",
"try",
":",
"function_class",
"=",
"function_code_to_function_map",
"[",
"function_code",
"]",
"except",
"KeyError",
":",
"raise... | 33.076923 | 16.769231 |
def stats():
'''Read a stream of floats and give summary statistics'''
import re
import sys
import math
values = []
for line in sys.stdin:
values.extend(map(float, re.findall(r'\d+\.?\d+', line)))
mean = sum(values) / len(values)
variance = sum((val - mean) ** 2 for val in value... | [
"def",
"stats",
"(",
")",
":",
"import",
"re",
"import",
"sys",
"import",
"math",
"values",
"=",
"[",
"]",
"for",
"line",
"in",
"sys",
".",
"stdin",
":",
"values",
".",
"extend",
"(",
"map",
"(",
"float",
",",
"re",
".",
"findall",
"(",
"r'\\d+\\.?... | 33 | 22.076923 |
def get_timeseries_values_for_indicators(
self, resolution: str = "month", months: Iterable[int] = range(6, 9)
):
""" Attach timeseries to indicators, for performing Bayesian inference.
"""
if resolution == "month":
funcs = [
partial(get_indicator_value, ... | [
"def",
"get_timeseries_values_for_indicators",
"(",
"self",
",",
"resolution",
":",
"str",
"=",
"\"month\"",
",",
"months",
":",
"Iterable",
"[",
"int",
"]",
"=",
"range",
"(",
"6",
",",
"9",
")",
")",
":",
"if",
"resolution",
"==",
"\"month\"",
":",
"fu... | 38.857143 | 18.047619 |
def _get_once(self, page_text):
"""Get once which will be used when you login."""
soup = BeautifulSoup(page_text, 'html.parser')
once = soup.find('input', attrs={'name': 'once'})['value']
return once | [
"def",
"_get_once",
"(",
"self",
",",
"page_text",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"page_text",
",",
"'html.parser'",
")",
"once",
"=",
"soup",
".",
"find",
"(",
"'input'",
",",
"attrs",
"=",
"{",
"'name'",
":",
"'once'",
"}",
")",
"[",
... | 45.4 | 14 |
def lognorm(x, mu, sigma=1.0):
""" Log-normal function from scipy """
return stats.lognorm(sigma, scale=mu).pdf(x) | [
"def",
"lognorm",
"(",
"x",
",",
"mu",
",",
"sigma",
"=",
"1.0",
")",
":",
"return",
"stats",
".",
"lognorm",
"(",
"sigma",
",",
"scale",
"=",
"mu",
")",
".",
"pdf",
"(",
"x",
")"
] | 40 | 6 |
def firmware_manifest_list(self, **kwargs): # noqa: E501
"""List manifests # noqa: E501
List firmware manifests. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.firmware... | [
"def",
"firmware_manifest_list",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
"firmware_manifest... | 164.96 | 137.92 |
def diff(**kwargs):
'''
Returns the difference between the candidate and the current configuration
id : 0
The rollback ID value (0-49)
CLI Example:
.. code-block:: bash
salt 'device_name' junos.diff 3
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
id_ = kwargs.po... | [
"def",
"diff",
"(",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"id_",
"=",
"kwargs",
".",
"pop",
"(",
"'id'",
",",
"0",
")",
"if",
"kwargs",
":",
"salt",
".... | 23 | 23.413793 |
def decode_texts(self, encoded_texts, unknown_token="<UNK>", inplace=True):
"""Decodes the texts using internal vocabulary. The list structure is maintained.
Args:
encoded_texts: The list of texts to decode.
unknown_token: The placeholder value for unknown token. (Default value:... | [
"def",
"decode_texts",
"(",
"self",
",",
"encoded_texts",
",",
"unknown_token",
"=",
"\"<UNK>\"",
",",
"inplace",
"=",
"True",
")",
":",
"if",
"len",
"(",
"self",
".",
"_token2idx",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"You need to build vocabu... | 41.333333 | 22.583333 |
def _addr_to_function(self, addr, blockaddr_to_function, known_functions):
"""
Convert an address to a Function object, and store the mapping in a dict. If the block is known to be part of a
function, just return that function.
:param int addr: Address to convert
:param dict blo... | [
"def",
"_addr_to_function",
"(",
"self",
",",
"addr",
",",
"blockaddr_to_function",
",",
"known_functions",
")",
":",
"if",
"addr",
"in",
"blockaddr_to_function",
":",
"f",
"=",
"blockaddr_to_function",
"[",
"addr",
"]",
"else",
":",
"is_syscall",
"=",
"self",
... | 41.738095 | 23.595238 |
def admin_link(obj):
"""
Returns a link to the admin URL of an object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_link }}
renders as::
<a href='/admin/foo/123'>Foo</a>
:param obj:... | [
"def",
"admin_link",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'get_admin_link'",
")",
":",
"return",
"mark_safe",
"(",
"obj",
".",
"get_admin_link",
"(",
")",
")",
"return",
"mark_safe",
"(",
"admin_link_fn",
"(",
"obj",
")",
")"
] | 24.863636 | 20.136364 |
def featuretypes(self):
"""
Iterate over feature types found in the database.
Returns
-------
A generator object that yields featuretypes (as strings)
"""
c = self.conn.cursor()
c.execute(
'''
SELECT DISTINCT featuretype from featu... | [
"def",
"featuretypes",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"'''\n SELECT DISTINCT featuretype from features\n '''",
")",
"for",
"i",
",",
"in",
"c",
":",
"yield",
"i"
] | 24.466667 | 18.866667 |
def stop(self):
"""Stop listening for keyboard input events."""
self.state = False
with display_manager(self.display) as d:
d.record_disable_context(self.ctx)
d.ungrab_keyboard(X.CurrentTime)
with display_manager(self.display2):
d.record_disable_contex... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"state",
"=",
"False",
"with",
"display_manager",
"(",
"self",
".",
"display",
")",
"as",
"d",
":",
"d",
".",
"record_disable_context",
"(",
"self",
".",
"ctx",
")",
"d",
".",
"ungrab_keyboard",
"(",
... | 40.888889 | 7.888889 |
def execute_deploy_from_linked_clone(self, si, logger, vcenter_data_model, reservation_id, deployment_params, cancellation_context, folder_manager):
"""
Calls the deployer to deploy vm from snapshot
:param cancellation_context:
:param str reservation_id:
:param si:
:param... | [
"def",
"execute_deploy_from_linked_clone",
"(",
"self",
",",
"si",
",",
"logger",
",",
"vcenter_data_model",
",",
"reservation_id",
",",
"deployment_params",
",",
"cancellation_context",
",",
"folder_manager",
")",
":",
"self",
".",
"_prepare_deployed_apps_folder",
"(",... | 49.1875 | 29.3125 |
def _check_contraint(self, edge1, edge2):
"""Check if two edges satisfy vine constraint.
Args:
:param edge1: edge object representing edge1
:param edge2: edge object representing edge2
:type edge1: Edge object
:type edge2: Edge object
Returns:
... | [
"def",
"_check_contraint",
"(",
"self",
",",
"edge1",
",",
"edge2",
")",
":",
"full_node",
"=",
"set",
"(",
"[",
"edge1",
".",
"L",
",",
"edge1",
".",
"R",
",",
"edge2",
".",
"L",
",",
"edge2",
".",
"R",
"]",
")",
"full_node",
".",
"update",
"(",... | 35.0625 | 15.125 |
def update_links_and_ffts(self):
"""FFT (856) Dealing with files."""
for field in record_get_field_instances(self.record,
tag='856',
ind1='4'):
subs = field_get_subfields(field)
newsub... | [
"def",
"update_links_and_ffts",
"(",
"self",
")",
":",
"for",
"field",
"in",
"record_get_field_instances",
"(",
"self",
".",
"record",
",",
"tag",
"=",
"'856'",
",",
"ind1",
"=",
"'4'",
")",
":",
"subs",
"=",
"field_get_subfields",
"(",
"field",
")",
"news... | 43.862069 | 16.310345 |
def recv(self):
"""Receive message from the backend or wait unilt next message."""
try:
message = self.ws.recv()
return json.loads(message)
except websocket._exceptions.WebSocketConnectionClosedException as ex:
raise SelenolWebSocketClosedException() from ex | [
"def",
"recv",
"(",
"self",
")",
":",
"try",
":",
"message",
"=",
"self",
".",
"ws",
".",
"recv",
"(",
")",
"return",
"json",
".",
"loads",
"(",
"message",
")",
"except",
"websocket",
".",
"_exceptions",
".",
"WebSocketConnectionClosedException",
"as",
"... | 44.571429 | 16.571429 |
def create_event(self, event):
"""Create event
Parameters
----------
event : iCalendar file as a string
(calendar containing one event to be added)
"""
ev = api.Event.create(self.journal.collection, event)
ev.save() | [
"def",
"create_event",
"(",
"self",
",",
"event",
")",
":",
"ev",
"=",
"api",
".",
"Event",
".",
"create",
"(",
"self",
".",
"journal",
".",
"collection",
",",
"event",
")",
"ev",
".",
"save",
"(",
")"
] | 27.1 | 15.1 |
def load_plug_in(self, name):
"""Loads a DBGF plug-in.
in name of type str
The plug-in name or DLL. Special name 'all' loads all installed plug-ins.
return plug_in_name of type str
The name of the loaded plug-in.
"""
if not isinstance(name, basestring):... | [
"def",
"load_plug_in",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"name can only be an instance of type basestring\"",
")",
"plug_in_name",
"=",
"self",
".",
"_call",
"(",... | 33 | 17.466667 |
def filter(self, u):
"""Filter the valid identities for this matcher.
:param u: unique identity which stores the identities to filter
:returns: a list of identities valid to work with this matcher.
:raises ValueError: when the unique identity is not an instance
of UniqueId... | [
"def",
"filter",
"(",
"self",
",",
"u",
")",
":",
"if",
"not",
"isinstance",
"(",
"u",
",",
"UniqueIdentity",
")",
":",
"raise",
"ValueError",
"(",
"\"<u> is not an instance of UniqueIdentity\"",
")",
"filtered",
"=",
"[",
"]",
"for",
"id_",
"in",
"u",
"."... | 30.290323 | 23.354839 |
def main(args, stop=False):
"""
Arguments parsing, etc..
"""
daemon = AMQPDaemon(
con_param=getConParams(
settings.RABBITMQ_CALIBRE_VIRTUALHOST
),
queue=settings.RABBITMQ_CALIBRE_INPUT_QUEUE,
out_exch=settings.RABBITMQ_CALIBRE_EXCHANGE,
out_key=setting... | [
"def",
"main",
"(",
"args",
",",
"stop",
"=",
"False",
")",
":",
"daemon",
"=",
"AMQPDaemon",
"(",
"con_param",
"=",
"getConParams",
"(",
"settings",
".",
"RABBITMQ_CALIBRE_VIRTUALHOST",
")",
",",
"queue",
"=",
"settings",
".",
"RABBITMQ_CALIBRE_INPUT_QUEUE",
... | 29.157895 | 16.105263 |
def _cmp_date(self):
"""Returns Calendar date used for comparison.
Use the earliest date out of all CalendarDates in this instance,
or some date in the future if there are no CalendarDates (e.g.
when Date is a phrase).
"""
dates = sorted(val for val in self.kw.values()
... | [
"def",
"_cmp_date",
"(",
"self",
")",
":",
"dates",
"=",
"sorted",
"(",
"val",
"for",
"val",
"in",
"self",
".",
"kw",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"val",
",",
"CalendarDate",
")",
")",
"if",
"dates",
":",
"return",
"dates",
"["... | 37.230769 | 16.307692 |
def wrap_subscribe(transport_layer, channel, callback, *args, **kwargs):
"""Listen to a queue on the transport layer, similar to the subscribe call in
transport/common_transport.py. Intercept all incoming messages and parse
for recipe information.
See common_transport.subscribe for possible additional k... | [
"def",
"wrap_subscribe",
"(",
"transport_layer",
",",
"channel",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_wrap_subscription",
"(",
"transport_layer",
",",
"transport_layer",
".",
"subscribe",
",",
"channel",
",",
"callb... | 52.588235 | 23.764706 |
def find_melody(file='440_480_clean.wav', chunksize=512):
"""Cut the sample into chunks and analyze each chunk.
Return a list [(Note, chunks)] where chunks is the number of chunks
where that note is the most dominant.
If two consequent chunks turn out to return the same Note they are
grouped toget... | [
"def",
"find_melody",
"(",
"file",
"=",
"'440_480_clean.wav'",
",",
"chunksize",
"=",
"512",
")",
":",
"(",
"data",
",",
"freq",
",",
"bits",
")",
"=",
"data_from_file",
"(",
"file",
")",
"res",
"=",
"[",
"]",
"for",
"d",
"in",
"analyze_chunks",
"(",
... | 31.913043 | 16.434783 |
def save_veto_definer(cp, out_dir, tags=None):
""" Retrieve the veto definer file and save it locally
Parameters
-----------
cp : ConfigParser instance
out_dir : path
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options.
"""
if ta... | [
"def",
"save_veto_definer",
"(",
"cp",
",",
"out_dir",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"make_analysis_dir",
"(",
"out_dir",
")",
"veto_def_url",
"=",
"cp",
".",
"get_opt_tags",
"(",
"\"workflow-... | 35.12 | 17.32 |
def read_csv_from_file(filename):
"""
Opens the target CSV file and creates a dictionary with one list for each CSV column.
:param str filename:
:return list of lists: column values
"""
logger_csvs.info("enter read_csv_from_file")
d = {}
l = []
try:
logger_csvs.info("open fi... | [
"def",
"read_csv_from_file",
"(",
"filename",
")",
":",
"logger_csvs",
".",
"info",
"(",
"\"enter read_csv_from_file\"",
")",
"d",
"=",
"{",
"}",
"l",
"=",
"[",
"]",
"try",
":",
"logger_csvs",
".",
"info",
"(",
"\"open file: {}\"",
".",
"format",
"(",
"fil... | 34.794118 | 17.911765 |
def parse(self, filename=None, file=None, debuglevel=0):
""" Parse file.
kwargs:
filename (str): File to parse
debuglevel (int): Parser debuglevel
"""
self.scope.push()
if not file:
# We use a path.
file = filename
else:
... | [
"def",
"parse",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"file",
"=",
"None",
",",
"debuglevel",
"=",
"0",
")",
":",
"self",
".",
"scope",
".",
"push",
"(",
")",
"if",
"not",
"file",
":",
"# We use a path.",
"file",
"=",
"filename",
"else",
... | 33.571429 | 16.714286 |
def c_drop(self, frequency):
'''
Capacitance of an electrode covered in liquid, normalized per unit
area (i.e., units are F/mm^2).
'''
try:
return np.interp(frequency,
self._c_drop['frequency'],
self._c_drop['c... | [
"def",
"c_drop",
"(",
"self",
",",
"frequency",
")",
":",
"try",
":",
"return",
"np",
".",
"interp",
"(",
"frequency",
",",
"self",
".",
"_c_drop",
"[",
"'frequency'",
"]",
",",
"self",
".",
"_c_drop",
"[",
"'capacitance'",
"]",
")",
"except",
":",
"... | 30.384615 | 19.615385 |
def get_response(self):
"""
Get a response from the chatbot and display it.
"""
user_input = self.usr_input.get()
self.usr_input.delete(0, tk.END)
response = self.chatbot.get_response(user_input)
self.conversation['state'] = 'normal'
self.conversation.in... | [
"def",
"get_response",
"(",
"self",
")",
":",
"user_input",
"=",
"self",
".",
"usr_input",
".",
"get",
"(",
")",
"self",
".",
"usr_input",
".",
"delete",
"(",
"0",
",",
"tk",
".",
"END",
")",
"response",
"=",
"self",
".",
"chatbot",
".",
"get_respons... | 30.3125 | 17.9375 |
def print_http_nfc_lease_info(info):
""" Prints information about the lease,
such as the entity covered by the lease,
and HTTP URLs for up/downloading file backings.
:param info:
:type info: vim.HttpNfcLease.Info
:return:
"""
print 'Lease timeout: {0.leaseTimeout}\n' \
'Disk Ca... | [
"def",
"print_http_nfc_lease_info",
"(",
"info",
")",
":",
"print",
"'Lease timeout: {0.leaseTimeout}\\n'",
"'Disk Capacity KB: {0.totalDiskCapacityInKB}'",
".",
"format",
"(",
"info",
")",
"device_number",
"=",
"1",
"if",
"info",
".",
"deviceUrl",
":",
"for",
"device_u... | 42.107143 | 16.035714 |
def delete_jobs(self,
user_ids,
job_ids,
task_ids,
labels,
create_time_min=None,
create_time_max=None):
"""Kills the operations associated with the specified job or job.task.
Args:
user_ids: List o... | [
"def",
"delete_jobs",
"(",
"self",
",",
"user_ids",
",",
"job_ids",
",",
"task_ids",
",",
"labels",
",",
"create_time_min",
"=",
"None",
",",
"create_time_max",
"=",
"None",
")",
":",
"# Look up the job(s)",
"tasks",
"=",
"list",
"(",
"self",
".",
"lookup_jo... | 36.081081 | 17.945946 |
def _decode_caveat_v1(key, caveat):
'''Decode a base64 encoded JSON id.
@param key the nacl private key to decode.
@param caveat a base64 encoded JSON string.
'''
data = base64.b64decode(caveat).decode('utf-8')
wrapper = json.loads(data)
tp_public_key = nacl.public.PublicKey(
base6... | [
"def",
"_decode_caveat_v1",
"(",
"key",
",",
"caveat",
")",
":",
"data",
"=",
"base64",
".",
"b64decode",
"(",
"caveat",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"wrapper",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"tp_public_key",
"=",
"nacl",
".",... | 35.512821 | 16.538462 |
def execute(helper, config, args):
"""
The init command
"""
# check to see if the application exists
if not helper.application_exists():
helper.create_application(get(config, 'app.description'))
else:
out("Application "+get(config, 'app.app_name')+" exists")
# create enviro... | [
"def",
"execute",
"(",
"helper",
",",
"config",
",",
"args",
")",
":",
"# check to see if the application exists",
"if",
"not",
"helper",
".",
"application_exists",
"(",
")",
":",
"helper",
".",
"create_application",
"(",
"get",
"(",
"config",
",",
"'app.descrip... | 44.679245 | 22.641509 |
def swd_read16(self, offset):
"""Gets a unit of ``16`` bits from the input buffer.
Args:
self (JLink): the ``JLink`` instance
offset (int): the offset (in bits) from which to start reading
Returns:
The integer read from the input buffer.
"""
value ... | [
"def",
"swd_read16",
"(",
"self",
",",
"offset",
")",
":",
"value",
"=",
"self",
".",
"_dll",
".",
"JLINK_SWD_GetU16",
"(",
"offset",
")",
"return",
"ctypes",
".",
"c_uint16",
"(",
"value",
")",
".",
"value"
] | 32.416667 | 16.833333 |
def scroll(self, x, y):
"""Scroll the contents of the console in the direction of x,y.
Uncovered areas will be cleared to the default background color.
Does not move the virutal cursor.
Args:
x (int): Distance to scroll along the x-axis.
y (int): Distance to scr... | [
"def",
"scroll",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"assert",
"isinstance",
"(",
"x",
",",
"_INTTYPES",
")",
",",
"\"x must be an integer, got %s\"",
"%",
"repr",
"(",
"x",
")",
"assert",
"isinstance",
"(",
"y",
",",
"_INTTYPES",
")",
",",
"\"y... | 41.597222 | 16.680556 |
def download_attachments(self, dataset_identifier, content_type="json",
download_dir="~/sodapy_downloads"):
'''
Download all of the attachments associated with a dataset. Return the paths of downloaded
files.
'''
metadata = self.get_metadata(dataset_i... | [
"def",
"download_attachments",
"(",
"self",
",",
"dataset_identifier",
",",
"content_type",
"=",
"\"json\"",
",",
"download_dir",
"=",
"\"~/sodapy_downloads\"",
")",
":",
"metadata",
"=",
"self",
".",
"get_metadata",
"(",
"dataset_identifier",
",",
"content_type",
"... | 44.916667 | 25.194444 |
def space_before(self):
"""
The EMU equivalent of the centipoints value in
`./a:spcBef/a:spcPts/@val`.
"""
spcBef = self.spcBef
if spcBef is None:
return None
spcPts = spcBef.spcPts
if spcPts is None:
return None
return spcP... | [
"def",
"space_before",
"(",
"self",
")",
":",
"spcBef",
"=",
"self",
".",
"spcBef",
"if",
"spcBef",
"is",
"None",
":",
"return",
"None",
"spcPts",
"=",
"spcBef",
".",
"spcPts",
"if",
"spcPts",
"is",
"None",
":",
"return",
"None",
"return",
"spcPts",
".... | 26.25 | 11.25 |
def verify_uri(endpoint_context, request, uri_type, client_id=None):
"""
A redirect URI
MUST NOT contain a fragment
MAY contain query component
:param endpoint_context:
:param request:
:param uri_type: redirect_uri/post_logout_redirect_uri
:return: An error response if the redirect URI ... | [
"def",
"verify_uri",
"(",
"endpoint_context",
",",
"request",
",",
"uri_type",
",",
"client_id",
"=",
"None",
")",
":",
"try",
":",
"_cid",
"=",
"request",
"[",
"\"client_id\"",
"]",
"except",
"KeyError",
":",
"_cid",
"=",
"client_id",
"if",
"not",
"_cid",... | 34.985507 | 21.043478 |
def parse_keqv_list(l):
"""Parse list of key=value strings where keys are not duplicated."""
parsed = {}
for elt in l:
k, v = elt.split('=', 1)
if v[0] == '"' and v[-1] == '"':
v = v[1:-1]
parsed[k] = v
return parsed | [
"def",
"parse_keqv_list",
"(",
"l",
")",
":",
"parsed",
"=",
"{",
"}",
"for",
"elt",
"in",
"l",
":",
"k",
",",
"v",
"=",
"elt",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"v",
"[",
"0",
"]",
"==",
"'\"'",
"and",
"v",
"[",
"-",
"1",
"]... | 28.888889 | 14.666667 |
def traverse_commits(self) -> Generator[Commit, None, None]:
"""
Analyze all the specified commits (all of them by default), returning
a generator of commits.
"""
if isinstance(self._path_to_repo, str):
self._path_to_repo = [self._path_to_repo]
for path_repo... | [
"def",
"traverse_commits",
"(",
"self",
")",
"->",
"Generator",
"[",
"Commit",
",",
"None",
",",
"None",
"]",
":",
"if",
"isinstance",
"(",
"self",
".",
"_path_to_repo",
",",
"str",
")",
":",
"self",
".",
"_path_to_repo",
"=",
"[",
"self",
".",
"_path_... | 39.105263 | 21.842105 |
def run_parse(self):
"""Parse one or more log files"""
# Data set already has source file names from load_inputs
parsedset = {}
parsedset['data_set'] = []
for log in self.input_files:
parsemodule = self.parse_modules[self.args.parser]
try:
... | [
"def",
"run_parse",
"(",
"self",
")",
":",
"# Data set already has source file names from load_inputs",
"parsedset",
"=",
"{",
"}",
"parsedset",
"[",
"'data_set'",
"]",
"=",
"[",
"]",
"for",
"log",
"in",
"self",
".",
"input_files",
":",
"parsemodule",
"=",
"self... | 38.857143 | 14.214286 |
def read_storage_class(self, name, **kwargs):
"""
read the specified StorageClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_storage_class(name, async_req=True)
>>> result... | [
"def",
"read_storage_class",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"read_storage_class_with_h... | 52.565217 | 25.26087 |
def status(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a trail name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.describe mytrail
'''
try:
conn... | [
"def",
"status",
"(",
"Name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
... | 37.948718 | 22.358974 |
def get_data(session=None, day=None, year=None):
"""
Get data for day (1-25) and year (>= 2015)
User's session cookie is needed (puzzle inputs differ by user)
"""
if session is None:
user = default_user()
else:
user = User(token=session)
if day is None:
day = current_... | [
"def",
"get_data",
"(",
"session",
"=",
"None",
",",
"day",
"=",
"None",
",",
"year",
"=",
"None",
")",
":",
"if",
"session",
"is",
"None",
":",
"user",
"=",
"default_user",
"(",
")",
"else",
":",
"user",
"=",
"User",
"(",
"token",
"=",
"session",
... | 31.176471 | 11.411765 |
def get_abbr_impl():
# type: () -> str
"""Return abbreviated implementation name."""
if hasattr(sys, 'pypy_version_info'):
pyimpl = 'pp'
elif sys.platform.startswith('java'):
pyimpl = 'jy'
elif sys.platform == 'cli':
pyimpl = 'ip'
else:
pyimpl = 'cp'
return py... | [
"def",
"get_abbr_impl",
"(",
")",
":",
"# type: () -> str",
"if",
"hasattr",
"(",
"sys",
",",
"'pypy_version_info'",
")",
":",
"pyimpl",
"=",
"'pp'",
"elif",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'java'",
")",
":",
"pyimpl",
"=",
"'jy'",
"elif",... | 26.083333 | 15 |
def set_parallel_multiple(self, value):
"""
Setter for 'parallel_multiple' field.
:param value - a new value of 'parallel_multiple' field. Must be a boolean type. Does not accept None value.
"""
if value is None or not isinstance(value, bool):
raise TypeError("Paralle... | [
"def",
"set_parallel_multiple",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"ParallelMultiple must be set to a bool\"",
")",
"else",
":",
"self",... | 44.888889 | 17.555556 |
def handle(self):
"""Handles kick off request."""
# Get and verify mr state.
mr_id = self.request.get("mapreduce_id")
# Log the mr_id since this is started in an unnamed task
logging.info("Processing kickoff for job %s", mr_id)
state = model.MapreduceState.get_by_job_id(mr_id)
if not self._c... | [
"def",
"handle",
"(",
"self",
")",
":",
"# Get and verify mr state.",
"mr_id",
"=",
"self",
".",
"request",
".",
"get",
"(",
"\"mapreduce_id\"",
")",
"# Log the mr_id since this is started in an unnamed task",
"logging",
".",
"info",
"(",
"\"Processing kickoff for job %s\... | 37.975 | 19.25 |
async def create_connection(self, protocol_factory, host, port, *,
resolve=False, ssl=None,
family=0, proto=0, flags=0):
'''Set up a connection to (host, port) through the proxy.
If resolve is True then host is resolved locally with
... | [
"async",
"def",
"create_connection",
"(",
"self",
",",
"protocol_factory",
",",
"host",
",",
"port",
",",
"*",
",",
"resolve",
"=",
"False",
",",
"ssl",
"=",
"None",
",",
"family",
"=",
"0",
",",
"proto",
"=",
"0",
",",
"flags",
"=",
"0",
")",
":",... | 46.030303 | 26.030303 |
def getCallSet(self, id_):
"""
Returns a CallSet with the specified id, or raises a
CallSetNotFoundException if it does not exist.
"""
if id_ not in self._callSetIdMap:
raise exceptions.CallSetNotFoundException(id_)
return self._callSetIdMap[id_] | [
"def",
"getCallSet",
"(",
"self",
",",
"id_",
")",
":",
"if",
"id_",
"not",
"in",
"self",
".",
"_callSetIdMap",
":",
"raise",
"exceptions",
".",
"CallSetNotFoundException",
"(",
"id_",
")",
"return",
"self",
".",
"_callSetIdMap",
"[",
"id_",
"]"
] | 37.375 | 8.625 |
def import_deleted_fields(self, data):
"""
Set data fields to deleted
"""
if self.get_read_only() and self.is_locked():
return
if isinstance(data, str):
data = [data]
for key in data:
if hasattr(self, key):
delattr(se... | [
"def",
"import_deleted_fields",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"get_read_only",
"(",
")",
"and",
"self",
".",
"is_locked",
"(",
")",
":",
"return",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"data",
"=",
"[",
"data... | 22.565217 | 16.913043 |
def allowed_values(self):
"""A tuple containing the allowed values for this Slot.
The Python equivalent of the CLIPS slot-allowed-values function.
"""
data = clips.data.DataObject(self._env)
lib.EnvDeftemplateSlotAllowedValues(
self._env, self._tpl, self._name, dat... | [
"def",
"allowed_values",
"(",
"self",
")",
":",
"data",
"=",
"clips",
".",
"data",
".",
"DataObject",
"(",
"self",
".",
"_env",
")",
"lib",
".",
"EnvDeftemplateSlotAllowedValues",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_tpl",
",",
"self",
".",
"_... | 32.583333 | 22.25 |
def _end_channel(self, channel):
"""
Soft end of ssh channel. End the writing thread as soon as the message queue is empty.
"""
self.stop_on_empty_queue[channel] = True
# by joining the we wait until its loop finishes.
# it won't loop forever since we've set self.stop_on... | [
"def",
"_end_channel",
"(",
"self",
",",
"channel",
")",
":",
"self",
".",
"stop_on_empty_queue",
"[",
"channel",
"]",
"=",
"True",
"# by joining the we wait until its loop finishes.",
"# it won't loop forever since we've set self.stop_on_empty_queue=True",
"write_thread",
"=",... | 39.545455 | 20.818182 |
def available_backends(self, hub=None, group=None, project=None, access_token=None, user_id=None):
"""
Get the backends available to use in the QX Platform
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set... | [
"def",
"available_backends",
"(",
"self",
",",
"hub",
"=",
"None",
",",
"group",
"=",
"None",
",",
"project",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"c... | 38.263158 | 18.578947 |
def Connect(self, Username, WaitConnected=False):
"""Connects application to user.
:Parameters:
Username : str
Name of the user to connect to.
WaitConnected : bool
If True, causes the method to wait until the connection is established.
:return: If ``... | [
"def",
"Connect",
"(",
"self",
",",
"Username",
",",
"WaitConnected",
"=",
"False",
")",
":",
"if",
"WaitConnected",
":",
"self",
".",
"_Connect_Event",
"=",
"threading",
".",
"Event",
"(",
")",
"self",
".",
"_Connect_Stream",
"=",
"[",
"None",
"]",
"sel... | 43.5 | 19.821429 |
def find_optimal_allocation(self, tokens):
"""
Finds longest, non-overlapping word-ranges of phrases in tokens stored in TokenTrie
:param tokens: tokens tokenize
:type tokens: list of str
:return: Optimal allocation of tokens to phrases
:rtype: list of TokenTrie.Token
... | [
"def",
"find_optimal_allocation",
"(",
"self",
",",
"tokens",
")",
":",
"token_ranges",
"=",
"self",
".",
"find_tracked_words",
"(",
"tokens",
")",
"token_ranges",
".",
"sort",
"(",
")",
"for",
"offset",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"token_ran... | 37.708333 | 18.291667 |
def from_str(string):
"""Generate a `SetReadingEvent` object from a string
"""
match = re.match(r'^START READING (\w+) FROM \w+ (\d+)$', string)
if match:
return SetReadingEvent(match.group(1), int(match.group(2)))
else:
raise EventParseError | [
"def",
"from_str",
"(",
"string",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r'^START READING (\\w+) FROM \\w+ (\\d+)$'",
",",
"string",
")",
"if",
"match",
":",
"return",
"SetReadingEvent",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"int",
"("... | 37.375 | 17.5 |
def NonUniformImage(x, y, z, ax=None, fig=None, cmap=None, alpha=None, scalex=True, scaley=True, add_cbar=True, **kwargs):
"""
Used to plot a set of coordinates.
Parameters
----------
x, y : :class:`numpy.ndarray`
1-D ndarrays of lengths N and M, respectively, specifying pixel centers
... | [
"def",
"NonUniformImage",
"(",
"x",
",",
"y",
",",
"z",
",",
"ax",
"=",
"None",
",",
"fig",
"=",
"None",
",",
"cmap",
"=",
"None",
",",
"alpha",
"=",
"None",
",",
"scalex",
"=",
"True",
",",
"scaley",
"=",
"True",
",",
"add_cbar",
"=",
"True",
... | 27.527778 | 20.555556 |
def reload_(jboss_config, host=None):
'''
Reload running jboss instance
jboss_config
Configuration dictionary with properties specified above.
host
The name of the host. JBoss domain mode only - and required if running in domain mode.
The host name is the "name" attribute of the... | [
"def",
"reload_",
"(",
"jboss_config",
",",
"host",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"\"======================== MODULE FUNCTION: jboss7.reload\"",
")",
"if",
"host",
"is",
"None",
":",
"operation",
"=",
"':reload'",
"else",
":",
"operation",
"="... | 48.533333 | 40.133333 |
def _ReturnConnection(self):
"""
Returns a connection back to the pool
@author: Nick Verbeck
@since: 9/7/2008
"""
if self.conn is not None:
if self.connInfo.commitOnEnd is True or self.commitOnEnd is True:
self.conn.Commit()
Pool().returnConnection(self.conn)
self.conn = None | [
"def",
"_ReturnConnection",
"(",
"self",
")",
":",
"if",
"self",
".",
"conn",
"is",
"not",
"None",
":",
"if",
"self",
".",
"connInfo",
".",
"commitOnEnd",
"is",
"True",
"or",
"self",
".",
"commitOnEnd",
"is",
"True",
":",
"self",
".",
"conn",
".",
"C... | 22.923077 | 16 |
def get_assessment_taken_form(self, *args, **kwargs):
"""Pass through to provider AssessmentTakenAdminSession.get_assessment_taken_form_for_update"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.get_resource_form_for_update
# This method might be a bit s... | [
"def",
"get_assessment_taken_form",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Implemented from kitosid template for -",
"# osid.resource.ResourceAdminSession.get_resource_form_for_update",
"# This method might be a bit sketchy. Time will tell.",
"if",
"is... | 65.444444 | 24.444444 |
def _get_struct_rect(self):
"""Get the RECT structure."""
bc = BitConsumer(self._src)
nbits = bc.u_get(5)
if self._read_twips:
return tuple(bc.s_get(nbits) for _ in range(4))
else:
return tuple(bc.s_get(nbits) / 20.0 for _ in range(4)) | [
"def",
"_get_struct_rect",
"(",
"self",
")",
":",
"bc",
"=",
"BitConsumer",
"(",
"self",
".",
"_src",
")",
"nbits",
"=",
"bc",
".",
"u_get",
"(",
"5",
")",
"if",
"self",
".",
"_read_twips",
":",
"return",
"tuple",
"(",
"bc",
".",
"s_get",
"(",
"nbi... | 36.5 | 14.375 |
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the Locate response payload and decode it
into its constituent parts.
Args:
input_buffer (stream): A data buffer containing encoded object
data, supporting a rea... | [
"def",
"read",
"(",
"self",
",",
"input_buffer",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"LocateResponsePayload",
",",
"self",
")",
".",
"read",
"(",
"input_buffer",
",",
"kmip_version",
"=",
"kmip_vers... | 39.166667 | 19.833333 |
def page_format(self, topmargin, bottommargin):
'''Specify settings for top and bottom margins. Physically printable area depends on media.
Args:
topmargin: the top margin, in dots. The top margin must be less than the bottom margin.
bottommargin: the bottom margin, in d... | [
"def",
"page_format",
"(",
"self",
",",
"topmargin",
",",
"bottommargin",
")",
":",
"tL",
"=",
"topmargin",
"%",
"256",
"tH",
"=",
"topmargin",
"/",
"256",
"BL",
"=",
"bottommargin",
"%",
"256",
"BH",
"=",
"topmargin",
"/",
"256",
"if",
"(",
"tL",
"+... | 43.631579 | 29.105263 |
def configure(self, options, conf):
"""Configure plugin.
"""
if not self.available():
self.enabled = False
return
Plugin.configure(self, options, conf)
self.conf = conf
if options.profile_stats_file:
self.pfile = options.profile_stats_f... | [
"def",
"configure",
"(",
"self",
",",
"options",
",",
"conf",
")",
":",
"if",
"not",
"self",
".",
"available",
"(",
")",
":",
"self",
".",
"enabled",
"=",
"False",
"return",
"Plugin",
".",
"configure",
"(",
"self",
",",
"options",
",",
"conf",
")",
... | 32.882353 | 8.588235 |
def cli():
"""Entry point for the application script"""
parser = get_argparser()
args = parser.parse_args()
check_args(args)
if args.v:
print('ERAlchemy version {}.'.format(__version__))
exit(0)
render_er(
args.i,
args.o,
include_tables=args.include_table... | [
"def",
"cli",
"(",
")",
":",
"parser",
"=",
"get_argparser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"check_args",
"(",
"args",
")",
"if",
"args",
".",
"v",
":",
"print",
"(",
"'ERAlchemy version {}.'",
".",
"format",
"(",
"__vers... | 26.055556 | 18.166667 |
def validate_path_parameters(target_path, api_path, path_parameters, context):
"""
Helper function for validating a request path
"""
base_path = context.get('basePath', '')
full_api_path = re.sub(NORMALIZE_SLASH_REGEX, '/', base_path + api_path)
parameter_values = get_path_parameter_values(
... | [
"def",
"validate_path_parameters",
"(",
"target_path",
",",
"api_path",
",",
"path_parameters",
",",
"context",
")",
":",
"base_path",
"=",
"context",
".",
"get",
"(",
"'basePath'",
",",
"''",
")",
"full_api_path",
"=",
"re",
".",
"sub",
"(",
"NORMALIZE_SLASH_... | 45 | 18.6 |
def connections_to_object(self, to_obj):
"""
Returns a ``Connection`` query set matching all connections with
the given object as a destination.
"""
self._validate_ctypes(None, to_obj)
return self.connections.filter(to_pk=to_obj.pk) | [
"def",
"connections_to_object",
"(",
"self",
",",
"to_obj",
")",
":",
"self",
".",
"_validate_ctypes",
"(",
"None",
",",
"to_obj",
")",
"return",
"self",
".",
"connections",
".",
"filter",
"(",
"to_pk",
"=",
"to_obj",
".",
"pk",
")"
] | 39.142857 | 7.428571 |
def _processCommandLineArgs():
"""
Get the command line arguments
Parameters: NONE
Returns:
files list of file specifications to be converted
outputFileNames list of output file specifications
(one per input file)
... | [
"def",
"_processCommandLineArgs",
"(",
")",
":",
"import",
"getopt",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"\"hvmo:\"",
",",
"[",
"\"help\"",
",",
"\"verbose\"",
",",
"\"multiEx... | 33.527473 | 24.626374 |
def list_sensors(parent_class, sensor_items, filter, strategy, status,
use_python_identifiers, tuple, refresh):
"""Helper for implementing :meth:`katcp.resource.KATCPResource.list_sensors`
Parameters
----------
sensor_items : tuple of sensor-item tuples
As would be returned th... | [
"def",
"list_sensors",
"(",
"parent_class",
",",
"sensor_items",
",",
"filter",
",",
"strategy",
",",
"status",
",",
"use_python_identifiers",
",",
"tuple",
",",
"refresh",
")",
":",
"filter_re",
"=",
"re",
".",
"compile",
"(",
"filter",
")",
"found_sensors",
... | 48.196721 | 17.196721 |
def indices_to_points(indices, pitch, origin):
"""
Convert indices of an (n,m,p) matrix into a set of voxel center points.
Parameters
----------
indices: (q, 3) int, index of voxel matrix (n,m,p)
pitch: float, what pitch was the voxel matrix computed with
origin: (3,) float, what is the ori... | [
"def",
"indices_to_points",
"(",
"indices",
",",
"pitch",
",",
"origin",
")",
":",
"indices",
"=",
"np",
".",
"asanyarray",
"(",
"indices",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"origin",
"=",
"np",
".",
"asanyarray",
"(",
"origin",
",",
"dtype... | 29.571429 | 20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.