text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def load_modules_alignak_configuration(self): # pragma: no cover, not yet with unit tests.
"""Load Alignak configuration from the arbiter modules
If module implements get_alignak_configuration, call this function
:param raw_objects: raw objects we got from reading config files
:type ra... | [
"def",
"load_modules_alignak_configuration",
"(",
"self",
")",
":",
"# pragma: no cover, not yet with unit tests.",
"alignak_cfg",
"=",
"{",
"}",
"# Ask configured modules if they got configuration for us",
"for",
"instance",
"in",
"self",
".",
"modules_manager",
".",
"instance... | 46.680851 | 20.914894 |
def license_loader(lic_dir=LIC_DIR):
"""Loads licenses from the given directory."""
lics = []
for ln in os.listdir(lic_dir):
lp = os.path.join(lic_dir, ln)
with open(lp) as lf:
txt = lf.read()
lic = License(txt)
lics.append(lic)
return lics | [
"def",
"license_loader",
"(",
"lic_dir",
"=",
"LIC_DIR",
")",
":",
"lics",
"=",
"[",
"]",
"for",
"ln",
"in",
"os",
".",
"listdir",
"(",
"lic_dir",
")",
":",
"lp",
"=",
"os",
".",
"path",
".",
"join",
"(",
"lic_dir",
",",
"ln",
")",
"with",
"open"... | 29.9 | 11.1 |
def __get_league_object():
"""Returns the xml object corresponding to the league
Only designed for internal use"""
# get data
data = mlbgame.data.get_properties()
# return league object
return etree.parse(data).getroot().find('leagues').find('league') | [
"def",
"__get_league_object",
"(",
")",
":",
"# get data",
"data",
"=",
"mlbgame",
".",
"data",
".",
"get_properties",
"(",
")",
"# return league object",
"return",
"etree",
".",
"parse",
"(",
"data",
")",
".",
"getroot",
"(",
")",
".",
"find",
"(",
"'leag... | 33.625 | 15.375 |
def register_renderer(app, id, renderer, force=True):
"""Registers a renderer on the application.
:param app: The :class:`~flask.Flask` application to register the renderer
on
:param id: Internal id-string for the renderer
:param renderer: Renderer to register
:param force: Whether ... | [
"def",
"register_renderer",
"(",
"app",
",",
"id",
",",
"renderer",
",",
"force",
"=",
"True",
")",
":",
"renderers",
"=",
"app",
".",
"extensions",
".",
"setdefault",
"(",
"'nav_renderers'",
",",
"{",
"}",
")",
"if",
"force",
":",
"renderers",
"[",
"i... | 36.1875 | 18.8125 |
def ContainsAddressStr(self, address):
"""
Determine if the wallet contains the address.
Args:
address (str): a string representing the public key.
Returns:
bool: True, if the address is present in the wallet. False otherwise.
"""
for key, contra... | [
"def",
"ContainsAddressStr",
"(",
"self",
",",
"address",
")",
":",
"for",
"key",
",",
"contract",
"in",
"self",
".",
"_contracts",
".",
"items",
"(",
")",
":",
"if",
"contract",
".",
"Address",
"==",
"address",
":",
"return",
"True",
"return",
"False"
] | 30.714286 | 18.571429 |
def perm(A, p):
"""
Symmetric permutation of a symmetric sparse matrix.
:param A: :py:class:`spmatrix`
:param p: :py:class:`matrix` or :class:`list` of length `A.size[0]`
"""
assert isinstance(A,spmatrix), "argument must be a sparse matrix"
assert A.size[0] == A.size[1], "A must be ... | [
"def",
"perm",
"(",
"A",
",",
"p",
")",
":",
"assert",
"isinstance",
"(",
"A",
",",
"spmatrix",
")",
",",
"\"argument must be a sparse matrix\"",
"assert",
"A",
".",
"size",
"[",
"0",
"]",
"==",
"A",
".",
"size",
"[",
"1",
"]",
",",
"\"A must be a squa... | 35.083333 | 22.416667 |
def _build_xpath_expr(attrs):
"""Build an xpath expression to simulate bs4's ability to pass in kwargs to
search for attributes when using the lxml parser.
Parameters
----------
attrs : dict
A dict of HTML attributes. These are NOT checked for validity.
Returns
-------
expr : u... | [
"def",
"_build_xpath_expr",
"(",
"attrs",
")",
":",
"# give class attribute as class_ because class is a python keyword",
"if",
"'class_'",
"in",
"attrs",
":",
"attrs",
"[",
"'class'",
"]",
"=",
"attrs",
".",
"pop",
"(",
"'class_'",
")",
"s",
"=",
"[",
"\"@{key}={... | 32.7 | 22.6 |
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip... | [
"def",
"_aix_memdata",
"(",
")",
":",
"grains",
"=",
"{",
"'mem_total'",
":",
"0",
",",
"'swap_total'",
":",
"0",
"}",
"prtconf",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'prtconf'",
")",
"if",
"prtconf",
":",
"for",
"line",
"in",
... | 36.884615 | 22.5 |
def _validate_iso8601_string(self, value):
"""Return the value or raise a ValueError if it is not a string in ISO8601 format."""
ISO8601_REGEX = r'(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})([+-](\d{2})\:(\d{2})|Z)'
if re.match(ISO8601_REGEX, value):
return value
e... | [
"def",
"_validate_iso8601_string",
"(",
"self",
",",
"value",
")",
":",
"ISO8601_REGEX",
"=",
"r'(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2})\\:(\\d{2})\\:(\\d{2})([+-](\\d{2})\\:(\\d{2})|Z)'",
"if",
"re",
".",
"match",
"(",
"ISO8601_REGEX",
",",
"value",
")",
":",
"return",
"valu... | 56.428571 | 20.428571 |
def admin_content_status(request):
"""
Returns a dictionary with the states and info of baking books,
and the filters from the GET request to pre-populate the form.
"""
statement, sql_args = get_baking_statuses_sql(request.GET)
states = []
status_filters = request.params.getall('status_filt... | [
"def",
"admin_content_status",
"(",
"request",
")",
":",
"statement",
",",
"sql_args",
"=",
"get_baking_statuses_sql",
"(",
"request",
".",
"GET",
")",
"states",
"=",
"[",
"]",
"status_filters",
"=",
"request",
".",
"params",
".",
"getall",
"(",
"'status_filte... | 44.348837 | 14.023256 |
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** i... | [
"def",
"_get_group_dn",
"(",
"self",
",",
"group_lookup_attribute_value",
")",
":",
"self",
".",
"ldap_connection",
".",
"search",
"(",
"search_base",
"=",
"self",
".",
"GROUP_SEARCH",
"[",
"'base_dn'",
"]",
",",
"search_filter",
"=",
"self",
".",
"GROUP_SEARCH"... | 51.074074 | 35.481481 |
def get_minions():
'''
Return a list of minions
'''
conn, mdb = _get_conn(ret=None)
ret = []
name = mdb.saltReturns.distinct('minion')
ret.append(name)
return ret | [
"def",
"get_minions",
"(",
")",
":",
"conn",
",",
"mdb",
"=",
"_get_conn",
"(",
"ret",
"=",
"None",
")",
"ret",
"=",
"[",
"]",
"name",
"=",
"mdb",
".",
"saltReturns",
".",
"distinct",
"(",
"'minion'",
")",
"ret",
".",
"append",
"(",
"name",
")",
... | 20.666667 | 20.444444 |
def create_parser():
""" create parser """
help_epilog = '''Getting more help:
heron-explorer help <command> Disply help and options for <command>\n
For detailed documentation, go to http://heronstreaming.io'''
parser = argparse.ArgumentParser(
prog='heron-explorer',
epilog=help_epilog,
... | [
"def",
"create_parser",
"(",
")",
":",
"help_epilog",
"=",
"'''Getting more help:\n heron-explorer help <command> Disply help and options for <command>\\n\n For detailed documentation, go to http://heronstreaming.io'''",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog"... | 28.083333 | 17.888889 |
def need_record_permission(factory_name):
"""Decorator checking that the user has the required permissions on record.
:param factory_name: name of the permission factory.
"""
def need_record_permission_builder(f):
@wraps(f)
def need_record_permission_decorator(self, record=None, *args,
... | [
"def",
"need_record_permission",
"(",
"factory_name",
")",
":",
"def",
"need_record_permission_builder",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"need_record_permission_decorator",
"(",
"self",
",",
"record",
"=",
"None",
",",
"*",
"args",
",",... | 38.363636 | 14.909091 |
def visit_Call(self, node):
"""Propagate 'debug' wrapper into inner function calls if needed.
Args:
node (ast.AST): node statement to surround.
"""
if self.depth == 0:
return node
if self.ignore_exceptions is None:
ignore_exceptions = ast.Nam... | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"depth",
"==",
"0",
":",
"return",
"node",
"if",
"self",
".",
"ignore_exceptions",
"is",
"None",
":",
"ignore_exceptions",
"=",
"ast",
".",
"Name",
"(",
"\"None\"",
",",
"ast",... | 34.758621 | 22.068966 |
def check_elastic(self):
'''
Checks if we need to break moderation in order to maintain our desired
throttle limit
@return: True if we need to break moderation
'''
if self.elastic and self.elastic_kick_in == self.limit:
value = self.redis_conn.zcard(self.wind... | [
"def",
"check_elastic",
"(",
"self",
")",
":",
"if",
"self",
".",
"elastic",
"and",
"self",
".",
"elastic_kick_in",
"==",
"self",
".",
"limit",
":",
"value",
"=",
"self",
".",
"redis_conn",
".",
"zcard",
"(",
"self",
".",
"window_key",
")",
"if",
"self... | 35.166667 | 22.666667 |
def unstructure_attrs_asdict(self, obj):
# type: (Any) -> Dict[str, Any]
"""Our version of `attrs.asdict`, so we can call back to us."""
attrs = obj.__class__.__attrs_attrs__
dispatch = self._unstructure_func.dispatch
rv = self._dict_factory()
for a in attrs:
... | [
"def",
"unstructure_attrs_asdict",
"(",
"self",
",",
"obj",
")",
":",
"# type: (Any) -> Dict[str, Any]",
"attrs",
"=",
"obj",
".",
"__class__",
".",
"__attrs_attrs__",
"dispatch",
"=",
"self",
".",
"_unstructure_func",
".",
"dispatch",
"rv",
"=",
"self",
".",
"_... | 38.545455 | 8.272727 |
def add_sibling(self, sibling):
"""
Designate this a multi-feature representative and add a co-feature.
Some features exist discontinuously on the sequence, and therefore
cannot be declared with a single GFF3 entry (which can encode only a
single interval). The canonical encodin... | [
"def",
"add_sibling",
"(",
"self",
",",
"sibling",
")",
":",
"assert",
"self",
".",
"is_pseudo",
"is",
"False",
"if",
"self",
".",
"siblings",
"is",
"None",
":",
"self",
".",
"siblings",
"=",
"list",
"(",
")",
"self",
".",
"multi_rep",
"=",
"self",
"... | 45.92 | 23.04 |
def _fix_lsm_bitspersample(self, parent):
"""Correct LSM bitspersample tag.
Old LSM writers may use a separate region for two 16-bit values,
although they fit into the tag value element of the tag.
"""
if self.code != 258 or self.count != 2:
return
# TODO: t... | [
"def",
"_fix_lsm_bitspersample",
"(",
"self",
",",
"parent",
")",
":",
"if",
"self",
".",
"code",
"!=",
"258",
"or",
"self",
".",
"count",
"!=",
"2",
":",
"return",
"# TODO: test this case; need example file",
"log",
".",
"warning",
"(",
"'TiffTag %i: correcting... | 42.666667 | 18.133333 |
def list_zones(self, max_results=None, page_token=None):
"""List zones for the project associated with this client.
See
https://cloud.google.com/dns/api/v1/managedZones/list
:type max_results: int
:param max_results: maximum number of zones to return, If not
... | [
"def",
"list_zones",
"(",
"self",
",",
"max_results",
"=",
"None",
",",
"page_token",
"=",
"None",
")",
":",
"path",
"=",
"\"/projects/%s/managedZones\"",
"%",
"(",
"self",
".",
"project",
",",
")",
"return",
"page_iterator",
".",
"HTTPIterator",
"(",
"clien... | 41.096774 | 19.774194 |
def simulate(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, grid_size=(80, 80), model="projection",
pixel_size=None, center=None):
"""Simulate scattering at a sphere
Parameters
----------
radius: float
Radius of the sphere [m]
sphere_index:... | [
"def",
"simulate",
"(",
"radius",
"=",
"5e-6",
",",
"sphere_index",
"=",
"1.339",
",",
"medium_index",
"=",
"1.333",
",",
"wavelength",
"=",
"550e-9",
",",
"grid_size",
"=",
"(",
"80",
",",
"80",
")",
",",
"model",
"=",
"\"projection\"",
",",
"pixel_size... | 32.818182 | 14.712121 |
def FromBinary(cls, record_data, record_count=1):
"""Create an UpdateRecord subclass from binary record data.
This should be called with a binary record blob (NOT including the
record type header) and it will decode it into a AddNodeRecord.
Args:
record_data (bytearray): Th... | [
"def",
"FromBinary",
"(",
"cls",
",",
"record_data",
",",
"record_count",
"=",
"1",
")",
":",
"_cmd",
",",
"address",
",",
"_resp_length",
",",
"payload",
"=",
"cls",
".",
"_parse_rpc_info",
"(",
"record_data",
")",
"descriptor",
"=",
"parse_binary_descriptor"... | 40.227273 | 29.045455 |
def persistent_menu(menu):
"""
more: https://developers.facebook.com/docs/messenger-platform/thread-settings/persistent-menu
:param menu:
:return:
"""
if len(menu) > 3:
raise Invalid('menu should not exceed 3 call to actions')
if any(len(item['call_to_actions']) > 5 for item in men... | [
"def",
"persistent_menu",
"(",
"menu",
")",
":",
"if",
"len",
"(",
"menu",
")",
">",
"3",
":",
"raise",
"Invalid",
"(",
"'menu should not exceed 3 call to actions'",
")",
"if",
"any",
"(",
"len",
"(",
"item",
"[",
"'call_to_actions'",
"]",
")",
">",
"5",
... | 36.526316 | 28.315789 |
def generate(self):
"""
Generates the report
"""
self._setup()
for config_name in self.report_info.config_to_test_names_map.keys():
config_dir = os.path.join(self.report_info.resource_dir, config_name)
utils.makedirs(config_dir)
testsuite = self._generate_junit_xml(config_name)
... | [
"def",
"generate",
"(",
"self",
")",
":",
"self",
".",
"_setup",
"(",
")",
"for",
"config_name",
"in",
"self",
".",
"report_info",
".",
"config_to_test_names_map",
".",
"keys",
"(",
")",
":",
"config_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sel... | 43.363636 | 21.727273 |
def cloud_train(train_dataset,
eval_dataset,
analysis_dir,
output_dir,
features,
model_type,
max_steps,
num_epochs,
train_batch_size,
eval_batch_size,
min_eval_... | [
"def",
"cloud_train",
"(",
"train_dataset",
",",
"eval_dataset",
",",
"analysis_dir",
",",
"output_dir",
",",
"features",
",",
"model_type",
",",
"max_steps",
",",
"num_epochs",
",",
"train_batch_size",
",",
"eval_batch_size",
",",
"min_eval_frequency",
",",
"top_n"... | 35.625 | 19.034091 |
def parse(self, commands):
""" Parse a list of commands.
"""
# Get rid of dummy objects that represented deleted objects in
# the last parsing round.
to_delete = []
for id_, val in self._objects.items():
if val == JUST_DELETED:
to_delete.appen... | [
"def",
"parse",
"(",
"self",
",",
"commands",
")",
":",
"# Get rid of dummy objects that represented deleted objects in",
"# the last parsing round.",
"to_delete",
"=",
"[",
"]",
"for",
"id_",
",",
"val",
"in",
"self",
".",
"_objects",
".",
"items",
"(",
")",
":",... | 29.6 | 13.066667 |
def recover_cfg(self, start=None, end=None, symbols=None, callback=None, arch_mode=None):
"""Recover CFG.
Args:
start (int): Start address.
end (int): End address.
symbols (dict): Symbol table.
callback (function): A callback function which is called afte... | [
"def",
"recover_cfg",
"(",
"self",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"symbols",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"arch_mode",
"=",
"None",
")",
":",
"# Set architecture in case it wasn't already set.",
"if",
"arch_mode",
... | 33.038462 | 22.5 |
def CBO_Gamma(self, **kwargs):
'''
Returns the strain-shifted Gamma-valley conduction band offset (CBO),
assuming the strain affects all conduction band valleys equally.
'''
return (self.unstrained.CBO_Gamma(**kwargs) +
self.CBO_strain_shift(**kwargs)) | [
"def",
"CBO_Gamma",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"(",
"self",
".",
"unstrained",
".",
"CBO_Gamma",
"(",
"*",
"*",
"kwargs",
")",
"+",
"self",
".",
"CBO_strain_shift",
"(",
"*",
"*",
"kwargs",
")",
")"
] | 43.142857 | 22.571429 |
def user(self, **params):
"""Stream user
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/user
"""
url = 'https://userstream.twitter.com/%s/user.json' \
% self.streamer.api_version
self.streamer._request(url, params=params) | [
"def",
"user",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"url",
"=",
"'https://userstream.twitter.com/%s/user.json'",
"%",
"self",
".",
"streamer",
".",
"api_version",
"self",
".",
"streamer",
".",
"_request",
"(",
"url",
",",
"params",
"=",
"params",
... | 32.888889 | 11.888889 |
def image(self,path_img):
""" Open image file """
im_open = Image.open(path_img)
im = im_open.convert("RGB")
# Convert the RGB image in printable image
pix_line, img_size = self._convert_image(im)
self._print_image(pix_line, img_size) | [
"def",
"image",
"(",
"self",
",",
"path_img",
")",
":",
"im_open",
"=",
"Image",
".",
"open",
"(",
"path_img",
")",
"im",
"=",
"im_open",
".",
"convert",
"(",
"\"RGB\"",
")",
"# Convert the RGB image in printable image",
"pix_line",
",",
"img_size",
"=",
"se... | 39.428571 | 7 |
def attach_keypress(fig, scaling=1.1):
"""
Attach a key press event handler that configures keys for closing a
figure and changing the figure size. Keys 'e' and 'c' respectively
expand and contract the figure, and key 'q' closes it.
**Note:** Resizing may not function correctly with all matplotlib
... | [
"def",
"attach_keypress",
"(",
"fig",
",",
"scaling",
"=",
"1.1",
")",
":",
"def",
"press",
"(",
"event",
")",
":",
"if",
"event",
".",
"key",
"==",
"'q'",
":",
"plt",
".",
"close",
"(",
"fig",
")",
"elif",
"event",
".",
"key",
"==",
"'e'",
":",
... | 32.710526 | 21.131579 |
def state_province_region(self, value=None):
"""Corresponds to IDD Field `state_province_region`
Args:
value (str): value for IDD Field `state_province_region`
if `value` is None it will not be checked against the
specification and is assumed to be a missing ... | [
"def",
"state_province_region",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"str",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of... | 36.416667 | 20.333333 |
def t_TITLE(self, token):
ur'\#\s+<wca-title>(?P<title>.+)\n'
token.value = token.lexer.lexmatch.group("title").decode("utf8")
token.lexer.lineno += 1
return token | [
"def",
"t_TITLE",
"(",
"self",
",",
"token",
")",
":",
"token",
".",
"value",
"=",
"token",
".",
"lexer",
".",
"lexmatch",
".",
"group",
"(",
"\"title\"",
")",
".",
"decode",
"(",
"\"utf8\"",
")",
"token",
".",
"lexer",
".",
"lineno",
"+=",
"1",
"r... | 38.2 | 15.8 |
def RegisterPartitionResolver(self, database_link, partition_resolver):
"""Registers the partition resolver associated with the database link
:param str database_link:
Database Self Link or ID based link.
:param object partition_resolver:
An instance of PartitionResolver... | [
"def",
"RegisterPartitionResolver",
"(",
"self",
",",
"database_link",
",",
"partition_resolver",
")",
":",
"if",
"not",
"database_link",
":",
"raise",
"ValueError",
"(",
"\"database_link is None or empty.\"",
")",
"if",
"partition_resolver",
"is",
"None",
":",
"raise... | 39.3125 | 20.3125 |
def _init_pressure(self):
"""
Internal. Initialises the pressure sensor via RTIMU
"""
if not self._pressure_init:
self._pressure_init = self._pressure.pressureInit()
if not self._pressure_init:
raise OSError('Pressure Init Failed') | [
"def",
"_init_pressure",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pressure_init",
":",
"self",
".",
"_pressure_init",
"=",
"self",
".",
"_pressure",
".",
"pressureInit",
"(",
")",
"if",
"not",
"self",
".",
"_pressure_init",
":",
"raise",
"OSError... | 32.888889 | 12.888889 |
def random_data(line_count=1, chars_per_line=80):
"""
Function to creates lines of random string data
Args:
line_count: An integer that says how many lines to return
chars_per_line: An integer that says how many characters per line to return
Returns:
A String
"""
divide... | [
"def",
"random_data",
"(",
"line_count",
"=",
"1",
",",
"chars_per_line",
"=",
"80",
")",
":",
"divide_lines",
"=",
"chars_per_line",
"*",
"line_count",
"return",
"'\\n'",
".",
"join",
"(",
"random_line_data",
"(",
"chars_per_line",
")",
"for",
"x",
"in",
"r... | 34.615385 | 24.769231 |
def set_error_callback(self, callback):
"""Assign a method to invoke when a request has encountered an
unrecoverable error in an action execution.
:param method callback: The method to invoke
"""
self.logger.debug('Setting error callback: %r', callback)
self._on_error =... | [
"def",
"set_error_callback",
"(",
"self",
",",
"callback",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Setting error callback: %r'",
",",
"callback",
")",
"self",
".",
"_on_error",
"=",
"callback"
] | 35.666667 | 15.111111 |
def network_protocol(self, layer: Optional[Layer] = None) -> str:
"""Get a random network protocol form OSI model.
:param layer: Enum object Layer.
:return: Protocol name.
:Example:
AMQP
"""
key = self._validate_enum(item=layer, enum=Layer)
protocols... | [
"def",
"network_protocol",
"(",
"self",
",",
"layer",
":",
"Optional",
"[",
"Layer",
"]",
"=",
"None",
")",
"->",
"str",
":",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"item",
"=",
"layer",
",",
"enum",
"=",
"Layer",
")",
"protocols",
"=",
"NET... | 31.583333 | 15.333333 |
def _prepare_version(self):
"""Setup the application version"""
if config.VERSION not in self._config:
self._config[config.VERSION] = __version__ | [
"def",
"_prepare_version",
"(",
"self",
")",
":",
"if",
"config",
".",
"VERSION",
"not",
"in",
"self",
".",
"_config",
":",
"self",
".",
"_config",
"[",
"config",
".",
"VERSION",
"]",
"=",
"__version__"
] | 42.5 | 8.25 |
def download(self, url, dir_path, filename=None):
""" Download the resources specified by url into dir_path. The resulting
file path is returned.
DownloadError is raised the resources cannot be downloaded.
"""
if not filename:
filename = url.rsplit('/', 1)[1]... | [
"def",
"download",
"(",
"self",
",",
"url",
",",
"dir_path",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"filename",
":",
"filename",
"=",
"url",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"1",
"]",
"path",
"=",
"os",
".",
"path",
... | 31.666667 | 15.866667 |
def parse_date(string, formation=None):
"""
string to date stamp
:param string: date string
:param formation: format string
:return: datetime.date
"""
if formation:
_stamp = datetime.datetime.strptime(string, formation).date()
return _stamp... | [
"def",
"parse_date",
"(",
"string",
",",
"formation",
"=",
"None",
")",
":",
"if",
"formation",
":",
"_stamp",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"string",
",",
"formation",
")",
".",
"date",
"(",
")",
"return",
"_stamp",
"_string",
... | 42.534884 | 20.813953 |
def eigtransform(self, sequences, right=True, mode='clip'):
r"""Transform a list of sequences by projecting the sequences onto
the first `n_timescales` dynamical eigenvectors.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequenc... | [
"def",
"eigtransform",
"(",
"self",
",",
"sequences",
",",
"right",
"=",
"True",
",",
"mode",
"=",
"'clip'",
")",
":",
"result",
"=",
"[",
"]",
"for",
"y",
"in",
"self",
".",
"transform",
"(",
"sequences",
",",
"mode",
"=",
"mode",
")",
":",
"if",
... | 41.985714 | 25 |
def p_params(self, p):
'params : params_begin param_end'
p[0] = p[1] + (p[2],)
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_params",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"(",
"p",
"[",
"2",
"]",
",",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 32 | 8.5 |
def SMA(Series, N, M=1):
"""
威廉SMA算法
本次修正主要是对于返回值的优化,现在的返回值会带上原先输入的索引index
2018/5/3
@yutiansut
"""
ret = []
i = 1
length = len(Series)
# 跳过X中前面几个 nan 值
while i < length:
if np.isnan(Series.iloc[i]):
i += 1
else:
break
preY = Series... | [
"def",
"SMA",
"(",
"Series",
",",
"N",
",",
"M",
"=",
"1",
")",
":",
"ret",
"=",
"[",
"]",
"i",
"=",
"1",
"length",
"=",
"len",
"(",
"Series",
")",
"# 跳过X中前面几个 nan 值",
"while",
"i",
"<",
"length",
":",
"if",
"np",
".",
"isnan",
"(",
"Series",
... | 21.16 | 19.48 |
def setDecel(self, vehID, decel):
"""setDecel(string, double) -> None
Sets the preferred maximal deceleration in m/s^2 for this vehicle.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_DECEL, vehID, decel) | [
"def",
"setDecel",
"(",
"self",
",",
"vehID",
",",
"decel",
")",
":",
"self",
".",
"_connection",
".",
"_sendDoubleCmd",
"(",
"tc",
".",
"CMD_SET_VEHICLE_VARIABLE",
",",
"tc",
".",
"VAR_DECEL",
",",
"vehID",
",",
"decel",
")"
] | 38.428571 | 15.571429 |
def Queue(self, name, initial=None, maxsize=None):
"""The queue datatype.
:param name: The name of the queue.
:keyword initial: Initial items in the queue.
See :class:`redish.types.Queue`.
"""
return types.Queue(name, self.api, initial=initial, maxsize=maxsize) | [
"def",
"Queue",
"(",
"self",
",",
"name",
",",
"initial",
"=",
"None",
",",
"maxsize",
"=",
"None",
")",
":",
"return",
"types",
".",
"Queue",
"(",
"name",
",",
"self",
".",
"api",
",",
"initial",
"=",
"initial",
",",
"maxsize",
"=",
"maxsize",
")"... | 30.3 | 18.2 |
def add_color_scheme_stack(self, scheme_name, custom=False):
"""Add a stack for a given scheme and connects the CONF values."""
color_scheme_groups = [
(_('Text'), ["normal", "comment", "string", "number", "keyword",
"builtin", "definition", "instance", ]),
... | [
"def",
"add_color_scheme_stack",
"(",
"self",
",",
"scheme_name",
",",
"custom",
"=",
"False",
")",
":",
"color_scheme_groups",
"=",
"[",
"(",
"_",
"(",
"'Text'",
")",
",",
"[",
"\"normal\"",
",",
"\"comment\"",
",",
"\"string\"",
",",
"\"number\"",
",",
"... | 38.898876 | 19.662921 |
def create_primary_zone_by_upload(self, account_name, zone_name, bind_file):
"""Creates a new primary zone by uploading a bind file
Arguments:
account_name -- The name of the account that will contain this zone.
zone_name -- The name of the zone. It must be unique.
bind_file --... | [
"def",
"create_primary_zone_by_upload",
"(",
"self",
",",
"account_name",
",",
"zone_name",
",",
"bind_file",
")",
":",
"zone_properties",
"=",
"{",
"\"name\"",
":",
"zone_name",
",",
"\"accountName\"",
":",
"account_name",
",",
"\"type\"",
":",
"\"PRIMARY\"",
"}"... | 55.666667 | 29.733333 |
def getParam(self, name=None):
""" Function getParam
Return a dict of parameters or a parameter value
@param key: The parameter name
@return RETURN: dict of parameters or a parameter value
"""
if 'parameters' in self.keys():
l = {x['name']: x['value'] for x i... | [
"def",
"getParam",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"'parameters'",
"in",
"self",
".",
"keys",
"(",
")",
":",
"l",
"=",
"{",
"x",
"[",
"'name'",
"]",
":",
"x",
"[",
"'value'",
"]",
"for",
"x",
"in",
"self",
"[",
"'paramete... | 32.875 | 14 |
def filter(self, *, type_=None, lang=None, attrs={}):
"""
Return an iterable which produces a sequence of the elements inside
this :class:`XSOList`, filtered by the criteria given as arguments. The
function starts with a working sequence consisting of the whole list.
If `type_` ... | [
"def",
"filter",
"(",
"self",
",",
"*",
",",
"type_",
"=",
"None",
",",
"lang",
"=",
"None",
",",
"attrs",
"=",
"{",
"}",
")",
":",
"result",
"=",
"self",
"if",
"type_",
"is",
"not",
"None",
":",
"result",
"=",
"self",
".",
"_filter_type",
"(",
... | 45.875 | 27.416667 |
def dip_and_closest_unimodal_from_cdf(xF, yF, plotting=False, verbose=False, eps=1e-12):
'''
Dip computed as distance between empirical distribution function (EDF) and
cumulative distribution function for the unimodal distribution with
smallest such distance. The optimal unimodal distributio... | [
"def",
"dip_and_closest_unimodal_from_cdf",
"(",
"xF",
",",
"yF",
",",
"plotting",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"eps",
"=",
"1e-12",
")",
":",
"## TODO! Preprocess xF and yF so that yF increasing and xF does",
"## not have more than two copies of each x-... | 38.133929 | 20.5 |
def mean_cl_boot(series, n_samples=1000, confidence_interval=0.95,
random_state=None):
"""
Bootstrapped mean with confidence limits
"""
return bootstrap_statistics(series, np.mean,
n_samples=n_samples,
confidence_interval=c... | [
"def",
"mean_cl_boot",
"(",
"series",
",",
"n_samples",
"=",
"1000",
",",
"confidence_interval",
"=",
"0.95",
",",
"random_state",
"=",
"None",
")",
":",
"return",
"bootstrap_statistics",
"(",
"series",
",",
"np",
".",
"mean",
",",
"n_samples",
"=",
"n_sampl... | 43.333333 | 11.555556 |
def _process_coref_span_annotations_for_word(label: str,
word_index: int,
clusters: DefaultDict[int, List[Tuple[int, int]]],
coref_stacks: DefaultDict[int, List[int]]) -> No... | [
"def",
"_process_coref_span_annotations_for_word",
"(",
"label",
":",
"str",
",",
"word_index",
":",
"int",
",",
"clusters",
":",
"DefaultDict",
"[",
"int",
",",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"]",
",",
"coref_stacks",
":",
"Defaul... | 53.851064 | 25.595745 |
def get_log_entry_form_for_create(self, log_entry_record_types):
"""Gets the log entry form for creating new log entries.
A new form should be requested for each create transaction.
arg: log_entry_record_types (osid.type.Type[]): array of log
entry record types
retur... | [
"def",
"get_log_entry_form_for_create",
"(",
"self",
",",
"log_entry_record_types",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.get_resource_form_for_create_template",
"for",
"arg",
"in",
"log_entry_record_types",
":",
"if",
"not",
"isinstance... | 46.416667 | 18 |
async def sqsStats(self, *args, **kwargs):
"""
Statistics on the sqs queues
This method is only for debugging the ec2-manager
This method is ``experimental``
"""
return await self._makeApiCall(self.funcinfo["sqsStats"], *args, **kwargs) | [
"async",
"def",
"sqsStats",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"sqsStats\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 27.8 | 18.6 |
def _loc(self, pos, idx):
"""Convert an index pair (alpha, beta) into a single index that corresponds to
the position of the value in the sorted list.
Most queries require the index be built. Details of the index are
described in self._build_index.
Indexing requires traversing ... | [
"def",
"_loc",
"(",
"self",
",",
"pos",
",",
"idx",
")",
":",
"if",
"not",
"pos",
":",
"return",
"idx",
"_index",
"=",
"self",
".",
"_index",
"if",
"not",
"len",
"(",
"_index",
")",
":",
"self",
".",
"_build_index",
"(",
")",
"total",
"=",
"0",
... | 28.986301 | 27.273973 |
def _ParseFileEntryWithParser(
self, parser_mediator, parser, file_entry, file_object=None):
"""Parses a file entry with a specific parser.
Args:
parser_mediator (ParserMediator): parser mediator.
parser (BaseParser): parser.
file_entry (dfvfs.FileEntry): file entry.
file_object (... | [
"def",
"_ParseFileEntryWithParser",
"(",
"self",
",",
"parser_mediator",
",",
"parser",
",",
"file_entry",
",",
"file_object",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"parser",
",",
"(",
"parsers_interface",
".",
"FileEntryParser",
",",
"parsers_i... | 39.101449 | 21.927536 |
def send_chat_action(self, chat_id, action):
"""
Use this method when you need to tell the user that something is happening on the bot's side.
The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear
its typing status).
:param chat_id:... | [
"def",
"send_chat_action",
"(",
"self",
",",
"chat_id",
",",
"action",
")",
":",
"return",
"apihelper",
".",
"send_chat_action",
"(",
"self",
".",
"token",
",",
"chat_id",
",",
"action",
")"
] | 62 | 32.727273 |
def parse_radix(self, radix, chars, stream):
"""
BinaryNum ::= [+-]? '2' RadixSymbol [0-1]+ RadixSymbol
OctalChar ::= [+-]? '8' RadixSymbol [0-7]+ RadixSymbol
HexadecimalNum ::= [+-]? '16' RadixSymbol [0-9a-zA-Z]+ RadixSymbol
"""
value = b''
sign = self.parse_sign... | [
"def",
"parse_radix",
"(",
"self",
",",
"radix",
",",
"chars",
",",
"stream",
")",
":",
"value",
"=",
"b''",
"sign",
"=",
"self",
".",
"parse_sign",
"(",
"stream",
")",
"self",
".",
"expect",
"(",
"stream",
",",
"b",
"(",
"str",
"(",
"radix",
")",
... | 33.307692 | 17.769231 |
async def install_sandboxed_update(filename, loop):
"""
Create a virtual environment and activate it, and then install an
update candidate (leaves virtual environment activated)
:return: a result dict and the path to python in the virtual environment
"""
log.debug("Creating virtual environment"... | [
"async",
"def",
"install_sandboxed_update",
"(",
"filename",
",",
"loop",
")",
":",
"log",
".",
"debug",
"(",
"\"Creating virtual environment\"",
")",
"venv_dir",
",",
"python",
",",
"venv_site_pkgs",
"=",
"await",
"create_virtual_environment",
"(",
"loop",
"=",
"... | 42 | 14.947368 |
def base(self, *paths, **query_kwargs):
"""create a new url object using the current base path as a base
if you had requested /foo/bar, then this would append *paths and **query_kwargs
to /foo/bar
:example:
# current path: /foo/bar
print url # http://host.com/f... | [
"def",
"base",
"(",
"self",
",",
"*",
"paths",
",",
"*",
"*",
"query_kwargs",
")",
":",
"kwargs",
"=",
"self",
".",
"_normalize_params",
"(",
"*",
"paths",
",",
"*",
"*",
"query_kwargs",
")",
"if",
"self",
".",
"path",
":",
"if",
"\"path\"",
"in",
... | 38.36 | 22.16 |
def findBinomialNsWithLowerBoundSampleMinimum(confidence, desiredValuesSorted,
p, numSamples, nMax):
"""
For each desired value, find an approximate n for which the sample minimum
has a probabilistic lower bound equal to this value.
For each value, find an adjacent... | [
"def",
"findBinomialNsWithLowerBoundSampleMinimum",
"(",
"confidence",
",",
"desiredValuesSorted",
",",
"p",
",",
"numSamples",
",",
"nMax",
")",
":",
"def",
"P",
"(",
"n",
",",
"numOccurrences",
")",
":",
"\"\"\"\n Given n, return probability than the sample minimum i... | 30.824561 | 24.157895 |
def __register(self, client_id, client_secret, email, scope, first_name,
last_name, original_ip, original_device, **kwargs):
"""Call documentation: `/user/register
<https://www.wepay.com/developer/reference/user#register>`_, plus
extra keyword parameter:
:keyw... | [
"def",
"__register",
"(",
"self",
",",
"client_id",
",",
"client_secret",
",",
"email",
",",
"scope",
",",
"first_name",
",",
"last_name",
",",
"original_ip",
",",
"original_device",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'client_id'",
":"... | 35.516129 | 19.548387 |
def neighbours(self, healpix_index):
"""
Find all the HEALPix pixels that are the neighbours of a HEALPix pixel
Parameters
----------
healpix_index : `~numpy.ndarray`
Array of HEALPix pixels
Returns
-------
neigh : `~numpy.ndarray`
... | [
"def",
"neighbours",
"(",
"self",
",",
"healpix_index",
")",
":",
"return",
"neighbours",
"(",
"healpix_index",
",",
"self",
".",
"nside",
",",
"order",
"=",
"self",
".",
"order",
")"
] | 37.055556 | 21.5 |
def from_schemafile(cls, schemafile):
"""Create a Flatson instance from a schemafile
"""
with open(schemafile) as f:
return cls(json.load(f)) | [
"def",
"from_schemafile",
"(",
"cls",
",",
"schemafile",
")",
":",
"with",
"open",
"(",
"schemafile",
")",
"as",
"f",
":",
"return",
"cls",
"(",
"json",
".",
"load",
"(",
"f",
")",
")"
] | 34.6 | 2.4 |
def get_object(cls, api_token, id):
"""
Class method that will return a LoadBalancer object by its ID.
Args:
api_token (str): DigitalOcean API token
id (str): Load Balancer ID
"""
load_balancer = cls(token=api_token, id=id)
load_balancer.load()
... | [
"def",
"get_object",
"(",
"cls",
",",
"api_token",
",",
"id",
")",
":",
"load_balancer",
"=",
"cls",
"(",
"token",
"=",
"api_token",
",",
"id",
"=",
"id",
")",
"load_balancer",
".",
"load",
"(",
")",
"return",
"load_balancer"
] | 30.545455 | 13.636364 |
def _dens(self,R,z,phi=0.,t=0.):
"""
NAME:
_dens
PURPOSE:
evaluate the density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the surfa... | [
"def",
"_dens",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"r2",
"=",
"R",
"**",
"2",
"+",
"z",
"**",
"2",
"if",
"r2",
"!=",
"self",
".",
"a2",
":",
"return",
"0.",
"else",
":",
"# pragma: no cove... | 24.571429 | 14.857143 |
def is_disabled(self, name):
"""Check if a given service name is disabled """
if self.services and name in self.services:
return self.services[name]['config'] == 'disabled'
return False | [
"def",
"is_disabled",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"services",
"and",
"name",
"in",
"self",
".",
"services",
":",
"return",
"self",
".",
"services",
"[",
"name",
"]",
"[",
"'config'",
"]",
"==",
"'disabled'",
"return",
"False"... | 43.4 | 13 |
def _function_handler(function, args, kwargs, pipe):
"""Runs the actual function in separate process and returns its result."""
signal.signal(signal.SIGINT, signal.SIG_IGN)
result = process_execute(function, *args, **kwargs)
send_result(pipe, result) | [
"def",
"_function_handler",
"(",
"function",
",",
"args",
",",
"kwargs",
",",
"pipe",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_IGN",
")",
"result",
"=",
"process_execute",
"(",
"function",
",",
"*",
"args"... | 37.428571 | 18 |
def get_shard_stats(self):
"""
:return: get stats for this mongodb shard
"""
return requests.get(self._stats_url, params={'include_stats': True},
headers={'X-Auth-Token': self._client.auth._token}
).json()['data']['stats'] | [
"def",
"get_shard_stats",
"(",
"self",
")",
":",
"return",
"requests",
".",
"get",
"(",
"self",
".",
"_stats_url",
",",
"params",
"=",
"{",
"'include_stats'",
":",
"True",
"}",
",",
"headers",
"=",
"{",
"'X-Auth-Token'",
":",
"self",
".",
"_client",
".",... | 43.428571 | 15.714286 |
def __fetch_issue_attachments(self, issue_id):
"""Get attachments of an issue"""
for attachments_raw in self.client.issue_collection(issue_id, "attachments"):
attachments = json.loads(attachments_raw)
for attachment in attachments['entries']:
yield attachment | [
"def",
"__fetch_issue_attachments",
"(",
"self",
",",
"issue_id",
")",
":",
"for",
"attachments_raw",
"in",
"self",
".",
"client",
".",
"issue_collection",
"(",
"issue_id",
",",
"\"attachments\"",
")",
":",
"attachments",
"=",
"json",
".",
"loads",
"(",
"attac... | 38.75 | 20.625 |
def callback_save_indices():
'''Save index from bokeh textinput'''
import datetime
import os
import pylleo
import yamlord
if datadirs_select.value != 'None':
path_dir = os.path.join(parent_input.value, datadirs_select.value)
cal_yaml_path = os.path.join(path_dir, 'cal.yml')
... | [
"def",
"callback_save_indices",
"(",
")",
":",
"import",
"datetime",
"import",
"os",
"import",
"pylleo",
"import",
"yamlord",
"if",
"datadirs_select",
".",
"value",
"!=",
"'None'",
":",
"path_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"parent_input",
".... | 33.052632 | 20.315789 |
def show_md5_view(md5):
'''Renders template with `stream_sample` of the md5.'''
if not WORKBENCH:
return flask.redirect('/')
md5_view = WORKBENCH.stream_sample(md5)
return flask.render_template('templates/md5_view.html', md5_view=list(md5_view), md5=md5) | [
"def",
"show_md5_view",
"(",
"md5",
")",
":",
"if",
"not",
"WORKBENCH",
":",
"return",
"flask",
".",
"redirect",
"(",
"'/'",
")",
"md5_view",
"=",
"WORKBENCH",
".",
"stream_sample",
"(",
"md5",
")",
"return",
"flask",
".",
"render_template",
"(",
"'templat... | 34.125 | 24.625 |
def is_naive_prime(self):
"""Checks if prime in very naive way
:return: True iff prime
"""
if self.to_int < 2:
return False
elif self.to_int % 2 == 0:
return False
return self.to_int in LOW_PRIMES | [
"def",
"is_naive_prime",
"(",
"self",
")",
":",
"if",
"self",
".",
"to_int",
"<",
"2",
":",
"return",
"False",
"elif",
"self",
".",
"to_int",
"%",
"2",
"==",
"0",
":",
"return",
"False",
"return",
"self",
".",
"to_int",
"in",
"LOW_PRIMES"
] | 26 | 11.5 |
async def _download_photo(self, photo, file, date, thumb, progress_callback):
"""Specialized version of .download_media() for photos"""
# Determine the photo and its largest size
if isinstance(photo, types.MessageMediaPhoto):
photo = photo.photo
if not isinstance(photo, types... | [
"async",
"def",
"_download_photo",
"(",
"self",
",",
"photo",
",",
"file",
",",
"date",
",",
"thumb",
",",
"progress_callback",
")",
":",
"# Determine the photo and its largest size",
"if",
"isinstance",
"(",
"photo",
",",
"types",
".",
"MessageMediaPhoto",
")",
... | 39.214286 | 18.107143 |
def _register_routes(self, methods):
"""
_register_routes
"""
# setup routes by decorator
methods = [(n, v) for (n, v) in methods if v.__name__ == "wrapper"]
methods = sorted(methods, key=lambda x: x[1]._order)
for name, value in methods:
value() # ex... | [
"def",
"_register_routes",
"(",
"self",
",",
"methods",
")",
":",
"# setup routes by decorator",
"methods",
"=",
"[",
"(",
"n",
",",
"v",
")",
"for",
"(",
"n",
",",
"v",
")",
"in",
"methods",
"if",
"v",
".",
"__name__",
"==",
"\"wrapper\"",
"]",
"metho... | 32.090909 | 13.363636 |
def funcGauss1D(x, mu, sig):
""" Create 1D Gaussian. Source:
http://mathworld.wolfram.com/GaussianFunction.html
"""
arrOut = np.exp(-np.power((x - mu)/sig, 2.)/2)
# normalize
arrOut = arrOut/(np.sqrt(2.*np.pi)*sig)
return arrOut | [
"def",
"funcGauss1D",
"(",
"x",
",",
"mu",
",",
"sig",
")",
":",
"arrOut",
"=",
"np",
".",
"exp",
"(",
"-",
"np",
".",
"power",
"(",
"(",
"x",
"-",
"mu",
")",
"/",
"sig",
",",
"2.",
")",
"/",
"2",
")",
"# normalize",
"arrOut",
"=",
"arrOut",
... | 27.666667 | 14.111111 |
def newNsPropEatName(self, ns, name, value):
"""Create a new property tagged with a namespace and carried
by a node. """
if ns is None: ns__o = None
else: ns__o = ns._o
ret = libxml2mod.xmlNewNsPropEatName(self._o, ns__o, name, value)
if ret is None:raise treeError('xm... | [
"def",
"newNsPropEatName",
"(",
"self",
",",
"ns",
",",
"name",
",",
"value",
")",
":",
"if",
"ns",
"is",
"None",
":",
"ns__o",
"=",
"None",
"else",
":",
"ns__o",
"=",
"ns",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlNewNsPropEatName",
"(",
"self"... | 43.888889 | 12.444444 |
def read_bonedata(self, fid):
"""Read bone data from an acclaim skeleton file stream."""
bone_count = 0
lin = self.read_line(fid)
while lin[0]!=':':
parts = lin.split()
if parts[0] == 'begin':
bone_count += 1
self.vertices.append(v... | [
"def",
"read_bonedata",
"(",
"self",
",",
"fid",
")",
":",
"bone_count",
"=",
"0",
"lin",
"=",
"self",
".",
"read_line",
"(",
"fid",
")",
"while",
"lin",
"[",
"0",
"]",
"!=",
"':'",
":",
"parts",
"=",
"lin",
".",
"split",
"(",
")",
"if",
"parts",... | 41.663366 | 18.871287 |
def decorate(func, caller):
"""
decorate(func, caller) decorates a function using a caller.
"""
evaldict = dict(_call_=caller, _func_=func)
fun = FunctionMaker.create(
func, "return _call_(_func_, %(shortsignature)s)",
evaldict, __wrapped__=func)
if hasattr(func, '__qualname__'):... | [
"def",
"decorate",
"(",
"func",
",",
"caller",
")",
":",
"evaldict",
"=",
"dict",
"(",
"_call_",
"=",
"caller",
",",
"_func_",
"=",
"func",
")",
"fun",
"=",
"FunctionMaker",
".",
"create",
"(",
"func",
",",
"\"return _call_(_func_, %(shortsignature)s)\"",
",... | 33.636364 | 9.818182 |
def buffer_write(library, session, data):
"""Writes data to a formatted I/O write buffer synchronously.
Corresponds to viBufWrite function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data to be writte... | [
"def",
"buffer_write",
"(",
"library",
",",
"session",
",",
"data",
")",
":",
"return_count",
"=",
"ViUInt32",
"(",
")",
"# [ViSession, ViBuf, ViUInt32, ViPUInt32]",
"ret",
"=",
"library",
".",
"viBufWrite",
"(",
"session",
",",
"data",
",",
"len",
"(",
"data"... | 38.235294 | 17.529412 |
def count_function(func):
"""
Decorator for functions that return a collection (technically a dict of collections) that should be
counted up. Also automatically falls back to the Cohort-default filter_fn and normalized_per_mb if
not specified.
"""
# Fall back to Cohort-level defaults.
@use_d... | [
"def",
"count_function",
"(",
"func",
")",
":",
"# Fall back to Cohort-level defaults.",
"@",
"use_defaults",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"row",
",",
"cohort",
",",
"filter_fn",
"=",
"None",
",",
"normalized_per_mb",
"=",
"None",
","... | 41.73913 | 17.652174 |
def pick(self, starting_node=None):
"""
Pick a node on the graph based on the links in a starting node.
Additionally, set ``self.current_node`` to the newly picked node.
* if ``starting_node`` is specified, start from there
* if ``starting_node`` is ``None``, start from ``self.... | [
"def",
"pick",
"(",
"self",
",",
"starting_node",
"=",
"None",
")",
":",
"if",
"starting_node",
"is",
"None",
":",
"if",
"self",
".",
"current_node",
"is",
"None",
":",
"random_node",
"=",
"random",
".",
"choice",
"(",
"self",
".",
"node_list",
")",
"s... | 39.289474 | 18.026316 |
def walletpassphrase(self, passphrase, timeout=99999999, mint_only=True):
"""used to unlock wallet for minting"""
return self.req("walletpassphrase", [passphrase, timeout, mint_only]) | [
"def",
"walletpassphrase",
"(",
"self",
",",
"passphrase",
",",
"timeout",
"=",
"99999999",
",",
"mint_only",
"=",
"True",
")",
":",
"return",
"self",
".",
"req",
"(",
"\"walletpassphrase\"",
",",
"[",
"passphrase",
",",
"timeout",
",",
"mint_only",
"]",
"... | 65.666667 | 23.333333 |
def try_mongodb_opts(self, host="localhost", database_name='INGInious'):
""" Try MongoDB configuration """
try:
mongo_client = MongoClient(host=host)
except Exception as e:
self._display_warning("Cannot connect to MongoDB on host %s: %s" % (host, str(e)))
retu... | [
"def",
"try_mongodb_opts",
"(",
"self",
",",
"host",
"=",
"\"localhost\"",
",",
"database_name",
"=",
"'INGInious'",
")",
":",
"try",
":",
"mongo_client",
"=",
"MongoClient",
"(",
"host",
"=",
"host",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
"."... | 34.952381 | 24.809524 |
def dirs(self, *args, **kwargs):
""" D.dirs() -> List of this directory's subdirectories.
The elements of the list are Path objects.
This does not walk recursively into subdirectories
(but see :meth:`walkdirs`).
Accepts parameters to :meth:`listdir`.
"""
return ... | [
"def",
"dirs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"listdir",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"p",
".",
"isdir",
"(",
")",
"]"
] | 36.6 | 15.7 |
def get_resource_retriever(url):
"""
Get the appropriate retriever object for the specified url based on url scheme.
Makes assumption that HTTP urls do not require any special authorization.
For HTTP urls: returns HTTPResourceRetriever
For s3:// urls returns S3ResourceRetriever
:param url: url... | [
"def",
"get_resource_retriever",
"(",
"url",
")",
":",
"if",
"url",
".",
"startswith",
"(",
"'http://'",
")",
"or",
"url",
".",
"startswith",
"(",
"'https://'",
")",
":",
"return",
"HttpResourceRetriever",
"(",
"url",
")",
"else",
":",
"raise",
"ValueError",... | 35.25 | 19.625 |
def is_comment_deleted(comid):
"""
Return True of the comment is deleted. Else False
:param comid: ID of comment to check
"""
query = """SELECT status from "cmtRECORDCOMMENT" WHERE id=%s"""
params = (comid,)
res = run_sql(query, params)
if res and res[0][0] != 'ok':
return True
... | [
"def",
"is_comment_deleted",
"(",
"comid",
")",
":",
"query",
"=",
"\"\"\"SELECT status from \"cmtRECORDCOMMENT\" WHERE id=%s\"\"\"",
"params",
"=",
"(",
"comid",
",",
")",
"res",
"=",
"run_sql",
"(",
"query",
",",
"params",
")",
"if",
"res",
"and",
"res",
"[",
... | 25 | 14 |
def change_openid(self, from_appid, openid_list):
'''微信公众号主体变更迁移用户 openid
详情请参考
http://kf.qq.com/faq/170221aUnmmU170221eUZJNf.html
:param from_appid: 原公众号的 appid
:param openid_list: 需要转换的openid,这些必须是旧账号目前关注的才行,否则会出错;一次最多100个
:return: 转换后的 openid 信息列表
'''
... | [
"def",
"change_openid",
"(",
"self",
",",
"from_appid",
",",
"openid_list",
")",
":",
"return",
"self",
".",
"_post",
"(",
"'changeopenid'",
",",
"data",
"=",
"{",
"'from_appid'",
":",
"from_appid",
",",
"'openid_list'",
":",
"openid_list",
"}",
",",
"result... | 32.8 | 21.066667 |
def setup_standalone_signals(instance):
"""Called when prefs dialog is running in standalone mode. It
makes the delete event of dialog and click on close button finish
the application.
"""
window = instance.get_widget('config-window')
window.connect('delete-event', Gtk.main_quit)
# We need ... | [
"def",
"setup_standalone_signals",
"(",
"instance",
")",
":",
"window",
"=",
"instance",
".",
"get_widget",
"(",
"'config-window'",
")",
"window",
".",
"connect",
"(",
"'delete-event'",
",",
"Gtk",
".",
"main_quit",
")",
"# We need to block the execution of the alread... | 38.4 | 15.2 |
def _apply_diff(environ, diff):
"""Apply a frozen environment.
:param dict diff: key-value pairs to apply to the environment.
:returns: A dict of the key-value pairs that are being changed.
"""
original = {}
if diff:
for k, v in diff.iteritems():
if v is None:
... | [
"def",
"_apply_diff",
"(",
"environ",
",",
"diff",
")",
":",
"original",
"=",
"{",
"}",
"if",
"diff",
":",
"for",
"k",
",",
"v",
"in",
"diff",
".",
"iteritems",
"(",
")",
":",
"if",
"v",
"is",
"None",
":",
"log",
".",
"log",
"(",
"5",
",",
"'... | 23.96875 | 19.875 |
def get_cell_content(self):
"""Returns cell content"""
try:
if self.code_array.cell_attributes[self.key]["button_cell"]:
return
except IndexError:
return
try:
return self.code_array[self.key]
except IndexError:
p... | [
"def",
"get_cell_content",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"code_array",
".",
"cell_attributes",
"[",
"self",
".",
"key",
"]",
"[",
"\"button_cell\"",
"]",
":",
"return",
"except",
"IndexError",
":",
"return",
"try",
":",
"return",
... | 20.6 | 23.8 |
def removeProfile(self, profile, silent=False):
"""
Removes the given profile from the toolbar.
:param profile | <projexui.widgets.xviewwidget.XViewProfile>
"""
if not profile:
return
if not silent:
title = 'Remove ... | [
"def",
"removeProfile",
"(",
"self",
",",
"profile",
",",
"silent",
"=",
"False",
")",
":",
"if",
"not",
"profile",
":",
"return",
"if",
"not",
"silent",
":",
"title",
"=",
"'Remove {0}'",
".",
"format",
"(",
"self",
".",
"profileText",
"(",
")",
")",
... | 38.543478 | 15.847826 |
def unpublish(scm, published_branch, verbose, fake):
"""Removes a published branch from the remote repository."""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check(require_remote=True)
branch = scm.fuzzy_match_branch(published_branch)
if not branch:
scm.display_available_bra... | [
"def",
"unpublish",
"(",
"scm",
",",
"published_branch",
",",
"verbose",
",",
"fake",
")",
":",
"scm",
".",
"fake",
"=",
"fake",
"scm",
".",
"verbose",
"=",
"fake",
"or",
"verbose",
"scm",
".",
"repo_check",
"(",
"require_remote",
"=",
"True",
")",
"br... | 35.190476 | 18.809524 |
def _drop_oldest_chunk(self):
'''
To handle the case when the items comming in the chunk
is more than the maximum capacity of the chunk. Our intent
behind is to remove the oldest chunk. So that the items come
flowing in.
>>> s = StreamCounter(5,5)
>>> data_stream ... | [
"def",
"_drop_oldest_chunk",
"(",
"self",
")",
":",
"chunk_id",
"=",
"min",
"(",
"self",
".",
"chunked_counts",
".",
"keys",
"(",
")",
")",
"chunk",
"=",
"self",
".",
"chunked_counts",
".",
"pop",
"(",
"chunk_id",
")",
"self",
".",
"n_counts",
"-=",
"l... | 33.896552 | 14.241379 |
def _cluster_hits(hits, clusters, assigned_hit_array, cluster_hit_indices, column_cluster_distance, row_cluster_distance, frame_cluster_distance, min_hit_charge, max_hit_charge, ignore_same_hits, noisy_pixels, disabled_pixels):
''' Main precompiled function that loopes over the hits and clusters them
'''
to... | [
"def",
"_cluster_hits",
"(",
"hits",
",",
"clusters",
",",
"assigned_hit_array",
",",
"cluster_hit_indices",
",",
"column_cluster_distance",
",",
"row_cluster_distance",
",",
"frame_cluster_distance",
",",
"min_hit_charge",
",",
"max_hit_charge",
",",
"ignore_same_hits",
... | 47.192 | 28.088 |
def setnonce(self, text=None):
"""
Set I{nonce} which is arbitraty set of bytes to prevent
reply attacks.
@param text: The nonce text value.
Generated when I{None}.
@type text: str
"""
if text is None:
s = []
s.append(self.usern... | [
"def",
"setnonce",
"(",
"self",
",",
"text",
"=",
"None",
")",
":",
"if",
"text",
"is",
"None",
":",
"s",
"=",
"[",
"]",
"s",
".",
"append",
"(",
"self",
".",
"username",
")",
"s",
".",
"append",
"(",
"self",
".",
"password",
")",
"s",
".",
"... | 29.777778 | 10.777778 |
def path(self, *paths, **kwargs):
"""Create new Path based on self.root and provided paths.
:param paths: List of sub paths
:param kwargs: required=False
:rtype: Path
"""
return self.__class__(self.__root__, *paths, **kwargs) | [
"def",
"path",
"(",
"self",
",",
"*",
"paths",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"__root__",
",",
"*",
"paths",
",",
"*",
"*",
"kwargs",
")"
] | 33.375 | 11.625 |
def authenticate_token( self, token ):
'''
authenticate_token checks the passed token and returns the user_id it is
associated with. it is assumed that this method won't be directly exposed to
the oauth client, but some kind of framework or wrapper. this allows the
framework to h... | [
"def",
"authenticate_token",
"(",
"self",
",",
"token",
")",
":",
"token_data",
"=",
"self",
".",
"data_store",
".",
"fetch",
"(",
"'tokens'",
",",
"token",
"=",
"token",
")",
"if",
"not",
"token_data",
":",
"raise",
"Proauth2Error",
"(",
"'access_denied'",
... | 52.583333 | 25.583333 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self,
'matching_results') and self.matching_results is not None:
_dict['matching_results'] = self.matching_results
if hasattr(self, 'hits') and self.hits is no... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'matching_results'",
")",
"and",
"self",
".",
"matching_results",
"is",
"not",
"None",
":",
"_dict",
"[",
"'matching_results'",
"]",
"=",
"self",
".",
... | 44.666667 | 19.666667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.