text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def run(items):
"""Perform detection of structural variations with delly.
Performs post-call filtering with a custom filter tuned based
on NA12878 Moleculo and PacBio data, using calls prepared by
@ryanlayer and @cc2qe
Filters using the high quality variant pairs (DV) compared with
high qualit... | [
"def",
"run",
"(",
"items",
")",
":",
"work_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"items",
"[",
"0",
"]",
"[",
"\"dirs\"",
"]",
"[",
"\"work\"",
"]",
",",
"\"structural\"",
",",
"dd",
".",
"get_sample_name... | 48.744186 | 21.953488 |
def _logfile_sigterm_handler(*_):
# type: (...) -> None
"""Handle exit signals and write out a log file.
Raises:
SystemExit: Contains the signal as the return code.
"""
logging.error('Received SIGTERM.')
write_logfile()
print('Received signal. Please see the log file for more inform... | [
"def",
"_logfile_sigterm_handler",
"(",
"*",
"_",
")",
":",
"# type: (...) -> None",
"logging",
".",
"error",
"(",
"'Received SIGTERM.'",
")",
"write_logfile",
"(",
")",
"print",
"(",
"'Received signal. Please see the log file for more information.'",
",",
"file",
"=",
... | 30.416667 | 16.833333 |
def grantxml2json(self, grant_xml):
"""Convert OpenAIRE grant XML into JSON."""
tree = etree.fromstring(grant_xml)
# XML harvested from OAI-PMH has a different format/structure
if tree.prefix == 'oai':
ptree = self.get_subtree(
tree, '/oai:record/oai:metadata/... | [
"def",
"grantxml2json",
"(",
"self",
",",
"grant_xml",
")",
":",
"tree",
"=",
"etree",
".",
"fromstring",
"(",
"grant_xml",
")",
"# XML harvested from OAI-PMH has a different format/structure",
"if",
"tree",
".",
"prefix",
"==",
"'oai'",
":",
"ptree",
"=",
"self",... | 42.865385 | 18.576923 |
def select_random(ports=None, exclude_ports=None):
"""
Returns random unused port number.
"""
if ports is None:
ports = available_good_ports()
if exclude_ports is None:
exclude_ports = set()
ports.difference_update(set(exclude_ports))
for port in random.sample(ports, min(l... | [
"def",
"select_random",
"(",
"ports",
"=",
"None",
",",
"exclude_ports",
"=",
"None",
")",
":",
"if",
"ports",
"is",
"None",
":",
"ports",
"=",
"available_good_ports",
"(",
")",
"if",
"exclude_ports",
"is",
"None",
":",
"exclude_ports",
"=",
"set",
"(",
... | 26.9375 | 14.5625 |
def keypress(self, win, char):
"""
returns:
1: get next char
0: exit edit mode, string isvalid
-1: cancel
"""
if not self._focused:
return 1
if self.log is not None:
self.log('char = {}\n'.format(char))
if char i... | [
"def",
"keypress",
"(",
"self",
",",
"win",
",",
"char",
")",
":",
"if",
"not",
"self",
".",
"_focused",
":",
"return",
"1",
"if",
"self",
".",
"log",
"is",
"not",
"None",
":",
"self",
".",
"log",
"(",
"'char = {}\\n'",
".",
"format",
"(",
"char",
... | 37.715328 | 12.678832 |
def get_vnetwork_dvpgs_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvpgs = ET.Element("get_vnetwork_dvpgs")
config = get_vnetwork_dvpgs
output = ET.SubElement(get_vnetwork_dvpgs, "output")
has_more = ET.Su... | [
"def",
"get_vnetwork_dvpgs_output_has_more",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_dvpgs",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_dvpgs\"",
")",
"config",
"=",
"get_v... | 39.583333 | 12.333333 |
def _convert_verbal_form( analysis ):
''' Converts ordinary verbal categories of the input analysis.
Performs one-to-one conversions. '''
assert FORM in analysis, '(!) The input analysis does not contain "'+FORM+'" key.'
for form, replacement in _verb_conversion_rules:
# Exact match
... | [
"def",
"_convert_verbal_form",
"(",
"analysis",
")",
":",
"assert",
"FORM",
"in",
"analysis",
",",
"'(!) The input analysis does not contain \"'",
"+",
"FORM",
"+",
"'\" key.'",
"for",
"form",
",",
"replacement",
"in",
"_verb_conversion_rules",
":",
"# Exact match",
"... | 49.75 | 16 |
def index_path(self, root):
"""Index a path.
:param root: Either a package directory, a .so or a .py module.
"""
basename = os.path.basename(root)
if os.path.splitext(basename)[0] != '__init__' and basename.startswith('_'):
return
location = self._determine_l... | [
"def",
"index_path",
"(",
"self",
",",
"root",
")",
":",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"root",
")",
"if",
"os",
".",
"path",
".",
"splitext",
"(",
"basename",
")",
"[",
"0",
"]",
"!=",
"'__init__'",
"and",
"basename",
".... | 41.615385 | 17.846154 |
def create(cls, messageType, extended, hopsleft=3, hopsmax=3):
"""Create message flags.
messageType: integter 0 to 7:
MESSAGE_TYPE_DIRECT_MESSAGE = 0
MESSAGE_TYPE_DIRECT_MESSAGE_ACK = 1
MESSAGE_TYPE_ALL_LINK_CLEANUP = 2
MESSAGE_TYPE_ALL_LINK_CLEANUP_ACK =... | [
"def",
"create",
"(",
"cls",
",",
"messageType",
",",
"extended",
",",
"hopsleft",
"=",
"3",
",",
"hopsmax",
"=",
"3",
")",
":",
"flags",
"=",
"MessageFlags",
"(",
"None",
")",
"if",
"messageType",
"<",
"8",
":",
"flags",
".",
"_messageType",
"=",
"m... | 34.903226 | 10.483871 |
async def access_log_middleware(app, handler):
"""Log each request in structured event log."""
event_log = app.get('smartmob.event_log') or structlog.get_logger()
clock = app.get('smartmob.clock') or timeit.default_timer
# Keep the request arrival time to ensure we get intuitive logging of
# event... | [
"async",
"def",
"access_log_middleware",
"(",
"app",
",",
"handler",
")",
":",
"event_log",
"=",
"app",
".",
"get",
"(",
"'smartmob.event_log'",
")",
"or",
"structlog",
".",
"get_logger",
"(",
")",
"clock",
"=",
"app",
".",
"get",
"(",
"'smartmob.clock'",
... | 32.977778 | 15.8 |
def rejectEdit(self):
"""
Cancels the edit for this label.
"""
if self._lineEdit:
self._lineEdit.hide()
self.editingCancelled.emit() | [
"def",
"rejectEdit",
"(",
"self",
")",
":",
"if",
"self",
".",
"_lineEdit",
":",
"self",
".",
"_lineEdit",
".",
"hide",
"(",
")",
"self",
".",
"editingCancelled",
".",
"emit",
"(",
")"
] | 26.857143 | 5.428571 |
def each_object_id(collection):
"""Yields each object ID in the given ``collection``.
The objects are not loaded."""
c_path = collection_path(collection)
paths = glob('%s/*.%s' % (c_path, _ext))
for path in paths:
match = regex.match(r'.+/(.+)\.%s$' % _ext, path)
yield match.groups()... | [
"def",
"each_object_id",
"(",
"collection",
")",
":",
"c_path",
"=",
"collection_path",
"(",
"collection",
")",
"paths",
"=",
"glob",
"(",
"'%s/*.%s'",
"%",
"(",
"c_path",
",",
"_ext",
")",
")",
"for",
"path",
"in",
"paths",
":",
"match",
"=",
"regex",
... | 39.5 | 7.125 |
def convert_errno(e):
"""
Convert an errno value (as from an ``OSError`` or ``IOError``) into a
standard SFTP result code. This is a convenience function for trapping
exceptions in server code and returning an appropriate result.
:param int e: an errno code, as from ``OSError.e... | [
"def",
"convert_errno",
"(",
"e",
")",
":",
"if",
"e",
"==",
"errno",
".",
"EACCES",
":",
"# permission denied",
"return",
"SFTP_PERMISSION_DENIED",
"elif",
"(",
"e",
"==",
"errno",
".",
"ENOENT",
")",
"or",
"(",
"e",
"==",
"errno",
".",
"ENOTDIR",
")",
... | 39.117647 | 18.176471 |
def add_team_repo(repo_name, team_name, profile="github", permission=None):
'''
Adds a repository to a team with team_name.
repo_name
The name of the repository to add.
team_name
The name of the team of which to add the repository.
profile
The name of the profile configura... | [
"def",
"add_team_repo",
"(",
"repo_name",
",",
"team_name",
",",
"profile",
"=",
"\"github\"",
",",
"permission",
"=",
"None",
")",
":",
"team",
"=",
"get_team",
"(",
"team_name",
",",
"profile",
"=",
"profile",
")",
"if",
"not",
"team",
":",
"log",
".",... | 28.814815 | 23.222222 |
def from_credentials(credentials):
"""Returns a new API object from an existing Credentials object.
:param credentials: The existing saved credentials.
:type credentials: Credentials
:return: A new API object populated with MyGeotab credentials.
:rtype: API
"""
r... | [
"def",
"from_credentials",
"(",
"credentials",
")",
":",
"return",
"API",
"(",
"username",
"=",
"credentials",
".",
"username",
",",
"password",
"=",
"credentials",
".",
"password",
",",
"database",
"=",
"credentials",
".",
"database",
",",
"session_id",
"=",
... | 46.545455 | 18.818182 |
def fetch_interfaces(self, interface, way):
"""Get the list of charms that provides or requires this interface.
@param interface The interface for the charm relation.
@param way The type of relation, either "provides" or "requires".
@return List of charms
"""
if not inte... | [
"def",
"fetch_interfaces",
"(",
"self",
",",
"interface",
",",
"way",
")",
":",
"if",
"not",
"interface",
":",
"return",
"[",
"]",
"if",
"way",
"==",
"'requires'",
":",
"request",
"=",
"'&requires='",
"+",
"interface",
"else",
":",
"request",
"=",
"'&pro... | 40.473684 | 14.894737 |
def is_grounded_to_name(c: Concept, name: str, cutoff=0.7) -> bool:
""" Check if a concept is grounded to a given name. """
return (top_grounding(c) == name) if is_well_grounded(c, cutoff) else False | [
"def",
"is_grounded_to_name",
"(",
"c",
":",
"Concept",
",",
"name",
":",
"str",
",",
"cutoff",
"=",
"0.7",
")",
"->",
"bool",
":",
"return",
"(",
"top_grounding",
"(",
"c",
")",
"==",
"name",
")",
"if",
"is_well_grounded",
"(",
"c",
",",
"cutoff",
"... | 68.333333 | 22 |
def get(cls):
"""Get the current API key.
if one has not been given via 'set' the env var STEAMODD_API_KEY will
be checked instead.
"""
apikey = cls.__api_key or cls.__api_key_env_var
if apikey:
return apikey
else:
raise APIKeyMissingError... | [
"def",
"get",
"(",
"cls",
")",
":",
"apikey",
"=",
"cls",
".",
"__api_key",
"or",
"cls",
".",
"__api_key_env_var",
"if",
"apikey",
":",
"return",
"apikey",
"else",
":",
"raise",
"APIKeyMissingError",
"(",
"\"API key not set\"",
")"
] | 29.909091 | 19.181818 |
def _initialize_buffers(self, view_size):
""" Create the buffers to cache tile drawing
:param view_size: (int, int): size of the draw area
:return: None
"""
def make_rect(x, y):
return Rect((x * tw, y * th), (tw, th))
tw, th = self.data.tile_size
mw... | [
"def",
"_initialize_buffers",
"(",
"self",
",",
"view_size",
")",
":",
"def",
"make_rect",
"(",
"x",
",",
"y",
")",
":",
"return",
"Rect",
"(",
"(",
"x",
"*",
"tw",
",",
"y",
"*",
"th",
")",
",",
"(",
"tw",
",",
"th",
")",
")",
"tw",
",",
"th... | 39 | 19.485714 |
def readBED(basefilename, useMAFencoding=False,blocksize = 1, start = 0, nSNPs = SP.inf, startpos = None, endpos = None, order = 'F',standardizeSNPs=False,ipos = 2,bim=None,fam=None):
'''
read [basefilename].bed,[basefilename].bim,[basefilename].fam
---------------------------------------------------------... | [
"def",
"readBED",
"(",
"basefilename",
",",
"useMAFencoding",
"=",
"False",
",",
"blocksize",
"=",
"1",
",",
"start",
"=",
"0",
",",
"nSNPs",
"=",
"SP",
".",
"inf",
",",
"startpos",
"=",
"None",
",",
"endpos",
"=",
"None",
",",
"order",
"=",
"'F'",
... | 40.94 | 18.966667 |
def from_edges(edges):
""" Return DirectedGraph created from edges
:param edges:
:return: DirectedGraph
"""
dag = DirectedGraph()
for _u, _v in edges:
dag.add_edge(_u, _v)
return dag | [
"def",
"from_edges",
"(",
"edges",
")",
":",
"dag",
"=",
"DirectedGraph",
"(",
")",
"for",
"_u",
",",
"_v",
"in",
"edges",
":",
"dag",
".",
"add_edge",
"(",
"_u",
",",
"_v",
")",
"return",
"dag"
] | 27.777778 | 10.444444 |
def list(self, cur_p=''):
'''
View the list of the Log.
'''
if cur_p == '':
current_page_number = 1
else:
current_page_number = int(cur_p)
current_page_number = 1 if current_page_number < 1 else current_page_number
pager_num = int(MLog.t... | [
"def",
"list",
"(",
"self",
",",
"cur_p",
"=",
"''",
")",
":",
"if",
"cur_p",
"==",
"''",
":",
"current_page_number",
"=",
"1",
"else",
":",
"current_page_number",
"=",
"int",
"(",
"cur_p",
")",
"current_page_number",
"=",
"1",
"if",
"current_page_number",... | 35.212121 | 21.818182 |
def _watcher(self):
"""Watch out if we've been disconnected, in that case, kill
all the jobs.
"""
while True:
gevent.sleep(1.0)
if not self.connected:
for ns_name, ns in list(six.iteritems(self.active_ns)):
ns.recv_disconnect()... | [
"def",
"_watcher",
"(",
"self",
")",
":",
"while",
"True",
":",
"gevent",
".",
"sleep",
"(",
"1.0",
")",
"if",
"not",
"self",
".",
"connected",
":",
"for",
"ns_name",
",",
"ns",
"in",
"list",
"(",
"six",
".",
"iteritems",
"(",
"self",
".",
"active_... | 32 | 13.230769 |
def outputs_of(self, partition_index):
"""The outputs of the partition at ``partition_index``.
Note that this returns a tuple of element indices, since coarse-
grained blackboxes may have multiple outputs.
"""
partition = self.partition[partition_index]
outputs = set(par... | [
"def",
"outputs_of",
"(",
"self",
",",
"partition_index",
")",
":",
"partition",
"=",
"self",
".",
"partition",
"[",
"partition_index",
"]",
"outputs",
"=",
"set",
"(",
"partition",
")",
".",
"intersection",
"(",
"self",
".",
"output_indices",
")",
"return",... | 43.444444 | 14.111111 |
def sign(self, message):
"""
>>> authlen = OmapiHMACMD5Authenticator.authlen
>>> len(OmapiHMACMD5Authenticator(b"foo", 16*b"x").sign(b"baz")) == authlen
True
@type message: bytes
@rtype: bytes
@returns: a signature of length self.authlen
"""
return hmac.HMAC(self.key, message, digestmod=hashlib.md5).... | [
"def",
"sign",
"(",
"self",
",",
"message",
")",
":",
"return",
"hmac",
".",
"HMAC",
"(",
"self",
".",
"key",
",",
"message",
",",
"digestmod",
"=",
"hashlib",
".",
"md5",
")",
".",
"digest",
"(",
")"
] | 28.909091 | 19.454545 |
def save(self, nodedict, root=''):
"""
Save a node dictionary in the .hdf5 file, starting from the root
dataset. A common application is to convert XML files into .hdf5
files, see the usage in :mod:`openquake.commands.to_hdf5`.
:param nodedict:
a dictionary with keys... | [
"def",
"save",
"(",
"self",
",",
"nodedict",
",",
"root",
"=",
"''",
")",
":",
"setitem",
"=",
"super",
"(",
")",
".",
"__setitem__",
"getitem",
"=",
"super",
"(",
")",
".",
"__getitem__",
"tag",
"=",
"nodedict",
"[",
"'tag'",
"]",
"text",
"=",
"no... | 37.4375 | 11.4375 |
def write(self, file_or_filename):
""" Writes case data as CSV.
"""
if isinstance(file_or_filename, basestring):
file = open(file_or_filename, "wb")
else:
file = file_or_filename
self.writer = csv.writer(file)
super(CSVWriter, self).write(file) | [
"def",
"write",
"(",
"self",
",",
"file_or_filename",
")",
":",
"if",
"isinstance",
"(",
"file_or_filename",
",",
"basestring",
")",
":",
"file",
"=",
"open",
"(",
"file_or_filename",
",",
"\"wb\"",
")",
"else",
":",
"file",
"=",
"file_or_filename",
"self",
... | 28 | 12.818182 |
def walkSignalPorts(rootPort: LPort):
"""
recursively walk ports without any children
"""
if rootPort.children:
for ch in rootPort.children:
yield from walkSignalPorts(ch)
else:
yield rootPort | [
"def",
"walkSignalPorts",
"(",
"rootPort",
":",
"LPort",
")",
":",
"if",
"rootPort",
".",
"children",
":",
"for",
"ch",
"in",
"rootPort",
".",
"children",
":",
"yield",
"from",
"walkSignalPorts",
"(",
"ch",
")",
"else",
":",
"yield",
"rootPort"
] | 25.777778 | 8.888889 |
def fermat_potential(self, x_image, y_image, x_source, y_source, kwargs_lens):
"""
fermat potential (negative sign means earlier arrival time)
:param x_image: image position
:param y_image: image position
:param x_source: source position
:param y_source: source position
... | [
"def",
"fermat_potential",
"(",
"self",
",",
"x_image",
",",
"y_image",
",",
"x_source",
",",
"y_source",
",",
"kwargs_lens",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"lens_model",
",",
"'fermat_potential'",
")",
":",
"return",
"self",
".",
"lens_model",... | 56.6 | 29.933333 |
def assert_is_valid_key(key):
"""
Raise KeyError if a given config key violates any requirements.
The requirements are the following and can be individually deactivated
in ``sacred.SETTINGS.CONFIG_KEYS``:
* ENFORCE_MONGO_COMPATIBLE (default: True):
make sure the keys don't contain a '.' o... | [
"def",
"assert_is_valid_key",
"(",
"key",
")",
":",
"if",
"SETTINGS",
".",
"CONFIG",
".",
"ENFORCE_KEYS_MONGO_COMPATIBLE",
"and",
"(",
"isinstance",
"(",
"key",
",",
"basestring",
")",
"and",
"(",
"'.'",
"in",
"key",
"or",
"key",
"[",
"0",
"]",
"==",
"'$... | 41.90566 | 22.509434 |
def _bind_target(self, target, ctx=None):
"""Method to override in order to specialize binding of target.
:param target: target to bind.
:param ctx: target ctx.
:return: bound target.
"""
result = target
try:
# get annotations from target if exists.... | [
"def",
"_bind_target",
"(",
"self",
",",
"target",
",",
"ctx",
"=",
"None",
")",
":",
"result",
"=",
"target",
"try",
":",
"# get annotations from target if exists.",
"local_annotations",
"=",
"get_local_property",
"(",
"target",
",",
"Annotation",
".",
"__ANNOTAT... | 29.823529 | 18.941176 |
def build_vars(path=None):
"""Build initial vars."""
init_vars = {
"__name__": "__main__",
"__package__": None,
"reload": reload,
}
if path is not None:
init_vars["__file__"] = fixpath(path)
# put reserved_vars in for auto-completio... | [
"def",
"build_vars",
"(",
"path",
"=",
"None",
")",
":",
"init_vars",
"=",
"{",
"\"__name__\"",
":",
"\"__main__\"",
",",
"\"__package__\"",
":",
"None",
",",
"\"reload\"",
":",
"reload",
",",
"}",
"if",
"path",
"is",
"not",
"None",
":",
"init_vars",
"["... | 31.615385 | 12.153846 |
def _get_bandgap_from_bands(energies, nelec):
"""Compute difference in conduction band min and valence band max"""
nelec = int(nelec)
valence = [x[nelec-1] for x in energies]
conduction = [x[nelec] for x in energies]
return max(min(conduction) - max(valence), 0.0) | [
"def",
"_get_bandgap_from_bands",
"(",
"energies",
",",
"nelec",
")",
":",
"nelec",
"=",
"int",
"(",
"nelec",
")",
"valence",
"=",
"[",
"x",
"[",
"nelec",
"-",
"1",
"]",
"for",
"x",
"in",
"energies",
"]",
"conduction",
"=",
"[",
"x",
"[",
"nelec",
... | 49.833333 | 8.5 |
def new_event(self, subject=None):
""" Returns a new (unsaved) Event object
:rtype: Event
"""
return self.event_constructor(parent=self, subject=subject,
calendar_id=self.calendar_id) | [
"def",
"new_event",
"(",
"self",
",",
"subject",
"=",
"None",
")",
":",
"return",
"self",
".",
"event_constructor",
"(",
"parent",
"=",
"self",
",",
"subject",
"=",
"subject",
",",
"calendar_id",
"=",
"self",
".",
"calendar_id",
")"
] | 35.428571 | 17 |
def context(self, identifier=None, meta=None):
""" Get or create a context, with the given identifier and/or
provenance meta data. A context can be used to add, update or delete
objects in the store. """
return Context(self, identifier=identifier, meta=meta) | [
"def",
"context",
"(",
"self",
",",
"identifier",
"=",
"None",
",",
"meta",
"=",
"None",
")",
":",
"return",
"Context",
"(",
"self",
",",
"identifier",
"=",
"identifier",
",",
"meta",
"=",
"meta",
")"
] | 57.2 | 12.8 |
def create_session(self, lock_type=library.LockType.shared,
session=None):
"""Lock this machine
Arguments:
lock_type - see IMachine.lock_machine for details
session - optionally define a session object to lock this machine
against. I... | [
"def",
"create_session",
"(",
"self",
",",
"lock_type",
"=",
"library",
".",
"LockType",
".",
"shared",
",",
"session",
"=",
"None",
")",
":",
"if",
"session",
"is",
"None",
":",
"session",
"=",
"library",
".",
"ISession",
"(",
")",
"# NOTE: The following ... | 39.914286 | 19.485714 |
def insert_item(self):
"""Insert item"""
index = self.currentIndex()
if not index.isValid():
row = self.model.rowCount()
else:
row = index.row()
data = self.model.get_data()
if isinstance(data, list):
key = row
dat... | [
"def",
"insert_item",
"(",
"self",
")",
":",
"index",
"=",
"self",
".",
"currentIndex",
"(",
")",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"row",
"=",
"self",
".",
"model",
".",
"rowCount",
"(",
")",
"else",
":",
"row",
"=",
"index",
... | 38.791667 | 14.958333 |
def find_visible_birthdays(request, data):
"""Return only the birthdays visible to current user.
"""
if request.user and (request.user.is_teacher or request.user.is_eighthoffice or request.user.is_eighth_admin):
return data
data['today']['users'] = [u for u in data['today']['users'] if u['public... | [
"def",
"find_visible_birthdays",
"(",
"request",
",",
"data",
")",
":",
"if",
"request",
".",
"user",
"and",
"(",
"request",
".",
"user",
".",
"is_teacher",
"or",
"request",
".",
"user",
".",
"is_eighthoffice",
"or",
"request",
".",
"user",
".",
"is_eighth... | 52.25 | 25.75 |
def get_mode(path, follow_symlinks=True):
'''
Return the mode of a file
path
file or directory of which to get the mode
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd
.. versionchange... | [
"def",
"get_mode",
"(",
"path",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"return",
"stats",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
",",
"follow_symlinks",
"=",
"follow_symlinks",
")",
".",
"get",
"(",
"'mode'",
",",
"''",
")... | 22.7 | 24.5 |
def triangle_areas(p1,p2,p3):
"""Compute an array of triangle areas given three arrays of triangle pts
p1,p2,p3 - three Nx2 arrays of points
"""
v1 = (p2 - p1).astype(np.float)
v2 = (p3 - p1).astype(np.float)
# Original:
# cross1 = v1[:,1] * v2[:,0]
# cross2 = v2[:,1] * v1[:,0]
... | [
"def",
"triangle_areas",
"(",
"p1",
",",
"p2",
",",
"p3",
")",
":",
"v1",
"=",
"(",
"p2",
"-",
"p1",
")",
".",
"astype",
"(",
"np",
".",
"float",
")",
"v2",
"=",
"(",
"p3",
"-",
"p1",
")",
".",
"astype",
"(",
"np",
".",
"float",
")",
"# Ori... | 25.481481 | 16.037037 |
def by_population_density(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.population_density.name,
ascending=False,
... | [
"def",
"by_population_density",
"(",
"self",
",",
"lower",
"=",
"-",
"1",
",",
"upper",
"=",
"2",
"**",
"31",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"population_density",
".",
"name",
",",
"asce... | 40.666667 | 14.444444 |
def setup_opt_parser():
"""
Setup the optparser
@returns: opt_parser.OptionParser
"""
#pylint: disable-msg=C0301
#line too long
usage = "usage: %prog [options]"
opt_parser = optparse.OptionParser(usage=usage)
opt_parser.add_option("--version", action='store_true', dest=
... | [
"def",
"setup_opt_parser",
"(",
")",
":",
"#pylint: disable-msg=C0301",
"#line too long",
"usage",
"=",
"\"usage: %prog [options]\"",
"opt_parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"usage",
"=",
"usage",
")",
"opt_parser",
".",
"add_option",
"(",
"\"--versio... | 49.632353 | 28.397059 |
def modify_prefix(arg, opts, shell_opts):
""" Modify the prefix 'arg' with the options 'opts'
"""
modify_confirmed = shell_opts.force
spec = { 'prefix': arg }
v = get_vrf(opts.get('vrf_rt'), abort=True)
spec['vrf_rt'] = v.rt
res = Prefix.list(spec)
if len(res) == 0:
print("Pre... | [
"def",
"modify_prefix",
"(",
"arg",
",",
"opts",
",",
"shell_opts",
")",
":",
"modify_confirmed",
"=",
"shell_opts",
".",
"force",
"spec",
"=",
"{",
"'prefix'",
":",
"arg",
"}",
"v",
"=",
"get_vrf",
"(",
"opts",
".",
"get",
"(",
"'vrf_rt'",
")",
",",
... | 30.897436 | 19.769231 |
def _af_annotate_and_filter(paired, items, in_file, out_file):
"""Populating FORMAT/AF, and dropping variants with AF<min_allele_fraction
Strelka2 doesn't report exact AF for a variant, however it can be calculated as alt_counts/dp from existing fields:
somatic
snps: GT:DP:FDP:SDP:SUBDP:AU:CU:GU:T... | [
"def",
"_af_annotate_and_filter",
"(",
"paired",
",",
"items",
",",
"in_file",
",",
"out_file",
")",
":",
"data",
"=",
"paired",
".",
"tumor_data",
"if",
"paired",
"else",
"items",
"[",
"0",
"]",
"min_freq",
"=",
"float",
"(",
"utils",
".",
"get_in",
"("... | 62.111111 | 29.203704 |
def send(self, topic, kmsg):
""" Send the message into the given topic
:param str topic: a kafka topic
:param ksr.transport.Message kmsg: Message to serialize
:return: Execution result
:rtype: kser.result.Result
"""
try:
self.client.do_request(
... | [
"def",
"send",
"(",
"self",
",",
"topic",
",",
"kmsg",
")",
":",
"try",
":",
"self",
".",
"client",
".",
"do_request",
"(",
"method",
"=",
"\"POST\"",
",",
"params",
"=",
"dict",
"(",
"format",
"=",
"\"raw\"",
")",
",",
"path",
"=",
"\"/topic/{}\"",
... | 33.931034 | 17.172414 |
def allocate(self, dut_configuration_list, args=None):
"""
Allocates resources from available local devices.
:param dut_configuration_list: List of ResourceRequirements objects
:param args: Not used
:return: AllocationContextList with allocated resources
"""
dut_... | [
"def",
"allocate",
"(",
"self",
",",
"dut_configuration_list",
",",
"args",
"=",
"None",
")",
":",
"dut_config_list",
"=",
"dut_configuration_list",
".",
"get_dut_configuration",
"(",
")",
"# if we need one or more local hardware duts let's search attached",
"# devices using ... | 45.666667 | 22.142857 |
def wait_time(self, value):
"""
Setter for **self.__wait_time** attribute.
:param value: Attribute value.
:type value: int or float
"""
if value is not None:
assert type(value) in (int, float), "'{0}' attribute: '{1}' type is not 'int' or 'float'!".format(
... | [
"def",
"wait_time",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"in",
"(",
"int",
",",
"float",
")",
",",
"\"'{0}' attribute: '{1}' type is not 'int' or 'float'!\"",
".",
"format",
"(",
... | 36.846154 | 20.692308 |
def commit(self):
"""Commit a batch."""
assert self.batch is not None, "No active batch, call start() first"
logger.debug("Comitting batch from %d sources...", len(self.batch))
# Determine item priority.
by_priority = []
for name in self.batch.keys():
priori... | [
"def",
"commit",
"(",
"self",
")",
":",
"assert",
"self",
".",
"batch",
"is",
"not",
"None",
",",
"\"No active batch, call start() first\"",
"logger",
".",
"debug",
"(",
"\"Comitting batch from %d sources...\"",
",",
"len",
"(",
"self",
".",
"batch",
")",
")",
... | 38.896552 | 19.758621 |
def scaled_tile(self, tile):
'''return a scaled tile'''
width = int(TILES_WIDTH / tile.scale)
height = int(TILES_HEIGHT / tile.scale)
scaled_tile = cv.CreateImage((width,height), 8, 3)
full_tile = self.load_tile(tile)
cv.Resize(full_tile, scaled_tile)
return scaled_tile | [
"def",
"scaled_tile",
"(",
"self",
",",
"tile",
")",
":",
"width",
"=",
"int",
"(",
"TILES_WIDTH",
"/",
"tile",
".",
"scale",
")",
"height",
"=",
"int",
"(",
"TILES_HEIGHT",
"/",
"tile",
".",
"scale",
")",
"scaled_tile",
"=",
"cv",
".",
"CreateImage",
... | 34.625 | 8.625 |
def add_path_with_storage_account(self, remote_path, storage_account):
# type: (SourcePath, str, str) -> None
"""Add a path with an associated storage account
:param SourcePath self: this
:param str remote_path: remote path
:param str storage_account: storage account to associate... | [
"def",
"add_path_with_storage_account",
"(",
"self",
",",
"remote_path",
",",
"storage_account",
")",
":",
"# type: (SourcePath, str, str) -> None",
"if",
"len",
"(",
"self",
".",
"_path_map",
")",
">=",
"1",
":",
"raise",
"RuntimeError",
"(",
"'cannot add multiple re... | 47.230769 | 12.692308 |
def get_authorizations_by_genus_type(self, authorization_genus_type):
"""Gets an ``AuthorizationList`` corresponding to the given authorization genus ``Type`` which does not include authorizations of genus types derived from the specified ``Type``.
In plenary mode, the returned list contains all known
... | [
"def",
"get_authorizations_by_genus_type",
"(",
"self",
",",
"authorization_genus_type",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resources_by_genus_type",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONC... | 56.464286 | 22.357143 |
def __makeShowColumnFunction(self, column_idx):
""" Creates a function that shows or hides a column."""
show_column = lambda checked: self.setColumnHidden(column_idx, not checked)
return show_column | [
"def",
"__makeShowColumnFunction",
"(",
"self",
",",
"column_idx",
")",
":",
"show_column",
"=",
"lambda",
"checked",
":",
"self",
".",
"setColumnHidden",
"(",
"column_idx",
",",
"not",
"checked",
")",
"return",
"show_column"
] | 54.75 | 16 |
def github_tags_newer(github_repo, versions_file, update_majors):
"""
Get new tags from a github repository. Cannot use github API because it
doesn't support chronological ordering of tags.
@param github_repo: the github repository, e.g. 'drupal/drupal/'.
@param versions_file: the file path where th... | [
"def",
"github_tags_newer",
"(",
"github_repo",
",",
"versions_file",
",",
"update_majors",
")",
":",
"github_repo",
"=",
"_github_normalize",
"(",
"github_repo",
")",
"vf",
"=",
"VersionsFile",
"(",
"versions_file",
")",
"current_highest",
"=",
"vf",
".",
"highes... | 41.516129 | 20.290323 |
def clone_bs4_elem(el):
"""Clone a bs4 tag before modifying it.
Code from `http://stackoverflow.com/questions/23057631/clone-element-with
-beautifulsoup`
"""
if isinstance(el, NavigableString):
return type(el)(el)
copy = Tag(None, el.builder, el.name, el.namespace, el.nsprefix)
# w... | [
"def",
"clone_bs4_elem",
"(",
"el",
")",
":",
"if",
"isinstance",
"(",
"el",
",",
"NavigableString",
")",
":",
"return",
"type",
"(",
"el",
")",
"(",
"el",
")",
"copy",
"=",
"Tag",
"(",
"None",
",",
"el",
".",
"builder",
",",
"el",
".",
"name",
"... | 34.833333 | 16.166667 |
def run(configobj=None):
"""TEAL interface for the `clean` function."""
clean(configobj['input'],
suffix=configobj['suffix'],
stat=configobj['stat'],
maxiter=configobj['maxiter'],
sigrej=configobj['sigrej'],
lower=configobj['lower'],
upper=configobj['u... | [
"def",
"run",
"(",
"configobj",
"=",
"None",
")",
":",
"clean",
"(",
"configobj",
"[",
"'input'",
"]",
",",
"suffix",
"=",
"configobj",
"[",
"'suffix'",
"]",
",",
"stat",
"=",
"configobj",
"[",
"'stat'",
"]",
",",
"maxiter",
"=",
"configobj",
"[",
"'... | 37.111111 | 4.666667 |
def encode(self, word, max_length=4, zero_pad=True):
"""Return the SoundexBR encoding of a word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 4)
zero_pad : bool
Pa... | [
"def",
"encode",
"(",
"self",
",",
"word",
",",
"max_length",
"=",
"4",
",",
"zero_pad",
"=",
"True",
")",
":",
"word",
"=",
"unicode_normalize",
"(",
"'NFKD'",
",",
"text_type",
"(",
"word",
".",
"upper",
"(",
")",
")",
")",
"word",
"=",
"''",
"."... | 26.42623 | 19.540984 |
def n2s(n):
"""
Number to string.
"""
s = hex(n)[2:].rstrip("L")
if len(s) % 2 != 0:
s = "0" + s
return s.decode("hex") | [
"def",
"n2s",
"(",
"n",
")",
":",
"s",
"=",
"hex",
"(",
"n",
")",
"[",
"2",
":",
"]",
".",
"rstrip",
"(",
"\"L\"",
")",
"if",
"len",
"(",
"s",
")",
"%",
"2",
"!=",
"0",
":",
"s",
"=",
"\"0\"",
"+",
"s",
"return",
"s",
".",
"decode",
"("... | 18 | 13.75 |
def store(self, loc, df):
"""Store dataframe in the given location.
Store some arbitrary dataframe:
>>> data.store('my_data', df)
Now recover it from the global store.
>>> data.my_data
...
"""
path = "%s.%s" % (self._root / "processed" / loc, FILE_EXTE... | [
"def",
"store",
"(",
"self",
",",
"loc",
",",
"df",
")",
":",
"path",
"=",
"\"%s.%s\"",
"%",
"(",
"self",
".",
"_root",
"/",
"\"processed\"",
"/",
"loc",
",",
"FILE_EXTENSION",
")",
"WRITE_DF",
"(",
"df",
",",
"path",
",",
"*",
"*",
"WRITE_DF_OPTS",
... | 25.733333 | 18.4 |
def authenticated(func):
"""
Decorator to check if Smappee's access token has expired.
If it has, use the refresh token to request a new access token
"""
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if self.refresh_token is not None and \
self.token_expira... | [
"def",
"authenticated",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"if",
"self",
".",
"refresh_token",
"is",
"not",
"None",
"an... | 33.307692 | 13.307692 |
async def handle_json_response(responses):
"""
get the json data response
:param responses: the json response
:return the json data without 'root' node
"""
json_data = {}
if responses.status != 200:
err_msg = HttpProcessingError(code=responses.status,
... | [
"async",
"def",
"handle_json_response",
"(",
"responses",
")",
":",
"json_data",
"=",
"{",
"}",
"if",
"responses",
".",
"status",
"!=",
"200",
":",
"err_msg",
"=",
"HttpProcessingError",
"(",
"code",
"=",
"responses",
".",
"status",
",",
"message",
"=",
"a... | 43.090909 | 15.909091 |
def curve(self):
"""Curve of the super helix."""
return HelicalCurve.pitch_and_radius(
self.major_pitch, self.major_radius,
handedness=self.major_handedness) | [
"def",
"curve",
"(",
"self",
")",
":",
"return",
"HelicalCurve",
".",
"pitch_and_radius",
"(",
"self",
".",
"major_pitch",
",",
"self",
".",
"major_radius",
",",
"handedness",
"=",
"self",
".",
"major_handedness",
")"
] | 38.6 | 8.4 |
def start_service(addr, n):
""" Start a service """
s = Subscriber(addr)
s.socket.set_string_option(nanomsg.SUB, nanomsg.SUB_SUBSCRIBE, 'test')
started = time.time()
for _ in range(n):
msg = s.socket.recv()
s.socket.close()
duration = time.time() - started
print('Raw SUB servi... | [
"def",
"start_service",
"(",
"addr",
",",
"n",
")",
":",
"s",
"=",
"Subscriber",
"(",
"addr",
")",
"s",
".",
"socket",
".",
"set_string_option",
"(",
"nanomsg",
".",
"SUB",
",",
"nanomsg",
".",
"SUB_SUBSCRIBE",
",",
"'test'",
")",
"started",
"=",
"time... | 24.133333 | 19.533333 |
def get_cursor(cls, cursor_type=_CursorType.PLAIN) -> Cursor:
"""
Yields:
new client-side cursor from existing db connection pool
"""
_cur = None
if cls._use_pool:
_connection_source = yield from cls.get_pool()
else:
_connection_source ... | [
"def",
"get_cursor",
"(",
"cls",
",",
"cursor_type",
"=",
"_CursorType",
".",
"PLAIN",
")",
"->",
"Cursor",
":",
"_cur",
"=",
"None",
"if",
"cls",
".",
"_use_pool",
":",
"_connection_source",
"=",
"yield",
"from",
"cls",
".",
"get_pool",
"(",
")",
"else"... | 40.227273 | 24.681818 |
def get_segmentation(X, rank, R, rank_labels, R_labels, niter=300,
bound_idxs=None, in_labels=None):
"""
Gets the segmentation (boundaries and labels) from the factorization
matrices.
Parameters
----------
X: np.array()
Features matrix (e.g. chromagram)
rank: in... | [
"def",
"get_segmentation",
"(",
"X",
",",
"rank",
",",
"R",
",",
"rank_labels",
",",
"R_labels",
",",
"niter",
"=",
"300",
",",
"bound_idxs",
"=",
"None",
",",
"in_labels",
"=",
"None",
")",
":",
"#import pylab as plt",
"#plt.imshow(X, interpolation=\"nearest\",... | 29.811594 | 20.681159 |
def process(*args, **kwargs):
"""Runs the decorated function in a concurrent process,
taking care of the result and error management.
Decorated functions will return a concurrent.futures.Future object
once called.
The timeout parameter will set a maximum execution time
for the decorated functi... | [
"def",
"process",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"get",
"(",
"'timeout'",
")",
"# decorator without parameters",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"len",
"(",
"kwargs",
")",
"==",
"0... | 36.115385 | 21.884615 |
def shot_taskfile_sel_changed(self, tf):
"""Callback for when the version selection has changed
:param tf: the selected taskfileinfo
:type tf: :class:`TaskFileInfo` | None
:returns: None
:rtype: None
:raises: None
"""
self.shot_open_pb.setEnabled(bool(tf)... | [
"def",
"shot_taskfile_sel_changed",
"(",
"self",
",",
"tf",
")",
":",
"self",
".",
"shot_open_pb",
".",
"setEnabled",
"(",
"bool",
"(",
"tf",
")",
")",
"# only allow new, if the releasetype is work",
"# only allow new, if there is a shot. if there is a shot, there should alwa... | 47.588235 | 19.411765 |
def get_dev_run_config(devid, auth, url):
"""
function takes the devId of a specific device and issues a RESTFUL call to get the most current running config
file as known by the HP IMC Base Platform ICC module for the target device.
:param devid: int or str value of the target device
:return: str w... | [
"def",
"get_dev_run_config",
"(",
"devid",
",",
"auth",
",",
"url",
")",
":",
"# checks to see if the imc credentials are already available",
"get_dev_run_url",
"=",
"\"/imcrs/icc/deviceCfg/\"",
"+",
"str",
"(",
"devid",
")",
"+",
"\"/currentRun\"",
"f_url",
"=",
"url",... | 52.041667 | 25.208333 |
def search_weekday(weekday, jd, direction, offset):
'''Determine the Julian date for the next or previous weekday'''
return weekday_before(weekday, jd + (direction * offset)) | [
"def",
"search_weekday",
"(",
"weekday",
",",
"jd",
",",
"direction",
",",
"offset",
")",
":",
"return",
"weekday_before",
"(",
"weekday",
",",
"jd",
"+",
"(",
"direction",
"*",
"offset",
")",
")"
] | 60 | 20 |
def add_parameter(self, parameter):
"""Adds the specified parameter value to the list."""
if parameter.name.lower() not in self.paramorder:
self.paramorder.append(parameter.name.lower())
self._parameters[parameter.name.lower()] = parameter | [
"def",
"add_parameter",
"(",
"self",
",",
"parameter",
")",
":",
"if",
"parameter",
".",
"name",
".",
"lower",
"(",
")",
"not",
"in",
"self",
".",
"paramorder",
":",
"self",
".",
"paramorder",
".",
"append",
"(",
"parameter",
".",
"name",
".",
"lower",... | 54.2 | 12 |
def removeNode(self, node):
"""
Remove the given node from the graph if it exists
"""
ident = self.getIdent(node)
if ident is not None:
self.graph.hide_node(ident) | [
"def",
"removeNode",
"(",
"self",
",",
"node",
")",
":",
"ident",
"=",
"self",
".",
"getIdent",
"(",
"node",
")",
"if",
"ident",
"is",
"not",
"None",
":",
"self",
".",
"graph",
".",
"hide_node",
"(",
"ident",
")"
] | 29.857143 | 6.714286 |
def _init_unhandled(l,inited_matrix):
'''
from elist.elist import *
from elist.jprint import pobj
l = [1,[4],2,[3,[5,6]]]
desc_matrix = init_desc_matrix(l)
unhandled = _init_unhandled(l,desc_matrix)
unhandled_data = unhandled['data']
unhandled_desc = unhandled... | [
"def",
"_init_unhandled",
"(",
"l",
",",
"inited_matrix",
")",
":",
"root_desc",
"=",
"inited_matrix",
"[",
"0",
"]",
"[",
"0",
"]",
"unhandled",
"=",
"{",
"'data'",
":",
"[",
"]",
",",
"'desc'",
":",
"[",
"]",
"}",
"length",
"=",
"l",
".",
"__len_... | 34.072727 | 12.836364 |
def get_related_node(self, node, relation):
"""Looks for an edge from node to some other node, such that the edge
is annotated with the given relation. If there exists such an edge,
returns the name of the node it points to. Otherwise, returns None."""
G = self.G
for edge in G.ed... | [
"def",
"get_related_node",
"(",
"self",
",",
"node",
",",
"relation",
")",
":",
"G",
"=",
"self",
".",
"G",
"for",
"edge",
"in",
"G",
".",
"edges",
"(",
"node",
")",
":",
"to",
"=",
"edge",
"[",
"1",
"]",
"to_relation",
"=",
"G",
".",
"edges",
... | 40.583333 | 14.5 |
def strip_cols(self):
"""
Remove leading and trailing white spaces in columns names
:example: ``ds.strip_cols()``
"""
cols = {}
skipped = []
for col in self.df.columns.values:
try:
cols[col] = col.strip()
except Exception:
... | [
"def",
"strip_cols",
"(",
"self",
")",
":",
"cols",
"=",
"{",
"}",
"skipped",
"=",
"[",
"]",
"for",
"col",
"in",
"self",
".",
"df",
".",
"columns",
".",
"values",
":",
"try",
":",
"cols",
"[",
"col",
"]",
"=",
"col",
".",
"strip",
"(",
")",
"... | 32.444444 | 12.666667 |
def prepare_data(fm, max_back, dur_cap=700):
'''
Computes angle and length differences up to given order and deletes
suspiciously long fixations.
Input
fm: Fixmat
Fixmat for which to comput angle and length differences
max_back: Int
Computes delta angle and ampli... | [
"def",
"prepare_data",
"(",
"fm",
",",
"max_back",
",",
"dur_cap",
"=",
"700",
")",
":",
"durations",
"=",
"np",
".",
"roll",
"(",
"fm",
".",
"end",
"-",
"fm",
".",
"start",
",",
"1",
")",
".",
"astype",
"(",
"float",
")",
"angles",
",",
"lengths... | 35.352941 | 20.176471 |
def get_object(self, name):
"""Retrieve an object by a dotted name relative to the model."""
parts = name.split(".")
space = self.spaces[parts.pop(0)]
if parts:
return space.get_object(".".join(parts))
else:
return space | [
"def",
"get_object",
"(",
"self",
",",
"name",
")",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"\".\"",
")",
"space",
"=",
"self",
".",
"spaces",
"[",
"parts",
".",
"pop",
"(",
"0",
")",
"]",
"if",
"parts",
":",
"return",
"space",
".",
"get_ob... | 34.625 | 12.625 |
def malloc(self, dwSize, lpAddress = None):
"""
Allocates memory into the address space of the process.
@see: L{free}
@type dwSize: int
@param dwSize: Number of bytes to allocate.
@type lpAddress: int
@param lpAddress: (Optional)
Desired address f... | [
"def",
"malloc",
"(",
"self",
",",
"dwSize",
",",
"lpAddress",
"=",
"None",
")",
":",
"hProcess",
"=",
"self",
".",
"get_handle",
"(",
"win32",
".",
"PROCESS_VM_OPERATION",
")",
"return",
"win32",
".",
"VirtualAllocEx",
"(",
"hProcess",
",",
"lpAddress",
"... | 32.136364 | 21.227273 |
def connect(self, host, port):
'''Connect to the provided host, port'''
conn = connection.Connection(host, port,
reconnection_backoff=self._reconnection_backoff,
auth_secret=self._auth_secret,
timeout=self._connect_timeout,
**self._identify_options)
... | [
"def",
"connect",
"(",
"self",
",",
"host",
",",
"port",
")",
":",
"conn",
"=",
"connection",
".",
"Connection",
"(",
"host",
",",
"port",
",",
"reconnection_backoff",
"=",
"self",
".",
"_reconnection_backoff",
",",
"auth_secret",
"=",
"self",
".",
"_auth_... | 36.636364 | 10.636364 |
def run(self, view, submitters, commenters):
"""Run stats and return the created Submission."""
logger.info('Analyzing subreddit: {}'.format(self.subreddit))
if view in TOP_VALUES:
callback = self.fetch_top_submissions
else:
callback = self.fetch_recent_submissio... | [
"def",
"run",
"(",
"self",
",",
"view",
",",
"submitters",
",",
"commenters",
")",
":",
"logger",
".",
"info",
"(",
"'Analyzing subreddit: {}'",
".",
"format",
"(",
"self",
".",
"subreddit",
")",
")",
"if",
"view",
"in",
"TOP_VALUES",
":",
"callback",
"=... | 35 | 18.75 |
def insert_many(self, doc_or_docs, **kwargs):
"""Insert method
"""
check = kwargs.pop('check', True)
if check is True:
for i in doc_or_docs:
i = self._valid_record(i)
return self.__collect.insert_many(doc_or_docs, **kwargs) | [
"def",
"insert_many",
"(",
"self",
",",
"doc_or_docs",
",",
"*",
"*",
"kwargs",
")",
":",
"check",
"=",
"kwargs",
".",
"pop",
"(",
"'check'",
",",
"True",
")",
"if",
"check",
"is",
"True",
":",
"for",
"i",
"in",
"doc_or_docs",
":",
"i",
"=",
"self"... | 31.555556 | 10.333333 |
def _escape(self, text):
"""Escape text according to self.escape"""
ret = EMPTYSTRING if text is None else str(text)
if self.escape:
return html_escape(ret)
else:
return ret | [
"def",
"_escape",
"(",
"self",
",",
"text",
")",
":",
"ret",
"=",
"EMPTYSTRING",
"if",
"text",
"is",
"None",
"else",
"str",
"(",
"text",
")",
"if",
"self",
".",
"escape",
":",
"return",
"html_escape",
"(",
"ret",
")",
"else",
":",
"return",
"ret"
] | 31.857143 | 14.142857 |
def _parse_properties(response, result_class):
'''
Extracts out resource properties and metadata information.
Ignores the standard http headers.
'''
if response is None or response.headers is None:
return None
props = result_class()
for key, value in response.headers.items():
... | [
"def",
"_parse_properties",
"(",
"response",
",",
"result_class",
")",
":",
"if",
"response",
"is",
"None",
"or",
"response",
".",
"headers",
"is",
"None",
":",
"return",
"None",
"props",
"=",
"result_class",
"(",
")",
"for",
"key",
",",
"value",
"in",
"... | 35.454545 | 23 |
def fix_e125(self, result):
"""Fix indentation undistinguish from the next logical line."""
num_indent_spaces = int(result['info'].split()[1])
line_index = result['line'] - 1
target = self.source[line_index]
spaces_to_add = num_indent_spaces - len(_get_indentation(target))
... | [
"def",
"fix_e125",
"(",
"self",
",",
"result",
")",
":",
"num_indent_spaces",
"=",
"int",
"(",
"result",
"[",
"'info'",
"]",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
"line_index",
"=",
"result",
"[",
"'line'",
"]",
"-",
"1",
"target",
"=",
"self... | 41.294118 | 19.588235 |
def is_total_slice(item, shape):
"""Determine whether `item` specifies a complete slice of array with the
given `shape`. Used to optimize __setitem__ operations on the Chunk
class."""
# N.B., assume shape is normalized
if item == Ellipsis:
return True
if item == slice(None):
re... | [
"def",
"is_total_slice",
"(",
"item",
",",
"shape",
")",
":",
"# N.B., assume shape is normalized",
"if",
"item",
"==",
"Ellipsis",
":",
"return",
"True",
"if",
"item",
"==",
"slice",
"(",
"None",
")",
":",
"return",
"True",
"if",
"isinstance",
"(",
"item",
... | 31.818182 | 17.5 |
def attach_parser(subparser):
"""Given a subparser, build and return the server parser."""
return subparser.add_parser(
'server',
help='Run a bottle based server',
parents=[
CONFIG.build_parser(
add_help=False,
# might need conflict_handler
... | [
"def",
"attach_parser",
"(",
"subparser",
")",
":",
"return",
"subparser",
".",
"add_parser",
"(",
"'server'",
",",
"help",
"=",
"'Run a bottle based server'",
",",
"parents",
"=",
"[",
"CONFIG",
".",
"build_parser",
"(",
"add_help",
"=",
"False",
",",
"# migh... | 28.083333 | 14.916667 |
def _getuie(self):
"""Return data as unsigned interleaved exponential-Golomb code.
Raises InterpretError if bitstring is not a single exponential-Golomb code.
"""
try:
value, newpos = self._readuie(0)
if value is None or newpos != self.len:
raise... | [
"def",
"_getuie",
"(",
"self",
")",
":",
"try",
":",
"value",
",",
"newpos",
"=",
"self",
".",
"_readuie",
"(",
"0",
")",
"if",
"value",
"is",
"None",
"or",
"newpos",
"!=",
"self",
".",
"len",
":",
"raise",
"ReadError",
"except",
"ReadError",
":",
... | 35.692308 | 22.307692 |
def apply(self, doc, clear, **kwargs):
"""Extract mentions from the given Document.
:param doc: A document to process.
:param clear: Whether or not to clear the existing database entries.
"""
# Reattach doc with the current session or DetachedInstanceError happens
doc =... | [
"def",
"apply",
"(",
"self",
",",
"doc",
",",
"clear",
",",
"*",
"*",
"kwargs",
")",
":",
"# Reattach doc with the current session or DetachedInstanceError happens",
"doc",
"=",
"self",
".",
"session",
".",
"merge",
"(",
"doc",
")",
"# Iterate over each mention clas... | 44.272727 | 17.431818 |
def get_queryset(self):
"""
Override :meth:``get_queryset``
"""
queryset = super(MultipleIDMixin, self).get_queryset()
if hasattr(self.request, 'query_params'):
ids = dict(self.request.query_params).get('ids[]')
else:
ids = dict(self.request.QUERY_... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"queryset",
"=",
"super",
"(",
"MultipleIDMixin",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"if",
"hasattr",
"(",
"self",
".",
"request",
",",
"'query_params'",
")",
":",
"ids",
"=",
"dict",
"(",
"se... | 35 | 14.333333 |
def _format_help(self, scope_info):
"""Return a help message for the options registered on this object.
Assumes that self._help_request is an instance of OptionsHelp.
:param scope_info: Scope of the options.
"""
scope = scope_info.scope
description = scope_info.description
show_recursive =... | [
"def",
"_format_help",
"(",
"self",
",",
"scope_info",
")",
":",
"scope",
"=",
"scope_info",
".",
"scope",
"description",
"=",
"scope_info",
".",
"description",
"show_recursive",
"=",
"self",
".",
"_help_request",
".",
"advanced",
"show_advanced",
"=",
"self",
... | 42.333333 | 16.6 |
def rank(self):
"""
Return the rank of the given hypergraph.
@rtype: int
@return: Rank of graph.
"""
max_rank = 0
for each in self.hyperedges():
if len(self.edge_links[each]) > max_rank:
max_rank = len(self.edge_links... | [
"def",
"rank",
"(",
"self",
")",
":",
"max_rank",
"=",
"0",
"for",
"each",
"in",
"self",
".",
"hyperedges",
"(",
")",
":",
"if",
"len",
"(",
"self",
".",
"edge_links",
"[",
"each",
"]",
")",
">",
"max_rank",
":",
"max_rank",
"=",
"len",
"(",
"sel... | 25.357143 | 15.357143 |
def to_etree(self):
"""
creates an etree element of a ``SaltEdge`` that mimicks a SaltXMI
<edges> element
"""
layers_attrib_val = ' '.join('//@layers.{}'.format(layer_id)
for layer_id in self.layers)
attribs = {
'{{{pre}}}... | [
"def",
"to_etree",
"(",
"self",
")",
":",
"layers_attrib_val",
"=",
"' '",
".",
"join",
"(",
"'//@layers.{}'",
".",
"format",
"(",
"layer_id",
")",
"for",
"layer_id",
"in",
"self",
".",
"layers",
")",
"attribs",
"=",
"{",
"'{{{pre}}}type'",
".",
"format",
... | 39.863636 | 18.772727 |
def PauliY(local_space, states=None):
r""" Pauli-type Y-operator
.. math::
\hat{\sigma}_x = \begin{pmatrix}
0 & -i \\
i & 0
\end{pmatrix}
on an arbitrary two-level system.
See :func:`PauliX`
"""
local_space, states = _get_pauli_args(local_space, state... | [
"def",
"PauliY",
"(",
"local_space",
",",
"states",
"=",
"None",
")",
":",
"local_space",
",",
"states",
"=",
"_get_pauli_args",
"(",
"local_space",
",",
"states",
")",
"g",
",",
"e",
"=",
"states",
"return",
"I",
"*",
"(",
"-",
"LocalSigma",
".",
"cre... | 23.052632 | 20.578947 |
def averageSequenceAccuracy(self, minOverlap, maxOverlap,
firstStat=0, lastStat=None):
"""
For each object, decide whether the TM uniquely classified it by checking
that the number of predictedActive cells are in an acceptable range.
"""
numCorrectSparsity = 0.0
num... | [
"def",
"averageSequenceAccuracy",
"(",
"self",
",",
"minOverlap",
",",
"maxOverlap",
",",
"firstStat",
"=",
"0",
",",
"lastStat",
"=",
"None",
")",
":",
"numCorrectSparsity",
"=",
"0.0",
"numCorrectClassifications",
"=",
"0.0",
"numStats",
"=",
"0.0",
"# For eac... | 39.384615 | 20.730769 |
def headloss_fric_rect(FlowRate, Width, DistCenter, Length, Nu, PipeRough, openchannel):
"""Return the major head loss due to wall shear in a rectangular channel.
This equation applies to both laminar and turbulent flows.
"""
#Checking input validity - inputs not checked here are checked by
#functi... | [
"def",
"headloss_fric_rect",
"(",
"FlowRate",
",",
"Width",
",",
"DistCenter",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
",",
"openchannel",
")",
":",
"#Checking input validity - inputs not checked here are checked by",
"#functions this function calls.",
"ut",
".",
"che... | 45.2 | 19.2 |
def load_time_data(self, RelativeChannelNo=None, SampleFreq=None, PointsToLoad=-1, NormaliseByMonitorOutput=False):
"""
Loads the time and voltage data and the wave description from the associated file.
Parameters
----------
RelativeChannelNo : int, optional
Channel... | [
"def",
"load_time_data",
"(",
"self",
",",
"RelativeChannelNo",
"=",
"None",
",",
"SampleFreq",
"=",
"None",
",",
"PointsToLoad",
"=",
"-",
"1",
",",
"NormaliseByMonitorOutput",
"=",
"False",
")",
":",
"f",
"=",
"open",
"(",
"self",
".",
"filepath",
",",
... | 57.957447 | 25.574468 |
def rm_anova2(dv=None, within=None, subject=None, data=None,
export_filename=None):
"""Two-way repeated measures ANOVA.
This is an internal function. The main call to this function should be done
by the :py:func:`pingouin.rm_anova` function.
Parameters
----------
dv : string
... | [
"def",
"rm_anova2",
"(",
"dv",
"=",
"None",
",",
"within",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"data",
"=",
"None",
",",
"export_filename",
"=",
"None",
")",
":",
"a",
",",
"b",
"=",
"within",
"# Validate the dataframe",
"_check_dataframe",
"(... | 35.170732 | 18.804878 |
def create_local_arrays_on_cube(cube, reified_arrays=None, array_stitch=None, array_factory=None):
"""
Function that creates arrays on the supplied hypercube, given the supplied
reified_arrays dictionary and array_stitch and array_factory functions.
Arguments
---------
cube : HyperCube
... | [
"def",
"create_local_arrays_on_cube",
"(",
"cube",
",",
"reified_arrays",
"=",
"None",
",",
"array_stitch",
"=",
"None",
",",
"array_factory",
"=",
"None",
")",
":",
"# Create a default array stitching method",
"if",
"array_stitch",
"is",
"None",
":",
"array_stitch",
... | 37.630435 | 23.804348 |
def clean_up(group, identifier, date):
"""Delete all of a groups local mbox, index, and state files.
:type group: str
:param group: group name
:type identifier: str
:param identifier: the identifier for the given group.
:rtype: bool
:returns: True
"""
#log.error('exception raised... | [
"def",
"clean_up",
"(",
"group",
",",
"identifier",
",",
"date",
")",
":",
"#log.error('exception raised, cleaning up files.')",
"glob_pat",
"=",
"'{g}.{d}.mbox*'",
".",
"format",
"(",
"g",
"=",
"group",
",",
"d",
"=",
"date",
")",
"for",
"f",
"in",
"glob",
... | 26.137931 | 18.551724 |
def plot_result(x_p, y_p, y_p_e, smoothed_data, smoothed_data_diff, filename=None):
''' Fit spline to the profile histogramed data, differentiate, determine MPV and plot.
Parameters
----------
x_p, y_p : array like
data points (x,y)
y_p_e : array like
error bars in y... | [
"def",
"plot_result",
"(",
"x_p",
",",
"y_p",
",",
"y_p_e",
",",
"smoothed_data",
",",
"smoothed_data_diff",
",",
"filename",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"'Plot results'",
")",
"plt",
".",
"close",
"(",
")",
"p1",
"=",
"plt",
".... | 61.233333 | 41.1 |
def convert_coordinates(self):
"""
Convert coordinate string to objects
"""
coord_list = []
# strip out "null" elements, i.e. ''. It might be possible to eliminate
# these some other way, i.e. with regex directly, but I don't know how.
# We need to copy in order ... | [
"def",
"convert_coordinates",
"(",
"self",
")",
":",
"coord_list",
"=",
"[",
"]",
"# strip out \"null\" elements, i.e. ''. It might be possible to eliminate",
"# these some other way, i.e. with regex directly, but I don't know how.",
"# We need to copy in order not to burn up the iterators"... | 52.466667 | 26.333333 |
def nativestring(val, encodings=None):
"""
Converts the inputted value to a native python string-type format.
:param val | <variant>
encodings | (<str>, ..) || None
:sa decoded
:return <unicode> || <str>
"""
# if it is already a nativ... | [
"def",
"nativestring",
"(",
"val",
",",
"encodings",
"=",
"None",
")",
":",
"# if it is already a native python string, don't do anything",
"if",
"type",
"(",
"val",
")",
"in",
"(",
"bytes_type",
",",
"unicode_type",
")",
":",
"return",
"val",
"# otherwise, attempt ... | 25 | 18.76 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.