text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def next(self):
"""
Expands multiple alleles into one record each
using an internal buffer (_next).
"""
def _alt(alt):
"""Parses the VCF row ALT object."""
# If alt is '.' in VCF, PyVCF returns None, convert back to '.'
if not alt:
... | [
"def",
"next",
"(",
"self",
")",
":",
"def",
"_alt",
"(",
"alt",
")",
":",
"\"\"\"Parses the VCF row ALT object.\"\"\"",
"# If alt is '.' in VCF, PyVCF returns None, convert back to '.'",
"if",
"not",
"alt",
":",
"return",
"'.'",
"else",
":",
"return",
"str",
"(",
"... | 29.896552 | 0.002235 |
def intersect(self, range_):
self.solver.intersection_broad_tests_count += 1
"""Remove variants whose version fall outside of the given range."""
if range_.is_any():
return self
if self.solver.optimised:
if range_ in self.been_intersected_with:
r... | [
"def",
"intersect",
"(",
"self",
",",
"range_",
")",
":",
"self",
".",
"solver",
".",
"intersection_broad_tests_count",
"+=",
"1",
"if",
"range_",
".",
"is_any",
"(",
")",
":",
"return",
"self",
"if",
"self",
".",
"solver",
".",
"optimised",
":",
"if",
... | 32.586207 | 0.002055 |
def restructuredtext(value, settings=RESTRUCTUREDTEXT_SETTINGS):
"""
RestructuredText processing with optionnally custom settings.
"""
try:
from docutils.core import publish_parts
except ImportError:
warnings.warn("The Python docutils library isn't installed.",
... | [
"def",
"restructuredtext",
"(",
"value",
",",
"settings",
"=",
"RESTRUCTUREDTEXT_SETTINGS",
")",
":",
"try",
":",
"from",
"docutils",
".",
"core",
"import",
"publish_parts",
"except",
"ImportError",
":",
"warnings",
".",
"warn",
"(",
"\"The Python docutils library i... | 36.2 | 0.001795 |
def set_mapping(self, x0, x1, update=True):
"""Configure this transform such that it maps points x0 => x1
Parameters
----------
x0 : array-like, shape (2, 2) or (2, 3)
Start location.
x1 : array-like, shape (2, 2) or (2, 3)
End location.
update : ... | [
"def",
"set_mapping",
"(",
"self",
",",
"x0",
",",
"x1",
",",
"update",
"=",
"True",
")",
":",
"# if args are Rect, convert to array first",
"if",
"isinstance",
"(",
"x0",
",",
"Rect",
")",
":",
"x0",
"=",
"x0",
".",
"_transform_in",
"(",
")",
"[",
":",
... | 30.843137 | 0.002465 |
def taql(command, style='Python', tables=[], globals={}, locals={}):
"""Execute a TaQL command and return a table object.
A `TaQL <../../doc/199.html>`_
command is an SQL-like command to do a selection of rows and/or
columns in a table.
The default style used in a TaQL command is python, which mea... | [
"def",
"taql",
"(",
"command",
",",
"style",
"=",
"'Python'",
",",
"tables",
"=",
"[",
"]",
",",
"globals",
"=",
"{",
"}",
",",
"locals",
"=",
"{",
"}",
")",
":",
"# Substitute possible tables given as $name.",
"cmd",
"=",
"command",
"# Copy the tables argum... | 39.728814 | 0.000416 |
def collection_year(soup):
"""
Pub date of type collection will hold a year element for VOR articles
"""
pub_date = first(raw_parser.pub_date(soup, pub_type="collection"))
if not pub_date:
pub_date = first(raw_parser.pub_date(soup, date_type="collection"))
if not pub_date:
return... | [
"def",
"collection_year",
"(",
"soup",
")",
":",
"pub_date",
"=",
"first",
"(",
"raw_parser",
".",
"pub_date",
"(",
"soup",
",",
"pub_type",
"=",
"\"collection\"",
")",
")",
"if",
"not",
"pub_date",
":",
"pub_date",
"=",
"first",
"(",
"raw_parser",
".",
... | 27.625 | 0.002188 |
def isempty(result):
''' Finds out if a scraping result should be considered empty. '''
if isinstance(result, list):
for element in result:
if isinstance(element, list):
if not isempty(element):
return False
else:
if element is not None:
return False
else:
if result is not None:
retur... | [
"def",
"isempty",
"(",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"list",
")",
":",
"for",
"element",
"in",
"result",
":",
"if",
"isinstance",
"(",
"element",
",",
"list",
")",
":",
"if",
"not",
"isempty",
"(",
"element",
")",
":",
... | 21.733333 | 0.041176 |
def _process_value(value):
"""Convert the value into a human readable diff string
"""
if not value:
value = _("Not set")
# XXX: bad data, e.g. in AS Method field
elif value == "None":
value = _("Not set")
# 0 is detected as the portal UID
elif value == "0":
pass
e... | [
"def",
"_process_value",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"value",
"=",
"_",
"(",
"\"Not set\"",
")",
"# XXX: bad data, e.g. in AS Method field",
"elif",
"value",
"==",
"\"None\"",
":",
"value",
"=",
"_",
"(",
"\"Not set\"",
")",
"# 0 is dete... | 33.714286 | 0.001374 |
def deploy_custom_domain(awsclient, api_name, api_target_stage,
api_base_path, domain_name, route_53_record,
cert_name, cert_arn, hosted_zone_id, ensure_cname):
"""Add custom domain to your API.
:param api_name:
:param api_target_stage:
:param api_base_... | [
"def",
"deploy_custom_domain",
"(",
"awsclient",
",",
"api_name",
",",
"api_target_stage",
",",
"api_base_path",
",",
"domain_name",
",",
"route_53_record",
",",
"cert_name",
",",
"cert_arn",
",",
"hosted_zone_id",
",",
"ensure_cname",
")",
":",
"api_base_path",
"="... | 40.677966 | 0.002034 |
def before(self, context):
"Invokes all before functions with context passed to them."
run.before_each.execute(context)
self._invoke(self._before, context) | [
"def",
"before",
"(",
"self",
",",
"context",
")",
":",
"run",
".",
"before_each",
".",
"execute",
"(",
"context",
")",
"self",
".",
"_invoke",
"(",
"self",
".",
"_before",
",",
"context",
")"
] | 44 | 0.011173 |
def _prepare_value(val, maxlen=50, notype=False):
"""
Stringify value `val`, ensuring that it is not too long.
"""
if val is None or val is True or val is False:
return str(val)
sval = repr(val)
sval = sval.replace("\n", " ").replace("\t", " ").replace("`", "'")
if len(sval) > maxlen... | [
"def",
"_prepare_value",
"(",
"val",
",",
"maxlen",
"=",
"50",
",",
"notype",
"=",
"False",
")",
":",
"if",
"val",
"is",
"None",
"or",
"val",
"is",
"True",
"or",
"val",
"is",
"False",
":",
"return",
"str",
"(",
"val",
")",
"sval",
"=",
"repr",
"(... | 33.333333 | 0.001946 |
def union_join(left, right, left_as='left', right_as='right'):
"""
Join function truest to the SQL style join. Merges both objects together in a sum-type,
saving references to each parent in ``left`` and ``right`` attributes.
>>> Dog = namedtuple('Dog', ['name', 'woof', 'weight'])
>>> dog ... | [
"def",
"union_join",
"(",
"left",
",",
"right",
",",
"left_as",
"=",
"'left'",
",",
"right_as",
"=",
"'right'",
")",
":",
"attrs",
"=",
"{",
"}",
"attrs",
".",
"update",
"(",
"get_object_attrs",
"(",
"right",
")",
")",
"attrs",
".",
"update",
"(",
"g... | 37.21875 | 0.002455 |
def from_disk(self, resource_list=None, paths=None):
"""Create or extend resource_list with resources from disk scan.
Assumes very simple disk path to URL mapping (in self.mapping): chop
path and replace with url_path. Returns the new or extended ResourceList
object.
If a resou... | [
"def",
"from_disk",
"(",
"self",
",",
"resource_list",
"=",
"None",
",",
"paths",
"=",
"None",
")",
":",
"num",
"=",
"0",
"# Either use resource_list passed in or make a new one",
"if",
"(",
"resource_list",
"is",
"None",
")",
":",
"resource_list",
"=",
"Resourc... | 39.425532 | 0.00158 |
def hasEdge(self, diff):
""" Test whether edge is in this sink. """
return diff.toVol in [d.toVol for d in self.diffs[diff.fromVol]] | [
"def",
"hasEdge",
"(",
"self",
",",
"diff",
")",
":",
"return",
"diff",
".",
"toVol",
"in",
"[",
"d",
".",
"toVol",
"for",
"d",
"in",
"self",
".",
"diffs",
"[",
"diff",
".",
"fromVol",
"]",
"]"
] | 48.666667 | 0.013514 |
def add_api_key(key, value):
"""
Adds a key to the bot's data
Args:
key: The name of the key to add
value: The value for the key
"""
if key is None or key == "":
logger.error("Key cannot be empty")
if value is None or value == "":
logger.error("Value cannot be ... | [
"def",
"add_api_key",
"(",
"key",
",",
"value",
")",
":",
"if",
"key",
"is",
"None",
"or",
"key",
"==",
"\"\"",
":",
"logger",
".",
"error",
"(",
"\"Key cannot be empty\"",
")",
"if",
"value",
"is",
"None",
"or",
"value",
"==",
"\"\"",
":",
"logger",
... | 26.454545 | 0.001105 |
def cipheringModeCommand():
"""CIPHERING MODE COMMAND Section 9.1.9"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0x35) # 00110101
c = RrCause()
#d=cipherModeSetting()
#e=cipherResponse()
# FIX
d = CipherModeSettingAndcipherResponse()
packet = a / b / c / d
return packet | [
"def",
"cipheringModeCommand",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x6",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x35",
")",
"# 00110101",
"c",
"=",
"RrCause",
"(",
")",
"#d=cipherModeSetting()",
"#e=cipherResponse()",
"# FIX",
"d... | 26.545455 | 0.019868 |
def upload_rotate(file_path, s3_bucket, s3_key_prefix, aws_key=None, aws_secret=None):
'''
Upload file_path to s3 bucket with prefix
Ex. upload_rotate('/tmp/file-2015-01-01.tar.bz2', 'backups', 'foo.net/')
would upload file to bucket backups with key=foo.net/file-2015-01-01.tar.bz2
and then rotate a... | [
"def",
"upload_rotate",
"(",
"file_path",
",",
"s3_bucket",
",",
"s3_key_prefix",
",",
"aws_key",
"=",
"None",
",",
"aws_secret",
"=",
"None",
")",
":",
"key",
"=",
"''",
".",
"join",
"(",
"[",
"s3_key_prefix",
",",
"os",
".",
"path",
".",
"basename",
... | 59.590909 | 0.009009 |
def _refs(obj, named, *ats, **kwds):
'''Return specific attribute objects of an object.
'''
if named:
for a in ats: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _NamedRef(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(... | [
"def",
"_refs",
"(",
"obj",
",",
"named",
",",
"*",
"ats",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"named",
":",
"for",
"a",
"in",
"ats",
":",
"# cf. inspect.getmembers()",
"if",
"hasattr",
"(",
"obj",
",",
"a",
")",
":",
"yield",
"_NamedRef",
"(",
... | 35 | 0.001637 |
def _slicespec2boundsspec(slicespec,scs):
"""
Convert an iterable slicespec (supplying r1,r2,c1,c2 of a
Slice) into a BoundingRegion specification.
Exact inverse of _boundsspec2slicespec().
"""
r1,r2,c1,c2 = slicespec
left,bottom = scs.matrix2sheet(r2,c1)
... | [
"def",
"_slicespec2boundsspec",
"(",
"slicespec",
",",
"scs",
")",
":",
"r1",
",",
"r2",
",",
"c1",
",",
"c2",
"=",
"slicespec",
"left",
",",
"bottom",
"=",
"scs",
".",
"matrix2sheet",
"(",
"r2",
",",
"c1",
")",
"right",
",",
"top",
"=",
"scs",
"."... | 30.076923 | 0.032258 |
def fetch_genome(genome_id):
'''Acquire a genome from Entrez
'''
# TODO: Can strandedness by found in fetched genome attributes?
# TODO: skip read/write step?
# Using a dummy email for now - does this violate NCBI guidelines?
email = 'loremipsum@gmail.com'
Entrez.email = email
print 'D... | [
"def",
"fetch_genome",
"(",
"genome_id",
")",
":",
"# TODO: Can strandedness by found in fetched genome attributes?",
"# TODO: skip read/write step?",
"# Using a dummy email for now - does this violate NCBI guidelines?",
"email",
"=",
"'loremipsum@gmail.com'",
"Entrez",
".",
"email",
"... | 32.5 | 0.001495 |
def build_pattern(log_format):
"""
Build regular expression to parse given format.
:param log_format: format string to parse
:return: regular expression to parse given format
"""
if log_format == 'combined':
log_format = LOG_FORMAT_COMBINED
elif log_format == 'common':
log_fo... | [
"def",
"build_pattern",
"(",
"log_format",
")",
":",
"if",
"log_format",
"==",
"'combined'",
":",
"log_format",
"=",
"LOG_FORMAT_COMBINED",
"elif",
"log_format",
"==",
"'common'",
":",
"log_format",
"=",
"LOG_FORMAT_COMMON",
"pattern",
"=",
"re",
".",
"sub",
"("... | 38.307692 | 0.001961 |
def row2dict(row, depth=None, exclude=None, exclude_pk=None,
exclude_underscore=None, only=None, fk_suffix=None):
"""
Recursively walk row attributes to serialize ones into a dict.
:param row: instance of the declarative base class
:param depth: number that represent the depth of related r... | [
"def",
"row2dict",
"(",
"row",
",",
"depth",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"exclude_pk",
"=",
"None",
",",
"exclude_underscore",
"=",
"None",
",",
"only",
"=",
"None",
",",
"fk_suffix",
"=",
"None",
")",
":",
"if",
"depth",
"==",
"0"... | 41.428571 | 0.000421 |
def total_accessibility(in_rsa, path=True):
"""Parses rsa file for the total surface accessibility data.
Parameters
----------
in_rsa : str
Path to naccess rsa file.
path : bool
Indicates if in_rsa is a path or a string.
Returns
-------
dssp_residues : 5-tuple(float)
... | [
"def",
"total_accessibility",
"(",
"in_rsa",
",",
"path",
"=",
"True",
")",
":",
"if",
"path",
":",
"with",
"open",
"(",
"in_rsa",
",",
"'r'",
")",
"as",
"inf",
":",
"rsa",
"=",
"inf",
".",
"read",
"(",
")",
"else",
":",
"rsa",
"=",
"in_rsa",
"["... | 27.103448 | 0.001229 |
def diff(self, end_date):
"""
difference expressed as a tuple of years, months, days
(see also the python lib dateutils.relativedelta)
:param BusinessDate start_date:
:param BusinessDate end_date:
:return (int, int, int):
"""
if end_date < self:
... | [
"def",
"diff",
"(",
"self",
",",
"end_date",
")",
":",
"if",
"end_date",
"<",
"self",
":",
"y",
",",
"m",
",",
"d",
"=",
"BusinessDate",
".",
"diff",
"(",
"end_date",
",",
"self",
")",
"return",
"-",
"y",
",",
"-",
"m",
",",
"-",
"d",
"y",
"=... | 26.75 | 0.002004 |
def volumes_delete(storage_pool, logger):
"""Deletes all storage volume disks contained in the given storage pool."""
try:
for vol_name in storage_pool.listVolumes():
try:
vol = storage_pool.storageVolLookupByName(vol_name)
vol.delete(0)
except lib... | [
"def",
"volumes_delete",
"(",
"storage_pool",
",",
"logger",
")",
":",
"try",
":",
"for",
"vol_name",
"in",
"storage_pool",
".",
"listVolumes",
"(",
")",
":",
"try",
":",
"vol",
"=",
"storage_pool",
".",
"storageVolLookupByName",
"(",
"vol_name",
")",
"vol",... | 43.75 | 0.001866 |
def list_all_discount_coupons(cls, **kwargs):
"""List DiscountCoupons
Return a list of DiscountCoupons
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_discount_coupons(async=True)
... | [
"def",
"list_all_discount_coupons",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_list_all_discount_coupons_with_http_info... | 38.478261 | 0.002205 |
def close(self):
""" Free any potential cycles. """
self.cell = None
self.coro = None
self.buffer = None
del self.dests[:]
del self.sources[:] | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"cell",
"=",
"None",
"self",
".",
"coro",
"=",
"None",
"self",
".",
"buffer",
"=",
"None",
"del",
"self",
".",
"dests",
"[",
":",
"]",
"del",
"self",
".",
"sources",
"[",
":",
"]"
] | 26.285714 | 0.010526 |
def register_rpc(self, address, rpc_id, func):
"""Register a single RPC handler with the given info.
This function can be used to directly register individual RPCs,
rather than delegating all RPCs at a given address to a virtual
Tile.
If calls to this function are mixed with ca... | [
"def",
"register_rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
",",
"func",
")",
":",
"if",
"rpc_id",
"<",
"0",
"or",
"rpc_id",
">",
"0xFFFF",
":",
"raise",
"RPCInvalidIDError",
"(",
"\"Invalid RPC ID: {}\"",
".",
"format",
"(",
"rpc_id",
")",
")",
"... | 40.961538 | 0.001835 |
def _FlushEvents(self):
"""Inserts the buffered event documents into Elasticsearch."""
try:
# pylint: disable=unexpected-keyword-arg
# pylint does not recognizes request_timeout as a valid kwarg. According
# to http://elasticsearch-py.readthedocs.io/en/master/api.html#timeout
# it should... | [
"def",
"_FlushEvents",
"(",
"self",
")",
":",
"try",
":",
"# pylint: disable=unexpected-keyword-arg",
"# pylint does not recognizes request_timeout as a valid kwarg. According",
"# to http://elasticsearch-py.readthedocs.io/en/master/api.html#timeout",
"# it should be supported.",
"self",
"... | 39.761905 | 0.010526 |
def projects(lancet, query):
"""List Harvest projects, optionally filtered with a regexp."""
projects = lancet.timer.projects()
if query:
regexp = re.compile(query, flags=re.IGNORECASE)
def match(project):
match = regexp.search(project['name'])
if match is None:
... | [
"def",
"projects",
"(",
"lancet",
",",
"query",
")",
":",
"projects",
"=",
"lancet",
".",
"timer",
".",
"projects",
"(",
")",
"if",
"query",
":",
"regexp",
"=",
"re",
".",
"compile",
"(",
"query",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"d... | 32.653846 | 0.001144 |
def get_correspondance_dict(self, classA, classB,
restrict=None,
replace_numeric=True):
""" Returns a correspondance between classification A and B as dict
Parameters
----------
classA: str
Valid classification... | [
"def",
"get_correspondance_dict",
"(",
"self",
",",
"classA",
",",
"classB",
",",
"restrict",
"=",
"None",
",",
"replace_numeric",
"=",
"True",
")",
":",
"result",
"=",
"{",
"nn",
":",
"None",
"for",
"nn",
"in",
"self",
".",
"data",
"[",
"classA",
"]",... | 35.24 | 0.002209 |
def dict_merge(*dict_list):
"""recursively merges dict's. not just simple a['key'] = b['key'], if
both a and bhave a key who's value is a dict then dict_merge is called
on both values and the result stored in the returned dictionary.
"""
result = collections.defaultdict(dict)
dicts_items = itert... | [
"def",
"dict_merge",
"(",
"*",
"dict_list",
")",
":",
"result",
"=",
"collections",
".",
"defaultdict",
"(",
"dict",
")",
"dicts_items",
"=",
"itertools",
".",
"chain",
"(",
"*",
"[",
"six",
".",
"iteritems",
"(",
"d",
"or",
"{",
"}",
")",
"for",
"d"... | 40.3 | 0.001212 |
def logged(level=logging.DEBUG):
"""
Useful logging decorator. If a method is logged, the beginning and end of
the method call will be logged at a pre-specified level.
Args:
level: Level to log method at. Defaults to DEBUG.
"""
def wrap(f):
_logger = logging.getLogger("{}.{}".fo... | [
"def",
"logged",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"_logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"{}.{}\"",
".",
"format",
"(",
"f",
".",
"__module__",
",",
"f",
".",
"__name__",
")",
")"... | 36.761905 | 0.001263 |
def insertion_rate(Nref, Ninsertions, eps=numpy.spacing(1)):
"""Insertion rate
Parameters
----------
Nref : int >=0
Number of entries in the reference.
Ninsertions : int >=0
Number of insertions.
eps : float
eps.
Default value numpy.spacing(1)
Returns
... | [
"def",
"insertion_rate",
"(",
"Nref",
",",
"Ninsertions",
",",
"eps",
"=",
"numpy",
".",
"spacing",
"(",
"1",
")",
")",
":",
"return",
"float",
"(",
"Ninsertions",
"/",
"(",
"Nref",
"+",
"eps",
")",
")"
] | 17.782609 | 0.00232 |
def spec(self):
"""Return a dict with values that can be fed directly into SelectiveRowGenerator"""
return dict(
headers=self.header_lines,
start=self.start_line,
comments=self.comment_lines,
end=self.end_line
) | [
"def",
"spec",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"headers",
"=",
"self",
".",
"header_lines",
",",
"start",
"=",
"self",
".",
"start_line",
",",
"comments",
"=",
"self",
".",
"comment_lines",
",",
"end",
"=",
"self",
".",
"end_line",
")"
] | 34.5 | 0.010601 |
def save_figure_raw_data(figure="gcf", **kwargs):
"""
This will just output an ascii file for each of the traces in the shown figure.
**kwargs are sent to dialogs.Save()
"""
# choose a path to save to
path = _s.dialogs.Save(**kwargs)
if path=="": return "aborted."
# if no argument was... | [
"def",
"save_figure_raw_data",
"(",
"figure",
"=",
"\"gcf\"",
",",
"*",
"*",
"kwargs",
")",
":",
"# choose a path to save to",
"path",
"=",
"_s",
".",
"dialogs",
".",
"Save",
"(",
"*",
"*",
"kwargs",
")",
"if",
"path",
"==",
"\"\"",
":",
"return",
"\"abo... | 27.59375 | 0.008753 |
def to_dd(degrees, minutes, seconds=0):
"""Convert degrees, minutes and optionally seconds to decimal angle.
Args:
degrees (float): Number of degrees
minutes (float): Number of minutes
seconds (float): Number of seconds
Returns:
float: Angle converted to decimal degrees
... | [
"def",
"to_dd",
"(",
"degrees",
",",
"minutes",
",",
"seconds",
"=",
"0",
")",
":",
"sign",
"=",
"-",
"1",
"if",
"any",
"(",
"i",
"<",
"0",
"for",
"i",
"in",
"(",
"degrees",
",",
"minutes",
",",
"seconds",
")",
")",
"else",
"1",
"return",
"sign... | 35.307692 | 0.002123 |
def _set_meta(self, title, published, category='', tags=''):
"""
the header
:param title: the title of the post
:param published: the date when the data
has been published by the provider
:param category: category of this data
:param tags:... | [
"def",
"_set_meta",
"(",
"self",
",",
"title",
",",
"published",
",",
"category",
"=",
"''",
",",
"tags",
"=",
"''",
")",
":",
"slug_published",
"=",
"slugify",
"(",
"arrow",
".",
"get",
"(",
"published",
")",
".",
"format",
"(",
"'YYYY-MM-DD HH:mm'",
... | 36.235294 | 0.001581 |
def permission_factory(obj, action):
"""Get default permission factory.
:param obj: An instance of :class:`invenio_files_rest.models.Bucket` or
:class:`invenio_files_rest.models.ObjectVersion` or
:class:`invenio_files_rest.models.MultipartObject` or ``None`` if
the action is global.
... | [
"def",
"permission_factory",
"(",
"obj",
",",
"action",
")",
":",
"need_class",
"=",
"_action2need_map",
"[",
"action",
"]",
"if",
"obj",
"is",
"None",
":",
"return",
"Permission",
"(",
"need_class",
"(",
"None",
")",
")",
"arg",
"=",
"None",
"if",
"isin... | 32.925926 | 0.001093 |
def get_iptc_data(filename):
"""Return a dict with the raw IPTC data."""
logger = logging.getLogger(__name__)
iptc_data = {}
raw_iptc = {}
# PILs IptcImagePlugin issues a SyntaxError in certain circumstances
# with malformed metadata, see PIL/IptcImagePlugin.py", line 71.
# ( https://gith... | [
"def",
"get_iptc_data",
"(",
"filename",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"iptc_data",
"=",
"{",
"}",
"raw_iptc",
"=",
"{",
"}",
"# PILs IptcImagePlugin issues a SyntaxError in certain circumstances",
"# with malformed metadata... | 38.970588 | 0.001473 |
def send(message, **kwargs):
"""Send a SocketIO message.
This function sends a simple SocketIO message to one or more connected
clients. The message can be a string or a JSON blob. This is a simpler
version of ``emit()``, which should be preferred. This is a function that
can only be called from a ... | [
"def",
"send",
"(",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"json",
"=",
"kwargs",
".",
"get",
"(",
"'json'",
",",
"False",
")",
"if",
"'namespace'",
"in",
"kwargs",
":",
"namespace",
"=",
"kwargs",
"[",
"'namespace'",
"]",
"else",
":",
"namesp... | 51.875 | 0.000394 |
def play_Bar(self, bar):
"""Convert a Bar object to MIDI events and write them to the
track_data."""
self.set_deltatime(self.delay)
self.delay = 0
self.set_meter(bar.meter)
self.set_deltatime(0)
self.set_key(bar.key)
for x in bar:
tick = int(ro... | [
"def",
"play_Bar",
"(",
"self",
",",
"bar",
")",
":",
"self",
".",
"set_deltatime",
"(",
"self",
".",
"delay",
")",
"self",
".",
"delay",
"=",
"0",
"self",
".",
"set_meter",
"(",
"bar",
".",
"meter",
")",
"self",
".",
"set_deltatime",
"(",
"0",
")"... | 37.333333 | 0.002488 |
def imei(self) -> str:
"""Generate a random IMEI.
:return: IMEI.
"""
num = self.random.choice(IMEI_TACS)
num = num + str(self.random.randint(100000, 999999))
return num + luhn_checksum(num) | [
"def",
"imei",
"(",
"self",
")",
"->",
"str",
":",
"num",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"IMEI_TACS",
")",
"num",
"=",
"num",
"+",
"str",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"100000",
",",
"999999",
")",
")",
"return... | 28.875 | 0.008403 |
def set_cookie(self, cookie=None):
"""Set the Cookie header."""
if cookie:
self._cookie = cookie.encode()
else:
self._cookie = None | [
"def",
"set_cookie",
"(",
"self",
",",
"cookie",
"=",
"None",
")",
":",
"if",
"cookie",
":",
"self",
".",
"_cookie",
"=",
"cookie",
".",
"encode",
"(",
")",
"else",
":",
"self",
".",
"_cookie",
"=",
"None"
] | 29.833333 | 0.01087 |
def clear_matplotlib_ticks(ax=None, axis="both"):
"""
Clears the default matplotlib axes, or the one specified by the axis
argument.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
axis: string, "both"
The axis to clear: "x" or "horizontal", "y... | [
"def",
"clear_matplotlib_ticks",
"(",
"ax",
"=",
"None",
",",
"axis",
"=",
"\"both\"",
")",
":",
"if",
"not",
"ax",
":",
"return",
"if",
"axis",
".",
"lower",
"(",
")",
"in",
"[",
"\"both\"",
",",
"\"x\"",
",",
"\"horizontal\"",
"]",
":",
"ax",
".",
... | 29.388889 | 0.001832 |
def ExpandPath(path, opts=None):
"""Applies all expansion mechanisms to the given path.
Args:
path: A path to expand.
opts: A `PathOpts` object.
Yields:
All paths possible to obtain from a given path by performing expansions.
"""
precondition.AssertType(path, Text)
for grouped_path in ExpandG... | [
"def",
"ExpandPath",
"(",
"path",
",",
"opts",
"=",
"None",
")",
":",
"precondition",
".",
"AssertType",
"(",
"path",
",",
"Text",
")",
"for",
"grouped_path",
"in",
"ExpandGroups",
"(",
"path",
")",
":",
"for",
"globbed_path",
"in",
"ExpandGlobs",
"(",
"... | 26.666667 | 0.012077 |
def store(report, address):
"""Stores the report on disk.
"""
now = time.time()
secs = int(now)
msecs = int((now - secs) * 1000)
submitted_date = filename = None # avoids warnings
while True:
submitted_date = '%d.%03d' % (secs, msecs)
filename = 'report_%s.txt' % submitted_d... | [
"def",
"store",
"(",
"report",
",",
"address",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"secs",
"=",
"int",
"(",
"now",
")",
"msecs",
"=",
"int",
"(",
"(",
"now",
"-",
"secs",
")",
"*",
"1000",
")",
"submitted_date",
"=",
"filename",
... | 35.645161 | 0.001762 |
def download_to_file(url, file_path, **kwargs):
"""
Descarga un archivo a través del protocolo HTTP, en uno o más intentos, y
escribe el contenido descargado el el path especificado.
Args:
url (str): URL (schema HTTP) del archivo a descargar.
file_path (str): Path del archivo a escribir... | [
"def",
"download_to_file",
"(",
"url",
",",
"file_path",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"download",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"with",
"open",
"(",
"file_path",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write... | 40.071429 | 0.001742 |
def finalize(self, ctx, shard_state):
"""See parent class."""
filenames = []
for filehandle in self._filehandles:
filenames.append(filehandle.name)
filehandle.close()
shard_state.writer_state = {"shard_filenames": filenames} | [
"def",
"finalize",
"(",
"self",
",",
"ctx",
",",
"shard_state",
")",
":",
"filenames",
"=",
"[",
"]",
"for",
"filehandle",
"in",
"self",
".",
"_filehandles",
":",
"filenames",
".",
"append",
"(",
"filehandle",
".",
"name",
")",
"filehandle",
".",
"close"... | 35.142857 | 0.011905 |
def post_build(self, pkt, pay):
"""
Apply the previous methods according to the writing cipher type.
"""
# Compute the length of TLSPlaintext fragment
hdr, frag = pkt[:5], pkt[5:]
if not isinstance(self.tls_session.rcs.cipher, Cipher_NULL):
frag = self._tls_au... | [
"def",
"post_build",
"(",
"self",
",",
"pkt",
",",
"pay",
")",
":",
"# Compute the length of TLSPlaintext fragment",
"hdr",
",",
"frag",
"=",
"pkt",
"[",
":",
"5",
"]",
",",
"pkt",
"[",
"5",
":",
"]",
"if",
"not",
"isinstance",
"(",
"self",
".",
"tls_s... | 43.807692 | 0.001718 |
def update_from_item(self, item):
"""
Update from i3status output. returns if item has changed.
"""
if not self.is_time_module:
# correct the output
# Restore the name/instance.
item["name"] = self.name
item["instance"] = self.instance
... | [
"def",
"update_from_item",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"self",
".",
"is_time_module",
":",
"# correct the output",
"# Restore the name/instance.",
"item",
"[",
"\"name\"",
"]",
"=",
"self",
".",
"name",
"item",
"[",
"\"instance\"",
"]",
"=... | 44.5 | 0.001047 |
def load_config(path=None, defaults=None):
"""
Loads and parses an INI style configuration file using Python's built-in
ConfigParser module.
If path is specified, load it.
If ``defaults`` (a list of strings) is given, try to load each entry as a
file, without throwing any error if the operatio... | [
"def",
"load_config",
"(",
"path",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"if",
"defaults",
"is",
"None",
":",
"defaults",
"=",
"DEFAULT_FILES",
"config",
"=",
"configparser",
".",
"SafeConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
... | 27.129032 | 0.001148 |
def parse_int(v, header_d):
"""Parse as an integer, or a subclass of Int."""
v = nullify(v)
if v is None:
return None
try:
# The converson to float allows converting float strings to ints.
# The conversion int('2.134') will fail.
return int(round(float(v), 0))
exce... | [
"def",
"parse_int",
"(",
"v",
",",
"header_d",
")",
":",
"v",
"=",
"nullify",
"(",
"v",
")",
"if",
"v",
"is",
"None",
":",
"return",
"None",
"try",
":",
"# The converson to float allows converting float strings to ints.",
"# The conversion int('2.134') will fail.",
... | 29.5 | 0.002347 |
def apex2geo(self, alat, alon, height, precision=1e-10):
"""Converts modified apex to geodetic coordinates.
Parameters
==========
alat : array_like
Modified apex latitude
alon : array_like
Modified apex longitude
height : array_like
Al... | [
"def",
"apex2geo",
"(",
"self",
",",
"alat",
",",
"alon",
",",
"height",
",",
"precision",
"=",
"1e-10",
")",
":",
"alat",
"=",
"helpers",
".",
"checklat",
"(",
"alat",
",",
"name",
"=",
"'alat'",
")",
"qlat",
",",
"qlon",
"=",
"self",
".",
"apex2q... | 36.578947 | 0.002102 |
def file_remove(self, path):
"""Removes a file on the device"""
log.info('Remove '+path)
cmd = 'file.remove("%s")' % path
res = self.__exchange(cmd)
log.info(res)
return res | [
"def",
"file_remove",
"(",
"self",
",",
"path",
")",
":",
"log",
".",
"info",
"(",
"'Remove '",
"+",
"path",
")",
"cmd",
"=",
"'file.remove(\"%s\")'",
"%",
"path",
"res",
"=",
"self",
".",
"__exchange",
"(",
"cmd",
")",
"log",
".",
"info",
"(",
"res"... | 30.714286 | 0.00905 |
def discard(self, interval):
"""
Returns self after removing interval and balancing.
If interval is not present, do nothing.
"""
done = []
return self.remove_interval_helper(interval, done, should_raise_error=False) | [
"def",
"discard",
"(",
"self",
",",
"interval",
")",
":",
"done",
"=",
"[",
"]",
"return",
"self",
".",
"remove_interval_helper",
"(",
"interval",
",",
"done",
",",
"should_raise_error",
"=",
"False",
")"
] | 32.125 | 0.011364 |
def convert_activation(node, **kwargs):
"""Map MXNet's Activation operator attributes to onnx's Tanh/Relu operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
act_type = attrs["act_type"]
# Creating a dictionary here, but if this titlecase pattern
#... | [
"def",
"convert_activation",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"act_type",
"=",
"attrs",
"[",
"\"act_type\"",
"]",
"# Creating a dictionary here, but if... | 25.6875 | 0.002345 |
def run_step(context):
"""pypyr step saves current utc datetime to context.
Args:
context: pypyr.context.Context. Mandatory.
The following context key is optional:
- nowUtcIn. str. Datetime formatting expression. For full list
of possible expressions, ... | [
"def",
"run_step",
"(",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"format_expression",
"=",
"context",
".",
"get",
"(",
"'nowUtcIn'",
",",
"None",
")",
"if",
"format_expression",
":",
"formatted_expression",
"=",
"context",
".",
"... | 34.111111 | 0.000792 |
def inasafe_exposure_summary_field_values(field, feature, parent):
"""Retrieve all values from a field in the exposure summary layer.
"""
_ = feature, parent # NOQA
layer = exposure_summary_layer()
if not layer:
return None
index = layer.fields().lookupField(field)
if index < 0:
... | [
"def",
"inasafe_exposure_summary_field_values",
"(",
"field",
",",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"layer",
"=",
"exposure_summary_layer",
"(",
")",
"if",
"not",
"layer",
":",
"return",
"None",
"index",
"=",
... | 23.947368 | 0.002114 |
def encode(self, word):
"""Return the Russell Index (integer output) of a word.
Parameters
----------
word : str
The word to transform
Returns
-------
int
The Russell Index value
Examples
--------
>>> pe = Russell... | [
"def",
"encode",
"(",
"self",
",",
"word",
")",
":",
"word",
"=",
"unicode_normalize",
"(",
"'NFKD'",
",",
"text_type",
"(",
"word",
".",
"upper",
"(",
")",
")",
")",
"word",
"=",
"word",
".",
"replace",
"(",
"'ß',",
" ",
"SS')",
"",
"word",
"=",
... | 26.755556 | 0.001603 |
def setNsProp(self, node, name, value):
"""Set (or reset) an attribute carried by a node. The ns
structure must be in scope, this is not checked """
if node is None: node__o = None
else: node__o = node._o
ret = libxml2mod.xmlSetNsProp(node__o, self._o, name, value)
if ... | [
"def",
"setNsProp",
"(",
"self",
",",
"node",
",",
"name",
",",
"value",
")",
":",
"if",
"node",
"is",
"None",
":",
"node__o",
"=",
"None",
"else",
":",
"node__o",
"=",
"node",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlSetNsProp",
"(",
"node__o",... | 46.555556 | 0.014052 |
def addPygletListener(self,event_type,handler):
"""
Registers an event handler.
The specified callable handler will be called every time an event with the same ``event_type`` is encountered.
All event arguments are passed as positional arguments.
This m... | [
"def",
"addPygletListener",
"(",
"self",
",",
"event_type",
",",
"handler",
")",
":",
"if",
"self",
".",
"cfg",
"[",
"\"debug.events.register\"",
"]",
":",
"print",
"(",
"\"Registered Event: %s Handler: %s\"",
"%",
"(",
"event_type",
",",
"handler",
")",
")",
... | 43.52 | 0.013489 |
def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False):
"""Converts a variable to a tensor."""
# pylint: disable=protected-access
if _enclosing_tpu_context() is None:
if hasattr(self._primary_var, '_dense_var_to_tensor'):
return self._primary_var._dense_var_to_tensor(dtype, name, ... | [
"def",
"_dense_var_to_tensor",
"(",
"self",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"None",
",",
"as_ref",
"=",
"False",
")",
":",
"# pylint: disable=protected-access",
"if",
"_enclosing_tpu_context",
"(",
")",
"is",
"None",
":",
"if",
"hasattr",
"(",
"... | 38.533333 | 0.010135 |
def send_respawn(self):
"""
Respawns the player.
"""
nick = self.player.nick
self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) | [
"def",
"send_respawn",
"(",
"self",
")",
":",
"nick",
"=",
"self",
".",
"player",
".",
"nick",
"self",
".",
"send_struct",
"(",
"'<B%iH'",
"%",
"len",
"(",
"nick",
")",
",",
"0",
",",
"*",
"map",
"(",
"ord",
",",
"nick",
")",
")"
] | 28.166667 | 0.011494 |
def _transform_constant_sequence(self, seq):
"""
Transform a frozenset or tuple.
"""
should_transform = is_a(self.types)
if not any(filter(should_transform, flatten(seq))):
# Tuple doesn't contain any transformable strings. Ignore.
yield LOAD_CONST(seq)
... | [
"def",
"_transform_constant_sequence",
"(",
"self",
",",
"seq",
")",
":",
"should_transform",
"=",
"is_a",
"(",
"self",
".",
"types",
")",
"if",
"not",
"any",
"(",
"filter",
"(",
"should_transform",
",",
"flatten",
"(",
"seq",
")",
")",
")",
":",
"# Tupl... | 33.296296 | 0.002162 |
def get_draft_page_by_id(self, page_id, status='draft'):
"""
Provide content by id with status = draft
:param page_id:
:param status:
:return:
"""
url = 'rest/api/content/{page_id}?status={status}'.format(page_id=page_id, status=status)
return self.get(url... | [
"def",
"get_draft_page_by_id",
"(",
"self",
",",
"page_id",
",",
"status",
"=",
"'draft'",
")",
":",
"url",
"=",
"'rest/api/content/{page_id}?status={status}'",
".",
"format",
"(",
"page_id",
"=",
"page_id",
",",
"status",
"=",
"status",
")",
"return",
"self",
... | 34.777778 | 0.009346 |
def get_self(self):
"""GetSelf.
Read identity of the home tenant request user.
:rtype: :class:`<IdentitySelf> <azure.devops.v5_0.identity.models.IdentitySelf>`
"""
response = self._send(http_method='GET',
location_id='4bb02b5b-c120-4be2-b68e-21f7c50a... | [
"def",
"get_self",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'GET'",
",",
"location_id",
"=",
"'4bb02b5b-c120-4be2-b68e-21f7c50a4b82'",
",",
"version",
"=",
"'5.0'",
")",
"return",
"self",
".",
"_deserialize",
"(",... | 46.888889 | 0.009302 |
def _get_images_dir():
'''
Extract the images dir from the configuration. First attempts to
find legacy virt.images, then tries virt:images.
'''
img_dir = __salt__['config.option']('virt.images')
if img_dir:
salt.utils.versions.warn_until(
'Sodium',
'\'virt.images... | [
"def",
"_get_images_dir",
"(",
")",
":",
"img_dir",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'virt.images'",
")",
"if",
"img_dir",
":",
"salt",
".",
"utils",
".",
"versions",
".",
"warn_until",
"(",
"'Sodium'",
",",
"'\\'virt.images\\' has been deprec... | 34.5 | 0.001567 |
def warning(self, text):
"""
Posts a warning message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but the... | [
"def",
"warning",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"queue",
".",
"put",
"(",
"dill",
".",
"dumps",
"(",
"LogMessageCommand",
"(",
"text",
"=",
"text",
",",
"level",
"=",
"logging",
".",
"WARNING",
")",
")",
")"
] | 72 | 0.009602 |
def create_cached_source_fc(header, cached_source_file):
"""
Creates :class:`parser.file_configuration_t` instance, configured to
contain path to GCC-XML generated XML file and C++ source file. If XML file
does not exists, it will be created and used for parsing. If XML file
exists, it will be used ... | [
"def",
"create_cached_source_fc",
"(",
"header",
",",
"cached_source_file",
")",
":",
"return",
"file_configuration_t",
"(",
"data",
"=",
"header",
",",
"cached_source_file",
"=",
"cached_source_file",
",",
"content_type",
"=",
"file_configuration_t",
".",
"CONTENT_TYPE... | 35.75 | 0.001362 |
def guess_stream_needs_encoding(fileobj, default=True):
"""
Guess the type (bytes/unicode) of this stream, and return whether or not it
requires text to be encoded before written into it.
"""
# XXX: Unicode
# On Python 2, stdout is bytes. However, we can't wrap it in a
# TextIOWrapper, as it... | [
"def",
"guess_stream_needs_encoding",
"(",
"fileobj",
",",
"default",
"=",
"True",
")",
":",
"# XXX: Unicode",
"# On Python 2, stdout is bytes. However, we can't wrap it in a",
"# TextIOWrapper, as it's not from IOBase, so it doesn't have .seekable.",
"# It does, however, have a mode, and ... | 29.829268 | 0.000792 |
def get_events(delegate_pubkey):
"""returns a list of named tuples of all transactions relevant to a specific delegates voters.
Flow: finds all voters and unvoters, SELECTs all transactions of those voters, names all transactions according to
the scheme: 'transaction', 'id amount timestamp recipientId sende... | [
"def",
"get_events",
"(",
"delegate_pubkey",
")",
":",
"res",
"=",
"DbCursor",
"(",
")",
".",
"execute_and_fetchall",
"(",
"\"\"\"\n SELECT *\n FROM(\n SELECT transactions.\"id\",\n transactions.\"amount\",\n transactions.\"fee\",\n ... | 34.939394 | 0.001687 |
def clean_streak(image, stat="pmode1", maxiter=15, sigrej=2.0,
lower=None, upper=None, binwidth=0.3, mask=None,
rpt_clean=0, atol=0.01, verbose=True):
"""
Apply destriping algorithm to input array.
Parameters
----------
image : `StripeArray` object
Arrays a... | [
"def",
"clean_streak",
"(",
"image",
",",
"stat",
"=",
"\"pmode1\"",
",",
"maxiter",
"=",
"15",
",",
"sigrej",
"=",
"2.0",
",",
"lower",
"=",
"None",
",",
"upper",
"=",
"None",
",",
"binwidth",
"=",
"0.3",
",",
"mask",
"=",
"None",
",",
"rpt_clean",
... | 35.123377 | 0.00036 |
def _autobox(content, format):
'''
Autobox response content.
:param content: Response content
:type content: str
:param format: Format to return
:type format: `yaxil.Format`
:returns: Autoboxed content
:rtype: dict|xml.etree.ElementTree.Element|csvreader
'''
if format == Format.... | [
"def",
"_autobox",
"(",
"content",
",",
"format",
")",
":",
"if",
"format",
"==",
"Format",
".",
"JSON",
":",
"return",
"json",
".",
"loads",
"(",
"content",
")",
"elif",
"format",
"==",
"Format",
".",
"XML",
":",
"return",
"etree",
".",
"fromstring",
... | 40.606061 | 0.002187 |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the KeyWrappingData struct to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStre... | [
"def",
"write",
"(",
"self",
",",
"output_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"local_stream",
"=",
"BytearrayStream",
"(",
")",
"if",
"self",
".",
"_wrapping_method",
":",
"self",
".",
"_wrapping_method",
... | 33.696429 | 0.00103 |
def find_binary_of_command(candidates):
"""
Calls `find_executable` from distuils for
provided candidates and returns first hit.
If no candidate mathces, a RuntimeError is raised
"""
from distutils.spawn import find_executable
for c in candidates:
binary_path = find_executable(c)
... | [
"def",
"find_binary_of_command",
"(",
"candidates",
")",
":",
"from",
"distutils",
".",
"spawn",
"import",
"find_executable",
"for",
"c",
"in",
"candidates",
":",
"binary_path",
"=",
"find_executable",
"(",
"c",
")",
"if",
"c",
"and",
"binary_path",
":",
"retu... | 35.307692 | 0.002123 |
def config_merge_diff(source='running',
merge_config=None,
merge_path=None,
saltenv='base'):
'''
.. versionadded:: 2019.2.0
Return the merge diff, as text, after merging the merge config into the
configuration source requested (without l... | [
"def",
"config_merge_diff",
"(",
"source",
"=",
"'running'",
",",
"merge_config",
"=",
"None",
",",
"merge_path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"config_txt",
"=",
"__salt__",
"[",
"'net.config'",
"]",
"(",
"source",
"=",
"source",
"... | 39.589744 | 0.001264 |
def _match_setters(self, query):
"""Tries to match in setters
:param query: message tuple
:type query: Tuple[bytes]
:return: response if found or None
:rtype: Tuple[bytes] | None
"""
q = query.decode('utf-8')
for name, parser, response, error_response in ... | [
"def",
"_match_setters",
"(",
"self",
",",
"query",
")",
":",
"q",
"=",
"query",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"name",
",",
"parser",
",",
"response",
",",
"error_response",
"in",
"self",
".",
"_setters",
":",
"try",
":",
"value",
"=",
"... | 32.04 | 0.002424 |
def fetchDocument(self, key, rawResults = False, rev = None) :
"""Fetches a document from the collection given it's key. This function always goes straight to the db and bypasses the cache. If you
want to take advantage of the cache use the __getitem__ interface: collection[key]"""
url = "%s/%s/... | [
"def",
"fetchDocument",
"(",
"self",
",",
"key",
",",
"rawResults",
"=",
"False",
",",
"rev",
"=",
"None",
")",
":",
"url",
"=",
"\"%s/%s/%s\"",
"%",
"(",
"self",
".",
"documentsURL",
",",
"self",
".",
"name",
",",
"key",
")",
"if",
"rev",
"is",
"n... | 54.705882 | 0.021142 |
def snpcount_numba(superints, snpsarr):
"""
Used to count the number of unique bases in a site for snpstring.
"""
## iterate over all loci
for iloc in xrange(superints.shape[0]):
for site in xrange(superints.shape[2]):
## make new array
catg = np.zeros(4, dtype=np.in... | [
"def",
"snpcount_numba",
"(",
"superints",
",",
"snpsarr",
")",
":",
"## iterate over all loci",
"for",
"iloc",
"in",
"xrange",
"(",
"superints",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"site",
"in",
"xrange",
"(",
"superints",
".",
"shape",
"[",
"... | 34.54717 | 0.020712 |
def raise_401(instance, authenticate, msg=None):
"""Abort the current request with a 401 (Unauthorized) response code. If
the message is given it's output as an error message in the response body
(correctly converted to the requested MIME type). Outputs the
WWW-Authenticate header as given by the authen... | [
"def",
"raise_401",
"(",
"instance",
",",
"authenticate",
",",
"msg",
"=",
"None",
")",
":",
"instance",
".",
"response",
".",
"status",
"=",
"401",
"instance",
".",
"response",
".",
"headers",
"[",
"'WWW-Authenticate'",
"]",
"=",
"authenticate",
"if",
"ms... | 49.066667 | 0.001333 |
def peek(self, n=0, skip=None, drop=False):
"""
Return the *n*th datum from the buffer.
"""
buffer = self._buffer
popleft = buffer.popleft
datum = None
if skip is not None:
stack = []
stackpush = stack.append
while n >= 0:
... | [
"def",
"peek",
"(",
"self",
",",
"n",
"=",
"0",
",",
"skip",
"=",
"None",
",",
"drop",
"=",
"False",
")",
":",
"buffer",
"=",
"self",
".",
"_buffer",
"popleft",
"=",
"buffer",
".",
"popleft",
"datum",
"=",
"None",
"if",
"skip",
"is",
"not",
"None... | 29.923077 | 0.002491 |
def __insert_image_info(self, title, _from, info):
"""
Insert API image INFO into matching image dict
We make one imageinfo request containing only unique image
filenames. We reduce duplication by asking for image data per
file, instead of per "kind" or source (Wikipedia, Wikida... | [
"def",
"__insert_image_info",
"(",
"self",
",",
"title",
",",
"_from",
",",
"info",
")",
":",
"for",
"img",
"in",
"self",
".",
"data",
"[",
"'image'",
"]",
":",
"if",
"'url'",
"not",
"in",
"img",
":",
"if",
"title",
"==",
"img",
"[",
"'file'",
"]",... | 47.842105 | 0.002157 |
def body_encode(body, maxlinelen=76, eol=NL):
"""Encode with quoted-printable, wrapping at maxlinelen characters.
Each line of encoded text will end with eol, which defaults to "\\n". Set
this to "\\r\\n" if you will be using the result of this function directly
in an email.
Each line will be wra... | [
"def",
"body_encode",
"(",
"body",
",",
"maxlinelen",
"=",
"76",
",",
"eol",
"=",
"NL",
")",
":",
"if",
"maxlinelen",
"<",
"4",
":",
"raise",
"ValueError",
"(",
"\"maxlinelen must be at least 4\"",
")",
"if",
"not",
"body",
":",
"return",
"body",
"# The la... | 37.568182 | 0.001179 |
def batch(sequence, callback, size=100, **kwargs):
"""Helper to setup batch requests.
There are endpoints which support updating multiple resources at once,
but they are often limited to 100 updates per request.
This function helps with splitting bigger requests into sequence of
smaller ones.
... | [
"def",
"batch",
"(",
"sequence",
",",
"callback",
",",
"size",
"=",
"100",
",",
"*",
"*",
"kwargs",
")",
":",
"batch_len",
",",
"rem",
"=",
"divmod",
"(",
"len",
"(",
"sequence",
")",
",",
"size",
")",
"if",
"rem",
">",
"0",
":",
"batch_len",
"+=... | 38.552632 | 0.000666 |
def wkid(self, value):
""" sets the wkid """
if isinstance(value, (int,
long)):
self._wkid = value | [
"def",
"wkid",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"self",
".",
"_wkid",
"=",
"value"
] | 30.4 | 0.012821 |
def get_user_information(self):
"""Gets the current user information, including sensor ID
Args:
None
Returns:
dictionary object containing information about the current user
"""
url = "https://api.neur.io/v1/users/current"
headers = self.__gen_headers()
headers["Content-Type"]... | [
"def",
"get_user_information",
"(",
"self",
")",
":",
"url",
"=",
"\"https://api.neur.io/v1/users/current\"",
"headers",
"=",
"self",
".",
"__gen_headers",
"(",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"application/json\"",
"r",
"=",
"requests",
".",
"... | 24.375 | 0.002469 |
def make_valid_avro(items, # type: Avro
alltypes, # type: Dict[Text, Dict[Text, Any]]
found, # type: Set[Text]
union=False # type: bool
):
# type: (...) -> Union[Avro, Dict, Text]
"""Convert our schema to... | [
"def",
"make_valid_avro",
"(",
"items",
",",
"# type: Avro",
"alltypes",
",",
"# type: Dict[Text, Dict[Text, Any]]",
"found",
",",
"# type: Set[Text]",
"union",
"=",
"False",
"# type: bool",
")",
":",
"# type: (...) -> Union[Avro, Dict, Text]",
"# Possibly could be integrated i... | 46.85 | 0.001045 |
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 | 0.015778 |
def get_config(app, prefix='hive_'):
"""Conveniently get the security configuration for the specified
application without the annoying 'SECURITY_' prefix.
:param app: The application to inspect
"""
items = app.config.items()
prefix = prefix.upper()
def strip_prefix(tup):
return (tu... | [
"def",
"get_config",
"(",
"app",
",",
"prefix",
"=",
"'hive_'",
")",
":",
"items",
"=",
"app",
".",
"config",
".",
"items",
"(",
")",
"prefix",
"=",
"prefix",
".",
"upper",
"(",
")",
"def",
"strip_prefix",
"(",
"tup",
")",
":",
"return",
"(",
"tup"... | 32.230769 | 0.00232 |
def filesessionmaker(sessionmaker, file_manager, file_managers=None):
u'''Wrapper of session maker adding link to a FileManager instance
to session.::
file_manager = FileManager(cfg.TRANSIENT_ROOT,
cfg.PERSISTENT_ROOT)
filesessionmaker(sessionmaker(...), file_... | [
"def",
"filesessionmaker",
"(",
"sessionmaker",
",",
"file_manager",
",",
"file_managers",
"=",
"None",
")",
":",
"registry",
"=",
"WeakKeyDictionary",
"(",
")",
"if",
"file_managers",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"file_mana... | 35.489362 | 0.00175 |
def finalize(self, *args):
"""Add my tabs"""
if not self.canvas:
Clock.schedule_once(self.finalize, 0)
return
deck_builder_kwargs = {
'pos_hint': {'x': 0, 'y': 0},
'starting_pos_hint': {'x': 0.05, 'top': 0.95},
'card_size_hint': (0.3, ... | [
"def",
"finalize",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"not",
"self",
".",
"canvas",
":",
"Clock",
".",
"schedule_once",
"(",
"self",
".",
"finalize",
",",
"0",
")",
"return",
"deck_builder_kwargs",
"=",
"{",
"'pos_hint'",
":",
"{",
"'x'",
... | 36.028986 | 0.001175 |
def prompt(self, prefix, text=u'', completer=None, tab=0, history=None):
"""
prompt for text input.
This returns a :class:`asyncio.Future`, which will have a string value
:param prefix: text to print before the input field
:type prefix: str
:param text: initial content o... | [
"def",
"prompt",
"(",
"self",
",",
"prefix",
",",
"text",
"=",
"u''",
",",
"completer",
"=",
"None",
",",
"tab",
"=",
"0",
",",
"history",
"=",
"None",
")",
":",
"history",
"=",
"history",
"or",
"[",
"]",
"fut",
"=",
"asyncio",
".",
"get_event_loop... | 35.630769 | 0.00084 |
def optik_option(self, provider, opt, optdict):
"""get our personal option definition and return a suitable form for
use with optik/optparse
"""
optdict = copy.copy(optdict)
if "action" in optdict:
self._nocallback_options[provider] = opt
else:
opt... | [
"def",
"optik_option",
"(",
"self",
",",
"provider",
",",
"opt",
",",
"optdict",
")",
":",
"optdict",
"=",
"copy",
".",
"copy",
"(",
"optdict",
")",
"if",
"\"action\"",
"in",
"optdict",
":",
"self",
".",
"_nocallback_options",
"[",
"provider",
"]",
"=",
... | 41.4 | 0.001574 |
def get_non_compulsory_fields(layer_purpose, layer_subcategory=None):
"""Get non compulsory field based on layer_purpose and layer_subcategory.
Used for get field in InaSAFE Fields step in wizard.
:param layer_purpose: The layer purpose.
:type layer_purpose: str
:param layer_subcategory: Exposure... | [
"def",
"get_non_compulsory_fields",
"(",
"layer_purpose",
",",
"layer_subcategory",
"=",
"None",
")",
":",
"all_fields",
"=",
"get_fields",
"(",
"layer_purpose",
",",
"layer_subcategory",
",",
"replace_null",
"=",
"False",
")",
"compulsory_field",
"=",
"get_compulsory... | 32.952381 | 0.001404 |
def identify(path_name, *, override=None, check_exists=True, default=ISDIR):
"""
Identify the type of a given path name (file or directory). If check_exists
is specified to be false, then the function will not set the identity based
on the path existing or not. If override is specified as either ISDIR o... | [
"def",
"identify",
"(",
"path_name",
",",
"*",
",",
"override",
"=",
"None",
",",
"check_exists",
"=",
"True",
",",
"default",
"=",
"ISDIR",
")",
":",
"head",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path_name",
")",
"if",
"check_exis... | 40.139535 | 0.000566 |
def score_group(group_name=None):
'''
Warning this is deprecated as of Compliance Checker v3.2!
Please do not using scoring groups and update your plugins
if necessary
'''
warnings.warn('Score_group is deprecated as of Compliance Checker v3.2.')
def _inner(func):
def _dec(s, ds):
... | [
"def",
"score_group",
"(",
"group_name",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"'Score_group is deprecated as of Compliance Checker v3.2.'",
")",
"def",
"_inner",
"(",
"func",
")",
":",
"def",
"_dec",
"(",
"s",
",",
"ds",
")",
":",
"ret_val",
... | 33.131579 | 0.001543 |
def _WaitForStartup(self, deadline):
"""Waits for the emulator to start.
Args:
deadline: deadline in seconds
Returns:
True if the emulator responds within the deadline, False otherwise.
"""
start = time.time()
sleep = 0.05
def Elapsed():
return time.time() - start
w... | [
"def",
"_WaitForStartup",
"(",
"self",
",",
"deadline",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"sleep",
"=",
"0.05",
"def",
"Elapsed",
"(",
")",
":",
"return",
"time",
".",
"time",
"(",
")",
"-",
"start",
"while",
"True",
":",
"try"... | 24.344828 | 0.010899 |
def check_many(self, domains):
"""
Check availability for a number of domains. Returns a dictionary
mapping the domain names to their statuses as a string
("active"/"free").
"""
return dict((item.domain, item.status) for item in self.check_domain_request(domains)) | [
"def",
"check_many",
"(",
"self",
",",
"domains",
")",
":",
"return",
"dict",
"(",
"(",
"item",
".",
"domain",
",",
"item",
".",
"status",
")",
"for",
"item",
"in",
"self",
".",
"check_domain_request",
"(",
"domains",
")",
")"
] | 43.714286 | 0.009615 |
def _guess_name(desc, taken=None):
"""Attempts to guess the menu entry name from the function name."""
taken = taken or []
name = ""
# Try to find the shortest name based on the given description.
for word in desc.split():
c = word[0].lower()
if not c.isalnum():
continue
... | [
"def",
"_guess_name",
"(",
"desc",
",",
"taken",
"=",
"None",
")",
":",
"taken",
"=",
"taken",
"or",
"[",
"]",
"name",
"=",
"\"\"",
"# Try to find the shortest name based on the given description.",
"for",
"word",
"in",
"desc",
".",
"split",
"(",
")",
":",
"... | 29.277778 | 0.001838 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.