text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _convert_suffix_to_docker_chars(suffix):
"""Rewrite string so that all characters are valid in a docker name suffix."""
# Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-]
accepted_characters = string.ascii_letters + string.digits + '_.-'
def label_char_transform(char):
if char in accepted_c... | [
"def",
"_convert_suffix_to_docker_chars",
"(",
"suffix",
")",
":",
"# Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-]",
"accepted_characters",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"'_.-'",
"def",
"label_char_transform",
"(",
"... | 37.454545 | 0.018957 |
def add(name,
uid=None,
gid=None,
groups=None,
home=None,
shell=None,
unique=True,
fullname='',
roomnumber='',
workphone='',
homephone='',
createhome=True,
loginclass=None,
**kwargs):
'''
Add a user to the mi... | [
"def",
"add",
"(",
"name",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"home",
"=",
"None",
",",
"shell",
"=",
"None",
",",
"unique",
"=",
"True",
",",
"fullname",
"=",
"''",
",",
"roomnumber",
"=",
"''",
... | 28.2 | 0.000623 |
def redirect(location, code=302):
"""Return a response object (a WSGI application) that, if called,
redirects the client to the target location. Supported codes are 301,
302, 303, 305, and 307. 300 is not supported because it's not a real
redirect and 304 because it's the answer for a request with a r... | [
"def",
"redirect",
"(",
"location",
",",
"code",
"=",
"302",
")",
":",
"from",
"werkzeug",
".",
"wrappers",
"import",
"Response",
"display_location",
"=",
"escape",
"(",
"location",
")",
"if",
"isinstance",
"(",
"location",
",",
"text_type",
")",
":",
"fro... | 44.928571 | 0.000778 |
def _check_submodule_using_git(self):
"""
Check if the given path is a git submodule. If so, attempt to initialize
and/or update the submodule if needed.
This function makes calls to the ``git`` command in subprocesses. The
``_check_submodule_no_git`` option uses pure Python t... | [
"def",
"_check_submodule_using_git",
"(",
"self",
")",
":",
"cmd",
"=",
"[",
"'git'",
",",
"'submodule'",
",",
"'status'",
",",
"'--'",
",",
"self",
".",
"path",
"]",
"try",
":",
"log",
".",
"info",
"(",
"'Running `{0}`; use the --no-git option to disable git '"... | 45.653333 | 0.002001 |
def __gridconnections(self):
"""Level-2 parser for gridconnections.
pattern:
object 2 class gridconnections counts 97 93 99
"""
try:
tok = self.__consume()
except DXParserNoTokens:
return
if tok.equals('counts'):
shape = []
... | [
"def",
"__gridconnections",
"(",
"self",
")",
":",
"try",
":",
"tok",
"=",
"self",
".",
"__consume",
"(",
")",
"except",
"DXParserNoTokens",
":",
"return",
"if",
"tok",
".",
"equals",
"(",
"'counts'",
")",
":",
"shape",
"=",
"[",
"]",
"try",
":",
"wh... | 33.076923 | 0.00226 |
def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
properties.pop('legend', None)
for prop in ['color', 'alpha']:
if prop not in properties:
continue
pval = properties.pop(prop)
line_prop = '... | [
"def",
"_init_glyph",
"(",
"self",
",",
"plot",
",",
"mapping",
",",
"properties",
")",
":",
"properties",
".",
"pop",
"(",
"'legend'",
",",
"None",
")",
"for",
"prop",
"in",
"[",
"'color'",
",",
"'alpha'",
"]",
":",
"if",
"prop",
"not",
"in",
"prope... | 39.1 | 0.002497 |
def check_password(password, encoded, setter=None, preferred='default'):
"""
Return a boolean of whether the raw password matches the three
part encoded digest.
If setter is specified, it'll be called when you need to
regenerate the password.
"""
if password is None:
return False
... | [
"def",
"check_password",
"(",
"password",
",",
"encoded",
",",
"setter",
"=",
"None",
",",
"preferred",
"=",
"'default'",
")",
":",
"if",
"password",
"is",
"None",
":",
"return",
"False",
"preferred",
"=",
"bCryptPasswordHasher",
"hasher",
"=",
"bCryptPassword... | 37 | 0.000976 |
def to_etree(self):
"""
creates an etree element of a ``SaltLayer`` that mimicks a SaltXMI
<layers> element
"""
nodes_attrib_val = ' '.join('//@nodes.{}'.format(node_id)
for node_id in self.nodes)
edges_attrib_val = ' '.join('//@edges.{... | [
"def",
"to_etree",
"(",
"self",
")",
":",
"nodes_attrib_val",
"=",
"' '",
".",
"join",
"(",
"'//@nodes.{}'",
".",
"format",
"(",
"node_id",
")",
"for",
"node_id",
"in",
"self",
".",
"nodes",
")",
"edges_attrib_val",
"=",
"' '",
".",
"join",
"(",
"'//@edg... | 42.181818 | 0.002107 |
def random_name(num_surnames=2):
"""
Returns a random person name
Arguments:
num_surnames -- number of surnames
"""
a = []
# Prefix
if random.random() < _PROB_PREF:
a.append(_prefixes[random.randint(0, len(_prefixes) - 1)])
# Forename
a.append(_forename... | [
"def",
"random_name",
"(",
"num_surnames",
"=",
"2",
")",
":",
"a",
"=",
"[",
"]",
"# Prefix\r",
"if",
"random",
".",
"random",
"(",
")",
"<",
"_PROB_PREF",
":",
"a",
".",
"append",
"(",
"_prefixes",
"[",
"random",
".",
"randint",
"(",
"0",
",",
"l... | 24.28 | 0.001585 |
def load_default_templates(self):
"""Load the default templates"""
for importer, modname, is_pkg in pkgutil.iter_modules(templates.__path__):
self.register_template('.'.join((templates.__name__, modname))) | [
"def",
"load_default_templates",
"(",
"self",
")",
":",
"for",
"importer",
",",
"modname",
",",
"is_pkg",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"templates",
".",
"__path__",
")",
":",
"self",
".",
"register_template",
"(",
"'.'",
".",
"join",
"(",
"("... | 57.5 | 0.012876 |
def maybe_upcast_for_op(obj):
"""
Cast non-pandas objects to pandas types to unify behavior of arithmetic
and comparison operations.
Parameters
----------
obj: object
Returns
-------
out : object
Notes
-----
Be careful to call this *after* determining the `name` attrib... | [
"def",
"maybe_upcast_for_op",
"(",
"obj",
")",
":",
"if",
"type",
"(",
"obj",
")",
"is",
"datetime",
".",
"timedelta",
":",
"# GH#22390 cast up to Timedelta to rely on Timedelta",
"# implementation; otherwise operation against numeric-dtype",
"# raises TypeError",
"return",
... | 37.055556 | 0.00073 |
def url(self, url, owner=None, **kwargs):
"""
Create the URL TI object.
Args:
owner:
url:
**kwargs:
Return:
"""
return URL(self.tcex, url, owner=owner, **kwargs) | [
"def",
"url",
"(",
"self",
",",
"url",
",",
"owner",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"URL",
"(",
"self",
".",
"tcex",
",",
"url",
",",
"owner",
"=",
"owner",
",",
"*",
"*",
"kwargs",
")"
] | 18.153846 | 0.008065 |
def uninitialize(cls) -> None:
"""Removes the ``SIGCHLD`` handler."""
if not cls._initialized:
return
signal.signal(signal.SIGCHLD, cls._old_sigchld)
cls._initialized = False | [
"def",
"uninitialize",
"(",
"cls",
")",
"->",
"None",
":",
"if",
"not",
"cls",
".",
"_initialized",
":",
"return",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGCHLD",
",",
"cls",
".",
"_old_sigchld",
")",
"cls",
".",
"_initialized",
"=",
"False"
] | 35.5 | 0.009174 |
def smp_to_dataframe(smp_filename,datetime_format=None):
""" load an smp file into a pandas dataframe (stacked in wide format)
Parameters
----------
smp_filename : str
smp filename to load
datetime_format : str
should be either "%m/%d/%Y %H:%M:%S" or "%d/%m/%Y %H:%M:%S"
If N... | [
"def",
"smp_to_dataframe",
"(",
"smp_filename",
",",
"datetime_format",
"=",
"None",
")",
":",
"if",
"datetime_format",
"is",
"not",
"None",
":",
"date_func",
"=",
"lambda",
"x",
":",
"datetime",
".",
"strptime",
"(",
"x",
",",
"datetime_format",
")",
"else"... | 32.172414 | 0.013528 |
def rand_str(length, allowed=CHARSET_ALPHA_DIGITS):
"""Generate fixed-length random string from your allowed character pool.
:param length: total length of this string.
:param allowed: allowed charset.
Example::
>>> import string
>>> rand_str(32)
H6ExQPNLzb4Vp3YZtfpyzLNPFwdfnw... | [
"def",
"rand_str",
"(",
"length",
",",
"allowed",
"=",
"CHARSET_ALPHA_DIGITS",
")",
":",
"res",
"=",
"list",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"length",
")",
":",
"res",
".",
"append",
"(",
"random",
".",
"choice",
"(",
"allowed",
")",
")",
... | 26.6875 | 0.002262 |
def Copy(self, name=None):
"""Returns a copy of this Cdf.
Args:
name: string name for the new Cdf
"""
if name is None:
name = self.name
return Cdf(list(self.xs), list(self.ps), name) | [
"def",
"Copy",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"name",
"return",
"Cdf",
"(",
"list",
"(",
"self",
".",
"xs",
")",
",",
"list",
"(",
"self",
".",
"ps",
")",
",",
"name... | 26.555556 | 0.008097 |
def team_billableInfo(self, **kwargs) -> SlackResponse:
"""Gets billable users information for the current team."""
self._validate_xoxp_token()
return self.api_call("team.billableInfo", http_verb="GET", params=kwargs) | [
"def",
"team_billableInfo",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"SlackResponse",
":",
"self",
".",
"_validate_xoxp_token",
"(",
")",
"return",
"self",
".",
"api_call",
"(",
"\"team.billableInfo\"",
",",
"http_verb",
"=",
"\"GET\"",
",",
"params",
... | 59.5 | 0.012448 |
def generator_by_digest(family, digest_size):
""" Return generator by hash generator family name and digest size
:param family: name of hash-generator family
:return: WHashGeneratorProto class
"""
for generator_name in WHash.available_generators(family=family):
generator = WHash.generator(generator_name)... | [
"def",
"generator_by_digest",
"(",
"family",
",",
"digest_size",
")",
":",
"for",
"generator_name",
"in",
"WHash",
".",
"available_generators",
"(",
"family",
"=",
"family",
")",
":",
"generator",
"=",
"WHash",
".",
"generator",
"(",
"generator_name",
")",
"if... | 36.666667 | 0.02439 |
def intervallookup(table, start='start', stop='stop', value=None,
include_stop=False):
"""
Construct an interval lookup for the given table. E.g.::
>>> import petl as etl
>>> table = [['start', 'stop', 'value'],
... [1, 4, 'foo'],
... [3, 7, ... | [
"def",
"intervallookup",
"(",
"table",
",",
"start",
"=",
"'start'",
",",
"stop",
"=",
"'stop'",
",",
"value",
"=",
"None",
",",
"include_stop",
"=",
"False",
")",
":",
"tree",
"=",
"tupletree",
"(",
"table",
",",
"start",
"=",
"start",
",",
"stop",
... | 29.945946 | 0.000874 |
def open(self):
"""
Open the Sender using the supplied conneciton.
If the handler has previously been redirected, the redirect
context will be used to create a new handler before opening it.
:param connection: The underlying client shared connection.
:type: connection: ~... | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"running",
"=",
"True",
"if",
"self",
".",
"redirected",
":",
"self",
".",
"target",
"=",
"self",
".",
"redirected",
".",
"address",
"self",
".",
"_handler",
"=",
"SendClient",
"(",
"self",
".",
"tar... | 39.375 | 0.002066 |
def makedirs_safe(fulldir):
"""Creates a directory if it does not exists. Takes into consideration
concurrent access support. Works like the shell's 'mkdir -p'.
"""
try:
if not os.path.exists(fulldir): os.makedirs(fulldir)
except OSError as exc: # Python >2.5
import errno
if exc.errno == errno.EE... | [
"def",
"makedirs_safe",
"(",
"fulldir",
")",
":",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fulldir",
")",
":",
"os",
".",
"makedirs",
"(",
"fulldir",
")",
"except",
"OSError",
"as",
"exc",
":",
"# Python >2.5",
"import",
"errno"... | 30.545455 | 0.023121 |
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):... | [
"def",
"install",
"(",
"name",
"=",
"None",
",",
"refresh",
"=",
"False",
",",
"pkgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"saltenv",
"=",
"kwargs",
".",
"pop",
"(",
"'saltenv'",
",",
"'base'",
")",
"refresh",
"=... | 40.6 | 0.001122 |
def user_organization_membership_show(self, user_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_memberships#show-membership"
api_path = "/api/v2/users/{user_id}/organization_memberships/{id}.json"
api_path = api_path.format(user_id=user_id, id=id)
retur... | [
"def",
"user_organization_membership_show",
"(",
"self",
",",
"user_id",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/users/{user_id}/organization_memberships/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"user_id",
"=",
... | 69.4 | 0.008547 |
def get_bg_color(image, bits_per_channel=None):
'''Obtains the background color from an image or array of RGB colors
by grouping similar colors into bins and finding the most frequent
one.
'''
assert image.shape[-1] == 3
quantized = quantize(image, bits_per_channel).astype(int)
packed = pack_rgb... | [
"def",
"get_bg_color",
"(",
"image",
",",
"bits_per_channel",
"=",
"None",
")",
":",
"assert",
"image",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"3",
"quantized",
"=",
"quantize",
"(",
"image",
",",
"bits_per_channel",
")",
".",
"astype",
"(",
"int",
")... | 25.166667 | 0.002128 |
def get_output(script, expanded):
"""Runs the script and obtains stdin/stderr.
:type script: str
:type expanded: str
:rtype: str | None
"""
env = dict(os.environ)
env.update(settings.env)
is_slow = shlex.split(expanded) in settings.slow_commands
with logs.debug_time(u'Call: {}; wi... | [
"def",
"get_output",
"(",
"script",
",",
"expanded",
")",
":",
"env",
"=",
"dict",
"(",
"os",
".",
"environ",
")",
"env",
".",
"update",
"(",
"settings",
".",
"env",
")",
"is_slow",
"=",
"shlex",
".",
"split",
"(",
"expanded",
")",
"in",
"settings",
... | 32.826087 | 0.001287 |
def get_global_palette(filenames, options):
'''Fetch the global palette for a series of input files by merging
their samples together into one large array.
'''
input_filenames = []
all_samples = []
if not options.quiet:
print('building global palette...')
for input_filename in file... | [
"def",
"get_global_palette",
"(",
"filenames",
",",
"options",
")",
":",
"input_filenames",
"=",
"[",
"]",
"all_samples",
"=",
"[",
"]",
"if",
"not",
"options",
".",
"quiet",
":",
"print",
"(",
"'building global palette...'",
")",
"for",
"input_filename",
"in"... | 23.55 | 0.001019 |
def button_state(self):
"""The button state that triggered this event.
For pointer events that are not of type
:attr:`~libinput.constant.EventType.POINTER_BUTTON`, this property
raises :exc:`AttributeError`.
Returns:
~libinput.constant.ButtonState: The button state triggering this
event.
Raises:
... | [
"def",
"button_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"POINTER_BUTTON",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput",
... | 28.055556 | 0.030651 |
def draw_chimera_embedding(G, *args, **kwargs):
"""Draws an embedding onto the chimera graph G, according to layout.
If interaction_edges is not None, then only display the couplers in that
list. If embedded_graph is not None, the only display the couplers between
chains with intended couplings accord... | [
"def",
"draw_chimera_embedding",
"(",
"G",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"draw_embedding",
"(",
"G",
",",
"chimera_layout",
"(",
"G",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 46.510638 | 0.001344 |
def trim_structure(struct, filtering="cube", n=2):
"""Remove outlier 'atoms' (aka bins) from a structure.
"""
X, Y, Z = (struct[:, i] for i in range(3))
if filtering == "sphere":
R = (np.std(X)**2 + np.std(Y)**2 + np.std(Z)**2) * (n**2)
f = (X - np.mean(X))**2 + (Y - np.mean(Y))**2 + (... | [
"def",
"trim_structure",
"(",
"struct",
",",
"filtering",
"=",
"\"cube\"",
",",
"n",
"=",
"2",
")",
":",
"X",
",",
"Y",
",",
"Z",
"=",
"(",
"struct",
"[",
":",
",",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
")",
"if",
"filtering",
"... | 32.26087 | 0.001309 |
def add_timezone(value, tz=None):
"""If the value is naive, then the timezone is added to it.
If no timezone is given, timezone.get_current_timezone() is used.
"""
tz = tz or timezone.get_current_timezone()
try:
if timezone.is_naive(value):
return timezone.make_aware(value, tz)
... | [
"def",
"add_timezone",
"(",
"value",
",",
"tz",
"=",
"None",
")",
":",
"tz",
"=",
"tz",
"or",
"timezone",
".",
"get_current_timezone",
"(",
")",
"try",
":",
"if",
"timezone",
".",
"is_naive",
"(",
"value",
")",
":",
"return",
"timezone",
".",
"make_awa... | 39.153846 | 0.001919 |
def writeData(f, data):
"""
Write a dictionary object to a file
:param f: The file to write to
:type f: file/string
:param data: The data to write to the file
:type data: dict
"""
if not isinstance(data, dict):
raise Exception(PyVDF.__ERR_NotDict.format(repr(data)))
data = PyV... | [
"def",
"writeData",
"(",
"f",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"raise",
"Exception",
"(",
"PyVDF",
".",
"__ERR_NotDict",
".",
"format",
"(",
"repr",
"(",
"data",
")",
")",
")",
"data",
"=",
"PyVD... | 23.291667 | 0.015464 |
def get_template_debug(template_name, error):
'''
This structure is what Django wants when errors occur in templates.
It gives the user a nice stack trace in the error page during debug.
'''
# This is taken from mako.exceptions.html_error_template(), which has an issue
# in Py3 where files get l... | [
"def",
"get_template_debug",
"(",
"template_name",
",",
"error",
")",
":",
"# This is taken from mako.exceptions.html_error_template(), which has an issue",
"# in Py3 where files get loaded as bytes but `lines = src.split('\\n')` below",
"# splits with a string. Not sure if this is a bug or if I... | 32.557252 | 0.002048 |
def colour(colour, message, bold=False):
""" Color a message """
return style(fg=colour, text=message, bold=bold) | [
"def",
"colour",
"(",
"colour",
",",
"message",
",",
"bold",
"=",
"False",
")",
":",
"return",
"style",
"(",
"fg",
"=",
"colour",
",",
"text",
"=",
"message",
",",
"bold",
"=",
"bold",
")"
] | 39.666667 | 0.008264 |
def __data_labels_distances(self,
indexed_string,
classifier_fn,
num_samples,
distance_metric='cosine'):
"""Generates a neighborhood around a prediction.
Generates neighborhoo... | [
"def",
"__data_labels_distances",
"(",
"self",
",",
"indexed_string",
",",
"classifier_fn",
",",
"num_samples",
",",
"distance_metric",
"=",
"'cosine'",
")",
":",
"def",
"distance_fn",
"(",
"x",
")",
":",
"return",
"sklearn",
".",
"metrics",
".",
"pairwise",
"... | 49.1 | 0.002396 |
def _netinfo_openbsd():
'''
Get process information for network connections using fstat
'''
ret = {}
_fstat_re = re.compile(
r'internet(6)? (?:stream tcp 0x\S+ (\S+)|dgram udp (\S+))'
r'(?: [<>=-]+ (\S+))?$'
)
out = __salt__['cmd.run']('fstat')
for line in out.splitlines(... | [
"def",
"_netinfo_openbsd",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"_fstat_re",
"=",
"re",
".",
"compile",
"(",
"r'internet(6)? (?:stream tcp 0x\\S+ (\\S+)|dgram udp (\\S+))'",
"r'(?: [<>=-]+ (\\S+))?$'",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'fstat... | 38.866667 | 0.000558 |
def from_xmrs(cls, xmrs, predicate_modifiers=False, **kwargs):
"""
Instantiate an Eds from an Xmrs (lossy conversion).
Args:
xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): Xmrs instance to
convert from
predicate_modifiers (function, bool): function that is
... | [
"def",
"from_xmrs",
"(",
"cls",
",",
"xmrs",
",",
"predicate_modifiers",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"eps",
"=",
"xmrs",
".",
"eps",
"(",
")",
"deps",
"=",
"_find_basic_dependencies",
"(",
"xmrs",
",",
"eps",
")",
"# if requested, fi... | 44.636364 | 0.001495 |
def query(hook=None,
api_url=None,
data=None):
'''
Mattermost object method function to construct and execute on the API URL.
:param api_url: The Mattermost API URL
:param hook: The Mattermost hook.
:param data: The data to be sent for POST method.
:return: ... | [
"def",
"query",
"(",
"hook",
"=",
"None",
",",
"api_url",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"method",
"=",
"'POST'",
"ret",
"=",
"{",
"'message'",
":",
"''",
",",
"'res'",
":",
"True",
"}",
"base_url",
"=",
"_urljoin",
"(",
"api_url"... | 32.840909 | 0.001344 |
def chisq(psr,formbats=False):
"""Return the total chisq for the current timing solution,
removing noise-averaged mean residual, and ignoring deleted points."""
if formbats:
psr.formbats()
res, err = psr.residuals(removemean=False)[psr.deleted == 0], psr.toaerrs[psr.deleted == 0]
... | [
"def",
"chisq",
"(",
"psr",
",",
"formbats",
"=",
"False",
")",
":",
"if",
"formbats",
":",
"psr",
".",
"formbats",
"(",
")",
"res",
",",
"err",
"=",
"psr",
".",
"residuals",
"(",
"removemean",
"=",
"False",
")",
"[",
"psr",
".",
"deleted",
"==",
... | 34.5 | 0.011765 |
def save(self, filepath=None, overwrite=False, verbose=True):
"""Save as root of a new file.
Parameters
----------
filepath : Path-like object (optional)
Filepath to write. If None, file is created using natural_name.
overwrite : boolean (optional)
Toggle... | [
"def",
"save",
"(",
"self",
",",
"filepath",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"filepath",
"is",
"None",
":",
"filepath",
"=",
"pathlib",
".",
"Path",
"(",
"\".\"",
")",
"/",
"self",
".",
"nat... | 30.533333 | 0.00141 |
def _collapse_address_list_recursive(addresses):
"""Loops through the addresses, collapsing concurrent netblocks.
Example:
ip1 = IPv4Network('1.1.0.0/24')
ip2 = IPv4Network('1.1.1.0/24')
ip3 = IPv4Network('1.1.2.0/24')
ip4 = IPv4Network('1.1.3.0/24')
ip5 = IPv4Network('... | [
"def",
"_collapse_address_list_recursive",
"(",
"addresses",
")",
":",
"ret_array",
"=",
"[",
"]",
"optimized",
"=",
"False",
"for",
"cur_addr",
"in",
"addresses",
":",
"if",
"not",
"ret_array",
":",
"ret_array",
".",
"append",
"(",
"cur_addr",
")",
"continue"... | 28.466667 | 0.000755 |
def do_shell(self, arg):
"run a shell commad"
print(">", arg)
sub_cmd = subprocess.Popen(arg, shell=True, stdout=subprocess.PIPE)
print(sub_cmd.communicate()[0]) | [
"def",
"do_shell",
"(",
"self",
",",
"arg",
")",
":",
"print",
"(",
"\">\"",
",",
"arg",
")",
"sub_cmd",
"=",
"subprocess",
".",
"Popen",
"(",
"arg",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"print",
"(",
"sub_... | 37.8 | 0.010363 |
def tilt(self,R,z,nsigma=None,mc=False,nmc=10000,
gl=True,ngl=_DEFAULTNGL,**kwargs):
"""
NAME:
tilt
PURPOSE:
calculate the tilt of the velocity ellipsoid by marginalizing over velocity
INPUT:
R - radius at which to calculate this (can be... | [
"def",
"tilt",
"(",
"self",
",",
"R",
",",
"z",
",",
"nsigma",
"=",
"None",
",",
"mc",
"=",
"False",
",",
"nmc",
"=",
"10000",
",",
"gl",
"=",
"True",
",",
"ngl",
"=",
"_DEFAULTNGL",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
... | 42.9875 | 0.029278 |
def _linux_iqn():
'''
Return iSCSI IQN from a Linux host.
'''
ret = []
initiator = '/etc/iscsi/initiatorname.iscsi'
try:
with salt.utils.files.fopen(initiator, 'r') as _iscsi:
for line in _iscsi:
line = line.strip()
if line.startswith('Initiat... | [
"def",
"_linux_iqn",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"initiator",
"=",
"'/etc/iscsi/initiatorname.iscsi'",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"initiator",
",",
"'r'",
")",
"as",
"_iscsi",
":",
"for",
"line",
... | 28.722222 | 0.001873 |
def apt_add_repository_from_apt_string(apt_string, apt_file):
""" adds a new repository file for apt """
apt_file_path = '/etc/apt/sources.list.d/%s' % apt_file
if not file_contains(apt_file_path, apt_string.lower(), use_sudo=True):
file_append(apt_file_path, apt_string.lower(), use_sudo=True)
... | [
"def",
"apt_add_repository_from_apt_string",
"(",
"apt_string",
",",
"apt_file",
")",
":",
"apt_file_path",
"=",
"'/etc/apt/sources.list.d/%s'",
"%",
"apt_file",
"if",
"not",
"file_contains",
"(",
"apt_file_path",
",",
"apt_string",
".",
"lower",
"(",
")",
",",
"use... | 41.4 | 0.002364 |
def load_product_class(self, mode):
"""Load recipe object, according to observing mode"""
product_entry = self.products[mode]
return self._get_base_class(product_entry) | [
"def",
"load_product_class",
"(",
"self",
",",
"mode",
")",
":",
"product_entry",
"=",
"self",
".",
"products",
"[",
"mode",
"]",
"return",
"self",
".",
"_get_base_class",
"(",
"product_entry",
")"
] | 31.5 | 0.010309 |
def addExtensionArg(self, namespace, key, value):
"""Add an extension argument to this OpenID authentication
request.
Use caution when adding arguments, because they will be
URL-escaped and appended to the redirect URL, which can easily
get quite long.
@param namespace:... | [
"def",
"addExtensionArg",
"(",
"self",
",",
"namespace",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"message",
".",
"setArg",
"(",
"namespace",
",",
"key",
",",
"value",
")"
] | 32.115385 | 0.002326 |
def check_job(cls, job_details):
""" Check the status of a specfic job """
return check_log(job_details.logfile, cls.string_exited, cls.string_successful) | [
"def",
"check_job",
"(",
"cls",
",",
"job_details",
")",
":",
"return",
"check_log",
"(",
"job_details",
".",
"logfile",
",",
"cls",
".",
"string_exited",
",",
"cls",
".",
"string_successful",
")"
] | 56 | 0.017647 |
def angle(vec1, vec2):
"""Calculate the angle between two Vector2's"""
dotp = Vector2.dot(vec1, vec2)
mag1 = vec1.length()
mag2 = vec2.length()
result = dotp / (mag1 * mag2)
return math.acos(result) | [
"def",
"angle",
"(",
"vec1",
",",
"vec2",
")",
":",
"dotp",
"=",
"Vector2",
".",
"dot",
"(",
"vec1",
",",
"vec2",
")",
"mag1",
"=",
"vec1",
".",
"length",
"(",
")",
"mag2",
"=",
"vec2",
".",
"length",
"(",
")",
"result",
"=",
"dotp",
"/",
"(",
... | 34.285714 | 0.00813 |
def get_xname(self, var, coords=None):
"""Get the name of the x-dimension
This method gives the name of the x-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
... | [
"def",
"get_xname",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"if",
"coords",
"is",
"not",
"None",
":",
"coord",
"=",
"self",
".",
"get_variable_by_axis",
"(",
"var",
",",
"'x'",
",",
"coords",
")",
"if",
"coord",
"is",
"not",
... | 34.285714 | 0.001621 |
def folder_source(path, folder):
"""
Returns the filenames and labels for a folder within a path
Returns:
-------
fnames: a list of the filenames within `folder`
all_lbls: a list of all of the labels in `folder`, where the # of labels is determined by the # of directories within `folder`
... | [
"def",
"folder_source",
"(",
"path",
",",
"folder",
")",
":",
"fnames",
",",
"lbls",
",",
"all_lbls",
"=",
"read_dirs",
"(",
"path",
",",
"folder",
")",
"lbl2idx",
"=",
"{",
"lbl",
":",
"idx",
"for",
"idx",
",",
"lbl",
"in",
"enumerate",
"(",
"all_lb... | 40.266667 | 0.008091 |
def get_header(self, idx, formatted=False):
"""
Return a list of the variable names at the given indices
"""
header = self._uname if not formatted else self._fname
return [header[x] for x in idx] | [
"def",
"get_header",
"(",
"self",
",",
"idx",
",",
"formatted",
"=",
"False",
")",
":",
"header",
"=",
"self",
".",
"_uname",
"if",
"not",
"formatted",
"else",
"self",
".",
"_fname",
"return",
"[",
"header",
"[",
"x",
"]",
"for",
"x",
"in",
"idx",
... | 38.333333 | 0.008511 |
def line_intersection(self, point1, point2, tolerance=1e-8):
"""
Computes the intersection points of a line with a simplex
Args:
point1, point2 ([float]): Points that determine the line
Returns:
points where the line intersects the simplex (0, 1, or 2)
"""... | [
"def",
"line_intersection",
"(",
"self",
",",
"point1",
",",
"point2",
",",
"tolerance",
"=",
"1e-8",
")",
":",
"b1",
"=",
"self",
".",
"bary_coords",
"(",
"point1",
")",
"b2",
"=",
"self",
".",
"bary_coords",
"(",
"point2",
")",
"l",
"=",
"b1",
"-",... | 39.933333 | 0.002445 |
def Heartbeat(self):
"""Sends a heartbeat to the Fleetspeak client.
If this daemonservice is configured to use heartbeats, clients that don't
call this method often enough are considered faulty and are restarted by
Fleetspeak.
"""
heartbeat_msg = common_pb2.Message(
message_type="Heartb... | [
"def",
"Heartbeat",
"(",
"self",
")",
":",
"heartbeat_msg",
"=",
"common_pb2",
".",
"Message",
"(",
"message_type",
"=",
"\"Heartbeat\"",
",",
"destination",
"=",
"common_pb2",
".",
"Address",
"(",
"service_name",
"=",
"\"system\"",
")",
")",
"self",
".",
"_... | 37.454545 | 0.00237 |
def Servers(self,cached=True):
"""Returns list of server objects, populates if necessary.
>>> clc.v2.Servers(["NY1BTDIPHYP0101","NY1BTDIWEB0101"]).Servers()
[<clc.APIv2.server.Server object at 0x1065b0d50>, <clc.APIv2.server.Server object at 0x1065b0e50>]
>>> print _[0]
NY1BTDIPHYP0101
"""
if not hasat... | [
"def",
"Servers",
"(",
"self",
",",
"cached",
"=",
"True",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_servers'",
")",
"or",
"not",
"cached",
":",
"self",
".",
"_servers",
"=",
"[",
"]",
"for",
"server",
"in",
"self",
".",
"servers_lst",
... | 31.4375 | 0.03668 |
def _solve(self, x0, A, l, u, xmin, xmax):
""" Solves using Python Interior Point Solver (PIPS).
"""
s = pips(self._costfcn, x0, A, l, u, xmin, xmax,
self._consfcn, self._hessfcn, self.opt)
return s | [
"def",
"_solve",
"(",
"self",
",",
"x0",
",",
"A",
",",
"l",
",",
"u",
",",
"xmin",
",",
"xmax",
")",
":",
"s",
"=",
"pips",
"(",
"self",
".",
"_costfcn",
",",
"x0",
",",
"A",
",",
"l",
",",
"u",
",",
"xmin",
",",
"xmax",
",",
"self",
"."... | 40.333333 | 0.012146 |
def _group_by_equal_size(obj_list, tot_groups, threshold=pow(2, 32)):
"""Partition a list of objects evenly and by file size
Files are placed according to largest file in the smallest bucket. If the
file is larger than the given threshold, then it is placed in a new bucket
by itself.
:param obj_lis... | [
"def",
"_group_by_equal_size",
"(",
"obj_list",
",",
"tot_groups",
",",
"threshold",
"=",
"pow",
"(",
"2",
",",
"32",
")",
")",
":",
"sorted_obj_list",
"=",
"sorted",
"(",
"[",
"(",
"obj",
"[",
"'size'",
"]",
",",
"obj",
")",
"for",
"obj",
"in",
"obj... | 41.357143 | 0.001688 |
def Lockhart_Martinelli(m, x, rhol, rhog, mul, mug, D, L=1, Re_c=2000):
r'''Calculates two-phase pressure drop with the Lockhart and Martinelli
(1949) correlation as presented in non-graphical form by Chisholm (1967).
.. math::
\Delta P = \Delta P_{l} \phi_{l}^2
.. math::
\phi_l^2 = 1 ... | [
"def",
"Lockhart_Martinelli",
"(",
"m",
",",
"x",
",",
"rhol",
",",
"rhog",
",",
"mul",
",",
"mug",
",",
"D",
",",
"L",
"=",
"1",
",",
"Re_c",
"=",
"2000",
")",
":",
"def",
"friction_factor",
"(",
"Re",
")",
":",
"# As in the original model",
"if",
... | 33.755556 | 0.000426 |
def actual_original_query_range(self):
""" This accounts for hard clipped bases
and a query sequence that hasnt been reverse complemented
:return: the range covered on the original query sequence
:rtype: GenomicRange
"""
l = self.original_query_sequence_length
a = self.alignment_ranges
... | [
"def",
"actual_original_query_range",
"(",
"self",
")",
":",
"l",
"=",
"self",
".",
"original_query_sequence_length",
"a",
"=",
"self",
".",
"alignment_ranges",
"qname",
"=",
"a",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"chr",
"qstart",
"=",
"a",
"[",
"0",
... | 30.210526 | 0.013514 |
def find_data_files(package, pattern):
"""
Include files matching ``pattern`` inside ``package``.
Parameters
----------
package : str
The package inside which to look for data files
pattern : str
Pattern (glob-style) to match for the data files (e.g. ``*.dat``).
This sup... | [
"def",
"find_data_files",
"(",
"package",
",",
"pattern",
")",
":",
"return",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"package",
",",
"pattern",
")",
",",
"recursive",
"=",
"True",
")"
] | 35.6875 | 0.001706 |
def objects(self):
"""
The objects in this listing.
:type: List[:class:`.ObjectInfo`]
"""
return [ObjectInfo(o, self._instance, self._bucket, self._client)
for o in self._proto.object] | [
"def",
"objects",
"(",
"self",
")",
":",
"return",
"[",
"ObjectInfo",
"(",
"o",
",",
"self",
".",
"_instance",
",",
"self",
".",
"_bucket",
",",
"self",
".",
"_client",
")",
"for",
"o",
"in",
"self",
".",
"_proto",
".",
"object",
"]"
] | 29.25 | 0.008299 |
def _find_best_root(self, covariation=True, force_positive=True, slope=0, **kwarks):
'''
Determine the node that, when the tree is rooted on this node, results
in the best regression of temporal constraints and root to tip distances.
Parameters
----------
infer_gtr : b... | [
"def",
"_find_best_root",
"(",
"self",
",",
"covariation",
"=",
"True",
",",
"force_positive",
"=",
"True",
",",
"slope",
"=",
"0",
",",
"*",
"*",
"kwarks",
")",
":",
"for",
"n",
"in",
"self",
".",
"tree",
".",
"find_clades",
"(",
")",
":",
"n",
".... | 39.869565 | 0.009585 |
def set_legend(self):
"""Create a legend for this product
"""
leg = super(Coherence, self).set_legend()
if leg is not None:
leg.set_title('Coherence with:')
return leg | [
"def",
"set_legend",
"(",
"self",
")",
":",
"leg",
"=",
"super",
"(",
"Coherence",
",",
"self",
")",
".",
"set_legend",
"(",
")",
"if",
"leg",
"is",
"not",
"None",
":",
"leg",
".",
"set_title",
"(",
"'Coherence with:'",
")",
"return",
"leg"
] | 30.428571 | 0.009132 |
def circular_gaussian_kernel(sd,radius):
"""Create a 2-d Gaussian convolution kernel
sd - standard deviation of the gaussian in pixels
radius - build a circular kernel that convolves all points in the circle
bounded by this radius
"""
i,j = np.mgrid[-radius:radius+1,-radius:ra... | [
"def",
"circular_gaussian_kernel",
"(",
"sd",
",",
"radius",
")",
":",
"i",
",",
"j",
"=",
"np",
".",
"mgrid",
"[",
"-",
"radius",
":",
"radius",
"+",
"1",
",",
"-",
"radius",
":",
"radius",
"+",
"1",
"]",
".",
"astype",
"(",
"float",
")",
"/",
... | 34.8 | 0.011189 |
def alerts(self):
"""
:rtype: twilio.rest.monitor.v1.alert.AlertList
"""
if self._alerts is None:
self._alerts = AlertList(self)
return self._alerts | [
"def",
"alerts",
"(",
"self",
")",
":",
"if",
"self",
".",
"_alerts",
"is",
"None",
":",
"self",
".",
"_alerts",
"=",
"AlertList",
"(",
"self",
")",
"return",
"self",
".",
"_alerts"
] | 27.714286 | 0.01 |
def escape(s, quote=True):
"""
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true (the default), the quotation mark
characters, both double quote (") and single quote (') characters are also
translated.
"""
assert not isinstance(s, bytes), ... | [
"def",
"escape",
"(",
"s",
",",
"quote",
"=",
"True",
")",
":",
"assert",
"not",
"isinstance",
"(",
"s",
",",
"bytes",
")",
",",
"'Pass a unicode string'",
"if",
"quote",
":",
"return",
"s",
".",
"translate",
"(",
"_escape_map_full",
")",
"return",
"s",
... | 38.909091 | 0.002283 |
async def _storeAppt(self, appt):
''' Store a single appointment '''
await self._hivedict.set(appt.iden, appt.pack()) | [
"async",
"def",
"_storeAppt",
"(",
"self",
",",
"appt",
")",
":",
"await",
"self",
".",
"_hivedict",
".",
"set",
"(",
"appt",
".",
"iden",
",",
"appt",
".",
"pack",
"(",
")",
")"
] | 43.666667 | 0.015038 |
def ssh_version():
'''
Returns the version of the installed ssh command
'''
# This function needs more granular checks and to be validated against
# older versions of ssh
ret = subprocess.Popen(
['ssh', '-V'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).co... | [
"def",
"ssh_version",
"(",
")",
":",
"# This function needs more granular checks and to be validated against",
"# older versions of ssh",
"ret",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'ssh'",
",",
"'-V'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
... | 30.095238 | 0.001534 |
def _write_var_data_sparse(self, f, zVar, var, dataType, numElems, recVary,
oneblock):
'''
Writes a VVR and a VXR for this block of sparse data
Parameters:
f : file
The open CDF file
zVar : bool
True if this ... | [
"def",
"_write_var_data_sparse",
"(",
"self",
",",
"f",
",",
"zVar",
",",
"var",
",",
"dataType",
",",
"numElems",
",",
"recVary",
",",
"oneblock",
")",
":",
"rec_start",
"=",
"oneblock",
"[",
"0",
"]",
"rec_end",
"=",
"oneblock",
"[",
"1",
"]",
"indat... | 34.716049 | 0.001037 |
def set_show_all(self, state):
"""Toggle 'show all files' state"""
if state:
self.fsmodel.setNameFilters([])
else:
self.fsmodel.setNameFilters(self.name_filters) | [
"def",
"set_show_all",
"(",
"self",
",",
"state",
")",
":",
"if",
"state",
":",
"self",
".",
"fsmodel",
".",
"setNameFilters",
"(",
"[",
"]",
")",
"else",
":",
"self",
".",
"fsmodel",
".",
"setNameFilters",
"(",
"self",
".",
"name_filters",
")"
] | 34.833333 | 0.009346 |
def output_pins(self, pins):
"""Set multiple pins high or low at once. Pins should be a dict of pin
name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins
will be set to the given values.
"""
[self._validate_pin(pin) for pin in pins.keys()]
# Set each c... | [
"def",
"output_pins",
"(",
"self",
",",
"pins",
")",
":",
"[",
"self",
".",
"_validate_pin",
"(",
"pin",
")",
"for",
"pin",
"in",
"pins",
".",
"keys",
"(",
")",
"]",
"# Set each changed pin's bit.",
"for",
"pin",
",",
"value",
"in",
"iter",
"(",
"pins"... | 41.785714 | 0.008361 |
def underline(self, msg):
"""Underline the input"""
return click.style(msg, underline=True) if self.colorize else msg | [
"def",
"underline",
"(",
"self",
",",
"msg",
")",
":",
"return",
"click",
".",
"style",
"(",
"msg",
",",
"underline",
"=",
"True",
")",
"if",
"self",
".",
"colorize",
"else",
"msg"
] | 43.666667 | 0.015038 |
def compute_upper_limit(mu_in, post, alpha=0.9):
"""
Returns the upper limit mu_high of confidence level alpha for a
posterior distribution post on the given parameter mu.
The posterior need not be normalized.
"""
if 0 < alpha < 1:
dp = integral_element(mu_in, post)
high_idx = bi... | [
"def",
"compute_upper_limit",
"(",
"mu_in",
",",
"post",
",",
"alpha",
"=",
"0.9",
")",
":",
"if",
"0",
"<",
"alpha",
"<",
"1",
":",
"dp",
"=",
"integral_element",
"(",
"mu_in",
",",
"post",
")",
"high_idx",
"=",
"bisect",
".",
"bisect_left",
"(",
"d... | 39.210526 | 0.001311 |
def _to_deprecated_string(self):
"""Returns an 'old-style' course id, represented as 'org/course/run'"""
return u'/'.join([self.org, self.course, self.run]) | [
"def",
"_to_deprecated_string",
"(",
"self",
")",
":",
"return",
"u'/'",
".",
"join",
"(",
"[",
"self",
".",
"org",
",",
"self",
".",
"course",
",",
"self",
".",
"run",
"]",
")"
] | 56.666667 | 0.011628 |
def create_run(cmd, project, exp, grp):
"""
Create a new 'run' in the database.
This creates a new transaction in the database and creates a new
run in this transaction. Afterwards we return both the transaction as
well as the run itself. The user is responsible for committing it when
the time ... | [
"def",
"create_run",
"(",
"cmd",
",",
"project",
",",
"exp",
",",
"grp",
")",
":",
"from",
"benchbuild",
".",
"utils",
"import",
"schema",
"as",
"s",
"session",
"=",
"s",
".",
"Session",
"(",
")",
"run",
"=",
"s",
".",
"Run",
"(",
"command",
"=",
... | 30.818182 | 0.000953 |
def all_combinations_of_ensembl_genomes(args):
"""
Use all combinations of species and release versions specified by the
commandline arguments to return a list of EnsemblRelease or Genome objects.
The results will typically be of type EnsemblRelease unless the
--custom-mirror argument was given.
... | [
"def",
"all_combinations_of_ensembl_genomes",
"(",
"args",
")",
":",
"species_list",
"=",
"args",
".",
"species",
"if",
"args",
".",
"species",
"else",
"[",
"\"human\"",
"]",
"release_list",
"=",
"args",
".",
"release",
"if",
"args",
".",
"release",
"else",
... | 45.595745 | 0.000914 |
def setClockFormat(clockFormat, **kwargs):
'''
Set the clock format, either 12h or 24h format.
CLI Example:
.. code-block:: bash
salt '*' gnome.setClockFormat <12h|24h> user=<username>
'''
if clockFormat != '12h' and clockFormat != '24h':
return False
_gsession = _GSettin... | [
"def",
"setClockFormat",
"(",
"clockFormat",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"clockFormat",
"!=",
"'12h'",
"and",
"clockFormat",
"!=",
"'24h'",
":",
"return",
"False",
"_gsession",
"=",
"_GSettings",
"(",
"user",
"=",
"kwargs",
".",
"get",
"(",
... | 28.352941 | 0.002008 |
def linestring_node_to_line(node, with_depth=False):
"""
Returns an instance of a Linestring node to :class:
openquake.hazardlib.geo.line.Line
"""
assert "LineString" in node.tag
crds = [float(x) for x in node.nodes[0].text.split()]
if with_depth:
return Line([Point(crds[iloc], crds[... | [
"def",
"linestring_node_to_line",
"(",
"node",
",",
"with_depth",
"=",
"False",
")",
":",
"assert",
"\"LineString\"",
"in",
"node",
".",
"tag",
"crds",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"node",
".",
"nodes",
"[",
"0",
"]",
".",
"tex... | 39.615385 | 0.001898 |
def get_window(self):
"""
Returns the object's parent window. Returns None if no window found.
"""
x = self
while not x._parent == None and \
not isinstance(x._parent, Window):
x = x._parent
return x._parent | [
"def",
"get_window",
"(",
"self",
")",
":",
"x",
"=",
"self",
"while",
"not",
"x",
".",
"_parent",
"==",
"None",
"and",
"not",
"isinstance",
"(",
"x",
".",
"_parent",
",",
"Window",
")",
":",
"x",
"=",
"x",
".",
"_parent",
"return",
"x",
".",
"_p... | 31.222222 | 0.027682 |
def schemas(raw=False):
"""
Return the list of H₂O schemas.
:param raw: if True, then the complete response to .../schemas is returned (including the metadata)
"""
json = _request_or_exit("/3/Metadata/schemas")
if raw: return json
assert "schemas" in json, "Unexpected result from /3/Metadat... | [
"def",
"schemas",
"(",
"raw",
"=",
"False",
")",
":",
"json",
"=",
"_request_or_exit",
"(",
"\"/3/Metadata/schemas\"",
")",
"if",
"raw",
":",
"return",
"json",
"assert",
"\"schemas\"",
"in",
"json",
",",
"\"Unexpected result from /3/Metadata/schemas call\"",
"# Simp... | 49.212121 | 0.01087 |
def start_update(self, draw=None, queues=None):
"""
Conduct the formerly registered updates
This method conducts the updates that have been registered via the
:meth:`update` method. You can call this method if the
:attr:`no_auto_update` attribute of this instance and the `auto_u... | [
"def",
"start_update",
"(",
"self",
",",
"draw",
"=",
"None",
",",
"queues",
"=",
"None",
")",
":",
"if",
"self",
".",
"plotter",
"is",
"not",
"None",
":",
"return",
"self",
".",
"plotter",
".",
"start_update",
"(",
"draw",
"=",
"draw",
",",
"queues"... | 42.571429 | 0.001312 |
def _have(self, name=None):
"""Check if a configure flag is set.
If called without argument, it returns all HAVE_* items.
Example:
{% if have('netinet/ip.h') %}...{% endif %}
"""
if name is None:
return (
(k, v) for k, v in self.env.ite... | [
"def",
"_have",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"return",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"env",
".",
"items",
"(",
")",
"if",
"k",
".",
"startswith",
... | 28.733333 | 0.008989 |
def _parseSymbols(self, sections):
"""Sets a list of symbols in each DYNSYM and SYMTAB section"""
for section in sections:
strtab = sections[section.header.sh_link]
if section.header.sh_type in (int(SHT.DYNSYM), int(SHT.SYMTAB)):
section.symbols = self.__parseSymb... | [
"def",
"_parseSymbols",
"(",
"self",
",",
"sections",
")",
":",
"for",
"section",
"in",
"sections",
":",
"strtab",
"=",
"sections",
"[",
"section",
".",
"header",
".",
"sh_link",
"]",
"if",
"section",
".",
"header",
".",
"sh_type",
"in",
"(",
"int",
"(... | 58.5 | 0.008427 |
def nodePop(ctxt):
"""Pops the top element node from the node stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.nodePop(ctxt__o)
if ret is None:raise treeError('nodePop() failed')
return xmlNode(_obj=ret) | [
"def",
"nodePop",
"(",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"nodePop",
"(",
"ctxt__o",
")",
"if",
"ret",
"is",
"None",
":",
"raise"... | 36.428571 | 0.019157 |
def get_qcontent(value):
"""qcontent = qtext / quoted-pair
We allow anything except the DQUOTE character, but if we find any ASCII
other than the RFC defined printable ASCII an NonPrintableDefect is
added to the token's defects list. Any quoted pairs are converted to their
unquoted values, so what... | [
"def",
"get_qcontent",
"(",
"value",
")",
":",
"ptext",
",",
"value",
",",
"_",
"=",
"_get_ptext_to_endchars",
"(",
"value",
",",
"'\"'",
")",
"ptext",
"=",
"ValueTerminal",
"(",
"ptext",
",",
"'ptext'",
")",
"_validate_xtext",
"(",
"ptext",
")",
"return",... | 38.5 | 0.001812 |
def set_status(self, new_status):
'''
Set the status of the report.
:param new_status: the new status of the report (either PASSED, FAILED or ERROR)
'''
if new_status not in Report.allowed_statuses:
raise Exception('status must be one of: %s' % (', '.join(Report.allo... | [
"def",
"set_status",
"(",
"self",
",",
"new_status",
")",
":",
"if",
"new_status",
"not",
"in",
"Report",
".",
"allowed_statuses",
":",
"raise",
"Exception",
"(",
"'status must be one of: %s'",
"%",
"(",
"', '",
".",
"join",
"(",
"Report",
".",
"allowed_status... | 42.666667 | 0.010204 |
def addInstance(self, groundTruth, prediction, record = None, result = None):
"""Compute and store metric value"""
self.value = self.avg(prediction) | [
"def",
"addInstance",
"(",
"self",
",",
"groundTruth",
",",
"prediction",
",",
"record",
"=",
"None",
",",
"result",
"=",
"None",
")",
":",
"self",
".",
"value",
"=",
"self",
".",
"avg",
"(",
"prediction",
")"
] | 51.333333 | 0.032051 |
def current(sam=False):
'''
Get the username that salt-minion is running under. If salt-minion is
running as a service it should return the Local System account. If salt is
running from a command prompt it should return the username that started the
command prompt.
.. versionadded:: 2015.5.6
... | [
"def",
"current",
"(",
"sam",
"=",
"False",
")",
":",
"try",
":",
"if",
"sam",
":",
"user_name",
"=",
"win32api",
".",
"GetUserNameEx",
"(",
"win32con",
".",
"NameSamCompatible",
")",
"else",
":",
"user_name",
"=",
"win32api",
".",
"GetUserName",
"(",
")... | 30.230769 | 0.002465 |
def parse_yaml_linenumbers(data, filename):
"""Parses yaml as ansible.utils.parse_yaml but with linenumbers.
The line numbers are stored in each node's LINE_NUMBER_KEY key.
"""
def compose_node(parent, index):
# the line number where the previous token has ended (plus empty lines)
line... | [
"def",
"parse_yaml_linenumbers",
"(",
"data",
",",
"filename",
")",
":",
"def",
"compose_node",
"(",
"parent",
",",
"index",
")",
":",
"# the line number where the previous token has ended (plus empty lines)",
"line",
"=",
"loader",
".",
"line",
"node",
"=",
"Composer... | 38.475 | 0.001901 |
def StoreCSRFCookie(user, response):
"""Decorator for WSGI handler that inserts CSRF cookie into response."""
csrf_token = GenerateCSRFToken(user, None)
response.set_cookie(
"csrftoken", csrf_token, max_age=CSRF_TOKEN_DURATION.seconds) | [
"def",
"StoreCSRFCookie",
"(",
"user",
",",
"response",
")",
":",
"csrf_token",
"=",
"GenerateCSRFToken",
"(",
"user",
",",
"None",
")",
"response",
".",
"set_cookie",
"(",
"\"csrftoken\"",
",",
"csrf_token",
",",
"max_age",
"=",
"CSRF_TOKEN_DURATION",
".",
"s... | 40.5 | 0.016129 |
def _run_node(self, node):
'''
calc_dict._run_node(node) calculates the results of the given calculation node in the
calc_dict's calculation plan and caches the results in the calc_dict. This should only
be called by calc_dict itself internally.
'''
#print IMap.indent, ('... | [
"def",
"_run_node",
"(",
"self",
",",
"node",
")",
":",
"#print IMap.indent, ('Node: %s' % node.name) #dbg",
"#IMap.indent = ' ' + IMap.indent #dbg",
"#",
"# We need to pause here and handle caching, if needed.",
"res",
"=",
"None",
"if",
"(",
"'memoize'",
"in",
"self",
".",... | 44.913793 | 0.009767 |
def filter_greys_using_image(image, target):
"""Filter out any values in target not in image
:param image: image containing values to appear in filtered image
:param target: the image to filter
:rtype: 2d :class:`numpy.ndarray` containing only value in image
and with the same dimensions ... | [
"def",
"filter_greys_using_image",
"(",
"image",
",",
"target",
")",
":",
"maskbase",
"=",
"numpy",
".",
"array",
"(",
"range",
"(",
"256",
")",
",",
"dtype",
"=",
"numpy",
".",
"uint8",
")",
"mask",
"=",
"numpy",
".",
"where",
"(",
"numpy",
".",
"in... | 41.083333 | 0.001984 |
def _already_cutoff_filtered(in_file, filter_type):
"""Check if we have a pre-existing cutoff-based filter file from previous VQSR failure.
"""
filter_file = "%s-filter%s.vcf.gz" % (utils.splitext_plus(in_file)[0], filter_type)
return utils.file_exists(filter_file) | [
"def",
"_already_cutoff_filtered",
"(",
"in_file",
",",
"filter_type",
")",
":",
"filter_file",
"=",
"\"%s-filter%s.vcf.gz\"",
"%",
"(",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"[",
"0",
"]",
",",
"filter_type",
")",
"return",
"utils",
".",
"file_e... | 55.4 | 0.010676 |
def parity_plot(X, Y, model, devmodel, axes_labels=None):
"""
A standard method of creating parity plots between predicted and
experimental values for trained models.
Parameters
----------
X: array
experimental input data
Y: array
experimental output data
model: model ob... | [
"def",
"parity_plot",
"(",
"X",
",",
"Y",
",",
"model",
",",
"devmodel",
",",
"axes_labels",
"=",
"None",
")",
":",
"model_outputs",
"=",
"Y",
".",
"shape",
"[",
"1",
"]",
"with",
"plt",
".",
"style",
".",
"context",
"(",
"'seaborn-whitegrid'",
")",
... | 38.490909 | 0.000461 |
def apply(self, var, props, reverse=False):
"""
Apply the VPM to variable *var* and properties *props*.
Args:
var: a variable
props: a dictionary mapping properties to values
reverse: if `True`, apply the rules in reverse (e.g. from
grammar-ex... | [
"def",
"apply",
"(",
"self",
",",
"var",
",",
"props",
",",
"reverse",
"=",
"False",
")",
":",
"vs",
",",
"vid",
"=",
"sort_vid_split",
"(",
"var",
")",
"if",
"reverse",
":",
"# variable type mapping is disabled in reverse",
"# tms = [(b, op, a) for a, op, b in se... | 41.170213 | 0.00101 |
def _chi2(self, theta, period, tmpid, return_gradient=False):
"""
Compute the chi2 for the given parameters, period, & template
Optionally return the gradient for faster optimization
"""
template = self.templates[tmpid]
phase = (self.t / period - theta[2]) % 1
mo... | [
"def",
"_chi2",
"(",
"self",
",",
"theta",
",",
"period",
",",
"tmpid",
",",
"return_gradient",
"=",
"False",
")",
":",
"template",
"=",
"self",
".",
"templates",
"[",
"tmpid",
"]",
"phase",
"=",
"(",
"self",
".",
"t",
"/",
"period",
"-",
"theta",
... | 40.1 | 0.002436 |
def addUsersToRole(self, rolename, users):
""" Assigns a role to multiple users """
params = {
"f" : "json",
"rolename" : rolename,
"users" : users
}
rURL = self._url + "/roles/addUsersToRole"
return self._post(url=rURL, param_dict=params,
... | [
"def",
"addUsersToRole",
"(",
"self",
",",
"rolename",
",",
"users",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"rolename\"",
":",
"rolename",
",",
"\"users\"",
":",
"users",
"}",
"rURL",
"=",
"self",
".",
"_url",
"+",
"\"/roles/addUs... | 40.5 | 0.016097 |
def devices(self, **params):
""" Method for `List Devices from an existing Distribution <https://m2x.att.com/developer/documentation/v2/distribution#List-Devices-from-an-existing-Distribution>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of avai... | [
"def",
"devices",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"DistributionDevice",
".",
"list",
"(",
"self",
".",
"api",
",",
"distribution_id",
"=",
"self",
".",
"id",
",",
"*",
"*",
"params",
")"
] | 65.272727 | 0.009615 |
def check_hints(self, ds):
'''
Checks for potentially mislabeled metadata and makes suggestions for how to correct
:param netCDF4.Dataset ds: An open netCDF dataset
:rtype: list
:return: List of results
'''
ret_val = []
ret_val.extend(self._check_hint_bo... | [
"def",
"check_hints",
"(",
"self",
",",
"ds",
")",
":",
"ret_val",
"=",
"[",
"]",
"ret_val",
".",
"extend",
"(",
"self",
".",
"_check_hint_bounds",
"(",
"ds",
")",
")",
"return",
"ret_val"
] | 26.230769 | 0.008499 |
def cookie_decode(data, key):
''' Verify and decode an encoded string. Return an object or None'''
if isinstance(data, unicode): data = data.encode('ascii') #2to3 hack
if cookie_is_encoded(data):
sig, msg = data.split(u'?'.encode('ascii'),1) #2to3 hack
if sig[1:] == base64.b64encode(hmac.new... | [
"def",
"cookie_decode",
"(",
"data",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"unicode",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"'ascii'",
")",
"#2to3 hack",
"if",
"cookie_is_encoded",
"(",
"data",
")",
":",
"sig",
",",
... | 50.5 | 0.019465 |
def _CheckLine(self, line):
"""Passes the line through each rule until a match is made.
Args:
line: A string, the current input line.
"""
for rule in self._cur_state:
matched = self._CheckRule(rule, line)
if matched:
for value in matched.groupdict():
self._AssignVar(... | [
"def",
"_CheckLine",
"(",
"self",
",",
"line",
")",
":",
"for",
"rule",
"in",
"self",
".",
"_cur_state",
":",
"matched",
"=",
"self",
".",
"_CheckRule",
"(",
"rule",
",",
"line",
")",
"if",
"matched",
":",
"for",
"value",
"in",
"matched",
".",
"group... | 32.578947 | 0.012559 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.