text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _default(self, obj):
""" return a serialized version of obj or raise a TypeError
:param obj:
:return: Serialized version of obj
"""
return obj.__dict__ if isinstance(obj, JsonObj) else json.JSONDecoder().decode(obj) | [
"def",
"_default",
"(",
"self",
",",
"obj",
")",
":",
"return",
"obj",
".",
"__dict__",
"if",
"isinstance",
"(",
"obj",
",",
"JsonObj",
")",
"else",
"json",
".",
"JSONDecoder",
"(",
")",
".",
"decode",
"(",
"obj",
")"
] | 36.285714 | 18.571429 |
def verifytablecell(self, window_name, object_name, row_index,
column_index, row_text):
"""
Verify table cell value with given text
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: st... | [
"def",
"verifytablecell",
"(",
"self",
",",
"window_name",
",",
"object_name",
",",
"row_index",
",",
"column_index",
",",
"row_text",
")",
":",
"try",
":",
"value",
"=",
"getcellvalue",
"(",
"window_name",
",",
"object_name",
",",
"row_index",
",",
"column_in... | 35.964286 | 15.25 |
def _station(self) -> str:
"""Extract station name."""
return str(self.obj.SBRes.SBReq.Start.Station.HafasName.Text.pyval) | [
"def",
"_station",
"(",
"self",
")",
"->",
"str",
":",
"return",
"str",
"(",
"self",
".",
"obj",
".",
"SBRes",
".",
"SBReq",
".",
"Start",
".",
"Station",
".",
"HafasName",
".",
"Text",
".",
"pyval",
")"
] | 45.333333 | 16.333333 |
def makeDataFiles(prefix, dir):
""" Create distutils data_files structure from dir
distutil will copy all file rooted under dir into prefix, excluding
dir itself, just like 'ditto src dst' works, and unlike 'cp -r src
dst, which copy src into dst'.
Typical usage:
# install the contents of 'w... | [
"def",
"makeDataFiles",
"(",
"prefix",
",",
"dir",
")",
":",
"# Strip 'dir/' from of path before joining with prefix",
"dir",
"=",
"dir",
".",
"rstrip",
"(",
"'/'",
")",
"strip",
"=",
"len",
"(",
"dir",
")",
"+",
"1",
"found",
"=",
"[",
"]",
"os",
".",
"... | 35.035714 | 17.285714 |
def loads(data, wrapper=dict):
"""
Loads Appinfo content into a Python object.
:param data: A byte-like object with the contents of an Appinfo file.
:param wrapper: A wrapping object for key-value pairs.
:return: An Ordered Dictionary with Appinfo data.
"""
if not isinstance(data, (bytes, by... | [
"def",
"loads",
"(",
"data",
",",
"wrapper",
"=",
"dict",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"bytes",
",",
"bytearray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'can only load a bytes-like object as an Appinfo but got '",
"+",
"type"... | 44.090909 | 19.181818 |
def to_bucket(self, timestamp, steps=0):
'''
Calculate the bucket from a timestamp.
'''
dt = datetime.utcfromtimestamp( timestamp )
if steps!=0:
if self._step == 'daily':
dt = dt + timedelta(days=steps)
elif self._step == 'weekly':
dt = dt + timedelta(weeks=steps)
... | [
"def",
"to_bucket",
"(",
"self",
",",
"timestamp",
",",
"steps",
"=",
"0",
")",
":",
"dt",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"timestamp",
")",
"if",
"steps",
"!=",
"0",
":",
"if",
"self",
".",
"_step",
"==",
"'daily'",
":",
"dt",
"=",
... | 31.052632 | 14.315789 |
def folderitem(self, obj, item, index):
"""Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by... | [
"def",
"folderitem",
"(",
"self",
",",
"obj",
",",
"item",
",",
"index",
")",
":",
"# ensure we have an object and not a brain",
"obj",
"=",
"api",
".",
"get_object",
"(",
"obj",
")",
"url",
"=",
"api",
".",
"get_url",
"(",
"obj",
")",
"title",
"=",
"api... | 38.205882 | 15.985294 |
def log_difference(lx, ly):
"""Returns log(exp(lx) - exp(ly)) without leaving log space."""
# Negative log of double-precision infinity
li = -709.78271289338397
diff = ly - lx
# Make sure log-difference can succeed
if np.any(diff >= 0):
raise ValueError(
'Cannot compute log(... | [
"def",
"log_difference",
"(",
"lx",
",",
"ly",
")",
":",
"# Negative log of double-precision infinity",
"li",
"=",
"-",
"709.78271289338397",
"diff",
"=",
"ly",
"-",
"lx",
"# Make sure log-difference can succeed",
"if",
"np",
".",
"any",
"(",
"diff",
">=",
"0",
... | 35.833333 | 13.25 |
def get_activity_lookup_session_for_objective_bank(self, objective_bank_id, proxy):
"""Gets the ``OsidSession`` associated with the activity lookup service for the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
objective bank
arg: proxy (osid.... | [
"def",
"get_activity_lookup_session_for_objective_bank",
"(",
"self",
",",
"objective_bank_id",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_activity_lookup",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
"# Also include chec... | 49 | 20.615385 |
def unflatten(d, splitter='tuple', inverse=False):
"""Unflatten dict-like object.
Parameters
----------
d: dict-like object
The dict that will be unflattened.
splitter: {'tuple', 'path', function} (default: 'tuple')
The key splitting method. If a function is given, the function will... | [
"def",
"unflatten",
"(",
"d",
",",
"splitter",
"=",
"'tuple'",
",",
"inverse",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"splitter",
",",
"str",
")",
":",
"splitter",
"=",
"SPLITTER_DICT",
"[",
"splitter",
"]",
"unflattened_dict",
"=",
"{",
"}",
... | 32.4 | 19.233333 |
def _import_images(controller, path):
"""
Copy images to the images directory or delete them if they
already exists.
"""
image_dir = controller.images_path()
root = os.path.join(path, "images")
for (dirpath, dirnames, filenames) in os.walk(root):
for filename in filenames:
... | [
"def",
"_import_images",
"(",
"controller",
",",
"path",
")",
":",
"image_dir",
"=",
"controller",
".",
"images_path",
"(",
")",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"images\"",
")",
"for",
"(",
"dirpath",
",",
"dirnames",
"... | 36.785714 | 12.5 |
def shifted_mean_gauss(image, offset = None, sigma = 5, voxelspacing = None, mask = slice(None)):
r"""
The approximate mean over a small region at an offset from each voxel.
Functions like `local_mean_gauss`, but instead of computing the average over a small
patch around the current voxel, the regi... | [
"def",
"shifted_mean_gauss",
"(",
"image",
",",
"offset",
"=",
"None",
",",
"sigma",
"=",
"5",
",",
"voxelspacing",
"=",
"None",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
")",
":",
"return",
"_extract_feature",
"(",
"_extract_shifted_mean_gauss",
",",
"... | 43.028571 | 28.428571 |
def _requested_name(self, name, action=None, func=None):
"""Create a unique name for an operator or a stream.
"""
if name is not None:
if name in self._used_names:
# start at 2 for the "second" one of this name
n = 2
while True:
... | [
"def",
"_requested_name",
"(",
"self",
",",
"name",
",",
"action",
"=",
"None",
",",
"func",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"if",
"name",
"in",
"self",
".",
"_used_names",
":",
"# start at 2 for the \"second\" one of this name... | 34.888889 | 11.972222 |
def expand_output_files(value, *args, **kwargs):
'''Process output files (perhaps a pattern) to determine input files.
'''
if any(isinstance(x, dynamic) for x in args) or any(
isinstance(y, dynamic) for y in kwargs.values()):
return sos_targets(_undetermined=value)
else:
retu... | [
"def",
"expand_output_files",
"(",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"x",
",",
"dynamic",
")",
"for",
"x",
"in",
"args",
")",
"or",
"any",
"(",
"isinstance",
"(",
"y",
",",
"dynamic",... | 37.083333 | 18.083333 |
def parse_radic_file(filename, settings, selection_mode="after",
reciprocal=None):
"""Import one result file as produced by the SIP256c SIP measuring device
(Radic Research)
Full settings dictionary: ::
settings = {
'filter_skip': (integer) skip dipoles we are inte... | [
"def",
"parse_radic_file",
"(",
"filename",
",",
"settings",
",",
"selection_mode",
"=",
"\"after\"",
",",
"reciprocal",
"=",
"None",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"'latin-1'",
")",
"as",
"fid",
... | 31.70297 | 19.267327 |
def __update_rating(uid, rating):
'''
Update rating.
'''
entry = TabRating.update(
rating=rating
).where(TabRating.uid == uid)
entry.execute() | [
"def",
"__update_rating",
"(",
"uid",
",",
"rating",
")",
":",
"entry",
"=",
"TabRating",
".",
"update",
"(",
"rating",
"=",
"rating",
")",
".",
"where",
"(",
"TabRating",
".",
"uid",
"==",
"uid",
")",
"entry",
".",
"execute",
"(",
")"
] | 24.375 | 15.625 |
def build_payload(self, payload):
""" Build payload of message. """
for segment in self.segments:
segment.pack(payload, commit=self.autocommit) | [
"def",
"build_payload",
"(",
"self",
",",
"payload",
")",
":",
"for",
"segment",
"in",
"self",
".",
"segments",
":",
"segment",
".",
"pack",
"(",
"payload",
",",
"commit",
"=",
"self",
".",
"autocommit",
")"
] | 42 | 6.75 |
def get_jump_target_maps(code, opc):
"""Returns a dictionary where the key is an offset and the values are
a list of instruction offsets which can get run before that
instruction. This includes jump instructions as well as non-jump
instructions. Therefore, the keys of the dictionary are reachible
in... | [
"def",
"get_jump_target_maps",
"(",
"code",
",",
"opc",
")",
":",
"offset2prev",
"=",
"{",
"}",
"prev_offset",
"=",
"-",
"1",
"for",
"offset",
",",
"op",
",",
"arg",
"in",
"unpack_opargs_wordcode",
"(",
"code",
",",
"opc",
")",
":",
"if",
"prev_offset",
... | 40.172414 | 12.931034 |
def new_partition(self, table, **kwargs):
""" Creates new partition and returns it.
Args:
table (orm.Table):
Returns:
orm.Partition
"""
from . import Partition
# Create the basic partition record, with a sequence ID.
if isinstance(tabl... | [
"def",
"new_partition",
"(",
"self",
",",
"table",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"import",
"Partition",
"# Create the basic partition record, with a sequence ID.",
"if",
"isinstance",
"(",
"table",
",",
"string_types",
")",
":",
"table",
"=",
"... | 22.694444 | 21.305556 |
def append_message(self,
message):
"""
Appends the given message at the end of the message list and delete the oldest one (top most).
:param message: The formatted text to log.
"""
# Delete the first message of the list
if len(self.messages) > 0:
... | [
"def",
"append_message",
"(",
"self",
",",
"message",
")",
":",
"# Delete the first message of the list",
"if",
"len",
"(",
"self",
".",
"messages",
")",
">",
"0",
":",
"del",
"self",
".",
"messages",
"[",
"0",
"]",
"# Append the new message at the end",
"self",... | 30.6875 | 15.8125 |
def safeRmTree(rootPath):
"""
Deletes a tree and returns true if it was correctly deleted
"""
shutil.rmtree(rootPath, True)
return not os.path.exists(rootPath) | [
"def",
"safeRmTree",
"(",
"rootPath",
")",
":",
"shutil",
".",
"rmtree",
"(",
"rootPath",
",",
"True",
")",
"return",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"rootPath",
")"
] | 27.714286 | 12.571429 |
def ext_pillar(minion_id,
pillar,
table='pillar',
id_field=None,
field=None,
pillar_key=None):
'''
Collect minion external pillars from a RethinkDB database
Arguments:
* `table`: The RethinkDB table containing external pillar in... | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"table",
"=",
"'pillar'",
",",
"id_field",
"=",
"None",
",",
"field",
"=",
"None",
",",
"pillar_key",
"=",
"None",
")",
":",
"host",
"=",
"__opts__",
"[",
"'rethinkdb.host'",
"]",
"port",
"=",
... | 32.44186 | 21.186047 |
def read_header(self):
""" Read header and return a Python dictionary of key:value pairs
"""
self.header = {}
for key, val in self.h5['data'].attrs.items():
if six.PY3:
key = bytes(key, 'ascii')
if key == b'src_raj':
self.header[k... | [
"def",
"read_header",
"(",
"self",
")",
":",
"self",
".",
"header",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"self",
".",
"h5",
"[",
"'data'",
"]",
".",
"attrs",
".",
"items",
"(",
")",
":",
"if",
"six",
".",
"PY3",
":",
"key",
"=",
"by... | 30 | 15.882353 |
def json_paginate(self, base_url, page_number):
""" Return a dict for a JSON paginate """
data = self.page(page_number)
first_id = None
last_id = None
if data:
first_id = data[0].id
last_id = data[-1].id
return {
'meta': {
... | [
"def",
"json_paginate",
"(",
"self",
",",
"base_url",
",",
"page_number",
")",
":",
"data",
"=",
"self",
".",
"page",
"(",
"page_number",
")",
"first_id",
"=",
"None",
"last_id",
"=",
"None",
"if",
"data",
":",
"first_id",
"=",
"data",
"[",
"0",
"]",
... | 33.055556 | 11.722222 |
def decstr2int(dec_str, decimals):
'''
Returns an integer that has the value of the decimal string:
dec_str*10^decimals
Arguments:
dec_str (string) that represents a decimal number
decimals (int): number of decimals for creating the integer output
Returns:
(int)
Rais... | [
"def",
"decstr2int",
"(",
"dec_str",
",",
"decimals",
")",
":",
"if",
"not",
"isinstance",
"(",
"decimals",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"'decimals must be an integer'",
")",
"try",
":",
"dollars",
",",
"cents",
"=",
"dec_str",
".",
"sp... | 29.7 | 19.2 |
def init_widget(self):
""" Bind the on property to the checked state """
super(UiKitEditText, self).init_widget()
#: Init font properties etc...
self.init_text()
d = self.declaration
if d.placeholder:
self.set_placeholder(d.placeholder)
if d.input_ty... | [
"def",
"init_widget",
"(",
"self",
")",
":",
"super",
"(",
"UiKitEditText",
",",
"self",
")",
".",
"init_widget",
"(",
")",
"#: Init font properties etc...",
"self",
".",
"init_text",
"(",
")",
"d",
"=",
"self",
".",
"declaration",
"if",
"d",
".",
"placeho... | 33.730769 | 16.307692 |
def process_default(self, event):
""" Fallback.
"""
if self.job.LOG.isEnabledFor(logging.DEBUG):
# On debug level, we subscribe to ALL events, so they're expected in that case ;)
if self.job.config.trace_inotify:
self.job.LOG.debug("Ignored inotify event:\... | [
"def",
"process_default",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"job",
".",
"LOG",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"# On debug level, we subscribe to ALL events, so they're expected in that case ;)",
"if",
"self",
".",
... | 46.111111 | 19 |
def download_price(self, symbol: str, currency: str, agent: str) -> PriceModel:
""" Download and save price online """
price = self.__download_price(symbol, currency, agent)
self.save()
return price | [
"def",
"download_price",
"(",
"self",
",",
"symbol",
":",
"str",
",",
"currency",
":",
"str",
",",
"agent",
":",
"str",
")",
"->",
"PriceModel",
":",
"price",
"=",
"self",
".",
"__download_price",
"(",
"symbol",
",",
"currency",
",",
"agent",
")",
"sel... | 45.2 | 20.4 |
def _load(self, file_parser, section_name):
"""The current element is loaded from the configuration file,
all constraints and requirements are checked.
"""
# pylint: disable-msg=W0621
log = logging.getLogger('argtoolbox')
try:
log.debug("looking for field (sec... | [
"def",
"_load",
"(",
"self",
",",
"file_parser",
",",
"section_name",
")",
":",
"# pylint: disable-msg=W0621",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'argtoolbox'",
")",
"try",
":",
"log",
".",
"debug",
"(",
"\"looking for field (section=\"",
"+",
"secti... | 43.575 | 14.5 |
def set_file(name, source, template=None, context=None, defaults=None, **kwargs):
'''
Set debconf selections from a file or a template
.. code-block:: yaml
<state_id>:
debconf.set_file:
- source: salt://pathto/pkg.selections
<state_id>:
debconf.set_file:
... | [
"def",
"set_file",
"(",
"name",
",",
"source",
",",
"template",
"=",
"None",
",",
"context",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",... | 27.760563 | 24.464789 |
def _GetReportService(self):
"""Lazily initializes a report service client."""
if not self._report_service:
self._report_service = self._ad_manager_client.GetService(
'ReportService', self._version, self._server)
return self._report_service | [
"def",
"_GetReportService",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_report_service",
":",
"self",
".",
"_report_service",
"=",
"self",
".",
"_ad_manager_client",
".",
"GetService",
"(",
"'ReportService'",
",",
"self",
".",
"_version",
",",
"self",
... | 43.833333 | 11.333333 |
def list_bucket(self, bucket):
"""Create several files and paginate through them.
Production apps should set page_size to a practical value.
Args:
bucket: bucket.
"""
self.response.write('Listbucket result:\n')
page_size = 1
stats = gcs.listbucket(bucket + '/foo', max_keys=page_size... | [
"def",
"list_bucket",
"(",
"self",
",",
"bucket",
")",
":",
"self",
".",
"response",
".",
"write",
"(",
"'Listbucket result:\\n'",
")",
"page_size",
"=",
"1",
"stats",
"=",
"gcs",
".",
"listbucket",
"(",
"bucket",
"+",
"'/foo'",
",",
"max_keys",
"=",
"pa... | 27.130435 | 19.782609 |
def _lookup_abs(self, p, klass, create=1):
"""
Fast (?) lookup of a *normalized* absolute path.
This method is intended for use by internal lookups with
already-normalized path data. For general-purpose lookups,
use the FS.Entry(), FS.Dir() or FS.File() methods.
The ca... | [
"def",
"_lookup_abs",
"(",
"self",
",",
"p",
",",
"klass",
",",
"create",
"=",
"1",
")",
":",
"k",
"=",
"_my_normcase",
"(",
"p",
")",
"try",
":",
"result",
"=",
"self",
".",
"_lookupDict",
"[",
"k",
"]",
"except",
"KeyError",
":",
"if",
"not",
"... | 43.219512 | 21.219512 |
def get_longest_orf(orfs):
"""Find longest ORF from the given list of ORFs."""
sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]
return sorted_orf | [
"def",
"get_longest_orf",
"(",
"orfs",
")",
":",
"sorted_orf",
"=",
"sorted",
"(",
"orfs",
",",
"key",
"=",
"lambda",
"x",
":",
"len",
"(",
"x",
"[",
"'sequence'",
"]",
")",
",",
"reverse",
"=",
"True",
")",
"[",
"0",
"]",
"return",
"sorted_orf"
] | 45.5 | 18.25 |
def is_parameter(self):
"""Whether this is a function parameter."""
return (isinstance(self.scope, CodeFunction)
and self in self.scope.parameters) | [
"def",
"is_parameter",
"(",
"self",
")",
":",
"return",
"(",
"isinstance",
"(",
"self",
".",
"scope",
",",
"CodeFunction",
")",
"and",
"self",
"in",
"self",
".",
"scope",
".",
"parameters",
")"
] | 44 | 9.75 |
def getGroundResolution(self, latitude, level):
'''
returns the ground resolution for based on latitude and zoom level.
'''
latitude = self.clipValue(latitude, self.min_lat, self.max_lat);
mapSize = self.getMapDimensionsByZoomLevel(level)
return math.cos(
lati... | [
"def",
"getGroundResolution",
"(",
"self",
",",
"latitude",
",",
"level",
")",
":",
"latitude",
"=",
"self",
".",
"clipValue",
"(",
"latitude",
",",
"self",
".",
"min_lat",
",",
"self",
".",
"max_lat",
")",
"mapSize",
"=",
"self",
".",
"getMapDimensionsByZ... | 43.777778 | 24.222222 |
def _put(self, url, data={}):
"""Wrapper around request.put() to use the API prefix. Returns a JSON response."""
r = requests.put(self._api_prefix + url,
data=json.dumps(data),
headers=self.headers,
auth=self.auth,
allow_redirects=False,
)
... | [
"def",
"_put",
"(",
"self",
",",
"url",
",",
"data",
"=",
"{",
"}",
")",
":",
"r",
"=",
"requests",
".",
"put",
"(",
"self",
".",
"_api_prefix",
"+",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"headers",
"=",
"self",
... | 37.111111 | 10.222222 |
def time_correlation_by_diagonalization(P, pi, obs1, obs2=None, time=1, rdl=None):
"""
calculates time correlation. Raises P to power 'times' by diagonalization.
If rdl tuple (R, D, L) is given, it will be used for
further calculation.
"""
if rdl is None:
raise ValueError("no rdl decompo... | [
"def",
"time_correlation_by_diagonalization",
"(",
"P",
",",
"pi",
",",
"obs1",
",",
"obs2",
"=",
"None",
",",
"time",
"=",
"1",
",",
"rdl",
"=",
"None",
")",
":",
"if",
"rdl",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"no rdl decomposition\"",
")... | 33.047619 | 17.047619 |
def _get_unicode(data, force=False):
"""Try to return a text aka unicode object from the given data."""
if isinstance(data, binary_type):
return data.decode('utf-8')
elif data is None:
return ''
elif force:
if PY2:
return unicode(data)
else:
return... | [
"def",
"_get_unicode",
"(",
"data",
",",
"force",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"binary_type",
")",
":",
"return",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
"elif",
"data",
"is",
"None",
":",
"return",
"''",
"elif",
... | 26.769231 | 15.538462 |
def _import_next_layer(self, proto, length):
"""Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Returns:
* bool -- flag if extraction of next layer succeeded
... | [
"def",
"_import_next_layer",
"(",
"self",
",",
"proto",
",",
"length",
")",
":",
"if",
"self",
".",
"_exproto",
"==",
"'null'",
"and",
"self",
".",
"_exlayer",
"==",
"'None'",
":",
"from",
"pcapkit",
".",
"protocols",
".",
"raw",
"import",
"Raw",
"as",
... | 38.730769 | 20.5 |
def _findRedundantProteins(protToPeps, pepToProts, proteins=None):
"""Returns a set of proteins with redundant peptide evidence.
After removing the redundant proteins from the "protToPeps" and "pepToProts"
mapping, all remaining proteins have at least one unique peptide. The
remaining proteins are a "m... | [
"def",
"_findRedundantProteins",
"(",
"protToPeps",
",",
"pepToProts",
",",
"proteins",
"=",
"None",
")",
":",
"if",
"proteins",
"is",
"None",
":",
"proteins",
"=",
"viewkeys",
"(",
"protToPeps",
")",
"pepFrequency",
"=",
"_getValueCounts",
"(",
"pepToProts",
... | 45.783784 | 22.243243 |
def model_attr(attr_name):
"""
Creates a setter that will set the specified model attribute
to the current value.
@param attr_name: the name of an attribute belonging to the model.
@type attr_name: str
"""
def model_attr(value, context, **_params):
setattr(context["model"], attr_nam... | [
"def",
"model_attr",
"(",
"attr_name",
")",
":",
"def",
"model_attr",
"(",
"value",
",",
"context",
",",
"*",
"*",
"_params",
")",
":",
"setattr",
"(",
"context",
"[",
"\"model\"",
"]",
",",
"attr_name",
",",
"value",
")",
"return",
"_attr",
"(",
")",
... | 27.923077 | 17.923077 |
def melspectrogram(y=None, sr=22050, S=None, n_fft=2048, hop_length=512,
win_length=None, window='hann', center=True, pad_mode='reflect',
power=2.0, **kwargs):
"""Compute a mel-scaled spectrogram.
If a spectrogram input `S` is provided, then it is mapped directly onto
... | [
"def",
"melspectrogram",
"(",
"y",
"=",
"None",
",",
"sr",
"=",
"22050",
",",
"S",
"=",
"None",
",",
"n_fft",
"=",
"2048",
",",
"hop_length",
"=",
"512",
",",
"win_length",
"=",
"None",
",",
"window",
"=",
"'hann'",
",",
"center",
"=",
"True",
",",... | 33.184211 | 21.684211 |
def add_unit(unit,**kwargs):
"""
Add the unit defined into the object "unit" to the DB
If unit["project_id"] is None it means that the unit is global, otherwise is property of a project
If the unit exists emits an exception
A minimal example:
.. code-block:: python
... | [
"def",
"add_unit",
"(",
"unit",
",",
"*",
"*",
"kwargs",
")",
":",
"new_unit",
"=",
"Unit",
"(",
")",
"new_unit",
".",
"dimension_id",
"=",
"unit",
"[",
"\"dimension_id\"",
"]",
"new_unit",
".",
"name",
"=",
"unit",
"[",
"'name'",
"]",
"# Needed to unifo... | 29.042553 | 21.510638 |
async def fetch_state(self, request):
"""Fetches data from a specific address in the validator's state tree.
Request:
query:
- head: The id of the block to use as the head of the chain
- address: The 70 character address of the data to be fetched
Res... | [
"async",
"def",
"fetch_state",
"(",
"self",
",",
"request",
")",
":",
"error_traps",
"=",
"[",
"error_handlers",
".",
"InvalidAddressTrap",
",",
"error_handlers",
".",
"StateNotFoundTrap",
"]",
"address",
"=",
"request",
".",
"match_info",
".",
"get",
"(",
"'a... | 38.8125 | 19.46875 |
def die(self, password=''):
"""
Tells the IRCd to die.
Optional arguments:
* password='' - Die command password.
"""
with self.lock:
self.send('DIE :%s' % password, error_check=True) | [
"def",
"die",
"(",
"self",
",",
"password",
"=",
"''",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"send",
"(",
"'DIE :%s'",
"%",
"password",
",",
"error_check",
"=",
"True",
")"
] | 29.375 | 9.875 |
def create_atomic_observe_operations(self, states, actions, internals, terminal, reward, index):
"""
Returns the tf op to fetch when unbuffered observations are passed in.
Args:
states (any): One state (usually a value tuple) or dict of states if multiple states are expected.
... | [
"def",
"create_atomic_observe_operations",
"(",
"self",
",",
"states",
",",
"actions",
",",
"internals",
",",
"terminal",
",",
"reward",
",",
"index",
")",
":",
"# Increment episode",
"num_episodes",
"=",
"tf",
".",
"count_nonzero",
"(",
"input_tensor",
"=",
"te... | 50.74359 | 29.461538 |
def search(self,
q,
start=1,
num=10,
sortField="username",
sortOrder="asc"):
"""
The User Search operation searches for users in the portal. The
search index is updated whenever users are created, updated, or
... | [
"def",
"search",
"(",
"self",
",",
"q",
",",
"start",
"=",
"1",
",",
"num",
"=",
"10",
",",
"sortField",
"=",
"\"username\"",
",",
"sortOrder",
"=",
"\"asc\"",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"q\"",
":",
"q",
",",
"... | 43.96 | 20 |
def update_subtask(self, subtask_id, revision, title=None, completed=None):
'''
Updates the subtask with the given ID
See https://developer.wunderlist.com/documentation/endpoints/subtask for detailed parameter information
Returns:
Subtask with given ID with properties and revis... | [
"def",
"update_subtask",
"(",
"self",
",",
"subtask_id",
",",
"revision",
",",
"title",
"=",
"None",
",",
"completed",
"=",
"None",
")",
":",
"return",
"subtasks_endpoint",
".",
"update_subtask",
"(",
"self",
",",
"subtask_id",
",",
"revision",
",",
"title",... | 44.4 | 36.8 |
def machine_info():
"""Retrieve core and memory information for the current machine.
"""
import psutil
BYTES_IN_GIG = 1073741824.0
free_bytes = psutil.virtual_memory().total
return [{"memory": float("%.1f" % (free_bytes / BYTES_IN_GIG)), "cores": multiprocessing.cpu_count(),
"name":... | [
"def",
"machine_info",
"(",
")",
":",
"import",
"psutil",
"BYTES_IN_GIG",
"=",
"1073741824.0",
"free_bytes",
"=",
"psutil",
".",
"virtual_memory",
"(",
")",
".",
"total",
"return",
"[",
"{",
"\"memory\"",
":",
"float",
"(",
"\"%.1f\"",
"%",
"(",
"free_bytes"... | 42 | 15.875 |
def power_off(self, si, logger, session, vcenter_data_model, vm_uuid, resource_fullname):
"""
Power off of a vm
:param vcenter_data_model: vcenter model
:param si: Service Instance
:param logger:
:param session:
:param vcenter_data_model: vcenter_data_model
... | [
"def",
"power_off",
"(",
"self",
",",
"si",
",",
"logger",
",",
"session",
",",
"vcenter_data_model",
",",
"vm_uuid",
",",
"resource_fullname",
")",
":",
"logger",
".",
"info",
"(",
"'retrieving vm by uuid: {0}'",
".",
"format",
"(",
"vm_uuid",
")",
")",
"vm... | 48.2 | 27.5 |
def sortarai(self,datablock,s,Zdiff):
"""
sorts data block in to first_Z, first_I, etc.
"""
# print "calling sortarai()"
first_Z,first_I,zptrm_check,ptrm_check,ptrm_tail=[],[],[],[],[]
field,phi,theta="","",""
starthere=0
Treat_I,Treat_Z,Treat_PZ,Treat_PI,... | [
"def",
"sortarai",
"(",
"self",
",",
"datablock",
",",
"s",
",",
"Zdiff",
")",
":",
"# print \"calling sortarai()\"",
"first_Z",
",",
"first_I",
",",
"zptrm_check",
",",
"ptrm_check",
",",
"ptrm_tail",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
... | 45.406832 | 18.729814 |
def get_value_ddist(self, attr_name, attr_value):
"""
Returns the class value probability distribution of the given
attribute value.
"""
assert not self.tree.data.is_continuous_class, \
"Discrete distributions are only maintained for " + \
"discrete class ... | [
"def",
"get_value_ddist",
"(",
"self",
",",
"attr_name",
",",
"attr_value",
")",
":",
"assert",
"not",
"self",
".",
"tree",
".",
"data",
".",
"is_continuous_class",
",",
"\"Discrete distributions are only maintained for \"",
"+",
"\"discrete class types.\"",
"ddist",
... | 41.769231 | 15.153846 |
def _fit_stages(self, X, y, y_pred, sample_weight, random_state,
begin_at_stage=0, monitor=None, X_idx_sorted=None):
"""Iteratively fits the stages.
For each stage it computes the progress (OOB, train score)
and delegates to ``_fit_stage``.
Returns the number of stag... | [
"def",
"_fit_stages",
"(",
"self",
",",
"X",
",",
"y",
",",
"y_pred",
",",
"sample_weight",
",",
"random_state",
",",
"begin_at_stage",
"=",
"0",
",",
"monitor",
"=",
"None",
",",
"X_idx_sorted",
"=",
"None",
")",
":",
"n_samples",
"=",
"X",
".",
"shap... | 39.42029 | 21.536232 |
def images(self):
"""Generate images for all the datasets from the scene."""
for ds_id, projectable in self.datasets.items():
if ds_id in self.wishlist:
yield projectable.to_image() | [
"def",
"images",
"(",
"self",
")",
":",
"for",
"ds_id",
",",
"projectable",
"in",
"self",
".",
"datasets",
".",
"items",
"(",
")",
":",
"if",
"ds_id",
"in",
"self",
".",
"wishlist",
":",
"yield",
"projectable",
".",
"to_image",
"(",
")"
] | 44.2 | 9 |
def bandit(self, choice_rewards):
"""
Multi-armed bandit method which chooses the arm for which the upper
confidence bound (UCB) of expected reward is greatest.
If there are multiple arms with the same UCB1 index, then one is chosen
at random.
An explanation is here:
... | [
"def",
"bandit",
"(",
"self",
",",
"choice_rewards",
")",
":",
"# count the larger of 1 and the total number of arm pulls",
"total_pulls",
"=",
"max",
"(",
"1",
",",
"sum",
"(",
"len",
"(",
"r",
")",
"for",
"r",
"in",
"choice_rewards",
".",
"values",
"(",
")",... | 38.521739 | 23.043478 |
def response_voice(self, media_id):
"""
将 media_id 所代表的语音组装为符合微信服务器要求的响应数据
:param media_id: 语音的 MediaID
:return: 符合微信服务器要求的 XML 响应数据
"""
self._check_parse()
response = VoiceReply(message=self.__message, media_id=media_id).render()
return self._encrypt_res... | [
"def",
"response_voice",
"(",
"self",
",",
"media_id",
")",
":",
"self",
".",
"_check_parse",
"(",
")",
"response",
"=",
"VoiceReply",
"(",
"message",
"=",
"self",
".",
"__message",
",",
"media_id",
"=",
"media_id",
")",
".",
"render",
"(",
")",
"return"... | 32.6 | 11.6 |
def get_all_function_definitions(base_most_function):
"""
Obtains all function definitions given a base-most function. This includes the provided function, plus any
overrides of that function.
Returns:
(list): Returns any the provided function and any overriding functions de... | [
"def",
"get_all_function_definitions",
"(",
"base_most_function",
")",
":",
"# We assume the provided function is the base-most function, so we check all derived contracts",
"# for a redefinition",
"return",
"[",
"base_most_function",
"]",
"+",
"[",
"function",
"for",
"derived_contra... | 58.384615 | 35.307692 |
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
log.debug('sdstack_etcd returner <save_load> called jid: %s', jid)
write_profile = __opts__.get('etcd.returner_write_profile')
client, path = _get_conn(__opts__, write_profile)
if write_profile:
ttl = ... | [
"def",
"save_load",
"(",
"jid",
",",
"load",
",",
"minions",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'sdstack_etcd returner <save_load> called jid: %s'",
",",
"jid",
")",
"write_profile",
"=",
"__opts__",
".",
"get",
"(",
"'etcd.returner_write_profile'",... | 32.9375 | 19.0625 |
def _prep_grabix_indexes(in_files, data):
"""Parallel preparation of grabix indexes for files.
"""
# if we have gzipped but not bgzipped, add a fake index for CWL support
# Also skips bgzip indexing if we don't need alignment splitting
if _ready_gzip_fastq(in_files, data) and (not _ready_gzip_fastq(... | [
"def",
"_prep_grabix_indexes",
"(",
"in_files",
",",
"data",
")",
":",
"# if we have gzipped but not bgzipped, add a fake index for CWL support",
"# Also skips bgzip indexing if we don't need alignment splitting",
"if",
"_ready_gzip_fastq",
"(",
"in_files",
",",
"data",
")",
"and",... | 59.0625 | 28.125 |
def propogate_candidates(self, node_ip):
"""
Used to progate new candidates to passive simultaneous
nodes.
"""
if node_ip in self.factory.candidates:
old_candidates = []
for candidate in self.factory.candidates[node_ip]:
# Not con... | [
"def",
"propogate_candidates",
"(",
"self",
",",
"node_ip",
")",
":",
"if",
"node_ip",
"in",
"self",
".",
"factory",
".",
"candidates",
":",
"old_candidates",
"=",
"[",
"]",
"for",
"candidate",
"in",
"self",
".",
"factory",
".",
"candidates",
"[",
"node_ip... | 36.615385 | 15.923077 |
def bcdc_package_show(package):
"""Query DataBC Catalogue API about given package
"""
params = {"id": package}
r = requests.get(bcdata.BCDC_API_URL + "package_show", params=params)
if r.status_code != 200:
raise ValueError("{d} is not present in DataBC API list".format(d=package))
return... | [
"def",
"bcdc_package_show",
"(",
"package",
")",
":",
"params",
"=",
"{",
"\"id\"",
":",
"package",
"}",
"r",
"=",
"requests",
".",
"get",
"(",
"bcdata",
".",
"BCDC_API_URL",
"+",
"\"package_show\"",
",",
"params",
"=",
"params",
")",
"if",
"r",
".",
"... | 41.5 | 15 |
def motion_commanded(self):
""" Whether motion is commanded or not.
``bool``
Can't be set.
Notes
-----
It is the value of the first bit of the 'TAS' command.
"""
rsp = self.driver.send_command('TAS', immediate=True)
if self.driver.command_error... | [
"def",
"motion_commanded",
"(",
"self",
")",
":",
"rsp",
"=",
"self",
".",
"driver",
".",
"send_command",
"(",
"'TAS'",
",",
"immediate",
"=",
"True",
")",
"if",
"self",
".",
"driver",
".",
"command_error",
"(",
"rsp",
")",
"or",
"len",
"(",
"rsp",
"... | 25.277778 | 21.277778 |
def matched(self, key, regex, ignore_case=False, multi_line=False):
"""
增加查询条件,限制查询结果对象指定字段满足指定的正则表达式。
:param key: 查询条件字段名
:param regex: 查询正则表达式
:param ignore_case: 查询是否忽略大小写,默认不忽略
:param multi_line: 查询是否匹配多行,默认不匹配
:rtype: Query
"""
if not isinsta... | [
"def",
"matched",
"(",
"self",
",",
"key",
",",
"regex",
",",
"ignore_case",
"=",
"False",
",",
"multi_line",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"regex",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"'match... | 32.142857 | 14.142857 |
def execute(self):
"""
Execute the task.
The sync map produced will be stored inside the task object.
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if there is a problem with the input parameters
:raises: :class:`~aeneas.executetask.ExecuteTaskExecutionError`: if ... | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Executing task...\"",
")",
"# check that we have the AudioFile object",
"if",
"self",
".",
"task",
".",
"audio_file",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The task does not seem t... | 52.428571 | 33.44898 |
def _update_priority(self, task, prio, worker):
"""
Update priority of the given task.
Priority can only be increased.
If the task doesn't exist, a placeholder task is created to preserve priority when the task is later scheduled.
"""
task.priority = prio = max(prio, tas... | [
"def",
"_update_priority",
"(",
"self",
",",
"task",
",",
"prio",
",",
"worker",
")",
":",
"task",
".",
"priority",
"=",
"prio",
"=",
"max",
"(",
"prio",
",",
"task",
".",
"priority",
")",
"for",
"dep",
"in",
"task",
".",
"deps",
"or",
"[",
"]",
... | 42.083333 | 14.583333 |
def difference(self, other):
"""
Summarise the differences between this node and the other node.
:param other: The other node
:return: A tuple containing the diff, the counts of the diff, and whether this plate is a sub-plate of the other
:type other: Node
"""
di... | [
"def",
"difference",
"(",
"self",
",",
"other",
")",
":",
"diff",
"=",
"(",
"tuple",
"(",
"set",
"(",
"self",
".",
"plates",
")",
"-",
"set",
"(",
"other",
".",
"plates",
")",
")",
",",
"tuple",
"(",
"set",
"(",
"other",
".",
"plates",
")",
"-"... | 52.333333 | 28.066667 |
def delete(self, force=False):
"""Delete a record.
If `force` is ``False``, the record is soft-deleted: record data will
be deleted but the record identifier and the history of the record will
be kept. This ensures that the same record identifier cannot be used
twice, and that y... | [
"def",
"delete",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"model",
"is",
"None",
":",
"raise",
"MissingModelError",
"(",
")",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"before_record_delete",
".",
"s... | 35.902439 | 21.609756 |
def try_lock(self, key, lease_time=-1, timeout=-1):
"""
Tries to acquire the lock for the specified key. When the lock is not available,
* If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately.
* If a timeout is provided, the current threa... | [
"def",
"try_lock",
"(",
"self",
",",
"key",
",",
"lease_time",
"=",
"-",
"1",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"check_not_none",
"(",
"key",
",",
"\"key can't be None\"",
")",
"key_data",
"=",
"self",
".",
"_to_data",
"(",
"key",
")",
"return",... | 60.73913 | 33.956522 |
def glyph_path(self, glyphs):
"""Adds closed paths for the glyphs to the current path.
The generated path if filled,
achieves an effect similar to that of :meth:`show_glyphs`.
:param glyphs:
The glyphs to show.
See :meth:`show_text_glyphs` for the data structure.... | [
"def",
"glyph_path",
"(",
"self",
",",
"glyphs",
")",
":",
"glyphs",
"=",
"ffi",
".",
"new",
"(",
"'cairo_glyph_t[]'",
",",
"glyphs",
")",
"cairo",
".",
"cairo_glyph_path",
"(",
"self",
".",
"_pointer",
",",
"glyphs",
",",
"len",
"(",
"glyphs",
")",
")... | 36.076923 | 16.923077 |
def waitforcard(self):
"""Wait for card insertion and returns a card service."""
AbstractCardRequest.waitforcard(self)
cardfound = False
# for non infinite timeout, a timer will signal
# the end of the time-out by setting the evt event
evt = threading.Event()
if ... | [
"def",
"waitforcard",
"(",
"self",
")",
":",
"AbstractCardRequest",
".",
"waitforcard",
"(",
"self",
")",
"cardfound",
"=",
"False",
"# for non infinite timeout, a timer will signal",
"# the end of the time-out by setting the evt event",
"evt",
"=",
"threading",
".",
"Event... | 40.427632 | 18.052632 |
def get_op_version(name):
'''
.. versionadded:: 2019.2.0
Returns the glusterfs volume op-version
name
Name of the glusterfs volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.get_op_version <volume>
'''
cmd = 'volume get {0} cluster.op-version'.format(name)... | [
"def",
"get_op_version",
"(",
"name",
")",
":",
"cmd",
"=",
"'volume get {0} cluster.op-version'",
".",
"format",
"(",
"name",
")",
"root",
"=",
"_gluster_xml",
"(",
"cmd",
")",
"if",
"not",
"_gluster_ok",
"(",
"root",
")",
":",
"return",
"False",
",",
"ro... | 22.575758 | 20.69697 |
def args(self, *args, **kwargs):
"""
Creates a ArgumentsExpectationRule and adds it to the expectation
"""
self._any_args = False
self._arguments_rule.set_args(*args, **kwargs)
return self | [
"def",
"args",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_any_args",
"=",
"False",
"self",
".",
"_arguments_rule",
".",
"set_args",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self"
] | 32.857143 | 12.285714 |
def X(self, i, j=slice(None, None, None)):
'''
Computes the design matrix at the given *PLD* order and the given
indices. The columns are the *PLD* vectors for the target at the
corresponding order, computed as the product of the fractional pixel
flux of all sets of :py:obj:`n` p... | [
"def",
"X",
"(",
"self",
",",
"i",
",",
"j",
"=",
"slice",
"(",
"None",
",",
"None",
",",
"None",
")",
")",
":",
"X1",
"=",
"self",
".",
"fpix",
"[",
"j",
"]",
"/",
"self",
".",
"norm",
"[",
"j",
"]",
".",
"reshape",
"(",
"-",
"1",
",",
... | 38.625 | 26 |
def get_group(self, name, user_name=None):
"""
Get information on the given group or whether or not a user is a member
of the group.
Args:
name (string): Name of group to query.
user_name (optional[string]): Supply None if not interested in
determinin... | [
"def",
"get_group",
"(",
"self",
",",
"name",
",",
"user_name",
"=",
"None",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"return",
"self",
".",
"project_service",
".",
"get_group",
"(",
"name",
",",
... | 35.157895 | 21.578947 |
def read_touchstone(fname):
r"""
Read a `Touchstone <https://ibis.org/connector/touchstone_spec11.pdf>`_ file.
According to the specification a data line can have at most values for four
complex parameters (plus potentially the frequency point), however this
function is able to process malformed fi... | [
"def",
"read_touchstone",
"(",
"fname",
")",
":",
"# pylint: disable=R0912,R0915,W0702",
"# Exceptions definitions",
"exnports",
"=",
"pexdoc",
".",
"exh",
".",
"addex",
"(",
"RuntimeError",
",",
"\"File *[fname]* does not have a valid extension\"",
")",
"exnoopt",
"=",
"... | 40.505 | 18.36 |
def undeploy(jboss_config, deployment):
'''
Undeploy the application from jboss instance
jboss_config
Configuration dictionary with properties specified above.
deployment
Deployment name to undeploy
CLI Example:
.. code-block:: bash
salt '*' jboss7.undeploy '{"cli_pat... | [
"def",
"undeploy",
"(",
"jboss_config",
",",
"deployment",
")",
":",
"log",
".",
"debug",
"(",
"\"======================== MODULE FUNCTION: jboss7.undeploy, deployment=%s\"",
",",
"deployment",
")",
"command",
"=",
"'undeploy {deployment} '",
".",
"format",
"(",
"deployme... | 39.888889 | 35.333333 |
def _start_again_message(self, message=None):
"""Simple method to form a start again message and give the answer in readable form."""
logging.debug("Start again message delivered: {}".format(message))
the_answer = ', '.join(
[str(d) for d in self.game.answer][:-1]
) + ', and ... | [
"def",
"_start_again_message",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"logging",
".",
"debug",
"(",
"\"Start again message delivered: {}\"",
".",
"format",
"(",
"message",
")",
")",
"the_answer",
"=",
"', '",
".",
"join",
"(",
"[",
"str",
"(",
... | 47 | 22.083333 |
def caf_to_fastq(infile, outfile, min_length=0, trim=False):
'''Convert a CAF file to fastq. Reads shorter than min_length are not output. If clipping information is in the CAF file (with a line Clipping QUAL ...) and trim=True, then trim the reads'''
caf_reader = caf.file_reader(infile)
fout = utils.open_f... | [
"def",
"caf_to_fastq",
"(",
"infile",
",",
"outfile",
",",
"min_length",
"=",
"0",
",",
"trim",
"=",
"False",
")",
":",
"caf_reader",
"=",
"caf",
".",
"file_reader",
"(",
"infile",
")",
"fout",
"=",
"utils",
".",
"open_file_write",
"(",
"outfile",
")",
... | 42.833333 | 30.722222 |
def fit_model(ts, sc=None):
"""
Fits an AR(1) + GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a AR+GARCH model as a Numpy array
Returns an ARGARCH model
"""
assert sc != None, "Missing SparkContext"
... | [
"def",
"fit_model",
"(",
"ts",
",",
"sc",
"=",
"None",
")",
":",
"assert",
"sc",
"!=",
"None",
",",
"\"Missing SparkContext\"",
"jvm",
"=",
"sc",
".",
"_jvm",
"jmodel",
"=",
"jvm",
".",
"com",
".",
"cloudera",
".",
"sparkts",
".",
"models",
".",
"ARG... | 29.0625 | 22.8125 |
def get_fit(self, TrapFreq, WidthOfPeakToFit, A_Initial=0.1e10, Gamma_Initial=400, silent=False, MakeFig=True, show_fig=True):
"""
Function that fits to a peak to the PSD to extract the
frequency, A factor and Gamma (damping) factor.
Parameters
----------
TrapFreq : flo... | [
"def",
"get_fit",
"(",
"self",
",",
"TrapFreq",
",",
"WidthOfPeakToFit",
",",
"A_Initial",
"=",
"0.1e10",
",",
"Gamma_Initial",
"=",
"400",
",",
"silent",
"=",
"False",
",",
"MakeFig",
"=",
"True",
",",
"show_fig",
"=",
"True",
")",
":",
"if",
"MakeFig",... | 40.974684 | 20.822785 |
def alpha_senders(self):
"""
Access the alpha_senders
:returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList
:rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList
"""
if self._alpha_senders is None:
self._alpha_senders = Alpha... | [
"def",
"alpha_senders",
"(",
"self",
")",
":",
"if",
"self",
".",
"_alpha_senders",
"is",
"None",
":",
"self",
".",
"_alpha_senders",
"=",
"AlphaSenderList",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]"... | 40.8 | 20.8 |
def followers(self):
"""获取关注此问题的用户
:return: 关注此问题的用户
:rtype: Author.Iterable
:问题: 要注意若执行过程中另外有人关注,可能造成重复获取到某些用户
"""
self._make_soup()
followers_url = self.url + 'followers'
for x in common_follower(followers_url, self.xsrf, self._session):
yie... | [
"def",
"followers",
"(",
"self",
")",
":",
"self",
".",
"_make_soup",
"(",
")",
"followers_url",
"=",
"self",
".",
"url",
"+",
"'followers'",
"for",
"x",
"in",
"common_follower",
"(",
"followers_url",
",",
"self",
".",
"xsrf",
",",
"self",
".",
"_session... | 28.545455 | 14.727273 |
def missing_or_other_newer(path, other_path, cwd=None):
"""
Investigate if path is non-existant or older than provided reference
path.
Parameters
==========
path: string
path to path which might be missing or too old
other_path: string
reference path
cwd: string
... | [
"def",
"missing_or_other_newer",
"(",
"path",
",",
"other_path",
",",
"cwd",
"=",
"None",
")",
":",
"cwd",
"=",
"cwd",
"or",
"'.'",
"path",
"=",
"get_abspath",
"(",
"path",
",",
"cwd",
"=",
"cwd",
")",
"other_path",
"=",
"get_abspath",
"(",
"other_path",... | 27.925926 | 20.444444 |
def unregister(self, thread):
"""
Unregisters an existing thread, so that this thread is no longer available.
This function is mainly used during plugin deactivation.
:param thread: Name of the thread
"""
if thread not in self.threads.keys():
self.log.warnin... | [
"def",
"unregister",
"(",
"self",
",",
"thread",
")",
":",
"if",
"thread",
"not",
"in",
"self",
".",
"threads",
".",
"keys",
"(",
")",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"Can not unregister thread %s\"",
"%",
"thread",
")",
"else",
":",
"d... | 36.230769 | 19.153846 |
def search(self, start=0, amount=15, order='asc', concise=False, user=True, dependencies=True, comments=True,
votes=True, filters=None):
"""
Search the LEX
:param start: Start at this result number
:param amount: Number of results to return
:param order: Ordering o... | [
"def",
"search",
"(",
"self",
",",
"start",
"=",
"0",
",",
"amount",
"=",
"15",
",",
"order",
"=",
"'asc'",
",",
"concise",
"=",
"False",
",",
"user",
"=",
"True",
",",
"dependencies",
"=",
"True",
",",
"comments",
"=",
"True",
",",
"votes",
"=",
... | 43.365854 | 24.439024 |
def process_step(self, form):
"""
Stores the validated data for `form` and cleans out validated forms
for next steps, as those might be affected by the current step. Note
that this behaviour is relied upon by the `LoginView` to prevent users
from bypassing the `TokenForm` by goin... | [
"def",
"process_step",
"(",
"self",
",",
"form",
")",
":",
"step",
"=",
"self",
".",
"steps",
".",
"current",
"# If the form is not-idempotent (cannot be validated multiple times),",
"# the cleaned data should be stored; marking the form as validated.",
"self",
".",
"storage",
... | 45.96 | 22.92 |
def load_http_response(cls, http_response):
"""
This method should return an instantiated class and set its response
to the requests.Response object.
"""
if not http_response.ok:
raise APIResponseError(http_response.text)
c = cls(http_response)
c.respo... | [
"def",
"load_http_response",
"(",
"cls",
",",
"http_response",
")",
":",
"if",
"not",
"http_response",
".",
"ok",
":",
"raise",
"APIResponseError",
"(",
"http_response",
".",
"text",
")",
"c",
"=",
"cls",
"(",
"http_response",
")",
"c",
".",
"response",
"=... | 32.076923 | 16.230769 |
def _execute_module(self, module_name=None, module_args=None, tmp=None,
task_vars=None, persist_files=False,
delete_remote_tmp=True, wrap_async=False):
"""
Collect up a module's execution environment then use it to invoke
target.run_module() or hel... | [
"def",
"_execute_module",
"(",
"self",
",",
"module_name",
"=",
"None",
",",
"module_args",
"=",
"None",
",",
"tmp",
"=",
"None",
",",
"task_vars",
"=",
"None",
",",
"persist_files",
"=",
"False",
",",
"delete_remote_tmp",
"=",
"True",
",",
"wrap_async",
"... | 39.738095 | 18.166667 |
def match_lists(pos1, pos2, tolerance=MATCH_TOLERANCE, spherical=False):
"""
Given two sets of x/y positions match the lists, uniquely.
:rtype : numpy.ma, numpy.ma
:param pos1: list of x/y positions.
:param pos2: list of x/y positions.
:param tolerance: float distance, in pixels, to consider a ... | [
"def",
"match_lists",
"(",
"pos1",
",",
"pos2",
",",
"tolerance",
"=",
"MATCH_TOLERANCE",
",",
"spherical",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"pos1",
",",
"numpy",
".",
"ndarray",
")",
"assert",
"isinstance",
"(",
"pos2",
",",
"numpy",
... | 41.649351 | 30.298701 |
def CopyFromStringTuple(self, time_elements_tuple):
"""Copies time elements from string-based time elements tuple.
Args:
time_elements_tuple (Optional[tuple[str, str, str, str, str, str]]):
time elements, contains year, month, day of month, hours, minutes and
seconds.
Raises:
... | [
"def",
"CopyFromStringTuple",
"(",
"self",
",",
"time_elements_tuple",
")",
":",
"if",
"len",
"(",
"time_elements_tuple",
")",
"<",
"6",
":",
"raise",
"ValueError",
"(",
"(",
"'Invalid time elements tuple at least 6 elements required,'",
"'got: {0:d}'",
")",
".",
"for... | 33.649123 | 19.385965 |
async def send_debug(self):
""" Sends the debug draw execution. Put this after your debug creation functions. """
await self._execute(
debug=sc_pb.RequestDebug(
debug=[
debug_pb.DebugCommand(
draw=debug_pb.DebugDraw(
... | [
"async",
"def",
"send_debug",
"(",
"self",
")",
":",
"await",
"self",
".",
"_execute",
"(",
"debug",
"=",
"sc_pb",
".",
"RequestDebug",
"(",
"debug",
"=",
"[",
"debug_pb",
".",
"DebugCommand",
"(",
"draw",
"=",
"debug_pb",
".",
"DebugDraw",
"(",
"text",
... | 42.7 | 18.65 |
def _process_info(raw_info: VideoInfo) -> VideoInfo:
"""Process raw information about the video (parse date, etc.)."""
raw_date = raw_info.date
date = datetime.strptime(raw_date, '%Y-%m-%d %H:%M') # 2018-04-05 17:00
video_info = raw_info._replace(date=date)
return video_info | [
"def",
"_process_info",
"(",
"raw_info",
":",
"VideoInfo",
")",
"->",
"VideoInfo",
":",
"raw_date",
"=",
"raw_info",
".",
"date",
"date",
"=",
"datetime",
".",
"strptime",
"(",
"raw_date",
",",
"'%Y-%m-%d %H:%M'",
")",
"# 2018-04-05 17:00",
"video_info",
"=",
... | 51.833333 | 14 |
def datasets_create_version(self, owner_slug, dataset_slug, dataset_new_version_request, **kwargs): # noqa: E501
"""Create a new dataset version # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> t... | [
"def",
"datasets_create_version",
"(",
"self",
",",
"owner_slug",
",",
"dataset_slug",
",",
"dataset_new_version_request",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
... | 57.090909 | 32.727273 |
def init_blueprint(self, blueprint, path='templates.yaml'):
"""Initialize a Flask Blueprint, similar to init_app, but without the access
to the application config.
Keyword Arguments:
blueprint {Flask Blueprint} -- Flask Blueprint instance to initialize (Default: {None})
... | [
"def",
"init_blueprint",
"(",
"self",
",",
"blueprint",
",",
"path",
"=",
"'templates.yaml'",
")",
":",
"if",
"self",
".",
"_route",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"\"route cannot be set when using blueprints!\"",
")",
"# we need to tuck our re... | 55.6 | 30.55 |
def begin(self):
"""
This method will implement the handshake of the
Bitcoin protocol. It will send the Version message,
and block until it receives a VerAck.
Once we receive the version, we'll send the verack,
and begin downloading.
"""
log.debug("handsha... | [
"def",
"begin",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"handshake (version %s)\"",
"%",
"PROTOCOL_VERSION",
")",
"version",
"=",
"Version",
"(",
")",
"version",
".",
"services",
"=",
"0",
"# can't send blocks",
"log",
".",
"debug",
"(",
"\"send V... | 37.923077 | 11.615385 |
def solve(self,problem):
"""
Solves optimization problem.
Parameters
----------
problem : Object
"""
# Local vars
norm2 = self.norm2
norminf = self.norminf
parameters = self.parameters
# Parameters
tol = param... | [
"def",
"solve",
"(",
"self",
",",
"problem",
")",
":",
"# Local vars",
"norm2",
"=",
"self",
".",
"norm2",
"norminf",
"=",
"self",
".",
"norminf",
"parameters",
"=",
"self",
".",
"parameters",
"# Parameters",
"tol",
"=",
"parameters",
"[",
"'tol'",
"]",
... | 34.981982 | 17.369369 |
def set_setting(self, setting, value):
"""
Set a specific setting value.
This will overwrite the current setting value for the specified
setting.
Args:
setting (string): The name of the setting to set (e.g.,
'certificate_path', 'hostname'). Required.... | [
"def",
"set_setting",
"(",
"self",
",",
"setting",
",",
"value",
")",
":",
"if",
"setting",
"not",
"in",
"self",
".",
"_expected_settings",
"+",
"self",
".",
"_optional_settings",
":",
"raise",
"exceptions",
".",
"ConfigurationError",
"(",
"\"Setting '{0}' is no... | 37.627907 | 13.302326 |
def get_usage(self):
"""
parses /proc/stat and calcualtes total and busy time
(more specific USER_HZ see man 5 proc for further informations )
"""
usage = {}
for cpu, timings in self.get_cpu_timings().items():
cpu_total = sum(timings)
del timings[... | [
"def",
"get_usage",
"(",
"self",
")",
":",
"usage",
"=",
"{",
"}",
"for",
"cpu",
",",
"timings",
"in",
"self",
".",
"get_cpu_timings",
"(",
")",
".",
"items",
"(",
")",
":",
"cpu_total",
"=",
"sum",
"(",
"timings",
")",
"del",
"timings",
"[",
"3",
... | 29.684211 | 18.736842 |
def remove_none_dict_values(obj):
"""
Remove None values from dict.
"""
if isinstance(obj, (list, tuple, set)):
return type(obj)(remove_none_dict_values(x) for x in obj)
elif isinstance(obj, dict):
return type(obj)((k, remove_none_dict_values(v))
for k, v in ... | [
"def",
"remove_none_dict_values",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"return",
"type",
"(",
"obj",
")",
"(",
"remove_none_dict_values",
"(",
"x",
")",
"for",
"x",
"in",
"ob... | 32.666667 | 10.833333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.