text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def create_api(app_id=None, login=None, password=None, phone_number=None,
scope='offline', api_version='5.92', http_params=None,
interactive=False, service_token=None, client_secret=None,
two_fa_supported=False, two_fa_force_sms=False):
"""Factory method to explicitly cr... | [
"def",
"create_api",
"(",
"app_id",
"=",
"None",
",",
"login",
"=",
"None",
",",
"password",
"=",
"None",
",",
"phone_number",
"=",
"None",
",",
"scope",
"=",
"'offline'",
",",
"api_version",
"=",
"'5.92'",
",",
"http_params",
"=",
"None",
",",
"interact... | 52.731707 | 20.536585 |
def clear_distribute_compositions(self):
"""Removes the distribution rights.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from temp... | [
"def",
"clear_distribute_compositions",
"(",
"self",
")",
":",
"# Implemented from template for osid.resource.ResourceForm.clear_group_template",
"if",
"(",
"self",
".",
"get_distribute_compositions_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
"or",
"self",
".",
"get... | 49 | 24.076923 |
def _dt_array_cmp(cls, op):
"""
Wrap comparison operations to convert datetime-like to datetime64
"""
opname = '__{name}__'.format(name=op.__name__)
nat_result = opname == '__ne__'
def wrapper(self, other):
if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)):
retu... | [
"def",
"_dt_array_cmp",
"(",
"cls",
",",
"op",
")",
":",
"opname",
"=",
"'__{name}__'",
".",
"format",
"(",
"name",
"=",
"op",
".",
"__name__",
")",
"nat_result",
"=",
"opname",
"==",
"'__ne__'",
"def",
"wrapper",
"(",
"self",
",",
"other",
")",
":",
... | 40.390244 | 19.243902 |
def fullPath(self):
""" Return full butter path from butter root. """
for ((dirTree, dirID, dirSeq), (dirPath, name)) in self.links.items():
try:
path = self.fileSystem.volumes[dirTree].fullPath
if path is not None:
return path + ("/" if pa... | [
"def",
"fullPath",
"(",
"self",
")",
":",
"for",
"(",
"(",
"dirTree",
",",
"dirID",
",",
"dirSeq",
")",
",",
"(",
"dirPath",
",",
"name",
")",
")",
"in",
"self",
".",
"links",
".",
"items",
"(",
")",
":",
"try",
":",
"path",
"=",
"self",
".",
... | 39.285714 | 21.214286 |
def _key_parenleft(self, text):
"""Action for '('"""
self.hide_completion_widget()
if self.get_current_line_to_cursor():
last_obj = self.get_last_obj()
if last_obj and not last_obj.isdigit():
self.insert_text(text)
self.show_object_i... | [
"def",
"_key_parenleft",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"hide_completion_widget",
"(",
")",
"if",
"self",
".",
"get_current_line_to_cursor",
"(",
")",
":",
"last_obj",
"=",
"self",
".",
"get_last_obj",
"(",
")",
"if",
"last_obj",
"and",
"... | 39.1 | 7.8 |
def wnfetd(window, n):
"""
Fetch a particular interval from a double precision window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnfetd_c.html
:param window: Input window
:type window: spiceypy.utils.support_types.SpiceCell
:param n: Index of interval to be fetched.
:type n... | [
"def",
"wnfetd",
"(",
"window",
",",
"n",
")",
":",
"assert",
"isinstance",
"(",
"window",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"window",
".",
"dtype",
"==",
"1",
"n",
"=",
"ctypes",
".",
"c_int",
"(",
"n",
")",
"left",
"=",
"ctypes",
".... | 32.952381 | 16.190476 |
def _findRedundantProteins(protToPeps, pepToProts, proteins=None):
"""Returns a set of proteins with redundant peptide evidence.
After removing the redundant proteins from the "protToPeps" and "pepToProts"
mapping, all remaining proteins have at least one unique peptide. The
remaining proteins are a "m... | [
"def",
"_findRedundantProteins",
"(",
"protToPeps",
",",
"pepToProts",
",",
"proteins",
"=",
"None",
")",
":",
"if",
"proteins",
"is",
"None",
":",
"proteins",
"=",
"viewkeys",
"(",
"protToPeps",
")",
"pepFrequency",
"=",
"_getValueCounts",
"(",
"pepToProts",
... | 45.783784 | 22.243243 |
def get_port_profile_for_intf_output_interface_port_profile_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_for_intf = ET.Element("get_port_profile_for_intf")
config = get_port_profile_for_intf
output = ET.SubElement(get_por... | [
"def",
"get_port_profile_for_intf_output_interface_port_profile_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_port_profile_for_intf",
"=",
"ET",
".",
"Element",
"(",
"\"get_port_profile_for_int... | 45.428571 | 15.928571 |
def make_2D_samples_gauss(n, m, sigma, random_state=None):
"""return n samples drawn from 2D gaussian N(m,sigma)
Parameters
----------
n : int
number of samples to make
m : np.array (2,)
mean value of the gaussian distribution
sigma : np.array (2,2)
covariance matrix of... | [
"def",
"make_2D_samples_gauss",
"(",
"n",
",",
"m",
",",
"sigma",
",",
"random_state",
"=",
"None",
")",
":",
"generator",
"=",
"check_random_state",
"(",
"random_state",
")",
"if",
"np",
".",
"isscalar",
"(",
"sigma",
")",
":",
"sigma",
"=",
"np",
".",
... | 30.852941 | 21.558824 |
def lookup_sig(cls, sigs, method_name, expr_args, stmt_or_expr, context):
"""
Using a list of args, determine the most accurate signature to use from
the given context
"""
def synonymise(s):
return s.replace('int128', 'num').replace('uint256', 'num')
# for s... | [
"def",
"lookup_sig",
"(",
"cls",
",",
"sigs",
",",
"method_name",
",",
"expr_args",
",",
"stmt_or_expr",
",",
"context",
")",
":",
"def",
"synonymise",
"(",
"s",
")",
":",
"return",
"s",
".",
"replace",
"(",
"'int128'",
",",
"'num'",
")",
".",
"replace... | 40.72 | 20.8 |
def file_format(self):
"""Formats device filesystem"""
log.info('Formating, can take minutes depending on flash size...')
res = self.__exchange('file.format()', timeout=300)
if 'format done' not in res:
log.error(res)
else:
log.info(res)
return res | [
"def",
"file_format",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Formating, can take minutes depending on flash size...'",
")",
"res",
"=",
"self",
".",
"__exchange",
"(",
"'file.format()'",
",",
"timeout",
"=",
"300",
")",
"if",
"'format done'",
"not",
"... | 34.666667 | 17 |
def setQuery(self, query):
"""
Sets the query information for this filter widget.
:param query | <orb.Query> || None
"""
if query is None:
return
count = {}
for widget in self.findChildren(QWidget):
... | [
"def",
"setQuery",
"(",
"self",
",",
"query",
")",
":",
"if",
"query",
"is",
"None",
":",
"return",
"count",
"=",
"{",
"}",
"for",
"widget",
"in",
"self",
".",
"findChildren",
"(",
"QWidget",
")",
":",
"column",
"=",
"nativestring",
"(",
"widget",
".... | 30.894737 | 16.368421 |
def get_slide_seg_list_belonged(dt_str, seg_duration, slide_step=1,
fmt='%Y-%m-%d %H:%M:%S'):
"""
获取该时刻所属的所有时间片列表
:param dt_str: datetime string, eg: 2016-10-31 12:22:11
:param seg_duration: 时间片长度, unit: minute
:param slide_step: 滑动步长
:param fmt: datetime string f... | [
"def",
"get_slide_seg_list_belonged",
"(",
"dt_str",
",",
"seg_duration",
",",
"slide_step",
"=",
"1",
",",
"fmt",
"=",
"'%Y-%m-%d %H:%M:%S'",
")",
":",
"dt",
"=",
"time_util",
".",
"str_to_datetime",
"(",
"dt_str",
",",
"fmt",
")",
"day_slide_seg_list",
"=",
... | 40.866667 | 15.266667 |
def publish(ctx, test=False):
"""Publish to the cheeseshop."""
clean(ctx)
if test:
run('python setup.py register -r test sdist bdist_wheel', echo=True)
run('twine upload dist/* -r test', echo=True)
else:
run('python setup.py register sdist bdist_wheel', echo=True)
run('tw... | [
"def",
"publish",
"(",
"ctx",
",",
"test",
"=",
"False",
")",
":",
"clean",
"(",
"ctx",
")",
"if",
"test",
":",
"run",
"(",
"'python setup.py register -r test sdist bdist_wheel'",
",",
"echo",
"=",
"True",
")",
"run",
"(",
"'twine upload dist/* -r test'",
",",... | 38 | 19.777778 |
def add_value_event(self, event_value, func, event_type=None, parameters=None, **kwargs):
"""
Add a function that is called when the value reach or pass the event_value.
:param event_value:
A single value or range specified as a tuple.
If it is a range the function spec... | [
"def",
"add_value_event",
"(",
"self",
",",
"event_value",
",",
"func",
",",
"event_type",
"=",
"None",
",",
"parameters",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_sensor_value",
".",
"add_value_event",
"(",
"event_value",
",",
"func"... | 40.130435 | 31.695652 |
def _parse(self):
"""! @brief SWO parser as generator function coroutine.
The generator yields every time it needs a byte of SWO data. The caller must use the
generator's send() method to provide the next byte.
"""
timestamp = 0
invalid = False
while True... | [
"def",
"_parse",
"(",
"self",
")",
":",
"timestamp",
"=",
"0",
"invalid",
"=",
"False",
"while",
"True",
":",
"byte",
"=",
"yield",
"hdr",
"=",
"byte",
"# Sync packet.",
"if",
"hdr",
"==",
"0",
":",
"packets",
"=",
"0",
"while",
"True",
":",
"# Check... | 41.744526 | 14.313869 |
def askForPreviousFutures(self):
"""Request a status for every future to the broker."""
# Don't request it too often (otherwise it ping-pongs because)
# the broker answer triggers the _poll of pop()
if time.time() < self.lastStatus + POLLING_TIME / 1000:
return
self.l... | [
"def",
"askForPreviousFutures",
"(",
"self",
")",
":",
"# Don't request it too often (otherwise it ping-pongs because)",
"# the broker answer triggers the _poll of pop()",
"if",
"time",
".",
"time",
"(",
")",
"<",
"self",
".",
"lastStatus",
"+",
"POLLING_TIME",
"/",
"1000",... | 41.066667 | 17.6 |
def renames(self, new):
""" .. seealso:: :func:`os.renames` """
os.renames(self, new)
return self._next_class(new) | [
"def",
"renames",
"(",
"self",
",",
"new",
")",
":",
"os",
".",
"renames",
"(",
"self",
",",
"new",
")",
"return",
"self",
".",
"_next_class",
"(",
"new",
")"
] | 33.75 | 8 |
def do_prompt(self, arg):
"""
Enable or disable prompt
:param arg: on|off
:return:
"""
if arg.lower() == 'off':
self.response_prompt = ''
self.prompt = ''
return
elif arg.lower() == 'on':
self.prompt = PROMPT
... | [
"def",
"do_prompt",
"(",
"self",
",",
"arg",
")",
":",
"if",
"arg",
".",
"lower",
"(",
")",
"==",
"'off'",
":",
"self",
".",
"response_prompt",
"=",
"''",
"self",
".",
"prompt",
"=",
"''",
"return",
"elif",
"arg",
".",
"lower",
"(",
")",
"==",
"'... | 32.214286 | 13.642857 |
def build_precache_map(config):
"""
Build a mapping of contexts and models from the configuration
"""
precache_map = {}
ss_name = config['ores']['scoring_system']
for context in config['scoring_systems'][ss_name]['scoring_contexts']:
precache_map[context] = {}
for model in config... | [
"def",
"build_precache_map",
"(",
"config",
")",
":",
"precache_map",
"=",
"{",
"}",
"ss_name",
"=",
"config",
"[",
"'ores'",
"]",
"[",
"'scoring_system'",
"]",
"for",
"context",
"in",
"config",
"[",
"'scoring_systems'",
"]",
"[",
"ss_name",
"]",
"[",
"'sc... | 43.48 | 18.76 |
def Baroczy(x, rhol, rhog, mul, mug):
r'''Calculates void fraction in two-phase flow according to the model of
[1]_ as given in [2]_, [3]_, and [4]_.
.. math::
\alpha = \left[1 + \left(\frac{1-x}{x}\right)^{0.74}\left(\frac{\rho_g}
{\rho_l}\right)^{0.65}\left(\frac{\mu_l}{\mu_g}\right)^{0.... | [
"def",
"Baroczy",
"(",
"x",
",",
"rhol",
",",
"rhog",
",",
"mul",
",",
"mug",
")",
":",
"Xtt",
"=",
"Lockhart_Martinelli_Xtt",
"(",
"x",
",",
"rhol",
",",
"rhog",
",",
"mul",
",",
"mug",
",",
"pow_x",
"=",
"0.74",
",",
"pow_rho",
"=",
"0.65",
","... | 37.607143 | 26.892857 |
def deprecated_opts_signature(args, kwargs):
"""
Utility to help with the deprecation of the old .opts method signature
Returns whether opts.apply_groups should be used (as a bool) and the
corresponding options.
"""
from .options import Options
groups = set(Options._option_groups)
opts ... | [
"def",
"deprecated_opts_signature",
"(",
"args",
",",
"kwargs",
")",
":",
"from",
".",
"options",
"import",
"Options",
"groups",
"=",
"set",
"(",
"Options",
".",
"_option_groups",
")",
"opts",
"=",
"{",
"kw",
"for",
"kw",
"in",
"kwargs",
"if",
"kw",
"!="... | 33.903226 | 13.709677 |
def _set_esp_key(self, v, load=False):
"""
Setter method for esp_key, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/authentication/ipsec_auth_key_config/esp_key (ipsec-authentication-hexkey-string)
If this variable is read-only (config: false) in the
source YANG file,... | [
"def",
"_set_esp_key",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",... | 87.708333 | 44.666667 |
def get_pending_boot_mode(self):
"""Retrieves the pending boot mode of the server.
Gets the boot mode to be set on next reset.
:returns: either LEGACY or UEFI.
:raises: IloError, on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
... | [
"def",
"get_pending_boot_mode",
"(",
"self",
")",
":",
"sushy_system",
"=",
"self",
".",
"_get_sushy_system",
"(",
"PROLIANT_SYSTEM_ID",
")",
"try",
":",
"return",
"BOOT_MODE_MAP",
".",
"get",
"(",
"sushy_system",
".",
"bios_settings",
".",
"pending_settings",
"."... | 40.588235 | 12.588235 |
def exists(self, obj_id, obj_type=None):
"""
Return whether the given object exists in the search index.
:param obj_id: The object's unique identifier.
:param obj_type: The object's type.
"""
return self.object_key(obj_id, obj_type) in self._data | [
"def",
"exists",
"(",
"self",
",",
"obj_id",
",",
"obj_type",
"=",
"None",
")",
":",
"return",
"self",
".",
"object_key",
"(",
"obj_id",
",",
"obj_type",
")",
"in",
"self",
".",
"_data"
] | 36 | 13.25 |
def format_messages(self, messages):
""" Formats several messages with :class:Look, encodes them
with :func:vital.tools.encoding.stdout_encode """
mess = ""
for message in self.message:
if self.pretty:
mess = "{}{}".format(mess, self.format_message(message... | [
"def",
"format_messages",
"(",
"self",
",",
"messages",
")",
":",
"mess",
"=",
"\"\"",
"for",
"message",
"in",
"self",
".",
"message",
":",
"if",
"self",
".",
"pretty",
":",
"mess",
"=",
"\"{}{}\"",
".",
"format",
"(",
"mess",
",",
"self",
".",
"form... | 42 | 12.153846 |
def validate_username(self, value):
"""
Verify that the username has a matching user.
"""
try:
self.user = User.objects.get(username=value)
except User.DoesNotExist:
raise serializers.ValidationError("User does not exist")
return value | [
"def",
"validate_username",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"self",
".",
"user",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"value",
")",
"except",
"User",
".",
"DoesNotExist",
":",
"raise",
"serializers",
".",
"Val... | 29.9 | 15.7 |
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_... | [
"def",
"build_ref_list",
"(",
"refs",
")",
":",
"ref_list",
"=",
"[",
"]",
"for",
"reference",
"in",
"refs",
":",
"ref",
"=",
"ea",
".",
"Citation",
"(",
")",
"# Publcation Type",
"utils",
".",
"set_attr_if_value",
"(",
"ref",
",",
"'publication_type'",
",... | 46.130435 | 23.543478 |
def hit(self, code, line, duration):
"""
A line has finished executing.
code (code)
container function's code object
line (int)
line number of just executed line
duration (float)
duration of the line, in seconds
"""
entry = self.line... | [
"def",
"hit",
"(",
"self",
",",
"code",
",",
"line",
",",
"duration",
")",
":",
"entry",
"=",
"self",
".",
"line_dict",
"[",
"line",
"]",
"[",
"code",
"]",
"entry",
"[",
"0",
"]",
"+=",
"1",
"entry",
"[",
"1",
"]",
"+=",
"duration"
] | 26.785714 | 10.357143 |
def endpoint(f):
"""This decorator marks this method as an endpoint. It is responsible for
the request workflow and will call each relevant method in turn."""
def check_authentication(self, **kwargs):
"""If the `authentication` variable is defined and not None, the
specified method wi... | [
"def",
"endpoint",
"(",
"f",
")",
":",
"def",
"check_authentication",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"If the `authentication` variable is defined and not None, the\n specified method will be run. On True the request will continue\n otherwise... | 44.44697 | 19.931818 |
def add_to_configs(self, configs):
"""Add configurations to all tomodirs
Parameters
----------
configs : :class:`numpy.ndarray`
Nx4 numpy array with abmn configurations
"""
for f, td in self.tds.items():
td.configs.add_to_configs(configs) | [
"def",
"add_to_configs",
"(",
"self",
",",
"configs",
")",
":",
"for",
"f",
",",
"td",
"in",
"self",
".",
"tds",
".",
"items",
"(",
")",
":",
"td",
".",
"configs",
".",
"add_to_configs",
"(",
"configs",
")"
] | 27.454545 | 13.636364 |
def find(self, key):
"Exact matching (returns value)"
index = self.follow_bytes(key, self.ROOT)
if index is None:
return -1
if not self.has_value(index):
return -1
return self.value(index) | [
"def",
"find",
"(",
"self",
",",
"key",
")",
":",
"index",
"=",
"self",
".",
"follow_bytes",
"(",
"key",
",",
"self",
".",
"ROOT",
")",
"if",
"index",
"is",
"None",
":",
"return",
"-",
"1",
"if",
"not",
"self",
".",
"has_value",
"(",
"index",
")"... | 30.625 | 11.625 |
def triangle_normal(a, b, c):
"""Return a vector orthogonal to the given triangle
Arguments:
a, b, c -- three 3D numpy vectors
"""
normal = np.cross(a - c, b - c)
norm = np.linalg.norm(normal)
return normal/norm | [
"def",
"triangle_normal",
"(",
"a",
",",
"b",
",",
"c",
")",
":",
"normal",
"=",
"np",
".",
"cross",
"(",
"a",
"-",
"c",
",",
"b",
"-",
"c",
")",
"norm",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"normal",
")",
"return",
"normal",
"/",
"nor... | 26.888889 | 12 |
def generate_molecule_object_dict(source, format, values):
"""Generate a dictionary that represents a Squonk MoleculeObject when
written as JSON
:param source: Molecules in molfile or smiles format
:param format: The format of the molecule. Either 'mol' or 'smiles'
:param values: Optional dict of v... | [
"def",
"generate_molecule_object_dict",
"(",
"source",
",",
"format",
",",
"values",
")",
":",
"m",
"=",
"{",
"\"uuid\"",
":",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
",",
"\"source\"",
":",
"source",
",",
"\"format\"",
":",
"format",
"}",
"if... | 40.583333 | 21.75 |
def netconf_config_change_changed_by_server_or_user_by_user_session_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_config_change = ET.SubElement(config, "netconf-config-change", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications")
... | [
"def",
"netconf_config_change_changed_by_server_or_user_by_user_session_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"netconf_config_change",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"... | 53.769231 | 24.769231 |
def delete_exchange(self, vhost, name):
"""
Delete the named exchange from the named vhost. The API returns a 204
on success, in which case this method returns True, otherwise the
error is raised.
:param string vhost: Vhost where target exchange was created
:param string... | [
"def",
"delete_exchange",
"(",
"self",
",",
"vhost",
",",
"name",
")",
":",
"vhost",
"=",
"quote",
"(",
"vhost",
",",
"''",
")",
"name",
"=",
"quote",
"(",
"name",
",",
"''",
")",
"path",
"=",
"Client",
".",
"urls",
"[",
"'exchange_by_name'",
"]",
... | 38.8 | 16.4 |
def unperturbed_hamiltonian(states):
r"""Return the unperturbed atomic hamiltonian for given states.
We calcualte the atomic hamiltonian in the basis of the ground states of \
rubidium 87 (in GHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([g], "magnetic"... | [
"def",
"unperturbed_hamiltonian",
"(",
"states",
")",
":",
"Ne",
"=",
"len",
"(",
"states",
")",
"H0",
"=",
"np",
".",
"zeros",
"(",
"(",
"Ne",
",",
"Ne",
")",
",",
"complex",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"H0",
"[",
"i",... | 37.470588 | 18.882353 |
def cut(cut, node_indices):
"""Check that the cut is for only the given nodes."""
if cut.indices != node_indices:
raise ValueError('{} nodes are not equal to subsystem nodes '
'{}'.format(cut, node_indices)) | [
"def",
"cut",
"(",
"cut",
",",
"node_indices",
")",
":",
"if",
"cut",
".",
"indices",
"!=",
"node_indices",
":",
"raise",
"ValueError",
"(",
"'{} nodes are not equal to subsystem nodes '",
"'{}'",
".",
"format",
"(",
"cut",
",",
"node_indices",
")",
")"
] | 48.8 | 12.6 |
def is_data_from_channel(channel=4): # function factory
'''Selecting FE data from given channel.
Parameters
----------
channel : int
Channel number (4 is default channel on Single Chip Card).
Returns
-------
Function.
Usage:
1 Selecting FE data from channel 4... | [
"def",
"is_data_from_channel",
"(",
"channel",
"=",
"4",
")",
":",
"# function factory\r",
"if",
"channel",
">=",
"0",
"and",
"channel",
"<",
"16",
":",
"def",
"f",
"(",
"value",
")",
":",
"return",
"np",
".",
"equal",
"(",
"np",
".",
"right_shift",
"(... | 38.818182 | 27.484848 |
def _scope_and_enforce_robots(self, site, parent_page, outlinks):
'''
Returns tuple (
dict of {page_id: Page} of fresh `brozzler.Page` representing in
scope links accepted by robots policy,
set of in scope urls (canonicalized) blocked by robots policy,
... | [
"def",
"_scope_and_enforce_robots",
"(",
"self",
",",
"site",
",",
"parent_page",
",",
"outlinks",
")",
":",
"pages",
"=",
"{",
"}",
"# {page_id: Page, ...}",
"blocked",
"=",
"set",
"(",
")",
"out_of_scope",
"=",
"set",
"(",
")",
"for",
"url",
"in",
"outli... | 45.285714 | 16.771429 |
def _postprocess(self, x, out=None):
"""Return the post-processed version of ``x``.
C2C: use ``tmp_f`` (C2C operation)
R2C: use ``tmp_f`` (C2C operation)
HALFC: use ``tmp_f`` (C2C operation)
The result is stored in ``out`` if given, otherwise in
a temporary or a new arr... | [
"def",
"_postprocess",
"(",
"self",
",",
"x",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"if",
"self",
".",
"domain",
".",
"field",
"==",
"ComplexNumbers",
"(",
")",
":",
"out",
"=",
"self",
".",
"_tmp_r",
"if",
"self",
".... | 40.052632 | 15.578947 |
def _set_link_oam_interface(self, v, load=False):
"""
Setter method for link_oam_interface, mapped from YANG variable /interface/ethernet/link_oam_interface (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_link_oam_interface is considered as a private
meth... | [
"def",
"_set_link_oam_interface",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
","... | 91.954545 | 43.363636 |
def run_remove_system(name, token, org, system, prompt):
"""
Removes a system from the repo.
"""
repo = get_repo(token=token, org=org, name=name)
try:
label = repo.get_label(name=system.strip())
label.delete()
click.secho("Successfully deleted {}".format(system), fg="green")
... | [
"def",
"run_remove_system",
"(",
"name",
",",
"token",
",",
"org",
",",
"system",
",",
"prompt",
")",
":",
"repo",
"=",
"get_repo",
"(",
"token",
"=",
"token",
",",
"org",
"=",
"org",
",",
"name",
"=",
"name",
")",
"try",
":",
"label",
"=",
"repo",... | 44 | 18.461538 |
def update_notification_list(self, apps=None, schema_editor=None, verbose=False):
"""Updates the notification model to ensure all registered
notifications classes are listed.
Typically called from a post_migrate signal.
Also, in tests you can register a notification and the Notificatio... | [
"def",
"update_notification_list",
"(",
"self",
",",
"apps",
"=",
"None",
",",
"schema_editor",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"Notification",
"=",
"(",
"apps",
"or",
"django_apps",
")",
".",
"get_model",
"(",
"\"edc_notification.notifica... | 44.918919 | 20.351351 |
def to_dict(self, get_value=None):
"""Dump counters as a dict"""
self.trim()
result = {}
for key, value in iteritems(self.counters):
if get_value is not None:
value = getattr(value, get_value)
r = result
for _key in key[:-1]:
... | [
"def",
"to_dict",
"(",
"self",
",",
"get_value",
"=",
"None",
")",
":",
"self",
".",
"trim",
"(",
")",
"result",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"self",
".",
"counters",
")",
":",
"if",
"get_value",
"is",
"not",
... | 32.833333 | 10.583333 |
def title(content, new_line_replacement=' ', tab_replacement=' '):
"""
Underlines content with '='. New lines and tabs will be replaced
:param str content:
:param str new_line_replacement:
:param str tab_replacement:
:return: unicode
"""
prepared_content ... | [
"def",
"title",
"(",
"content",
",",
"new_line_replacement",
"=",
"' '",
",",
"tab_replacement",
"=",
"' '",
")",
":",
"prepared_content",
"=",
"content",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"'\\n'",
",",
"new_line_replacement",
")",
".",
"replace"... | 47.4 | 20 |
def _topology_from_residue(res):
"""Converts a openmm.app.Topology.Residue to openmm.app.Topology.
Parameters
----------
res : openmm.app.Topology.Residue
An individual residue in an openmm.app.Topology
Returns
-------
topology : openmm.app.Topology
The generated topology
... | [
"def",
"_topology_from_residue",
"(",
"res",
")",
":",
"topology",
"=",
"app",
".",
"Topology",
"(",
")",
"chain",
"=",
"topology",
".",
"addChain",
"(",
")",
"new_res",
"=",
"topology",
".",
"addResidue",
"(",
"res",
".",
"name",
",",
"chain",
")",
"a... | 28.257143 | 16.657143 |
def set_title(self, title):
"""
Set terminal title.
"""
if self.term not in ('linux', 'eterm-color'): # Not supported by the Linux console.
self.write_raw('\x1b]2;%s\x07' % title.replace('\x1b', '').replace('\x07', '')) | [
"def",
"set_title",
"(",
"self",
",",
"title",
")",
":",
"if",
"self",
".",
"term",
"not",
"in",
"(",
"'linux'",
",",
"'eterm-color'",
")",
":",
"# Not supported by the Linux console.",
"self",
".",
"write_raw",
"(",
"'\\x1b]2;%s\\x07'",
"%",
"title",
".",
"... | 43.166667 | 21.5 |
def c3(x, lag):
"""
This function calculates the value of
.. math::
\\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} \cdot x_{i}
which is
.. math::
\\mathbb{E}[L^2(X)^2 \cdot L(X) \cdot X]
where :math:`\\mathbb{E}` is the mean and :math:`L` is t... | [
"def",
"c3",
"(",
"x",
",",
"lag",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"(",
"np",
".",
"ndarray",
",",
"pd",
".",
"Series",
")",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"n",
"=",
"x",
".",
"size",
"if",
"2... | 28.432432 | 25.621622 |
def as_urlpatterns(self):
"""
Creates the appropriate URLs for this object.
"""
urls = []
# for each of our actions
for action in self.actions:
view_class = self.view_for_action(action)
view_pattern = self.pattern_for_view(view_class, action)
... | [
"def",
"as_urlpatterns",
"(",
"self",
")",
":",
"urls",
"=",
"[",
"]",
"# for each of our actions",
"for",
"action",
"in",
"self",
".",
"actions",
":",
"view_class",
"=",
"self",
".",
"view_for_action",
"(",
"action",
")",
"view_pattern",
"=",
"self",
".",
... | 32.214286 | 17.928571 |
def front(self, *fields):
'''Return the front pair of the structure'''
v, f = tuple(self.irange(0, 0, fields=fields))
if v:
return (v[0], dict(((field, f[field][0]) for field in f))) | [
"def",
"front",
"(",
"self",
",",
"*",
"fields",
")",
":",
"v",
",",
"f",
"=",
"tuple",
"(",
"self",
".",
"irange",
"(",
"0",
",",
"0",
",",
"fields",
"=",
"fields",
")",
")",
"if",
"v",
":",
"return",
"(",
"v",
"[",
"0",
"]",
",",
"dict",
... | 43.6 | 19.6 |
def get_plot(self_or_cls, obj, renderer=None, **kwargs):
"""
Given a HoloViews Viewable return a corresponding plot instance.
"""
if isinstance(obj, DynamicMap) and obj.unbounded:
dims = ', '.join('%r' % dim for dim in obj.unbounded)
msg = ('DynamicMap cannot be d... | [
"def",
"get_plot",
"(",
"self_or_cls",
",",
"obj",
",",
"renderer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"DynamicMap",
")",
"and",
"obj",
".",
"unbounded",
":",
"dims",
"=",
"', '",
".",
"join",
"(",
... | 44.605263 | 18.921053 |
def currentItem( self ):
"""
Returns the current navigation item from the current path.
:return <XNavigationItem> || None
"""
model = self.navigationModel()
if ( not model ):
return None
return model.itemByPath(self.text()) | [
"def",
"currentItem",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"navigationModel",
"(",
")",
"if",
"(",
"not",
"model",
")",
":",
"return",
"None",
"return",
"model",
".",
"itemByPath",
"(",
"self",
".",
"text",
"(",
")",
")"
] | 27.545455 | 13.545455 |
def _main(argv):
"""
Handle arguments for the 'lumi-upload' command.
"""
parser = argparse.ArgumentParser(
description=DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'-b',
'--base-url',
default=URL_BASE,
h... | [
"def",
"_main",
"(",
"argv",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"DESCRIPTION",
",",
"formatter_class",
"=",
"argparse",
".",
"RawDescriptionHelpFormatter",
",",
")",
"parser",
".",
"add_argument",
"(",
"'-b'",
... | 27.805556 | 21.472222 |
def as_ipywidget(self):
""" Provides an IPywidgets player that can be used in a notebook. """
from IPython.display import Audio
return Audio(data=self.y, rate=self.sr) | [
"def",
"as_ipywidget",
"(",
"self",
")",
":",
"from",
"IPython",
".",
"display",
"import",
"Audio",
"return",
"Audio",
"(",
"data",
"=",
"self",
".",
"y",
",",
"rate",
"=",
"self",
".",
"sr",
")"
] | 37.6 | 13 |
def on_trial_complete(self,
trial_id,
result=None,
error=False,
early_terminated=False):
"""Passes the result to skopt unless early terminated or errored.
The result is internally negated when intera... | [
"def",
"on_trial_complete",
"(",
"self",
",",
"trial_id",
",",
"result",
"=",
"None",
",",
"error",
"=",
"False",
",",
"early_terminated",
"=",
"False",
")",
":",
"skopt_trial_info",
"=",
"self",
".",
"_live_trial_mapping",
".",
"pop",
"(",
"trial_id",
")",
... | 42.5 | 14.928571 |
def _judeNOtIn(self, raw_str, ele_list):
'''
判断ele是否在原始字符串中
args:
raw_str 源字符串
ele_list 待检查的列表
return
boolean
'''
for ele in ele_list:
if ele in raw_str:
return False
return True | [
"def",
"_judeNOtIn",
"(",
"self",
",",
"raw_str",
",",
"ele_list",
")",
":",
"for",
"ele",
"in",
"ele_list",
":",
"if",
"ele",
"in",
"raw_str",
":",
"return",
"False",
"return",
"True"
] | 22.076923 | 17.923077 |
def draw_graph(self):
"""
The central logic for drawing the graph.
Sets self.graph (the 'g' element in the SVG root)
"""
transform = 'translate (%s %s)' % (self.border_left, self.border_top)
self.graph = etree.SubElement(self.root, 'g', transform=transform)
etree.SubElement(self.graph, 'rect', {
'x':... | [
"def",
"draw_graph",
"(",
"self",
")",
":",
"transform",
"=",
"'translate (%s %s)'",
"%",
"(",
"self",
".",
"border_left",
",",
"self",
".",
"border_top",
")",
"self",
".",
"graph",
"=",
"etree",
".",
"SubElement",
"(",
"self",
".",
"root",
",",
"'g'",
... | 23.903226 | 19.83871 |
def count(args):
"""
%prog count *.gz
Count reads based on FASTQC results. FASTQC needs to be run on all the input
data given before running this command.
"""
from jcvi.utils.table import loadtable, write_csv
p = OptionParser(count.__doc__)
p.add_option("--dir",
help="S... | [
"def",
"count",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"table",
"import",
"loadtable",
",",
"write_csv",
"p",
"=",
"OptionParser",
"(",
"count",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--dir\"",
",",
"help",
"=",
"\"Sub-... | 32.025641 | 20.128205 |
def get_ldap_user_membership(self, user_dn):
"""Retrieve user membership from LDAP server."""
#Escape parenthesis in DN
membership_filter = self.conf_LDAP_SYNC_GROUP_MEMBERSHIP_FILTER.replace('{distinguishedName}', user_dn.replace('(', "\(").replace(')', "\)"))
try:
uri, grou... | [
"def",
"get_ldap_user_membership",
"(",
"self",
",",
"user_dn",
")",
":",
"#Escape parenthesis in DN",
"membership_filter",
"=",
"self",
".",
"conf_LDAP_SYNC_GROUP_MEMBERSHIP_FILTER",
".",
"replace",
"(",
"'{distinguishedName}'",
",",
"user_dn",
".",
"replace",
"(",
"'(... | 68.090909 | 40.090909 |
def from_table(cls, table, length, prefix=0, flatten=False):
"""
Extract from the given table a tree for word length, taking only
prefixes of prefix length (if greater than 0) into account to compute
successors.
:param table: the table to extract the tree from;
:... | [
"def",
"from_table",
"(",
"cls",
",",
"table",
",",
"length",
",",
"prefix",
"=",
"0",
",",
"flatten",
"=",
"False",
")",
":",
"# Build the expanded tree with necessary suffix and length",
"tree",
"=",
"defaultdict",
"(",
"dict",
")",
"# The tree",
"pending",
"=... | 48.394737 | 17.131579 |
def area(triangles=None, crosses=None, sum=False):
"""
Calculates the sum area of input triangles
Parameters
----------
triangles : (n, 3, 3) float
Vertices of triangles
crosses : (n, 3) float or None
As a speedup don't re- compute cross products
sum : bool
Return summed a... | [
"def",
"area",
"(",
"triangles",
"=",
"None",
",",
"crosses",
"=",
"None",
",",
"sum",
"=",
"False",
")",
":",
"if",
"crosses",
"is",
"None",
":",
"crosses",
"=",
"cross",
"(",
"triangles",
")",
"area",
"=",
"(",
"np",
".",
"sum",
"(",
"crosses",
... | 25.791667 | 16.958333 |
def glm(data, xseq, **params):
"""
Fit GLM
"""
X = sm.add_constant(data['x'])
Xseq = sm.add_constant(xseq)
init_kwargs, fit_kwargs = separate_method_kwargs(
params['method_args'], sm.GLM, sm.GLM.fit)
model = sm.GLM(data['y'], X, **init_kwargs)
results = model.fit(**fit_kwargs)
... | [
"def",
"glm",
"(",
"data",
",",
"xseq",
",",
"*",
"*",
"params",
")",
":",
"X",
"=",
"sm",
".",
"add_constant",
"(",
"data",
"[",
"'x'",
"]",
")",
"Xseq",
"=",
"sm",
".",
"add_constant",
"(",
"xseq",
")",
"init_kwargs",
",",
"fit_kwargs",
"=",
"s... | 26.363636 | 15.363636 |
def permission_required(perm, login_url=None):
"""Replacement for django.contrib.auth.decorators.permission_required that
returns 403 Forbidden if the user is already logged in.
"""
return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url) | [
"def",
"permission_required",
"(",
"perm",
",",
"login_url",
"=",
"None",
")",
":",
"return",
"user_passes_test",
"(",
"lambda",
"u",
":",
"u",
".",
"has_perm",
"(",
"perm",
")",
",",
"login_url",
"=",
"login_url",
")"
] | 44.333333 | 16.833333 |
def _get_prtfmt(self, objgowr, verbose):
"""Get print format containing markers."""
prtfmt = objgowr.get_prtfmt('fmt')
prtfmt = prtfmt.replace('# ', '')
# print('PPPPPPPPPPP', prtfmt)
if not verbose:
prtfmt = prtfmt.replace('{hdr1usr01:2}', '')
prtfmt = pr... | [
"def",
"_get_prtfmt",
"(",
"self",
",",
"objgowr",
",",
"verbose",
")",
":",
"prtfmt",
"=",
"objgowr",
".",
"get_prtfmt",
"(",
"'fmt'",
")",
"prtfmt",
"=",
"prtfmt",
".",
"replace",
"(",
"'# '",
",",
"''",
")",
"# print('PPPPPPPPPPP', prtfmt)",
"if",
"not"... | 51.571429 | 13.857143 |
def write_ioc(root, output_dir=None, force=False):
"""
Serialize an IOC, as defined by a set of etree Elements, to a .IOC file.
:param root: etree Element to write out. Should have the tag 'OpenIOC'
:param output_dir: Directory to write the ioc out to. default is current working directory.
:param... | [
"def",
"write_ioc",
"(",
"root",
",",
"output_dir",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"root_tag",
"=",
"'OpenIOC'",
"if",
"not",
"force",
"and",
"root",
".",
"tag",
"!=",
"root_tag",
":",
"raise",
"ValueError",
"(",
"'Root tag is not \"{}\... | 35.771429 | 19.028571 |
def uploadFiles(self):
"""
Uploads all the files in 'filesToSync'
"""
for each_file in self.filesToSync:
self.uploadFile(each_file["name"], each_file["ispickle"], each_file["at_home"]) | [
"def",
"uploadFiles",
"(",
"self",
")",
":",
"for",
"each_file",
"in",
"self",
".",
"filesToSync",
":",
"self",
".",
"uploadFile",
"(",
"each_file",
"[",
"\"name\"",
"]",
",",
"each_file",
"[",
"\"ispickle\"",
"]",
",",
"each_file",
"[",
"\"at_home\"",
"]"... | 37.166667 | 12.833333 |
def get_im(self, force_update=False):
"""Get the influence map for the model, generating it if necessary.
Parameters
----------
force_update : bool
Whether to generate the influence map when the function is called.
If False, returns the previously generated influ... | [
"def",
"get_im",
"(",
"self",
",",
"force_update",
"=",
"False",
")",
":",
"if",
"self",
".",
"_im",
"and",
"not",
"force_update",
":",
"return",
"self",
".",
"_im",
"if",
"not",
"self",
".",
"model",
":",
"raise",
"Exception",
"(",
"\"Cannot get influen... | 46.536082 | 18.164948 |
def messages(self):
'''A generator yielding the :class:`MacIndexMessage`
structures in this index file.'''
# The file contains the fixed-size file header followed by
# fixed-size message structures, followed by minimal message
# information (subject, from, to). Start after the ... | [
"def",
"messages",
"(",
"self",
")",
":",
"# The file contains the fixed-size file header followed by",
"# fixed-size message structures, followed by minimal message",
"# information (subject, from, to). Start after the file",
"# header and then simply return the message structures in",
"# sequ... | 50.947368 | 24.105263 |
def boost(self, boost):
"""Sets boost mode."""
_LOGGER.debug("Setting boost mode: %s", boost)
value = struct.pack('BB', PROP_BOOST, bool(boost))
self._conn.make_request(PROP_WRITE_HANDLE, value) | [
"def",
"boost",
"(",
"self",
",",
"boost",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting boost mode: %s\"",
",",
"boost",
")",
"value",
"=",
"struct",
".",
"pack",
"(",
"'BB'",
",",
"PROP_BOOST",
",",
"bool",
"(",
"boost",
")",
")",
"self",
".",
... | 44.4 | 13.2 |
def get_conn(self, urlparsed=None):
"""Returns an HTTPConnection based on the urlparse result given or the
default Swift cluster (internal url) urlparse result.
:param urlparsed: The result from urlparse.urlparse or None to use the
default Swift cluster's value
... | [
"def",
"get_conn",
"(",
"self",
",",
"urlparsed",
"=",
"None",
")",
":",
"if",
"not",
"urlparsed",
":",
"urlparsed",
"=",
"self",
".",
"dsc_parsed2",
"if",
"urlparsed",
".",
"scheme",
"==",
"'http'",
":",
"return",
"HTTPConnection",
"(",
"urlparsed",
".",
... | 41.307692 | 14.307692 |
def construct_parameter_validators(parameter, context):
"""
Constructs a dictionary of validator functions for the provided parameter
definition.
"""
validators = ValidationDict()
if '$ref' in parameter:
validators.add_validator(
'$ref', ParameterReferenceValidator(parameter[... | [
"def",
"construct_parameter_validators",
"(",
"parameter",
",",
"context",
")",
":",
"validators",
"=",
"ValidationDict",
"(",
")",
"if",
"'$ref'",
"in",
"parameter",
":",
"validators",
".",
"add_validator",
"(",
"'$ref'",
",",
"ParameterReferenceValidator",
"(",
... | 37.095238 | 17.571429 |
def head_tail_middle(src):
"""Returns a tuple consisting of the head of a enumerable, the middle
as a list and the tail of the enumerable. If the enumerable is 1 item, the
middle will be empty and the tail will be None.
>>> head_tail_middle([1, 2, 3, 4])
1, [2, 3], 4
"""
if len(src) == 0:... | [
"def",
"head_tail_middle",
"(",
"src",
")",
":",
"if",
"len",
"(",
"src",
")",
"==",
"0",
":",
"return",
"None",
",",
"[",
"]",
",",
"None",
"if",
"len",
"(",
"src",
")",
"==",
"1",
":",
"return",
"src",
"[",
"0",
"]",
",",
"[",
"]",
",",
"... | 25.421053 | 19.842105 |
def formatted_prefix(self, **format_info):
"""
Gets a dict with format info, and formats a prefix template with that info. For example:
if our prefix template is:
'some_file_{groups[0]}_{file_number}'
And we have this method called with:
formatted_prefix(groups=[US], fi... | [
"def",
"formatted_prefix",
"(",
"self",
",",
"*",
"*",
"format_info",
")",
":",
"prefix_name",
"=",
"self",
".",
"prefix_template",
".",
"format",
"(",
"*",
"*",
"format_info",
")",
"file_number",
"=",
"format_info",
".",
"pop",
"(",
"'file_number'",
",",
... | 39.47619 | 17.095238 |
def fire_event(key, msg, tag, sock_dir, args=None, transport='zeromq'):
'''
Fire deploy action
'''
event = salt.utils.event.get_event(
'master',
sock_dir,
transport,
listen=False)
try:
event.fire_event(msg, tag)
except ValueError:
# We're using at... | [
"def",
"fire_event",
"(",
"key",
",",
"msg",
",",
"tag",
",",
"sock_dir",
",",
"args",
"=",
"None",
",",
"transport",
"=",
"'zeromq'",
")",
":",
"event",
"=",
"salt",
".",
"utils",
".",
"event",
".",
"get_event",
"(",
"'master'",
",",
"sock_dir",
","... | 27.26087 | 21.086957 |
def build_request(self):
"""Build a prepared request object."""
clientheaders = {}
if (self.parent_url and
self.parent_url.lower().startswith(HTTP_SCHEMAS)):
clientheaders["Referer"] = self.parent_url
kwargs = dict(
method='GET',
url=self.u... | [
"def",
"build_request",
"(",
"self",
")",
":",
"clientheaders",
"=",
"{",
"}",
"if",
"(",
"self",
".",
"parent_url",
"and",
"self",
".",
"parent_url",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"HTTP_SCHEMAS",
")",
")",
":",
"clientheaders",
"[",
... | 36 | 13.75 |
def __extract_modules(self, loader, name, is_pkg):
""" if module found load module and save all attributes in the module found """
mod = loader.find_module(name).load_module(name)
""" find the attribute method on each module """
if hasattr(mod, '__method__'):
""" register ... | [
"def",
"__extract_modules",
"(",
"self",
",",
"loader",
",",
"name",
",",
"is_pkg",
")",
":",
"mod",
"=",
"loader",
".",
"find_module",
"(",
"name",
")",
".",
"load_module",
"(",
"name",
")",
"\"\"\" find the attribute method on each module \"\"\"",
"if",
"hasat... | 40.9 | 21.25 |
def gauss_fit(map_data, chs=None, mode='deg', amplitude=1, x_mean=0, y_mean=0, x_stddev=None, y_stddev=None, theta=None, cov_matrix=None, noise=0, **kwargs):
"""make a 2D Gaussian model and fit the observed data with the model.
Args:
map_data (xarray.Dataarray): Dataarray of cube or single chs.
... | [
"def",
"gauss_fit",
"(",
"map_data",
",",
"chs",
"=",
"None",
",",
"mode",
"=",
"'deg'",
",",
"amplitude",
"=",
"1",
",",
"x_mean",
"=",
"0",
",",
"y_mean",
"=",
"0",
",",
"x_stddev",
"=",
"None",
",",
"y_stddev",
"=",
"None",
",",
"theta",
"=",
... | 48.424 | 26.936 |
def cli(ctx, common_name, directory, blatdb="", genus="", species="", public=False):
"""Add an organism
Output:
a dictionary with information about the new organism
"""
return ctx.gi.organisms.add_organism(common_name, directory, blatdb=blatdb, genus=genus, species=species, public=public) | [
"def",
"cli",
"(",
"ctx",
",",
"common_name",
",",
"directory",
",",
"blatdb",
"=",
"\"\"",
",",
"genus",
"=",
"\"\"",
",",
"species",
"=",
"\"\"",
",",
"public",
"=",
"False",
")",
":",
"return",
"ctx",
".",
"gi",
".",
"organisms",
".",
"add_organis... | 37.5 | 32.125 |
def getconnections(self, vhost = None):
"Return accepted connections, optionally filtered by vhost"
if vhost is None:
return list(self.managed_connections)
else:
return [c for c in self.managed_connections if c.protocol.vhost == vhost] | [
"def",
"getconnections",
"(",
"self",
",",
"vhost",
"=",
"None",
")",
":",
"if",
"vhost",
"is",
"None",
":",
"return",
"list",
"(",
"self",
".",
"managed_connections",
")",
"else",
":",
"return",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"managed_connec... | 46.333333 | 20.666667 |
def popupWidget(self):
"""
Returns the popup widget for this editor.
:return <skyline.gui.XPopupWidget>
"""
if not self._popup:
btns = QDialogButtonBox.Save | QDialogButtonBox.Cancel
self._popup = XPopupWidget(self, btns)
... | [
"def",
"popupWidget",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_popup",
":",
"btns",
"=",
"QDialogButtonBox",
".",
"Save",
"|",
"QDialogButtonBox",
".",
"Cancel",
"self",
".",
"_popup",
"=",
"XPopupWidget",
"(",
"self",
",",
"btns",
")",
"self",... | 36.538462 | 12.230769 |
def qwarp_align(dset_from,dset_to,skull_strip=True,mask=None,affine_suffix='_aff',suffix='_qwarp',prefix=None):
'''aligns ``dset_from`` to ``dset_to`` using 3dQwarp
Will run ``3dSkullStrip`` (unless ``skull_strip`` is ``False``), ``3dUnifize``,
``3dAllineate``, and then ``3dQwarp``. This method will add su... | [
"def",
"qwarp_align",
"(",
"dset_from",
",",
"dset_to",
",",
"skull_strip",
"=",
"True",
",",
"mask",
"=",
"None",
",",
"affine_suffix",
"=",
"'_aff'",
",",
"suffix",
"=",
"'_qwarp'",
",",
"prefix",
"=",
"None",
")",
":",
"dset_ss",
"=",
"lambda",
"dset"... | 47.120482 | 30.662651 |
def _build_body_schema(serializer, body_parameters):
""" body is built differently, since it's a single argument no matter what. """
description = ""
if isinstance(body_parameters, Param):
schema = serializer.to_json_schema(body_parameters.arginfo.type)
description = body_parameters.descript... | [
"def",
"_build_body_schema",
"(",
"serializer",
",",
"body_parameters",
")",
":",
"description",
"=",
"\"\"",
"if",
"isinstance",
"(",
"body_parameters",
",",
"Param",
")",
":",
"schema",
"=",
"serializer",
".",
"to_json_schema",
"(",
"body_parameters",
".",
"ar... | 34.9375 | 14.84375 |
def synchronous(function, event):
"""
Runs the function synchronously taking care of exceptions.
"""
try:
function(event)
except Exception as error:
logger = get_function_logger(function)
logger.exception(error) | [
"def",
"synchronous",
"(",
"function",
",",
"event",
")",
":",
"try",
":",
"function",
"(",
"event",
")",
"except",
"Exception",
"as",
"error",
":",
"logger",
"=",
"get_function_logger",
"(",
"function",
")",
"logger",
".",
"exception",
"(",
"error",
")"
] | 27.444444 | 11.444444 |
def hqwe(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH,
zetaV, xdirect, qweargs, use_ne_eval, msrc, mrec):
r"""Hankel Transform using Quadrature-With-Extrapolation.
*Quadrature-With-Extrapolation* was introduced to geophysics by
[Key12]_. It is one of many so-called *ISE* meth... | [
"def",
"hqwe",
"(",
"zsrc",
",",
"zrec",
",",
"lsrc",
",",
"lrec",
",",
"off",
",",
"factAng",
",",
"depth",
",",
"ab",
",",
"etaH",
",",
"etaV",
",",
"zetaH",
",",
"zetaV",
",",
"xdirect",
",",
"qweargs",
",",
"use_ne_eval",
",",
"msrc",
",",
"m... | 36.358885 | 23.299652 |
def available(self, src, dst, model):
"""
Iterate over all registered plugins or plugin points and prepare to add
them to database.
"""
for name, point in six.iteritems(src):
inst = dst.pop(name, None)
if inst is None:
self.print_(1, "Regis... | [
"def",
"available",
"(",
"self",
",",
"src",
",",
"dst",
",",
"model",
")",
":",
"for",
"name",
",",
"point",
"in",
"six",
".",
"iteritems",
"(",
"src",
")",
":",
"inst",
"=",
"dst",
".",
"pop",
"(",
"name",
",",
"None",
")",
"if",
"inst",
"is"... | 44.6875 | 14.3125 |
def get_containers_by_name(self, name):
"""
get all task which relative with task name
:param name: :class:`str`, task name
:return: :class:`list`, container list
"""
code, containers = self.get_containers()
if code != httplib.OK:
return []
... | [
"def",
"get_containers_by_name",
"(",
"self",
",",
"name",
")",
":",
"code",
",",
"containers",
"=",
"self",
".",
"get_containers",
"(",
")",
"if",
"code",
"!=",
"httplib",
".",
"OK",
":",
"return",
"[",
"]",
"return",
"[",
"container",
"for",
"container... | 33.846154 | 14.307692 |
def get_object_header(self, ref):
""" Use this method to quickly examine the type and size of the object behind
the given ref.
:note: The method will only suffer from the costs of command invocation
once and reuses the command in subsequent calls.
:return: (hexsha, type_string, size_as_int)"""
cm... | [
"def",
"get_object_header",
"(",
"self",
",",
"ref",
")",
":",
"cmd",
"=",
"self",
".",
"__get_persistent_cmd",
"(",
"\"cat_file_header\"",
",",
"\"cat_file\"",
",",
"batch_check",
"=",
"True",
")",
"return",
"self",
".",
"__get_object_header",
"(",
"cmd",
","... | 43.3 | 19.7 |
def com_google_fonts_check_name_familyname(ttFont, style, familyname_with_spaces):
""" Check name table: FONT_FAMILY_NAME entries. """
from fontbakery.utils import name_entry_id
failed = False
only_weight = get_only_weight(style)
for name in ttFont['name'].names:
if name.nameID == NameID.FONT_FAMILY_NAME:... | [
"def",
"com_google_fonts_check_name_familyname",
"(",
"ttFont",
",",
"style",
",",
"familyname_with_spaces",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"name_entry_id",
"failed",
"=",
"False",
"only_weight",
"=",
"get_only_weight",
"(",
"style",
")",
"f... | 38.166667 | 16.527778 |
def fishqq(lon=None, lat=None, di_block=None):
"""
Test whether a distribution is Fisherian and make a corresponding Q-Q plot.
The Q-Q plot shows the data plotted against the value expected from a
Fisher distribution. The first plot is the uniform plot which is the
Fisher model distribution in terms... | [
"def",
"fishqq",
"(",
"lon",
"=",
"None",
",",
"lat",
"=",
"None",
",",
"di_block",
"=",
"None",
")",
":",
"if",
"di_block",
"is",
"None",
":",
"all_dirs",
"=",
"make_di_block",
"(",
"lon",
",",
"lat",
")",
"else",
":",
"all_dirs",
"=",
"di_block",
... | 35.607955 | 17.255682 |
def transform(self, photo, **kwds):
"""
Endpoint: /photo/<id>/transform.json
Performs the specified transformations.
eg. transform(photo, rotate=90)
Returns the transformed photo.
"""
result = self._client.post("/photo/%s/transform.json" %
... | [
"def",
"transform",
"(",
"self",
",",
"photo",
",",
"*",
"*",
"kwds",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"post",
"(",
"\"/photo/%s/transform.json\"",
"%",
"self",
".",
"_extract_id",
"(",
"photo",
")",
",",
"*",
"*",
"kwds",
")",
"... | 39.166667 | 16.5 |
async def fastStreamedQuery(self, url, *, headers=None, verify=True):
""" Send a GET request with short timeout, do not retry, and return streamed response. """
response = await self.session.get(url,
headers=self._buildHeaders(headers),
... | [
"async",
"def",
"fastStreamedQuery",
"(",
"self",
",",
"url",
",",
"*",
",",
"headers",
"=",
"None",
",",
"verify",
"=",
"True",
")",
":",
"response",
"=",
"await",
"self",
".",
"session",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"... | 44.3 | 20.9 |
def query(self, sql=None, filename=None, **kwargs):
""" run raw sql from sql or file against.
:param sql: Raw SQL query to pass directly to the connection.
:type sql: string
:param filename: Path to a file containing a SQL query. The path should be relative to CWD.
:type filenam... | [
"def",
"query",
"(",
"self",
",",
"sql",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"query",
"(",
"sql",
"=",
"sql",
",",
"filename",
"=",
"filename",
",",
"db",
"=",
"self",
".",
"db_names",
"["... | 40.541667 | 25.125 |
def overlay_gateway_monitor_remote_endpoint(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
... | [
"def",
"overlay_gateway_monitor_remote_endpoint",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"overlay_gateway",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"overlay-gateway\"",
",",
"xml... | 48.4 | 17.933333 |
def reopen(self, file_obj):
"""Reopen the file-like object in a safe manner."""
file_obj.open('U')
if sys.version_info[0] <= 2:
return file_obj
else:
return codecs.getreader('utf-8')(file_obj) | [
"def",
"reopen",
"(",
"self",
",",
"file_obj",
")",
":",
"file_obj",
".",
"open",
"(",
"'U'",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<=",
"2",
":",
"return",
"file_obj",
"else",
":",
"return",
"codecs",
".",
"getreader",
"(",
"'utf-8'... | 34.571429 | 12.142857 |
def alias_field(model, field):
"""
Return the prefix name of a field
"""
for part in field.split(LOOKUP_SEP)[:-1]:
model = associate_model(model,part)
return model.__name__ + "-" + field.split(LOOKUP_SEP)[-1] | [
"def",
"alias_field",
"(",
"model",
",",
"field",
")",
":",
"for",
"part",
"in",
"field",
".",
"split",
"(",
"LOOKUP_SEP",
")",
"[",
":",
"-",
"1",
"]",
":",
"model",
"=",
"associate_model",
"(",
"model",
",",
"part",
")",
"return",
"model",
".",
"... | 32.857143 | 6 |
def glibc_version_string():
"Returns glibc version string, or None if not using glibc."
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
# manpage says, "If filename is NULL, then the returned handle is for the
# main program". This way we can let the linker do the work to figure ou... | [
"def",
"glibc_version_string",
"(",
")",
":",
"# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen",
"# manpage says, \"If filename is NULL, then the returned handle is for the",
"# main program\". This way we can let the linker do the work to figure out",
"# which libc our process ... | 39.304348 | 21.217391 |
def mismatches(args):
"""
%prog mismatches blastfile
Print out histogram of mismatches of HSPs, usually for evaluating SNP level.
"""
from jcvi.utils.cbook import percentage
from jcvi.graphics.histogram import stem_leaf_plot
p = OptionParser(mismatches.__doc__)
opts, args = p.parse_ar... | [
"def",
"mismatches",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"cbook",
"import",
"percentage",
"from",
"jcvi",
".",
"graphics",
".",
"histogram",
"import",
"stem_leaf_plot",
"p",
"=",
"OptionParser",
"(",
"mismatches",
".",
"__doc__",
")",
... | 25.482759 | 18.241379 |
def get_bibtex_string(self):
"""
Get BibTeX reference from CIF file.
:param data:
:return: BibTeX string
"""
bibtex_keys = {'author': ('_publ_author_name', '_citation_author_name'),
'title': ('_publ_section_title', '_citation_title'),
... | [
"def",
"get_bibtex_string",
"(",
"self",
")",
":",
"bibtex_keys",
"=",
"{",
"'author'",
":",
"(",
"'_publ_author_name'",
",",
"'_citation_author_name'",
")",
",",
"'title'",
":",
"(",
"'_publ_section_title'",
",",
"'_citation_title'",
")",
",",
"'journal'",
":",
... | 47.333333 | 28.866667 |
def set(self, item_name, item_value):
"""
Sets the value of an option in the configuration.
:param str item_name: The name of the option to set.
:param item_value: The value of the option to set.
"""
if self.prefix:
item_name = self.prefix + self.seperator + item_name
item_names = item_name.split(self... | [
"def",
"set",
"(",
"self",
",",
"item_name",
",",
"item_value",
")",
":",
"if",
"self",
".",
"prefix",
":",
"item_name",
"=",
"self",
".",
"prefix",
"+",
"self",
".",
"seperator",
"+",
"item_name",
"item_names",
"=",
"item_name",
".",
"split",
"(",
"se... | 28.833333 | 13.722222 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.