text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def encode_fetch_request(cls, payloads=(), max_wait_time=100, min_bytes=4096):
"""
Encodes a FetchRequest struct
Arguments:
payloads: list of FetchRequestPayload
max_wait_time (int, optional): ms to block waiting for min_bytes
data. Defaults to 100.
... | [
"def",
"encode_fetch_request",
"(",
"cls",
",",
"payloads",
"=",
"(",
")",
",",
"max_wait_time",
"=",
"100",
",",
"min_bytes",
"=",
"4096",
")",
":",
"return",
"kafka",
".",
"protocol",
".",
"fetch",
".",
"FetchRequest",
"[",
"0",
"]",
"(",
"replica_id",... | 37.64 | 17.32 |
def get_common_properties(root):
"""Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with common properties
"""
properties = {}
for elem in root.iterfind('co... | [
"def",
"get_common_properties",
"(",
"root",
")",
":",
"properties",
"=",
"{",
"}",
"for",
"elem",
"in",
"root",
".",
"iterfind",
"(",
"'commonProperties/property'",
")",
":",
"name",
"=",
"elem",
".",
"attrib",
"[",
"'name'",
"]",
"if",
"name",
"==",
"'... | 44.308642 | 23.938272 |
def encode(request, data):
""" Add request content data to request body, set Content-type header.
Should be overridden by subclasses if not using JSON encoding.
Args:
request (HTTPRequest): The request object.
data (dict, None): Data to be encoded.
Returns:
... | [
"def",
"encode",
"(",
"request",
",",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"request",
"request",
".",
"add_header",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
"request",
".",
"data",
"=",
"json",
".",
"dumps",
"(",
"da... | 28.157895 | 20.736842 |
def _update_weight(self, data, R, n_local_subj, local_weight_offset):
"""update local weight
Parameters
----------
data : list of 2D array, element i has shape=[n_voxel, n_tr]
Subjects' fMRI data.
R : list of 2D arrays, element i has shape=[n_voxel, n_dim]
... | [
"def",
"_update_weight",
"(",
"self",
",",
"data",
",",
"R",
",",
"n_local_subj",
",",
"local_weight_offset",
")",
":",
"for",
"s",
",",
"subj_data",
"in",
"enumerate",
"(",
"data",
")",
":",
"base",
"=",
"s",
"*",
"self",
".",
"prior_size",
"centers",
... | 35.666667 | 19.377778 |
def get_patches_ignore_regex(self):
"""Returns a string representing a regex for filtering out patches
This string is parsed from a comment in the specfile that contains the
word filter-out followed by an equal sign.
For example, a comment as such:
# patches_ignore=(regex)
... | [
"def",
"get_patches_ignore_regex",
"(",
"self",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'# *patches_ignore=([\\w *.+?[\\]|{,}\\-_]+)'",
",",
"self",
".",
"txt",
")",
"if",
"not",
"match",
":",
"return",
"None",
"regex_string",
"=",
"match",
".",
"g... | 34.043478 | 18.26087 |
def check_overlap(self, other):
"""Check overlap with another spectrum.
Also see :ref:`pysynphot-command-checko`.
This checks whether the wavelength set of the given spectrum
is defined everywhere within ``self``.
Wavelength values where throughput is zero are excluded from the ... | [
"def",
"check_overlap",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
".",
"isAnalytic",
"and",
"not",
"isinstance",
"(",
"other",
",",
"Box",
")",
":",
"# then it's defined everywhere, except for Box",
"return",
"'full'",
"swave",
"=",
"self",
".",
"wav... | 28.029851 | 20.716418 |
def release(self):
"""Release a semaphore, incrementing the internal counter by one.
When the counter is zero on entry and another thread is waiting for it
to become larger than zero again, wake up that thread.
If the number of releases exceeds the number of acquires,
raise a V... | [
"def",
"release",
"(",
"self",
")",
":",
"with",
"self",
".",
"__cond",
":",
"if",
"self",
".",
"__value",
">=",
"self",
".",
"_initial_value",
":",
"raise",
"ValueError",
"(",
"\"Semaphore released too many times\"",
")",
"self",
".",
"__value",
"+=",
"1",
... | 36 | 20.933333 |
def parse_args(argv=None):
"""Parses CLI arguments.
Args:
argv: optional list of arguments to parse. sys.argv is used by default.
Raises:
dvc.exceptions.DvcParserError: raised for argument parsing errors.
"""
parent_parser = get_parent_parser()
# Main parser
desc = "Data V... | [
"def",
"parse_args",
"(",
"argv",
"=",
"None",
")",
":",
"parent_parser",
"=",
"get_parent_parser",
"(",
")",
"# Main parser",
"desc",
"=",
"\"Data Version Control\"",
"parser",
"=",
"DvcParser",
"(",
"prog",
"=",
"\"dvc\"",
",",
"description",
"=",
"desc",
",... | 24.195652 | 22.130435 |
def scalars_impl(self, run, tag_regex_string):
"""Given a tag regex and single run, return ScalarEvents.
Args:
run: A run string.
tag_regex_string: A regular expression that captures portions of tags.
Raises:
ValueError: if the scalars plugin is not registered.
Returns:
A dict... | [
"def",
"scalars_impl",
"(",
"self",
",",
"run",
",",
"tag_regex_string",
")",
":",
"if",
"not",
"tag_regex_string",
":",
"# The user provided no regex.",
"return",
"{",
"_REGEX_VALID_PROPERTY",
":",
"False",
",",
"_TAG_TO_EVENTS_PROPERTY",
":",
"{",
"}",
",",
"}",... | 28.87931 | 21.017241 |
def sflow_collector_collector_port_number(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
sflow = ET.SubElement(config, "sflow", xmlns="urn:brocade.com:mgmt:brocade-sflow")
collector = ET.SubElement(sflow, "collector")
collector_ip_address_key = ... | [
"def",
"sflow_collector_collector_port_number",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"sflow",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"sflow\"",
",",
"xmlns",
"=",
"\"urn:b... | 52.133333 | 21.666667 |
def inject(fun: Callable) -> Callable:
"""
A decorator for injection dependencies into functions/methods, based
on their type annotations.
.. code-block:: python
class SomeClass:
@inject
def __init__(self, my_dep: DepType) -> None:
self.my_dep = my_dep
... | [
"def",
"inject",
"(",
"fun",
":",
"Callable",
")",
"->",
"Callable",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"fun",
")",
"injectables",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"for",
"name",
",",
"param",
"in",
"sig",
... | 27.439024 | 19.341463 |
def get_version() :
"returns the libdbus library version as a tuple of integers (major, minor, micro)."
major = ct.c_int()
minor = ct.c_int()
micro = ct.c_int()
dbus.dbus_get_version(ct.byref(major), ct.byref(minor), ct.byref(micro))
return \
(major.value, minor.value, micro.value) | [
"def",
"get_version",
"(",
")",
":",
"major",
"=",
"ct",
".",
"c_int",
"(",
")",
"minor",
"=",
"ct",
".",
"c_int",
"(",
")",
"micro",
"=",
"ct",
".",
"c_int",
"(",
")",
"dbus",
".",
"dbus_get_version",
"(",
"ct",
".",
"byref",
"(",
"major",
")",
... | 38.375 | 24.125 |
def write_ds9region(self, region, *args, **kwargs):
"""Create a ds9 compatible region file from the ROI.
It calls the `to_ds9` method and write the result to the region file. Only the file name is required.
All other parameters will be forwarded to the `to_ds9` method, see the documentation of... | [
"def",
"write_ds9region",
"(",
"self",
",",
"region",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lines",
"=",
"self",
".",
"to_ds9",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"with",
"open",
"(",
"region",
",",
"'w'",
")",
"as",
... | 40.2 | 20.8 |
def items(self):
"""
Returns an iterator over the named bitfields in the structure as
2-tuples of (key, value). Uses a clone so as to only read from
the underlying data once.
"""
temp = self.clone()
return [(f, getattr(temp, f)) for f in iter(self)] | [
"def",
"items",
"(",
"self",
")",
":",
"temp",
"=",
"self",
".",
"clone",
"(",
")",
"return",
"[",
"(",
"f",
",",
"getattr",
"(",
"temp",
",",
"f",
")",
")",
"for",
"f",
"in",
"iter",
"(",
"self",
")",
"]"
] | 34.111111 | 17.444444 |
def get_stack_data(self, frame, traceback, event_type):
"""Get the stack frames data at each of the hooks above (Ie. for each
line of the Python code)"""
heap_data = Heap(self.options)
stack_data = StackFrames(self.options)
stack_frames, cur_frame_ind = self.get_stack(frame, trac... | [
"def",
"get_stack_data",
"(",
"self",
",",
"frame",
",",
"traceback",
",",
"event_type",
")",
":",
"heap_data",
"=",
"Heap",
"(",
"self",
".",
"options",
")",
"stack_data",
"=",
"StackFrames",
"(",
"self",
".",
"options",
")",
"stack_frames",
",",
"cur_fra... | 39.106383 | 18.212766 |
def pipe_commands_to_file(cmds, path, extra_env=None, show_stderr=False):
"""
Executes the list of commands piping each one into the next and writing
stdout of the last process into a file at the given path.
"""
env = extend_env(extra_env) if extra_env else None
env_str = (get_env_str(extra_env)... | [
"def",
"pipe_commands_to_file",
"(",
"cmds",
",",
"path",
",",
"extra_env",
"=",
"None",
",",
"show_stderr",
"=",
"False",
")",
":",
"env",
"=",
"extend_env",
"(",
"extra_env",
")",
"if",
"extra_env",
"else",
"None",
"env_str",
"=",
"(",
"get_env_str",
"("... | 36.794118 | 19.5 |
def call(func, *args, **kwargs):
"""
:return:
a delegator function that returns a tuple (``func``, (seed tuple,)+ ``args``, ``kwargs``).
That is, seed tuple is inserted before supplied positional arguments.
By default, a thread wrapping ``func`` and all those arguments is spawned.
""... | [
"def",
"call",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"f",
"(",
"seed_tuple",
")",
":",
"return",
"func",
",",
"(",
"seed_tuple",
",",
")",
"+",
"args",
",",
"kwargs",
"return",
"f"
] | 39.6 | 22.6 |
def maxnorm_regularizer(scale=1.0):
"""Max-norm regularization returns a function that can be used to apply max-norm regularization to weights.
More about max-norm, see `wiki-max norm <https://en.wikipedia.org/wiki/Matrix_norm#Max_norm>`_.
The implementation follows `TensorFlow contrib <https://github.com/... | [
"def",
"maxnorm_regularizer",
"(",
"scale",
"=",
"1.0",
")",
":",
"if",
"isinstance",
"(",
"scale",
",",
"numbers",
".",
"Integral",
")",
":",
"raise",
"ValueError",
"(",
"'scale cannot be an integer: %s'",
"%",
"scale",
")",
"if",
"isinstance",
"(",
"scale",
... | 41.136364 | 27.886364 |
def _get_merged(self, tax_id):
"""Returns tax_id into which `tax_id` has been merged or `tax_id` of
not obsolete.
"""
cmd = """
SELECT COALESCE(
(SELECT new_tax_id FROM {merged}
WHERE old_tax_id = {x}), {x})
""".format(x=self.placeholder, merged=self.me... | [
"def",
"_get_merged",
"(",
"self",
",",
"tax_id",
")",
":",
"cmd",
"=",
"\"\"\"\n SELECT COALESCE(\n (SELECT new_tax_id FROM {merged}\n WHERE old_tax_id = {x}), {x})\n \"\"\"",
".",
"format",
"(",
"x",
"=",
"self",
".",
"placeholder",
",",
"merged... | 30.066667 | 12.333333 |
def send_bcm(bcm_socket, data):
"""
Send raw frame to a BCM socket and handle errors.
"""
try:
return bcm_socket.send(data)
except OSError as e:
base = "Couldn't send CAN BCM frame. OS Error {}: {}\n".format(e.errno, e.strerror)
if e.errno == errno.EINVAL:
raise ... | [
"def",
"send_bcm",
"(",
"bcm_socket",
",",
"data",
")",
":",
"try",
":",
"return",
"bcm_socket",
".",
"send",
"(",
"data",
")",
"except",
"OSError",
"as",
"e",
":",
"base",
"=",
"\"Couldn't send CAN BCM frame. OS Error {}: {}\\n\"",
".",
"format",
"(",
"e",
... | 32.3 | 23.5 |
def _Dhcpcd(self, interfaces, logger):
"""Use dhcpcd to activate the interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
"""
for interface in interfaces:
dhcpcd = ['/sbin/dhcpcd']
try:
... | [
"def",
"_Dhcpcd",
"(",
"self",
",",
"interfaces",
",",
"logger",
")",
":",
"for",
"interface",
"in",
"interfaces",
":",
"dhcpcd",
"=",
"[",
"'/sbin/dhcpcd'",
"]",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"dhcpcd",
"+",
"[",
"'-x'",
",",
"interfa... | 39.315789 | 16.578947 |
async def uint(self, elem, elem_type, params=None):
"""
Integer types
:param elem:
:param elem_type:
:param params:
:return:
"""
if self.writing:
return IntegerModel(elem, elem_type.WIDTH) if self.modelize else elem
else:
re... | [
"async",
"def",
"uint",
"(",
"self",
",",
"elem",
",",
"elem_type",
",",
"params",
"=",
"None",
")",
":",
"if",
"self",
".",
"writing",
":",
"return",
"IntegerModel",
"(",
"elem",
",",
"elem_type",
".",
"WIDTH",
")",
"if",
"self",
".",
"modelize",
"e... | 30 | 18 |
def save(self, full=False, force=False):
'''
Saves the current entity to Redis. Will only save changed data by
default, but you can force a full save by passing ``full=True``.
If the underlying entity was deleted and you want to re-save the entity,
you can pass ``force=True`` to... | [
"def",
"save",
"(",
"self",
",",
"full",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"# handle the pre-commit hooks",
"was_new",
"=",
"self",
".",
"_new",
"if",
"was_new",
":",
"self",
".",
"_before_insert",
"(",
")",
"else",
":",
"self",
".",
... | 33.392857 | 19.607143 |
def return_features_base(dbpath, set_object, names):
"""
Generic function which returns a list of extracted features from the database
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
names :... | [
"def",
"return_features_base",
"(",
"dbpath",
",",
"set_object",
",",
"names",
")",
":",
"engine",
"=",
"create_engine",
"(",
"'sqlite:////'",
"+",
"dbpath",
")",
"session_cl",
"=",
"sessionmaker",
"(",
"bind",
"=",
"engine",
")",
"session",
"=",
"session_cl",... | 38.764706 | 20.470588 |
def DoRarExtraction(rarArchive, targetFile, dstDir):
"""
RAR extraction with exception catching
Parameters
----------
rarArchive : RarFile object
RarFile object to extract.
targetFile : string
Target file name.
dstDir : string
Target directory.
Returns
----------
boolea... | [
"def",
"DoRarExtraction",
"(",
"rarArchive",
",",
"targetFile",
",",
"dstDir",
")",
":",
"try",
":",
"rarArchive",
".",
"extract",
"(",
"targetFile",
",",
"dstDir",
")",
"except",
"BaseException",
"as",
"ex",
":",
"goodlogging",
".",
"Log",
".",
"Info",
"(... | 20.666667 | 21.777778 |
def is_element_visible(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is visible on the page.
@Params
driver - the webdriver object (required)
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELE... | [
"def",
"is_element_visible",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
")",
":",
"try",
":",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"return",
"element",
... | 34.4 | 17.333333 |
def numericalparameters(self):
"""Numeric parameter declaration lines."""
lines = Lines()
if self.model.NUMERICAL:
lines.add(0, '@cython.final')
lines.add(0, 'cdef class NumConsts(object):')
for name in ('nmb_methods', 'nmb_stages'):
lines.add(... | [
"def",
"numericalparameters",
"(",
"self",
")",
":",
"lines",
"=",
"Lines",
"(",
")",
"if",
"self",
".",
"model",
".",
"NUMERICAL",
":",
"lines",
".",
"add",
"(",
"0",
",",
"'@cython.final'",
")",
"lines",
".",
"add",
"(",
"0",
",",
"'cdef class NumCon... | 54.65 | 19.65 |
def remove_prefix(self, id):
""" Remove a prefix from pool 'id'.
"""
if 'prefix' not in request.params:
abort(400, 'Missing prefix.')
prefix = Prefix.get(int(request.params['prefix']))
prefix.pool = None
prefix.save()
redirect(url(controller = 'pool'... | [
"def",
"remove_prefix",
"(",
"self",
",",
"id",
")",
":",
"if",
"'prefix'",
"not",
"in",
"request",
".",
"params",
":",
"abort",
"(",
"400",
",",
"'Missing prefix.'",
")",
"prefix",
"=",
"Prefix",
".",
"get",
"(",
"int",
"(",
"request",
".",
"params",
... | 30.727273 | 15.818182 |
def InitUser():
"""Initialize application user.
Retrieve existing user credentials from datastore or add new user.
Returns:
AppUser instance of the application user.
"""
result = AppUser.query(AppUser.user == users.get_current_user()).fetch()
if result:
app_user = result[0]
else:
app_user =... | [
"def",
"InitUser",
"(",
")",
":",
"result",
"=",
"AppUser",
".",
"query",
"(",
"AppUser",
".",
"user",
"==",
"users",
".",
"get_current_user",
"(",
")",
")",
".",
"fetch",
"(",
")",
"if",
"result",
":",
"app_user",
"=",
"result",
"[",
"0",
"]",
"el... | 24.611111 | 24.388889 |
def create_card(self, base_info, payee, invoice_type, detail=None):
"""
创建发票卡券模板
注意这里的对象和会员卡有类似之处,但是含义有不同。创建发票卡券模板是创建发票卡券的基础。
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1496561481_1TyO7
:param base_info:发票卡券模板基础信息
:type base_info: dict
:param payee: 收款方(开票方... | [
"def",
"create_card",
"(",
"self",
",",
"base_info",
",",
"payee",
",",
"invoice_type",
",",
"detail",
"=",
"None",
")",
":",
"return",
"self",
".",
"_post",
"(",
"'platform/createcard'",
",",
"data",
"=",
"{",
"'invoice_info'",
":",
"{",
"'base_info'",
":... | 31.923077 | 14.230769 |
def applymap(self, func, subset=None, **kwargs):
"""
Apply a function elementwise, updating the HTML
representation with the result.
Parameters
----------
func : function
``func`` should take a scalar and return a scalar
subset : IndexSlice
... | [
"def",
"applymap",
"(",
"self",
",",
"func",
",",
"subset",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_todo",
".",
"append",
"(",
"(",
"lambda",
"instance",
":",
"getattr",
"(",
"instance",
",",
"'_applymap'",
")",
",",
"(",
"fu... | 28.461538 | 19.769231 |
def _step2func(self, samples, force, ipyclient):
""" hidden wrapped function to start step 2"""
## print header
if self._headers:
print("\n Step 2: Filtering reads ")
## If no samples in this assembly then it means you skipped step1,
if not self.samples.keys():
... | [
"def",
"_step2func",
"(",
"self",
",",
"samples",
",",
"force",
",",
"ipyclient",
")",
":",
"## print header",
"if",
"self",
".",
"_headers",
":",
"print",
"(",
"\"\\n Step 2: Filtering reads \"",
")",
"## If no samples in this assembly then it means you skipped step1,",... | 35.136364 | 19.590909 |
def execute(self, lf_raw: str) -> int:
"""
Very basic model for executing friction logical forms. For now returns answer index (or
-1 if no answer can be concluded)
"""
# Remove "a:" prefixes from attributes (hack)
logical_form = re.sub(r"\(a:", r"(", lf_raw)
pars... | [
"def",
"execute",
"(",
"self",
",",
"lf_raw",
":",
"str",
")",
"->",
"int",
":",
"# Remove \"a:\" prefixes from attributes (hack)",
"logical_form",
"=",
"re",
".",
"sub",
"(",
"r\"\\(a:\"",
",",
"r\"(\"",
",",
"lf_raw",
")",
"parse",
"=",
"semparse_util",
".",... | 38.8125 | 14.1875 |
def line_to(self, x, y):
"""Adds a line to the path from the current point
to position ``(x, y)`` in user-space coordinates.
After this call the current point will be ``(x, y)``.
If there is no current point before the call to :meth:`line_to`
this method will behave as ``context... | [
"def",
"line_to",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"cairo",
".",
"cairo_line_to",
"(",
"self",
".",
"_pointer",
",",
"x",
",",
"y",
")",
"self",
".",
"_check_status",
"(",
")"
] | 36.125 | 19.875 |
def transform(function):
"""Return a processor for a style's "transform" function.
"""
def transform_fn(_, result):
if isinstance(result, Nothing):
return result
lgr.debug("Transforming %r with %r", result, function)
try:
retur... | [
"def",
"transform",
"(",
"function",
")",
":",
"def",
"transform_fn",
"(",
"_",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"Nothing",
")",
":",
"return",
"result",
"lgr",
".",
"debug",
"(",
"\"Transforming %r with %r\"",
",",
"result"... | 40 | 15.826087 |
def get_formset_class(self, form, name):
"""
Either return the formset class that was provided as argument to the
__init__ method, or build one based on the ``parent_model`` and
``model`` attributes.
"""
if self.formset_class is not None:
return self.formset_c... | [
"def",
"get_formset_class",
"(",
"self",
",",
"form",
",",
"name",
")",
":",
"if",
"self",
".",
"formset_class",
"is",
"not",
"None",
":",
"return",
"self",
".",
"formset_class",
"formset_class",
"=",
"inlineformset_factory",
"(",
"self",
".",
"get_parent_mode... | 39.846154 | 8.461538 |
def save_form(self, commit=True):
"""
This calls Django's ``ModelForm.save()``. It only takes care of
saving this actual form, and leaves the nested forms and formsets
alone.
We separate this out of the
:meth:`~django_superform.forms.SuperModelForm.save` method to make
... | [
"def",
"save_form",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"return",
"super",
"(",
"SuperModelFormMixin",
",",
"self",
")",
".",
"save",
"(",
"commit",
"=",
"commit",
")"
] | 38 | 19.454545 |
def get_visible_commands(self) -> List[str]:
"""Returns a list of commands that have not been hidden or disabled."""
commands = self.get_all_commands()
# Remove the hidden commands
for name in self.hidden_commands:
if name in commands:
commands.remove(name)
... | [
"def",
"get_visible_commands",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"commands",
"=",
"self",
".",
"get_all_commands",
"(",
")",
"# Remove the hidden commands",
"for",
"name",
"in",
"self",
".",
"hidden_commands",
":",
"if",
"name",
"in",
"co... | 32.266667 | 11.666667 |
def _check_param_limits(self, q, chiA, chiB, allow_extrap):
""" Checks that params are within allowed range of paramters.
Raises a warning if outside self.soft_param_lims limits and
raises an error if outside self.hard_param_lims.
If allow_extrap=True, skips these checks.
"""
... | [
"def",
"_check_param_limits",
"(",
"self",
",",
"q",
",",
"chiA",
",",
"chiB",
",",
"allow_extrap",
")",
":",
"if",
"q",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'Mass ratio should be >= 1.'",
")",
"chiAmag",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
... | 43.731707 | 21.536585 |
def enable(self, snmp_agent, snmp_location=None, snmp_interface=None):
"""
Enable SNMP on the engine. Specify a list of interfaces
by ID to enable only on those interfaces. Only interfaces
that have NDI's are supported.
:param str,Element snmp_agent: the SNMP agent refer... | [
"def",
"enable",
"(",
"self",
",",
"snmp_agent",
",",
"snmp_location",
"=",
"None",
",",
"snmp_interface",
"=",
"None",
")",
":",
"agent",
"=",
"element_resolver",
"(",
"snmp_agent",
")",
"snmp_interface",
"=",
"[",
"]",
"if",
"not",
"snmp_interface",
"else"... | 48.15 | 19.75 |
def split_data_cwl_items(items, default_keys=None):
"""Split a set of CWL output dictionaries into data samples and CWL items.
Handles cases where we're arrayed on multiple things, like a set of regional
VCF calls and data objects.
"""
key_lens = set([])
for data in items:
key_lens.add(... | [
"def",
"split_data_cwl_items",
"(",
"items",
",",
"default_keys",
"=",
"None",
")",
":",
"key_lens",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"data",
"in",
"items",
":",
"key_lens",
".",
"add",
"(",
"len",
"(",
"_get_all_cwlkeys",
"(",
"[",
"data",
"]",
... | 36.941176 | 15.852941 |
def deletegroup(self, group_id):
"""
Deletes an group by ID
:param group_id: id of the group to delete
:return: True if it deleted, False if it couldn't. False could happen for several reasons, but there isn't a good way of differentiating them
"""
request = requests.del... | [
"def",
"deletegroup",
"(",
"self",
",",
"group_id",
")",
":",
"request",
"=",
"requests",
".",
"delete",
"(",
"'{0}/{1}'",
".",
"format",
"(",
"self",
".",
"groups_url",
",",
"group_id",
")",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"verify",
... | 42.416667 | 24.583333 |
def _create_color_buttons(self):
"""Create color choice buttons"""
button_size = (30, 30)
button_style = wx.NO_BORDER
try:
self.linecolor_choice = \
csel.ColourSelect(self, -1, unichr(0x2500), (0, 0, 0),
size=button_size, st... | [
"def",
"_create_color_buttons",
"(",
"self",
")",
":",
"button_size",
"=",
"(",
"30",
",",
"30",
")",
"button_style",
"=",
"wx",
".",
"NO_BORDER",
"try",
":",
"self",
".",
"linecolor_choice",
"=",
"csel",
".",
"ColourSelect",
"(",
"self",
",",
"-",
"1",
... | 42.294118 | 21.205882 |
def requestedFormat(request,acceptedFormat):
"""Return the response format requested by client
Client could specify requested format using:
(options are processed in this order)
- `format` field in http request
- `Accept` header in http request
Example:
... | [
"def",
"requestedFormat",
"(",
"request",
",",
"acceptedFormat",
")",
":",
"if",
"'format'",
"in",
"request",
".",
"args",
":",
"fieldFormat",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'format'",
")",
"if",
"fieldFormat",
"not",
"in",
"acceptedFormat",
... | 41.347826 | 17.608696 |
def get_assessment_offered_mdata():
"""Return default mdata map for AssessmentOffered"""
return {
'level': {
'element_label': {
'text': 'level',
'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
... | [
"def",
"get_assessment_offered_mdata",
"(",
")",
":",
"return",
"{",
"'level'",
":",
"{",
"'element_label'",
":",
"{",
"'text'",
":",
"'level'",
",",
"'languageTypeId'",
":",
"str",
"(",
"DEFAULT_LANGUAGE_TYPE",
")",
",",
"'scriptTypeId'",
":",
"str",
"(",
"DE... | 37.031414 | 15.230366 |
def accel_move_tab_left(self, *args):
# TODO KEYBINDINGS ONLY
""" Callback to move a tab to the left """
pos = self.get_notebook().get_current_page()
if pos != 0:
self.move_tab(pos, pos - 1)
return True | [
"def",
"accel_move_tab_left",
"(",
"self",
",",
"*",
"args",
")",
":",
"# TODO KEYBINDINGS ONLY",
"pos",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"if",
"pos",
"!=",
"0",
":",
"self",
".",
"move_tab",
"(",
"pos",
",",... | 35.428571 | 9.428571 |
def satellites_configuration(self):
"""Return all the configuration data of satellites
:return: dict containing satellites data
Output looks like this ::
{'arbiter' : [{'property1':'value1' ..}, {'property2', 'value11' ..}, ..],
'scheduler': [..],
'poller': [..],
... | [
"def",
"satellites_configuration",
"(",
"self",
")",
":",
"res",
"=",
"{",
"}",
"for",
"s_type",
"in",
"[",
"'arbiter'",
",",
"'scheduler'",
",",
"'poller'",
",",
"'reactionner'",
",",
"'receiver'",
",",
"'broker'",
"]",
":",
"lst",
"=",
"[",
"]",
"res",... | 37.119048 | 17.952381 |
def erase_characters(self, count=None):
"""Erase the indicated # of characters, starting with the
character at cursor position. Character attributes are set
cursor attributes. The cursor remains in the same position.
:param int count: number of characters to erase.
.. note::
... | [
"def",
"erase_characters",
"(",
"self",
",",
"count",
"=",
"None",
")",
":",
"self",
".",
"dirty",
".",
"add",
"(",
"self",
".",
"cursor",
".",
"y",
")",
"count",
"=",
"count",
"or",
"1",
"line",
"=",
"self",
".",
"buffer",
"[",
"self",
".",
"cur... | 39.809524 | 19.52381 |
def put_events(environment, start_response, headers):
"""
Store events in backends
POST body should contain a JSON encoded version of:
{ namespace: namespace_name (optional),
events: { stream_name1 : [event1, event2, ...],
stream_name2 : [event1, event2, ...],
... }
}... | [
"def",
"put_events",
"(",
"environment",
",",
"start_response",
",",
"headers",
")",
":",
"errors",
"=",
"[",
"]",
"events_to_insert",
"=",
"defaultdict",
"(",
"list",
")",
"request_json",
"=",
"environment",
"[",
"'json'",
"]",
"namespace",
"=",
"request_json... | 33.016393 | 20.196721 |
def get_collection(self, name):
'''get a collection, if it exists, otherwise return None.
'''
from sregistry.database.models import Collection
return Collection.query.filter(Collection.name == name).first() | [
"def",
"get_collection",
"(",
"self",
",",
"name",
")",
":",
"from",
"sregistry",
".",
"database",
".",
"models",
"import",
"Collection",
"return",
"Collection",
".",
"query",
".",
"filter",
"(",
"Collection",
".",
"name",
"==",
"name",
")",
".",
"first",
... | 43.6 | 20.4 |
def reset(self):
"""Reset itself and recursively all its children."""
watchers.MATCHER.debug("Node <%s> reset", self)
self._reset()
for child in self.children:
child.node.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"watchers",
".",
"MATCHER",
".",
"debug",
"(",
"\"Node <%s> reset\"",
",",
"self",
")",
"self",
".",
"_reset",
"(",
")",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
"node",
".",
"reset",
"(... | 36.166667 | 12.166667 |
def _read_message(self):
""" Reads a message from the socket and converts it to a message. """
# first 4 bytes is Big-Endian payload length
payload_info = self._read_bytes_from_socket(4)
read_len = unpack(">I", payload_info)[0]
# now read the payload
payload = self._read... | [
"def",
"_read_message",
"(",
"self",
")",
":",
"# first 4 bytes is Big-Endian payload length",
"payload_info",
"=",
"self",
".",
"_read_bytes_from_socket",
"(",
"4",
")",
"read_len",
"=",
"unpack",
"(",
"\">I\"",
",",
"payload_info",
")",
"[",
"0",
"]",
"# now rea... | 34.714286 | 16.214286 |
def create(obj: PersistedObject, obj_type: Type[Any], arg_name: str):
"""
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param obj:
:param obj_type:
:param arg_nam... | [
"def",
"create",
"(",
"obj",
":",
"PersistedObject",
",",
"obj_type",
":",
"Type",
"[",
"Any",
"]",
",",
"arg_name",
":",
"str",
")",
":",
"return",
"MissingMandatoryAttributeFiles",
"(",
"'Multifile object '",
"+",
"str",
"(",
"obj",
")",
"+",
"' cannot be ... | 48.266667 | 33.066667 |
def _zforce(self,R,z,phi=0.,t=0.):
"""
NAME:
zforce
PURPOSE:
evaluate vertical force K_z (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
K_z (R,z)
... | [
"def",
"_zforce",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"if",
"True",
":",
"if",
"isinstance",
"(",
"R",
",",
"nu",
".",
"ndarray",
")",
":",
"if",
"not",
"isinstance",
"(",
"z",
",",
"nu",
"... | 42.676471 | 24.794118 |
def read(input_taxonomy_io):
'''Parse in a taxonomy from the given I/O.
Parameters
----------
input_taxonomy_io: io
an open io object that is iterable. This stream is neither opened
nor closed by this method
Returns
-------
A GreenGenesTa... | [
"def",
"read",
"(",
"input_taxonomy_io",
")",
":",
"tax",
"=",
"{",
"}",
"for",
"line",
"in",
"input_taxonomy_io",
":",
"if",
"len",
"(",
"line",
".",
"strip",
"(",
")",
")",
"==",
"0",
":",
"continue",
"#ignore empty lines",
"splits",
"=",
"line",
"."... | 42.457143 | 25.714286 |
def gc(ctx):
"""Runs housekeeping tasks to free up space.
For now, this only removes saved but unused (unreachable) test results.
"""
vcs = ctx.obj['vcs']
count = 0
with locking.lock(vcs, locking.Lock.tests_history):
known_signatures = set(get_committed_signatures(vcs) + get_staged_sign... | [
"def",
"gc",
"(",
"ctx",
")",
":",
"vcs",
"=",
"ctx",
".",
"obj",
"[",
"'vcs'",
"]",
"count",
"=",
"0",
"with",
"locking",
".",
"lock",
"(",
"vcs",
",",
"locking",
".",
"Lock",
".",
"tests_history",
")",
":",
"known_signatures",
"=",
"set",
"(",
... | 40 | 19.642857 |
def get_provider(self, name):
"""Allows for lazy instantiation of providers (Jinja2 templating is heavy, so only instantiate it if
necessary)."""
if name not in self.providers:
cls = self.provider_classes[name]
# instantiate the provider
self.providers[name] =... | [
"def",
"get_provider",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"providers",
":",
"cls",
"=",
"self",
".",
"provider_classes",
"[",
"name",
"]",
"# instantiate the provider",
"self",
".",
"providers",
"[",
"name",
"]",
... | 44.875 | 3.625 |
def cuts_from_bbox(mask_nii, cuts=3):
"""Finds equi-spaced cuts for presenting images"""
from nibabel.affines import apply_affine
mask_data = mask_nii.get_data() > 0.0
# First, project the number of masked voxels on each axes
ijk_counts = [
mask_data.sum(2).sum(1), # project sagittal plan... | [
"def",
"cuts_from_bbox",
"(",
"mask_nii",
",",
"cuts",
"=",
"3",
")",
":",
"from",
"nibabel",
".",
"affines",
"import",
"apply_affine",
"mask_data",
"=",
"mask_nii",
".",
"get_data",
"(",
")",
">",
"0.0",
"# First, project the number of masked voxels on each axes",
... | 44.530612 | 23.877551 |
def update_gol(self):
"""
Function that performs one step of the Game of Life
"""
updated_grid = [[self.update_cell(row, col) \
for col in range(self.get_grid_width())] \
for row in range(self.get_grid_height())]
... | [
"def",
"update_gol",
"(",
"self",
")",
":",
"updated_grid",
"=",
"[",
"[",
"self",
".",
"update_cell",
"(",
"row",
",",
"col",
")",
"for",
"col",
"in",
"range",
"(",
"self",
".",
"get_grid_width",
"(",
")",
")",
"]",
"for",
"row",
"in",
"range",
"(... | 34.9 | 17.5 |
def debug(s, *args):
"""debug(s, x1, ..., xn) logs s.format(x1, ..., xn)."""
# Get the path name and line number of the function which called us.
previous_frame = inspect.currentframe().f_back
try:
pathname, lineno, _, _, _ = inspect.getframeinfo(previous_frame)
# if path is in cwd, simp... | [
"def",
"debug",
"(",
"s",
",",
"*",
"args",
")",
":",
"# Get the path name and line number of the function which called us.",
"previous_frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"try",
":",
"pathname",
",",
"lineno",
",",
"_",
",",
"_... | 43.684211 | 12.263158 |
def U(Document, __raw__=None, **update):
"""Generate a MongoDB update document through paramater interpolation.
Arguments passed by name have their name interpreted as an optional operation prefix (defaulting to `set`, e.g.
`push`), a double-underscore separated field reference (e.g. `foo`, or `foo__bar`, or `foo_... | [
"def",
"U",
"(",
"Document",
",",
"__raw__",
"=",
"None",
",",
"*",
"*",
"update",
")",
":",
"ops",
"=",
"Update",
"(",
"__raw__",
")",
"args",
"=",
"_process_arguments",
"(",
"Document",
",",
"UPDATE_ALIASES",
",",
"{",
"}",
",",
"update",
",",
"UPD... | 31.235294 | 26.558824 |
def shutdown(self):
"""Shutdown ZAP."""
if not self.is_running():
self.logger.warn('ZAP is not running.')
return
self.logger.debug('Shutting down ZAP.')
self.zap.core.shutdown()
timeout_time = time.time() + self.timeout
while self.is_running():
... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_running",
"(",
")",
":",
"self",
".",
"logger",
".",
"warn",
"(",
"'ZAP is not running.'",
")",
"return",
"self",
".",
"logger",
".",
"debug",
"(",
"'Shutting down ZAP.'",
")",
"self... | 31.375 | 17.3125 |
def feed_fetch_force(request, id, redirect_to):
"""Forcibly fetch tweets for the feed"""
feed = Feed.objects.get(id=id)
feed.fetch(force=True)
msg = _("Fetched tweets for %s" % feed.name)
messages.success(request, msg, fail_silently=True)
return HttpResponseRedirect(redirect_to) | [
"def",
"feed_fetch_force",
"(",
"request",
",",
"id",
",",
"redirect_to",
")",
":",
"feed",
"=",
"Feed",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"id",
")",
"feed",
".",
"fetch",
"(",
"force",
"=",
"True",
")",
"msg",
"=",
"_",
"(",
"\"Fetched t... | 42.428571 | 7.571429 |
def set_max_beds(self, max_beds):
"""
The maximum number of beds.
:param max_beds:
:return:
"""
if not isinstance(max_beds, int):
raise DaftException("Maximum number of beds should be an integer.")
self._max_beds = str(max_beds)
self._query_pa... | [
"def",
"set_max_beds",
"(",
"self",
",",
"max_beds",
")",
":",
"if",
"not",
"isinstance",
"(",
"max_beds",
",",
"int",
")",
":",
"raise",
"DaftException",
"(",
"\"Maximum number of beds should be an integer.\"",
")",
"self",
".",
"_max_beds",
"=",
"str",
"(",
... | 32.636364 | 15 |
def results(self):
"""
Returns a list of tuple, ordered by similarity.
"""
d = dict()
words = [word.strip() for word in self.haystack]
if not words:
raise NoResultException('No similar word found.')
for w in words:
d[w] = Levenshtein.rati... | [
"def",
"results",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
")",
"words",
"=",
"[",
"word",
".",
"strip",
"(",
")",
"for",
"word",
"in",
"self",
".",
"haystack",
"]",
"if",
"not",
"words",
":",
"raise",
"NoResultException",
"(",
"'No similar word... | 28.571429 | 21.285714 |
def render_headers(self):
"""
Renders the headers for this request field.
"""
lines = []
sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']
for sort_key in sort_keys:
if self.headers.get(sort_key, False):
lines.append('%s:... | [
"def",
"render_headers",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"sort_keys",
"=",
"[",
"'Content-Disposition'",
",",
"'Content-Type'",
",",
"'Content-Location'",
"]",
"for",
"sort_key",
"in",
"sort_keys",
":",
"if",
"self",
".",
"headers",
".",
"get"... | 34.666667 | 19 |
def to_grayscale(img):
"""Convert PIL image to numpy grayscale array and numpy alpha array.
Args:
img (PIL.Image): PIL Image object.
Returns:
(gray, alpha): both numpy arrays.
"""
gray = numpy.asarray(ImageOps.grayscale(img)).astype(numpy.float)
imbands = img.getbands()
alpha ... | [
"def",
"to_grayscale",
"(",
"img",
")",
":",
"gray",
"=",
"numpy",
".",
"asarray",
"(",
"ImageOps",
".",
"grayscale",
"(",
"img",
")",
")",
".",
"astype",
"(",
"numpy",
".",
"float",
")",
"imbands",
"=",
"img",
".",
"getbands",
"(",
")",
"alpha",
"... | 24.941176 | 21.470588 |
def to_structure(matrix, alpha=1):
"""Compute best matching 3D genome structure from underlying input matrix
using ShRec3D-derived method from Lesne et al., 2014.
Link: https://www.ncbi.nlm.nih.gov/pubmed/25240436
The method performs two steps: first compute distance matrix by treating
contact dat... | [
"def",
"to_structure",
"(",
"matrix",
",",
"alpha",
"=",
"1",
")",
":",
"connected",
"=",
"largest_connected_component",
"(",
"matrix",
")",
"distances",
"=",
"to_distance",
"(",
"connected",
",",
"alpha",
")",
"n",
",",
"m",
"=",
"connected",
".",
"shape"... | 42.6 | 21.55 |
def format_config_for_graphql(config):
'''This recursive descent thing formats a config dict for GraphQL.'''
def _format_config_subdict(config, current_indent=0):
check.dict_param(config, 'config', key_type=str)
printer = IndentingStringIoPrinter(indent_level=2, current_indent=current_indent)
... | [
"def",
"format_config_for_graphql",
"(",
"config",
")",
":",
"def",
"_format_config_subdict",
"(",
"config",
",",
"current_indent",
"=",
"0",
")",
":",
"check",
".",
"dict_param",
"(",
"config",
",",
"'config'",
",",
"key_type",
"=",
"str",
")",
"printer",
"... | 37.80597 | 21.41791 |
def plot_reliability_diagram(confidence, labels, filepath):
"""
Takes in confidence values for predictions and correct
labels for the data, plots a reliability diagram.
:param confidence: nb_samples x nb_classes (e.g., output of softmax)
:param labels: vector of nb_samples
:param filepath: where to save the... | [
"def",
"plot_reliability_diagram",
"(",
"confidence",
",",
"labels",
",",
"filepath",
")",
":",
"assert",
"len",
"(",
"confidence",
".",
"shape",
")",
"==",
"2",
"assert",
"len",
"(",
"labels",
".",
"shape",
")",
"==",
"1",
"assert",
"confidence",
".",
"... | 35.205882 | 15.882353 |
def _WritePathInfo(self, client_id, path_info):
"""Writes a single path info record for given client."""
if client_id not in self.metadatas:
raise db.UnknownClientError(client_id)
path_record = self._GetPathRecord(client_id, path_info)
path_record.AddPathInfo(path_info)
parent_path_info = pa... | [
"def",
"_WritePathInfo",
"(",
"self",
",",
"client_id",
",",
"path_info",
")",
":",
"if",
"client_id",
"not",
"in",
"self",
".",
"metadatas",
":",
"raise",
"db",
".",
"UnknownClientError",
"(",
"client_id",
")",
"path_record",
"=",
"self",
".",
"_GetPathReco... | 40.5 | 13.333333 |
def methodReturnReceived(self, mret):
"""
Called when a method return message is received
"""
d, timeout = self._pendingCalls.get(mret.reply_serial, (None, None))
if timeout:
timeout.cancel()
if d:
del self._pendingCalls[mret.reply_serial]
... | [
"def",
"methodReturnReceived",
"(",
"self",
",",
"mret",
")",
":",
"d",
",",
"timeout",
"=",
"self",
".",
"_pendingCalls",
".",
"get",
"(",
"mret",
".",
"reply_serial",
",",
"(",
"None",
",",
"None",
")",
")",
"if",
"timeout",
":",
"timeout",
".",
"c... | 33.1 | 13.9 |
def _extract_columns(self, table_name):
''' a method to extract the column properties of an existing table '''
import re
from sqlalchemy import MetaData, VARCHAR, INTEGER, BLOB, BOOLEAN, FLOAT
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION, BIT, BYTEA
... | [
"def",
"_extract_columns",
"(",
"self",
",",
"table_name",
")",
":",
"import",
"re",
"from",
"sqlalchemy",
"import",
"MetaData",
",",
"VARCHAR",
",",
"INTEGER",
",",
"BLOB",
",",
"BOOLEAN",
",",
"FLOAT",
"from",
"sqlalchemy",
".",
"dialects",
".",
"postgresq... | 45.268293 | 18.146341 |
def verify_response_duration(self, expected=None, zero=0, threshold_percent=0,
break_in_fail=True):
"""
Verify that response duration is in bounds.
:param expected: seconds what is expected duration
:param zero: seconds if one to normalize duration befor... | [
"def",
"verify_response_duration",
"(",
"self",
",",
"expected",
"=",
"None",
",",
"zero",
"=",
"0",
",",
"threshold_percent",
"=",
"0",
",",
"break_in_fail",
"=",
"True",
")",
":",
"was",
"=",
"self",
".",
"timedelta",
"-",
"zero",
"error",
"=",
"abs",
... | 48.272727 | 18 |
def isValue(self):
"""Indicate that |ASN.1| object represents ASN.1 value.
If *isValue* is `False` then this object represents just ASN.1 schema.
If *isValue* is `True` then, in addition to its ASN.1 schema features,
this object can also be used like a Python built-in object (e.g. `int... | [
"def",
"isValue",
"(",
"self",
")",
":",
"for",
"componentValue",
"in",
"self",
".",
"_componentValues",
":",
"if",
"componentValue",
"is",
"noValue",
"or",
"not",
"componentValue",
".",
"isValue",
":",
"return",
"False",
"return",
"True"
] | 41.580645 | 29.516129 |
def download(supported_tags, date_array, tag, sat_id,
ftp_site='cdaweb.gsfc.nasa.gov',
data_path=None, user=None, password=None,
fake_daily_files_from_monthly=False):
"""Routine to download NASA CDAWeb CDF data.
This routine is intended to be used by pysat instrumen... | [
"def",
"download",
"(",
"supported_tags",
",",
"date_array",
",",
"tag",
",",
"sat_id",
",",
"ftp_site",
"=",
"'cdaweb.gsfc.nasa.gov'",
",",
"data_path",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"fake_daily_files_from_monthly",
... | 37.330097 | 21.009709 |
def group_by(self, key_selector=identity,
element_selector=identity,
result_selector=lambda key, grouping: grouping):
'''Groups the elements according to the value of a key extracted by a
selector function.
Note: This method has different behaviour to itertools... | [
"def",
"group_by",
"(",
"self",
",",
"key_selector",
"=",
"identity",
",",
"element_selector",
"=",
"identity",
",",
"result_selector",
"=",
"lambda",
"key",
",",
"grouping",
":",
"grouping",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
... | 46.5 | 27.224138 |
def get_vboxes(self):
"""
Get the maximum ID of the VBoxes
:return: Maximum VBox ID
:rtype: int
"""
vbox_list = []
vbox_max = None
for node in self.nodes:
if node['type'] == 'VirtualBoxVM':
vbox_list.append(node['vbox_id'])
... | [
"def",
"get_vboxes",
"(",
"self",
")",
":",
"vbox_list",
"=",
"[",
"]",
"vbox_max",
"=",
"None",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"if",
"node",
"[",
"'type'",
"]",
"==",
"'VirtualBoxVM'",
":",
"vbox_list",
".",
"append",
"(",
"node",
"... | 24.6875 | 13.5625 |
def __write_list_tmpl(html_tpl):
'''
doing for directory.
'''
out_dir = os.path.join(os.getcwd(), CRUD_PATH, 'infolist')
if os.path.exists(out_dir):
pass
else:
os.mkdir(out_dir)
# for var_name in VAR_NAMES:
for var_name, bl_val in SWITCH_DICS.items():
if var_name.... | [
"def",
"__write_list_tmpl",
"(",
"html_tpl",
")",
":",
"out_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"CRUD_PATH",
",",
"'infolist'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"out_dir",
")",
":",
"... | 37.681818 | 16.545455 |
def get_ipv6_neighbors_table(self):
"""
Get IPv6 neighbors table information.
Return a list of dictionaries having the following set of keys:
* interface (string)
* mac (string)
* ip (string)
* age (float) in seconds
* state (string)
... | [
"def",
"get_ipv6_neighbors_table",
"(",
"self",
")",
":",
"ipv6_neighbors_table",
"=",
"[",
"]",
"command",
"=",
"\"show ipv6 neighbors\"",
"output",
"=",
"self",
".",
"_send_command",
"(",
"command",
")",
"ipv6_neighbors",
"=",
"\"\"",
"fields",
"=",
"re",
".",... | 36.480769 | 14.519231 |
def add_fields(store_name, field_names):
"""
A class-decorator that creates layout managers with a set of named
fields.
"""
def decorate(cls):
def _add(index, name):
def _set_dir(self, value): getattr(self, store_name)[index] = value
def _get_dir(self): return getattr... | [
"def",
"add_fields",
"(",
"store_name",
",",
"field_names",
")",
":",
"def",
"decorate",
"(",
"cls",
")",
":",
"def",
"_add",
"(",
"index",
",",
"name",
")",
":",
"def",
"_set_dir",
"(",
"self",
",",
"value",
")",
":",
"getattr",
"(",
"self",
",",
... | 30.882353 | 21.235294 |
def _message(self, beacon_config, invert_hello=False):
""" Overridden :meth:`.WBeaconGouverneurMessenger._message` method. Appends encoded host group names
to requests and responses.
:param beacon_config: beacon configuration
:return: bytes
"""
m = WBeaconGouverneurMessenger._message(self, beacon_config, i... | [
"def",
"_message",
"(",
"self",
",",
"beacon_config",
",",
"invert_hello",
"=",
"False",
")",
":",
"m",
"=",
"WBeaconGouverneurMessenger",
".",
"_message",
"(",
"self",
",",
"beacon_config",
",",
"invert_hello",
"=",
"invert_hello",
")",
"hostgroups",
"=",
"se... | 41.5 | 19.416667 |
def remove(self, projectname=None, complete=False,
yes=False, all_projects=False, **kwargs):
"""
Delete an existing experiment and/or projectname
Parameters
----------
projectname: str
The name for which the data shall be removed. If True, the
... | [
"def",
"remove",
"(",
"self",
",",
"projectname",
"=",
"None",
",",
"complete",
"=",
"False",
",",
"yes",
"=",
"False",
",",
"all_projects",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"app_main",
"(",
"*",
"*",
"kwargs",
")",
"if... | 40.710145 | 17.231884 |
def get_dev_alarms(auth, url, devid=None, devip=None):
"""
function takes the devId of a specific device and issues a RESTFUL call to get the current
alarms for the target device.
:param devid: int or str value of the target device
:param devip: str of ipv4 address of the target device
:param... | [
"def",
"get_dev_alarms",
"(",
"auth",
",",
"url",
",",
"devid",
"=",
"None",
",",
"devip",
"=",
"None",
")",
":",
"# checks to see if the imc credentials are already available",
"if",
"devip",
"is",
"not",
"None",
":",
"devid",
"=",
"get_dev_details",
"(",
"devi... | 35.976744 | 25 |
def setRandomParams(self):
"""
set random hyperparameters
"""
params = SP.randn(self.getNumberParams())
self.setParams(params) | [
"def",
"setRandomParams",
"(",
"self",
")",
":",
"params",
"=",
"SP",
".",
"randn",
"(",
"self",
".",
"getNumberParams",
"(",
")",
")",
"self",
".",
"setParams",
"(",
"params",
")"
] | 26.833333 | 6.5 |
def poll(self, command="start", *, delay=120):
"""
Poll a point every x seconds (delay=x sec)
Can be stopped by using point.poll('stop') or .poll(0) or .poll(False)
or by setting a delay = 0
:param command: (str) start or stop polling
:param delay: (int) time dela... | [
"def",
"poll",
"(",
"self",
",",
"command",
"=",
"\"start\"",
",",
"*",
",",
"delay",
"=",
"120",
")",
":",
"if",
"delay",
">",
"120",
":",
"self",
".",
"_log",
".",
"warning",
"(",
"\"Segmentation not supported, forcing delay to 120 seconds (or higher)\"",
")... | 35.065574 | 18.47541 |
def start_workunit(self, workunit):
"""Implementation of Reporter callback."""
if not self.is_under_main_root(workunit):
return
label_format = self._get_label_format(workunit)
if label_format == LabelFormat.FULL:
if not WorkUnitLabel.SUPPRESS_LABEL in workunit.labels:
self._emit_in... | [
"def",
"start_workunit",
"(",
"self",
",",
"workunit",
")",
":",
"if",
"not",
"self",
".",
"is_under_main_root",
"(",
"workunit",
")",
":",
"return",
"label_format",
"=",
"self",
".",
"_get_label_format",
"(",
"workunit",
")",
"if",
"label_format",
"==",
"La... | 35.25 | 16.85 |
def full_pixels(space, data, gap_pixels=1):
"""returns the given data distributed in the space ensuring it's full pixels
and with the given gap.
this will result in minor sub-pixel inaccuracies.
XXX - figure out where to place these guys as they are quite useful
"""
available = space - (len(data... | [
"def",
"full_pixels",
"(",
"space",
",",
"data",
",",
"gap_pixels",
"=",
"1",
")",
":",
"available",
"=",
"space",
"-",
"(",
"len",
"(",
"data",
")",
"-",
"1",
")",
"*",
"gap_pixels",
"# 8 recs 7 gaps",
"res",
"=",
"[",
"]",
"for",
"i",
",",
"val",... | 33.105263 | 18.315789 |
def cleanup(first_I, first_Z):
"""
cleans up unbalanced steps
failure can be from unbalanced final step, or from missing steps,
this takes care of missing steps
"""
cont = 0
Nmin = len(first_I)
if len(first_Z) < Nmin:
Nmin = len(first_Z)
for kk in range(Nmin):
if ... | [
"def",
"cleanup",
"(",
"first_I",
",",
"first_Z",
")",
":",
"cont",
"=",
"0",
"Nmin",
"=",
"len",
"(",
"first_I",
")",
"if",
"len",
"(",
"first_Z",
")",
"<",
"Nmin",
":",
"Nmin",
"=",
"len",
"(",
"first_Z",
")",
"for",
"kk",
"in",
"range",
"(",
... | 30.681818 | 11.863636 |
def strptime(s, fmt, tzinfo=None):
"""
A function to replace strptime in the time module. Should behave
identically to the strptime function except it returns a datetime.datetime
object instead of a time.struct_time object.
Also takes an optional tzinfo parameter which is a time zone info object.
"""
res = time... | [
"def",
"strptime",
"(",
"s",
",",
"fmt",
",",
"tzinfo",
"=",
"None",
")",
":",
"res",
"=",
"time",
".",
"strptime",
"(",
"s",
",",
"fmt",
")",
"return",
"datetime",
".",
"datetime",
"(",
"tzinfo",
"=",
"tzinfo",
",",
"*",
"res",
"[",
":",
"6",
... | 42.222222 | 14.222222 |
def iter(self, headers_only=False, page_size=None):
"""Yield all time series objects selected by the query.
The generator returned iterates over
:class:`~google.cloud.monitoring_v3.types.TimeSeries` objects
containing points ordered from oldest to newest.
Note that the :class:`... | [
"def",
"iter",
"(",
"self",
",",
"headers_only",
"=",
"False",
",",
"page_size",
"=",
"None",
")",
":",
"if",
"self",
".",
"_end_time",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Query time interval not specified.\"",
")",
"params",
"=",
"self",
".",
... | 35.571429 | 21.971429 |
def decrypt(self, ciphertext):
'Decrypt a block of cipher text using the AES block cipher.'
if len(ciphertext) != 16:
raise ValueError('wrong block length')
rounds = len(self._Kd) - 1
(s1, s2, s3) = [3, 2, 1]
a = [0, 0, 0, 0]
# Convert ciphertext to (ints ^... | [
"def",
"decrypt",
"(",
"self",
",",
"ciphertext",
")",
":",
"if",
"len",
"(",
"ciphertext",
")",
"!=",
"16",
":",
"raise",
"ValueError",
"(",
"'wrong block length'",
")",
"rounds",
"=",
"len",
"(",
"self",
".",
"_Kd",
")",
"-",
"1",
"(",
"s1",
",",
... | 40.454545 | 23.30303 |
def _query_iterator(result, chunksize, columns, index_col=None,
coerce_float=True, parse_dates=None):
"""Return generator through chunked result set"""
while True:
data = result.fetchmany(chunksize)
if not data:
break
else:
... | [
"def",
"_query_iterator",
"(",
"result",
",",
"chunksize",
",",
"columns",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"parse_dates",
"=",
"None",
")",
":",
"while",
"True",
":",
"data",
"=",
"result",
".",
"fetchmany",
"(",
"ch... | 41.5 | 19.916667 |
def get_form(self, request, obj=None, **kwargs):
"""
Extend the form for the given plugin with the form SharableCascadeForm
"""
Form = type(str('ExtSharableForm'), (SharableCascadeForm, kwargs.pop('form', self.form)), {})
Form.base_fields['shared_glossary'].limit_choices_to = dic... | [
"def",
"get_form",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"Form",
"=",
"type",
"(",
"str",
"(",
"'ExtSharableForm'",
")",
",",
"(",
"SharableCascadeForm",
",",
"kwargs",
".",
"pop",
"(",
"'form'",
","... | 58.375 | 27.625 |
def canonicalize(ctx, statement, namespace_targets, version, api, config_fn):
"""Canonicalize statement
Target namespaces can be provided in the following manner:
bel stmt canonicalize "<BELStmt>" --namespace_targets '{"HGNC": ["EG", "SP"], "CHEMBL": ["CHEBI"]}'
the value of target_namespa... | [
"def",
"canonicalize",
"(",
"ctx",
",",
"statement",
",",
"namespace_targets",
",",
"version",
",",
"api",
",",
"config_fn",
")",
":",
"if",
"config_fn",
":",
"config",
"=",
"bel",
".",
"db",
".",
"Config",
".",
"merge_config",
"(",
"ctx",
".",
"config",... | 36.311111 | 22.444444 |
def sort(self):
"""
Sort the families by template name.
.. rubric:: Example
>>> party = Party(families=[Family(template=Template(name='b')),
... Family(template=Template(name='a'))])
>>> party[0]
Family of 0 detections from template b
... | [
"def",
"sort",
"(",
"self",
")",
":",
"self",
".",
"families",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"template",
".",
"name",
")",
"return",
"self"
] | 29.1875 | 19.3125 |
def backup_download(self, filename=None):
"""Download backup file from WebDAV (cloud only)."""
if self.deploymentType != 'Cloud':
logging.warning(
'This functionality is not available in Server version')
return None
remote_file = self.backup_progress()['fi... | [
"def",
"backup_download",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"self",
".",
"deploymentType",
"!=",
"'Cloud'",
":",
"logging",
".",
"warning",
"(",
"'This functionality is not available in Server version'",
")",
"return",
"None",
"remote_file",... | 45.653846 | 16.346154 |
def pow4(x, alpha, a, b, c):
"""pow4
Parameters
----------
x: int
alpha: float
a: float
b: float
c: float
Returns
-------
float
c - (a*x+b)**-alpha
"""
return c - (a*x+b)**-alpha | [
"def",
"pow4",
"(",
"x",
",",
"alpha",
",",
"a",
",",
"b",
",",
"c",
")",
":",
"return",
"c",
"-",
"(",
"a",
"*",
"x",
"+",
"b",
")",
"**",
"-",
"alpha"
] | 13.176471 | 23.176471 |
def set_attributes(self, obj, **attributes):
""" Set attributes.
:param obj: requested object.
:param attributes: dictionary of {attribute: value} to set
"""
attributes_url = '{}/{}/attributes'.format(self.session_url, obj.ref)
attributes_list = [{u'name': str(name), u'... | [
"def",
"set_attributes",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"attributes",
")",
":",
"attributes_url",
"=",
"'{}/{}/attributes'",
".",
"format",
"(",
"self",
".",
"session_url",
",",
"obj",
".",
"ref",
")",
"attributes_list",
"=",
"[",
"{",
"u'name'",
... | 47.818182 | 26.727273 |
def normalize_name(name, overrides=None):
'''Normalize the key name to title case.
For example, ``normalize_name('content-id')`` will become ``Content-Id``
Args:
name (str): The name to normalize.
overrides (set, sequence): A set or sequence containing keys that
should be cased... | [
"def",
"normalize_name",
"(",
"name",
",",
"overrides",
"=",
"None",
")",
":",
"normalized_name",
"=",
"name",
".",
"title",
"(",
")",
"if",
"overrides",
":",
"override_map",
"=",
"dict",
"(",
"[",
"(",
"name",
".",
"title",
"(",
")",
",",
"name",
")... | 31.041667 | 26.958333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.