text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def move(self, x, y):
"""Changes the overlay's position relative to the IFramebuffer.
in x of type int
in y of type int
"""
if not isinstance(x, baseinteger):
raise TypeError("x can only be an instance of type baseinteger")
if not isinstance(y, baseinteger)... | [
"def",
"move",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"x can only be an instance of type baseinteger\"",
")",
"if",
"not",
"isinstance",
"(",
"y",
",",
"bas... | 31.857143 | 19.142857 |
def check_uniqueness(self, *args, **kwargs):
"""Check if the given "value" (via `args`) is unique or not.
For the parameters, see ``BaseIndex.check_uniqueness``
"""
if not self.field.unique:
return
try:
pk = self.instance.pk.get()
except Attrib... | [
"def",
"check_uniqueness",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"field",
".",
"unique",
":",
"return",
"try",
":",
"pk",
"=",
"self",
".",
"instance",
".",
"pk",
".",
"get",
"(",
")",
"except... | 26.8 | 20.55 |
def get_message(self, timeout=0.5):
"""
Attempts to retrieve the latest message received by the instance. If no message is
available it blocks for given timeout or until a message is received, or else
returns None (whichever is shorter). This method does not block after
:meth:`ca... | [
"def",
"get_message",
"(",
"self",
",",
"timeout",
"=",
"0.5",
")",
":",
"try",
":",
"return",
"self",
".",
"buffer",
".",
"get",
"(",
"block",
"=",
"not",
"self",
".",
"is_stopped",
",",
"timeout",
"=",
"timeout",
")",
"except",
"Empty",
":",
"retur... | 45.466667 | 24.533333 |
def prox_min(X, step, thresh=0):
"""Projection onto numbers above `thresh`
"""
thresh_ = _step_gamma(step, thresh)
below = X - thresh_ < 0
X[below] = thresh_
return X | [
"def",
"prox_min",
"(",
"X",
",",
"step",
",",
"thresh",
"=",
"0",
")",
":",
"thresh_",
"=",
"_step_gamma",
"(",
"step",
",",
"thresh",
")",
"below",
"=",
"X",
"-",
"thresh_",
"<",
"0",
"X",
"[",
"below",
"]",
"=",
"thresh_",
"return",
"X"
] | 26.285714 | 9.714286 |
def install_handler(self, app):
"""Install log handler."""
from raven.contrib.celery import register_logger_signal, \
register_signal
from raven.contrib.flask import Sentry, make_client
from raven.handlers.logging import SentryHandler
# Installs sentry in app.extensi... | [
"def",
"install_handler",
"(",
"self",
",",
"app",
")",
":",
"from",
"raven",
".",
"contrib",
".",
"celery",
"import",
"register_logger_signal",
",",
"register_signal",
"from",
"raven",
".",
"contrib",
".",
"flask",
"import",
"Sentry",
",",
"make_client",
"fro... | 35.958333 | 18.791667 |
def count(self, view, include=None):
"""
Return a ViewCount for a view.
:param include: list of objects to sideload. `Side-loading API Docs
<https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.
:param view: View or view id
"""
return self._get(... | [
"def",
"count",
"(",
"self",
",",
"view",
",",
"include",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get",
"(",
"self",
".",
"_build_url",
"(",
"self",
".",
"endpoint",
".",
"count",
"(",
"id",
"=",
"view",
",",
"include",
"=",
"include",
")",... | 41.666667 | 19.222222 |
def _get(self, plugin_name):
"""
Retrieves the plugin with given name
:param plugin_name: Name of the plugin to retrieve
:return samtranslator.plugins.BasePlugin: Returns the plugin object if found. None, otherwise
"""
for p in self._plugins:
if p.name == pl... | [
"def",
"_get",
"(",
"self",
",",
"plugin_name",
")",
":",
"for",
"p",
"in",
"self",
".",
"_plugins",
":",
"if",
"p",
".",
"name",
"==",
"plugin_name",
":",
"return",
"p",
"return",
"None"
] | 28 | 20.307692 |
def _set_alias(self, v, load=False):
"""
Setter method for alias, mapped from YANG variable /zoning/defined_configuration/alias (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_alias is considered as a private
method. Backends looking to populate this variable ... | [
"def",
"_set_alias",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 118.045455 | 57.045455 |
def get_ao_chans(dev):
"""Discover and return a list of the names of all analog output channels for the given device
:param dev: the device name
:type dev: str
"""
buf = create_string_buffer(256)
buflen = c_uint32(sizeof(buf))
DAQmxGetDevAOPhysicalChans(dev.encode(), buf, buflen)
pybuf ... | [
"def",
"get_ao_chans",
"(",
"dev",
")",
":",
"buf",
"=",
"create_string_buffer",
"(",
"256",
")",
"buflen",
"=",
"c_uint32",
"(",
"sizeof",
"(",
"buf",
")",
")",
"DAQmxGetDevAOPhysicalChans",
"(",
"dev",
".",
"encode",
"(",
")",
",",
"buf",
",",
"buflen"... | 32 | 13.833333 |
def in_words(amount, gender=None):
"""
Numeral in words
@param amount: numeral
@type amount: C{integer types}, C{float} or C{Decimal}
@param gender: gender (MALE, FEMALE or NEUTER)
@type gender: C{int}
@return: in-words reprsentation of numeral
@rtype: C{unicode}
raise ValueError... | [
"def",
"in_words",
"(",
"amount",
",",
"gender",
"=",
"None",
")",
":",
"check_positive",
"(",
"amount",
")",
"if",
"isinstance",
"(",
"amount",
",",
"Decimal",
")",
"and",
"amount",
".",
"as_tuple",
"(",
")",
"[",
"2",
"]",
"==",
"0",
":",
"# если ц... | 28.756757 | 17.567568 |
def _wrap_result(name, data, sparse_index, fill_value, dtype=None):
"""
wrap op result to have correct dtype
"""
if name.startswith('__'):
# e.g. __eq__ --> eq
name = name[2:-2]
if name in ('eq', 'ne', 'lt', 'gt', 'le', 'ge'):
dtype = np.bool
fill_value = lib.item_from_... | [
"def",
"_wrap_result",
"(",
"name",
",",
"data",
",",
"sparse_index",
",",
"fill_value",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'__'",
")",
":",
"# e.g. __eq__ --> eq",
"name",
"=",
"name",
"[",
"2",
":",
"-",
"2",
... | 29.3 | 13.7 |
def _new_alloc_handle(stype, shape, ctx, delay_alloc, dtype, aux_types, aux_shapes=None):
"""Return a new handle with specified storage type, shape, dtype and context.
Empty handle is only used to hold results
Returns
-------
handle
A new empty ndarray handle
"""
hdl = NDArrayHandl... | [
"def",
"_new_alloc_handle",
"(",
"stype",
",",
"shape",
",",
"ctx",
",",
"delay_alloc",
",",
"dtype",
",",
"aux_types",
",",
"aux_shapes",
"=",
"None",
")",
":",
"hdl",
"=",
"NDArrayHandle",
"(",
")",
"for",
"aux_t",
"in",
"aux_types",
":",
"if",
"np",
... | 42.121212 | 19.212121 |
def _init_map(self, record_types=None, **kwargs):
"""Initialize form map"""
osid_objects.OsidObjectForm._init_map(self, record_types=record_types)
self._my_map['assignedAgencyIds'] = [str(kwargs['agency_id'])] | [
"def",
"_init_map",
"(",
"self",
",",
"record_types",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"osid_objects",
".",
"OsidObjectForm",
".",
"_init_map",
"(",
"self",
",",
"record_types",
"=",
"record_types",
")",
"self",
".",
"_my_map",
"[",
"'assign... | 57.5 | 19.25 |
def set_secondary_ips(self, name, vrid, secondary_ips, run=True):
"""Configure the secondary_ip property of the vrrp
Notes:
set_secondary_ips takes a list of secondary ip addresses
which are to be set on the virtal router. An empty list will
remove any existing secon... | [
"def",
"set_secondary_ips",
"(",
"self",
",",
"name",
",",
"vrid",
",",
"secondary_ips",
",",
"run",
"=",
"True",
")",
":",
"cmds",
"=",
"[",
"]",
"# Get the current set of tracks defined for the vrrp",
"curr_sec_ips",
"=",
"[",
"]",
"vrrps",
"=",
"self",
".",... | 38.623188 | 23.971014 |
def install_new_pipeline():
"""
Install above transformer into the existing pipeline creator.
"""
def new_create_pipeline(context, *args, **kwargs):
result = old_create_pipeline(context, *args, **kwargs)
result.insert(1, DAAPObjectTransformer(context))
return result
old_cr... | [
"def",
"install_new_pipeline",
"(",
")",
":",
"def",
"new_create_pipeline",
"(",
"context",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"old_create_pipeline",
"(",
"context",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"result... | 30.692308 | 19.153846 |
def _raster_layers(self):
"""Return a list of raster layers available.
:return: List of raster layers available in the geopackage.
:rtype: list
.. versionadded:: 4.0
"""
layers = []
raster_datasource = gdal.Open(self.uri.absoluteFilePath())
if raster_da... | [
"def",
"_raster_layers",
"(",
"self",
")",
":",
"layers",
"=",
"[",
"]",
"raster_datasource",
"=",
"gdal",
".",
"Open",
"(",
"self",
".",
"uri",
".",
"absoluteFilePath",
"(",
")",
")",
"if",
"raster_datasource",
":",
"subdatasets",
"=",
"raster_datasource",
... | 32 | 19.761905 |
def decode_address(self, addr):
"""Initialize the address from a string. Lots of different forms are supported."""
if _debug: Address._debug("decode_address %r (%s)", addr, type(addr))
# start out assuming this is a local station
self.addrType = Address.localStationAddr
self.ad... | [
"def",
"decode_address",
"(",
"self",
",",
"addr",
")",
":",
"if",
"_debug",
":",
"Address",
".",
"_debug",
"(",
"\"decode_address %r (%s)\"",
",",
"addr",
",",
"type",
"(",
"addr",
")",
")",
"# start out assuming this is a local station",
"self",
".",
"addrType... | 38.738197 | 22.030043 |
def shuffle(self, *args):
"""Shuffles all arguments and returns them.
ARG_1,...,ARG_N
%{SHUFFLE:A, B ,...,F} -> 'CDA B FE'
"""
call_args = list(args)
self.random.shuffle(call_args)
return ''.join(call_args) | [
"def",
"shuffle",
"(",
"self",
",",
"*",
"args",
")",
":",
"call_args",
"=",
"list",
"(",
"args",
")",
"self",
".",
"random",
".",
"shuffle",
"(",
"call_args",
")",
"return",
"''",
".",
"join",
"(",
"call_args",
")"
] | 28.777778 | 10.111111 |
def set_colors(self,*args,**kw):
"""Shorthand access to the color table scheme selector method."""
# Set own color table
self.color_scheme_table.set_active_scheme(*args,**kw)
# for convenience, set Colors to the active scheme
self.Colors = self.color_scheme_table.active_colors
... | [
"def",
"set_colors",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Set own color table",
"self",
".",
"color_scheme_table",
".",
"set_active_scheme",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"# for convenience, set Colors to the active sche... | 44.8 | 13.9 |
def change_host_event_handler(self, host, event_handler_command):
"""Modify host event handler
Format of the line that triggers function call::
CHANGE_HOST_EVENT_HANDLER;<host_name>;<event_handler_command>
:param host: host to modify event handler
:type host: alignak.objects.ho... | [
"def",
"change_host_event_handler",
"(",
"self",
",",
"host",
",",
"event_handler_command",
")",
":",
"host",
".",
"modified_attributes",
"|=",
"DICT_MODATTR",
"[",
"\"MODATTR_EVENT_HANDLER_COMMAND\"",
"]",
".",
"value",
"data",
"=",
"{",
"\"commands\"",
":",
"self"... | 44.375 | 19.4375 |
def get_kkf(ekey):
"""
:param ekey: export key, for instance ('uhs/rlz-1', 'xml')
:returns: key, kind and fmt from the export key, i.e. 'uhs', 'rlz-1', 'xml'
"""
key, fmt = ekey
if '/' in key:
key, kind = key.split('/', 1)
else:
kind = ''
return key, kind, fmt | [
"def",
"get_kkf",
"(",
"ekey",
")",
":",
"key",
",",
"fmt",
"=",
"ekey",
"if",
"'/'",
"in",
"key",
":",
"key",
",",
"kind",
"=",
"key",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"else",
":",
"kind",
"=",
"''",
"return",
"key",
",",
"kind",
","... | 27.090909 | 18 |
def set_system_time(newtime, utc_offset=None):
'''
Set the system time.
:param str newtime:
The time to set. Can be any of the following formats.
- HH:MM:SS AM/PM
- HH:MM AM/PM
- HH:MM:SS (24 hour)
- HH:MM (24 hour)
Note that the salt command line parser par... | [
"def",
"set_system_time",
"(",
"newtime",
",",
"utc_offset",
"=",
"None",
")",
":",
"fmts",
"=",
"[",
"'%I:%M:%S %p'",
",",
"'%I:%M %p'",
",",
"'%H:%M:%S'",
",",
"'%H:%M'",
"]",
"dt_obj",
"=",
"_try_parse_datetime",
"(",
"newtime",
",",
"fmts",
")",
"if",
... | 35.918919 | 25.756757 |
def offset(self, offset):
"""
Apply an OFFSET to the query and return the newly resulting Query.
"""
query = self._copy()
query._offset = offset
return query | [
"def",
"offset",
"(",
"self",
",",
"offset",
")",
":",
"query",
"=",
"self",
".",
"_copy",
"(",
")",
"query",
".",
"_offset",
"=",
"offset",
"return",
"query"
] | 28.428571 | 13 |
def get_plugin_actions(self):
"""Return a list of actions related to plugin"""
self.history_action = create_action(self, _("History..."),
None, ima.icon('history'),
_("Set history maximum entries"),
... | [
"def",
"get_plugin_actions",
"(",
"self",
")",
":",
"self",
".",
"history_action",
"=",
"create_action",
"(",
"self",
",",
"_",
"(",
"\"History...\"",
")",
",",
"None",
",",
"ima",
".",
"icon",
"(",
"'history'",
")",
",",
"_",
"(",
"\"Set history maximum e... | 56.75 | 23.4375 |
def get_block_by_hash(self, block_hash: str, is_full: bool = False) -> dict:
"""
This interface is used to get the hexadecimal hash value of specified block height in current network.
:param block_hash: a hexadecimal value of block hash.
:param is_full:
:return: the block inform... | [
"def",
"get_block_by_hash",
"(",
"self",
",",
"block_hash",
":",
"str",
",",
"is_full",
":",
"bool",
"=",
"False",
")",
"->",
"dict",
":",
"payload",
"=",
"self",
".",
"generate_json_rpc_payload",
"(",
"RpcMethod",
".",
"GET_BLOCK",
",",
"[",
"block_hash",
... | 44.230769 | 23.769231 |
async def reset_webhook(self, check=True) -> bool:
"""
Reset webhook
:param check: check before deleting
:return:
"""
if check:
wh = await self.bot.get_webhook_info()
if not wh.url:
return False
return await self.bot.delet... | [
"async",
"def",
"reset_webhook",
"(",
"self",
",",
"check",
"=",
"True",
")",
"->",
"bool",
":",
"if",
"check",
":",
"wh",
"=",
"await",
"self",
".",
"bot",
".",
"get_webhook_info",
"(",
")",
"if",
"not",
"wh",
".",
"url",
":",
"return",
"False",
"... | 24.538462 | 15.461538 |
def nav_controller_output_encode(self, nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error):
'''
The state of the fixed wing navigation and position controller.
nav_roll : Current desired roll in degrees (float)... | [
"def",
"nav_controller_output_encode",
"(",
"self",
",",
"nav_roll",
",",
"nav_pitch",
",",
"nav_bearing",
",",
"target_bearing",
",",
"wp_dist",
",",
"alt_error",
",",
"aspd_error",
",",
"xtrack_error",
")",
":",
"return",
"MAVLink_nav_controller_output_message",
"("... | 75.066667 | 51.333333 |
def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.... | [
"def",
"_complete_with_items",
"(",
"self",
",",
"cursor",
",",
"items",
")",
":",
"self",
".",
"_cancel_completion",
"(",
")",
"if",
"len",
"(",
"items",
")",
"==",
"1",
":",
"cursor",
".",
"setPosition",
"(",
"self",
".",
"_control",
".",
"textCursor",... | 40.6 | 17.25 |
def _stmt_graph_annotate_edges(self, edges_to_annotate, **new_labels):
"""
Add new annotations to edges in the statement dependence graph.
:param list edges_to_annotate: A list of edges to annotate.
:param new_labels: New labels to be added to those edges.
:returns: None
... | [
"def",
"_stmt_graph_annotate_edges",
"(",
"self",
",",
"edges_to_annotate",
",",
"*",
"*",
"new_labels",
")",
":",
"graph",
"=",
"self",
".",
"graph",
"for",
"src",
",",
"dst",
"in",
"edges_to_annotate",
":",
"if",
"src",
"not",
"in",
"graph",
":",
"contin... | 29.481481 | 18.148148 |
def override(self, override, use_parent=False):
"""
Allows temporarily pushing an override context, yields the new context
into the following block.
"""
self.push(override, use_parent)
yield self.current
self.pop() | [
"def",
"override",
"(",
"self",
",",
"override",
",",
"use_parent",
"=",
"False",
")",
":",
"self",
".",
"push",
"(",
"override",
",",
"use_parent",
")",
"yield",
"self",
".",
"current",
"self",
".",
"pop",
"(",
")"
] | 32.875 | 11.125 |
def removeItems(self, items):
"""
Removes all the inputed items from the scene at once. The \
list of items will be stored in an internal cache. When \
updating a node or connection's prepareToRemove method, \
any additional items that need to be removed as a result \
o... | [
"def",
"removeItems",
"(",
"self",
",",
"items",
")",
":",
"count",
"=",
"0",
"self",
".",
"_removalQueue",
"=",
"items",
"blocked",
"=",
"self",
".",
"signalsBlocked",
"(",
")",
"self",
".",
"blockSignals",
"(",
"True",
")",
"update",
"=",
"set",
"(",... | 34.5 | 16.5 |
def check_api_key(request, key, hproPk):
"""Check if an API key is valid"""
if settings.PIAPI_STANDALONE:
return True
(_, _, hproject) = getPlugItObject(hproPk)
if not hproject:
return False
if hproject.plugItApiKey is None or hproject.plugItApiKey == '':
return False
... | [
"def",
"check_api_key",
"(",
"request",
",",
"key",
",",
"hproPk",
")",
":",
"if",
"settings",
".",
"PIAPI_STANDALONE",
":",
"return",
"True",
"(",
"_",
",",
"_",
",",
"hproject",
")",
"=",
"getPlugItObject",
"(",
"hproPk",
")",
"if",
"not",
"hproject",
... | 22.866667 | 21.533333 |
def deploy_s3(
src, requirements=None, local_package=None,
config_file='config.yaml', profile_name=None,
preserve_vpc=False
):
"""Deploys a new function via AWS S3.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g... | [
"def",
"deploy_s3",
"(",
"src",
",",
"requirements",
"=",
"None",
",",
"local_package",
"=",
"None",
",",
"config_file",
"=",
"'config.yaml'",
",",
"profile_name",
"=",
"None",
",",
"preserve_vpc",
"=",
"False",
")",
":",
"# Load and parse the config file.",
"pa... | 39.371429 | 22.114286 |
def pct_negative(self, threshold=0.0):
"""Pct. of periods in which `self` is less than `threshold.`
Parameters
----------
threshold : {float, TSeries, pd.Series}, default 0.
Returns
-------
float
"""
return np.count_nonzero(self[self < threshold... | [
"def",
"pct_negative",
"(",
"self",
",",
"threshold",
"=",
"0.0",
")",
":",
"return",
"np",
".",
"count_nonzero",
"(",
"self",
"[",
"self",
"<",
"threshold",
"]",
")",
"/",
"self",
".",
"count",
"(",
")"
] | 25 | 22.461538 |
def process_files():
"""
Process files with a single progress bar
"""
with enlighten.Counter(total=100, desc='Simple', unit='ticks') as pbar:
for num in range(100): # pylint: disable=unused-variable
time.sleep(0.05)
pbar.update() | [
"def",
"process_files",
"(",
")",
":",
"with",
"enlighten",
".",
"Counter",
"(",
"total",
"=",
"100",
",",
"desc",
"=",
"'Simple'",
",",
"unit",
"=",
"'ticks'",
")",
"as",
"pbar",
":",
"for",
"num",
"in",
"range",
"(",
"100",
")",
":",
"# pylint: dis... | 30.111111 | 16.777778 |
def get_central_coors(self, row, col):
"""Get the coordinates of central grid.
Args:
row: row number, range from 0 to (nRows - 1).
col: col number, range from 0 to (nCols - 1).
Returns:
XY coordinates. If the row or col are invalid, raise ValueError.
... | [
"def",
"get_central_coors",
"(",
"self",
",",
"row",
",",
"col",
")",
":",
"if",
"row",
"<",
"0",
"or",
"row",
">=",
"self",
".",
"nRows",
"or",
"col",
"<",
"0",
"or",
"col",
">=",
"self",
".",
"nCols",
":",
"raise",
"ValueError",
"(",
"\"The row (... | 41.705882 | 23.117647 |
def json_normalize(data, record_path=None, meta=None,
meta_prefix=None,
record_prefix=None,
errors='raise',
sep='.'):
"""
Normalize semi-structured JSON data into a flat table.
Parameters
----------
data : dict or list of d... | [
"def",
"json_normalize",
"(",
"data",
",",
"record_path",
"=",
"None",
",",
"meta",
"=",
"None",
",",
"meta_prefix",
"=",
"None",
",",
"record_prefix",
"=",
"None",
",",
"errors",
"=",
"'raise'",
",",
"sep",
"=",
"'.'",
")",
":",
"def",
"_pull_field",
... | 35.553191 | 20.340426 |
def get_bugs_summaries(self, bugids):
"""
Get multiple bug objects' summaries only (faster).
param bugids: ``list`` of ``int``, bug numbers.
returns: deferred that when fired returns a list of ``AttrDict``s
representing these bugs.
"""
payload = {'ids': ... | [
"def",
"get_bugs_summaries",
"(",
"self",
",",
"bugids",
")",
":",
"payload",
"=",
"{",
"'ids'",
":",
"bugids",
",",
"'include_fields'",
":",
"[",
"'id'",
",",
"'summary'",
"]",
"}",
"d",
"=",
"self",
".",
"call",
"(",
"'Bug.get'",
",",
"payload",
")",... | 38.416667 | 14.416667 |
def includeme(config):
"""Configures the session manager"""
settings = config.registry.settings
session_factory = SignedCookieSessionFactory(settings['session_key'])
config.set_session_factory(session_factory) | [
"def",
"includeme",
"(",
"config",
")",
":",
"settings",
"=",
"config",
".",
"registry",
".",
"settings",
"session_factory",
"=",
"SignedCookieSessionFactory",
"(",
"settings",
"[",
"'session_key'",
"]",
")",
"config",
".",
"set_session_factory",
"(",
"session_fac... | 44.2 | 11.8 |
def replace(input, **params):
"""
Replaces field value
:param input:
:param params:
:return:
"""
PARAM_REPLACE_LIST = 'replace'
REPLACE_FIELD = 'field'
REPLACE_FIND_VALUE = 'value.to_find'
REPLACE_WITH_VALUE = 'value.replace_with'
replace_list = params.get(PARAM_REPLACE_LIST... | [
"def",
"replace",
"(",
"input",
",",
"*",
"*",
"params",
")",
":",
"PARAM_REPLACE_LIST",
"=",
"'replace'",
"REPLACE_FIELD",
"=",
"'field'",
"REPLACE_FIND_VALUE",
"=",
"'value.to_find'",
"REPLACE_WITH_VALUE",
"=",
"'value.replace_with'",
"replace_list",
"=",
"params",
... | 29.388889 | 15.944444 |
def doc_reader(infile):
"""Parse docx and odf files."""
if infile.endswith('.docx'):
docid = 'word/document.xml'
else:
docid = 'content.xml'
try:
zfile = zipfile.ZipFile(infile)
except:
print('Sorry, can\'t open {}.'.format(infile))
return
body = ET.fromst... | [
"def",
"doc_reader",
"(",
"infile",
")",
":",
"if",
"infile",
".",
"endswith",
"(",
"'.docx'",
")",
":",
"docid",
"=",
"'word/document.xml'",
"else",
":",
"docid",
"=",
"'content.xml'",
"try",
":",
"zfile",
"=",
"zipfile",
".",
"ZipFile",
"(",
"infile",
... | 29.928571 | 16.714286 |
def reject_record(self, record):
"""Reject a record for inclusion in the community.
:param record: Record object.
"""
with db.session.begin_nested():
req = InclusionRequest.get(self.id, record.id)
if req is None:
raise InclusionRequestMissingError... | [
"def",
"reject_record",
"(",
"self",
",",
"record",
")",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"req",
"=",
"InclusionRequest",
".",
"get",
"(",
"self",
".",
"id",
",",
"record",
".",
"id",
")",
"if",
"req",
"is",
"N... | 37.909091 | 13.636364 |
def write(obj, data=None, **kwargs):
"""Write a value in to loader source
:param obj: settings object
:param data: vars to be stored
:param kwargs: vars to be stored
:return:
"""
if obj.REDIS_ENABLED_FOR_DYNACONF is False:
raise RuntimeError(
"Redis is not configured \n"... | [
"def",
"write",
"(",
"obj",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"obj",
".",
"REDIS_ENABLED_FOR_DYNACONF",
"is",
"False",
":",
"raise",
"RuntimeError",
"(",
"\"Redis is not configured \\n\"",
"\"export REDIS_ENABLED_FOR_DYNACONF=true\\n... | 32.16 | 15.8 |
def is_contradictory(self, other):
"""
Can these two strings coexist ?
"""
other = StringCell.coerce(other)
if self.value is None or other.value is None:
# None = empty, and won't contradict anything
return False
def sequence_in(s1, s2):
... | [
"def",
"is_contradictory",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"StringCell",
".",
"coerce",
"(",
"other",
")",
"if",
"self",
".",
"value",
"is",
"None",
"or",
"other",
".",
"value",
"is",
"None",
":",
"# None = empty, and won't contradict anyt... | 32.625 | 14.1875 |
def val_accuracy(show_swap):
"""http://wiki.apache.org/spamassassin/TopSharedMemoryBug"""
kv = kernel_ver()
pid = os.getpid()
swap_accuracy = -1
if kv[:2] == (2,4):
if proc.open('meminfo').read().find("Inact_") == -1:
return 1, swap_accuracy
return 0, swap_accuracy
el... | [
"def",
"val_accuracy",
"(",
"show_swap",
")",
":",
"kv",
"=",
"kernel_ver",
"(",
")",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"swap_accuracy",
"=",
"-",
"1",
"if",
"kv",
"[",
":",
"2",
"]",
"==",
"(",
"2",
",",
"4",
")",
":",
"if",
"proc",
... | 36 | 13.692308 |
def send(self, *sender, **kwargs):
"""Emit this signal on behalf of `sender`, passing on kwargs.
This is an extension of `Signal.send` that changes one thing:
Exceptions raised in calling the receiver are logged but do not fail
"""
if len(sender) == 0:
sender = None
... | [
"def",
"send",
"(",
"self",
",",
"*",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"sender",
")",
"==",
"0",
":",
"sender",
"=",
"None",
"elif",
"len",
"(",
"sender",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"'send() accep... | 35.84 | 20.56 |
def setup(parser):
"""Add common sampling options to CLI parser.
Parameters
----------
parser : argparse object
Returns
----------
Updated argparse object
"""
parser.add_argument(
'-p', '--paramfile', type=str, required=True,
help='Parameter Range File')
parser.... | [
"def",
"setup",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'-p'",
",",
"'--paramfile'",
",",
"type",
"=",
"str",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'Parameter Range File'",
")",
"parser",
".",
"add_argument",
"(",
"'-o'",
... | 29.807692 | 20.423077 |
def _init_boto3_clients(self, profile, region):
"""
The utililty requires boto3 clients to CloudFormation.
Args:
None
Returns:
Good or Bad; True or False
"""
try:
session = None
if profile and region:
sessi... | [
"def",
"_init_boto3_clients",
"(",
"self",
",",
"profile",
",",
"region",
")",
":",
"try",
":",
"session",
"=",
"None",
"if",
"profile",
"and",
"region",
":",
"session",
"=",
"boto3",
".",
"session",
".",
"Session",
"(",
"profile_name",
"=",
"profile",
"... | 31.461538 | 19.846154 |
def antenna1(self, context):
""" antenna1 data source """
lrow, urow = MS.uvw_row_extents(context)
antenna1 = self._manager.ordered_uvw_table.getcol(
MS.ANTENNA1, startrow=lrow, nrow=urow-lrow)
return antenna1.reshape(context.shape).astype(context.dtype) | [
"def",
"antenna1",
"(",
"self",
",",
"context",
")",
":",
"lrow",
",",
"urow",
"=",
"MS",
".",
"uvw_row_extents",
"(",
"context",
")",
"antenna1",
"=",
"self",
".",
"_manager",
".",
"ordered_uvw_table",
".",
"getcol",
"(",
"MS",
".",
"ANTENNA1",
",",
"... | 41.857143 | 17.285714 |
def _phase_kuramoto(self, teta, t, argv):
"""!
@brief Overrided method for calculation of oscillator phase.
@param[in] teta (double): Current value of phase.
@param[in] t (double): Time (can be ignored).
@param[in] argv (uint): Index of oscillator whose phase repre... | [
"def",
"_phase_kuramoto",
"(",
"self",
",",
"teta",
",",
"t",
",",
"argv",
")",
":",
"index",
"=",
"argv",
"# index of oscillator\r",
"phase",
"=",
"0.0",
"# phase of a specified oscillator that will calculated in line with current env. states.\r",
"neighbors",
"=",
"self... | 39.5 | 22.107143 |
def difference(self, other):
"""
Returns a FrozenList with elements from other removed from self.
Parameters
----------
other : array-like
The array-like whose elements we are removing self.
Returns
-------
diff : FrozenList
The c... | [
"def",
"difference",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"set",
"(",
"other",
")",
"temp",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
"if",
"x",
"not",
"in",
"other",
"]",
"return",
"type",
"(",
"self",
")",
"(",
"temp",
")"
] | 27.647059 | 19.058824 |
def _find_conda():
"""Find the conda executable robustly across conda versions.
Returns
-------
conda : str
Path to the conda executable.
Raises
------
IOError
If the executable cannot be found in either the CONDA_EXE environment
variable or in the PATH.
Notes
... | [
"def",
"_find_conda",
"(",
")",
":",
"if",
"'CONDA_EXE'",
"in",
"os",
".",
"environ",
":",
"conda",
"=",
"os",
".",
"environ",
"[",
"'CONDA_EXE'",
"]",
"else",
":",
"conda",
"=",
"util",
".",
"which",
"(",
"'conda'",
")",
"return",
"conda"
] | 30.344828 | 24.793103 |
def I(self):
r"""Returns the set of intermediate states
"""
return list(set(range(self.nstates)) - set(self._A) - set(self._B)) | [
"def",
"I",
"(",
"self",
")",
":",
"return",
"list",
"(",
"set",
"(",
"range",
"(",
"self",
".",
"nstates",
")",
")",
"-",
"set",
"(",
"self",
".",
"_A",
")",
"-",
"set",
"(",
"self",
".",
"_B",
")",
")"
] | 29.6 | 20.6 |
def makeHttpRequest(method, url, payload, headers, retries=MAX_RETRIES, session=None):
""" Make an HTTP request and retry it until success, return request """
retry = -1
response = None
while retry < retries:
retry += 1
# if this isn't the first retry then we sleep
if retry > 0:
... | [
"def",
"makeHttpRequest",
"(",
"method",
",",
"url",
",",
"payload",
",",
"headers",
",",
"retries",
"=",
"MAX_RETRIES",
",",
"session",
"=",
"None",
")",
":",
"retry",
"=",
"-",
"1",
"response",
"=",
"None",
"while",
"retry",
"<",
"retries",
":",
"ret... | 38.95122 | 19.609756 |
def get_rupture_surface(mag, nodal_plane, hypocenter, msr,
rupture_aspect_ratio, upper_seismogenic_depth,
lower_seismogenic_depth, mesh_spacing=1.0):
"""
Create and return rupture surface object with given properties.
:param mag:
Magnitude value, used... | [
"def",
"get_rupture_surface",
"(",
"mag",
",",
"nodal_plane",
",",
"hypocenter",
",",
"msr",
",",
"rupture_aspect_ratio",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
",",
"mesh_spacing",
"=",
"1.0",
")",
":",
"assert",
"(",
"upper_seismogenic_depth... | 47.107843 | 18.637255 |
def getclamdata(filename, custom_formats=None):
global CUSTOM_FORMATS #pylint: disable=global-statement
"""This function reads the CLAM Data from an XML file. Use this to read
the clam.xml file from your system wrapper. It returns a CLAMData instance.
If you make use of CUSTOM_FORMATS, you need to pas... | [
"def",
"getclamdata",
"(",
"filename",
",",
"custom_formats",
"=",
"None",
")",
":",
"global",
"CUSTOM_FORMATS",
"#pylint: disable=global-statement",
"f",
"=",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"xml",
"=",
... | 46.461538 | 20 |
def collect_appendvars(ap_, cls):
"""
colleziona elementi per le liste.
"""
for key, value in cls.__dict__.items():
if key.startswith('appendvars_'):
varname = key[11:]
if varname not in ap_.appendvars:
ap_.appendvars[varname] = []
if value not... | [
"def",
"collect_appendvars",
"(",
"ap_",
",",
"cls",
")",
":",
"for",
"key",
",",
"value",
"in",
"cls",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'appendvars_'",
")",
":",
"varname",
"=",
"key",
"[",
"11",
... | 36.076923 | 5 |
def AcceptableMimeType(accept_patterns, mime_type):
"""Return True iff mime_type is acceptable for one of accept_patterns.
Note that this function assumes that all patterns in accept_patterns
will be simple types of the form "type/subtype", where one or both
of these can be "*". We do not support param... | [
"def",
"AcceptableMimeType",
"(",
"accept_patterns",
",",
"mime_type",
")",
":",
"if",
"'/'",
"not",
"in",
"mime_type",
":",
"raise",
"exceptions",
".",
"InvalidUserInputError",
"(",
"'Invalid MIME type: \"%s\"'",
"%",
"mime_type",
")",
"unsupported_patterns",
"=",
... | 40.676471 | 19.823529 |
def disassemble_around(self, lpAddress, dwSize = 64):
"""
Disassemble around the given address.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@type dwSize: int
@param dwSize: Delta offset.
Code will be read from lpAddre... | [
"def",
"disassemble_around",
"(",
"self",
",",
"lpAddress",
",",
"dwSize",
"=",
"64",
")",
":",
"dwDelta",
"=",
"int",
"(",
"float",
"(",
"dwSize",
")",
"/",
"2.0",
")",
"addr_1",
"=",
"lpAddress",
"-",
"dwDelta",
"addr_2",
"=",
"lpAddress",
"size_1",
... | 36.96875 | 13.71875 |
def num_samples(self, sr=None):
"""
Return the number of samples.
Args:
sr (int): Calculate the number of samples with the given
sampling-rate. If None use the native sampling-rate.
Returns:
int: Number of samples
"""
native... | [
"def",
"num_samples",
"(",
"self",
",",
"sr",
"=",
"None",
")",
":",
"native_sr",
"=",
"self",
".",
"sampling_rate",
"num_samples",
"=",
"units",
".",
"seconds_to_sample",
"(",
"self",
".",
"duration",
",",
"native_sr",
")",
"if",
"sr",
"is",
"not",
"Non... | 29.263158 | 19.578947 |
def delete(self, addon_id, data={}, **kwargs):
"""
Delete addon for given id
Args:
addon_id : Id for which addon object has to be deleted
"""
return super(Addon, self).delete(addon_id, data, **kwargs) | [
"def",
"delete",
"(",
"self",
",",
"addon_id",
",",
"data",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Addon",
",",
"self",
")",
".",
"delete",
"(",
"addon_id",
",",
"data",
",",
"*",
"*",
"kwargs",
")"
] | 30.75 | 16.5 |
def format_int(n, singular=_Default, plural=_Default):
"""
Return `singular.format(n)` if n is 1, or `plural.format(n)` otherwise. If
plural is not specified, then it is assumed to be same as singular but
suffixed with an 's'.
:param n:
Integer which determines pluralness.
:param singu... | [
"def",
"format_int",
"(",
"n",
",",
"singular",
"=",
"_Default",
",",
"plural",
"=",
"_Default",
")",
":",
"n",
"=",
"int",
"(",
"n",
")",
"if",
"singular",
"in",
"(",
"None",
",",
"_Default",
")",
":",
"if",
"plural",
"is",
"_Default",
":",
"plura... | 26.636364 | 22.272727 |
def _Rforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | [
"def",
"_Rforce",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"l",
",",
"n",
"=",
"bovy_coords",
".",
"Rz_to_lambdanu",
"(",
"R",
",",
"z",
",",
"ac",
"=",
"self",
".",
"_ac",
",",
"Delta",
"=",
"s... | 32.227273 | 15.954545 |
def circuit_to_instruction(circuit):
"""Build an ``Instruction`` object from a ``QuantumCircuit``.
The instruction is anonymous (not tied to a named quantum register),
and so can be inserted into another circuit. The instruction will
have the same string name as the circuit.
Args:
circuit ... | [
"def",
"circuit_to_instruction",
"(",
"circuit",
")",
":",
"instruction",
"=",
"Instruction",
"(",
"name",
"=",
"circuit",
".",
"name",
",",
"num_qubits",
"=",
"sum",
"(",
"[",
"qreg",
".",
"size",
"for",
"qreg",
"in",
"circuit",
".",
"qregs",
"]",
")",
... | 38.869565 | 19.956522 |
def _replace_words(replacements, string):
"""Replace words with corresponding values in replacements dict.
Words must be separated by spaces or newlines.
"""
output_lines = []
for line in string.split('\n'):
output_words = []
for word in line.split(' '):
new_word = repla... | [
"def",
"_replace_words",
"(",
"replacements",
",",
"string",
")",
":",
"output_lines",
"=",
"[",
"]",
"for",
"line",
"in",
"string",
".",
"split",
"(",
"'\\n'",
")",
":",
"output_words",
"=",
"[",
"]",
"for",
"word",
"in",
"line",
".",
"split",
"(",
... | 37.923077 | 11.076923 |
def phantomjs(ctx, phantomjs_path, port, auto_restart, args):
"""
Run phantomjs fetcher if phantomjs is installed.
"""
args = args or ctx.default_map and ctx.default_map.get('args', [])
import subprocess
g = ctx.obj
_quit = []
phantomjs_fetcher = os.path.join(
os.path.dirname(py... | [
"def",
"phantomjs",
"(",
"ctx",
",",
"phantomjs_path",
",",
"port",
",",
"auto_restart",
",",
"args",
")",
":",
"args",
"=",
"args",
"or",
"ctx",
".",
"default_map",
"and",
"ctx",
".",
"default_map",
".",
"get",
"(",
"'args'",
",",
"[",
"]",
")",
"im... | 30.809524 | 19.809524 |
def _report_spelling_error(error, file_path):
"""Report a spelling error."""
line = error.line_offset + 1
code = "file/spelling_error"
description = _SPELLCHECK_MESSAGES[error.error_type].format(error.word)
if error.suggestions is not None:
description = (description +
... | [
"def",
"_report_spelling_error",
"(",
"error",
",",
"file_path",
")",
":",
"line",
"=",
"error",
".",
"line_offset",
"+",
"1",
"code",
"=",
"\"file/spelling_error\"",
"description",
"=",
"_SPELLCHECK_MESSAGES",
"[",
"error",
".",
"error_type",
"]",
".",
"format"... | 44.571429 | 14 |
def _parse_state_file(state_file_path='terraform.tfstate'):
'''
Parses the terraform state file passing different resource types to the right handler
'''
ret = {}
with salt.utils.files.fopen(state_file_path, 'r') as fh_:
tfstate = salt.utils.json.load(fh_)
modules = tfstate.get('modules... | [
"def",
"_parse_state_file",
"(",
"state_file_path",
"=",
"'terraform.tfstate'",
")",
":",
"ret",
"=",
"{",
"}",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"state_file_path",
",",
"'r'",
")",
"as",
"fh_",
":",
"tfstate",
"=",
"salt",
"... | 33.125 | 20.8125 |
def _validate_monotonic(self):
"""
Validate on is_monotonic.
"""
if not self._on.is_monotonic:
formatted = self.on or 'index'
raise ValueError("{0} must be "
"monotonic".format(formatted)) | [
"def",
"_validate_monotonic",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_on",
".",
"is_monotonic",
":",
"formatted",
"=",
"self",
".",
"on",
"or",
"'index'",
"raise",
"ValueError",
"(",
"\"{0} must be \"",
"\"monotonic\"",
".",
"format",
"(",
"format... | 33.25 | 5.5 |
def current_frame(self, n):
"""Sets current frame to ``n``
:param integer n: Frame to set to ``current_frame``
"""
self.sound.seek(n)
self._current_frame = n | [
"def",
"current_frame",
"(",
"self",
",",
"n",
")",
":",
"self",
".",
"sound",
".",
"seek",
"(",
"n",
")",
"self",
".",
"_current_frame",
"=",
"n"
] | 27.428571 | 13.571429 |
def _loadConfiguration(self):
"""
Load module configuration files.
:return: <void>
"""
configPath = os.path.join(self.path, "config")
if not os.path.isdir(configPath):
return
config = Config(configPath)
Config.mergeDictionaries(config.getDat... | [
"def",
"_loadConfiguration",
"(",
"self",
")",
":",
"configPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"\"config\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"configPath",
")",
":",
"return",
"config",
"=... | 25.923077 | 17.307692 |
def setup_app(config):
'''Deprecated.'''
if isinstance(config, str):
data = _deserialize(config)
elif isinstance(config, dict):
data = config
else:
raise ConfigError('must provide a filename or dictionary')
db_conn_data = data.pop('db', None)
app = App(**data)
if n... | [
"def",
"setup_app",
"(",
"config",
")",
":",
"if",
"isinstance",
"(",
"config",
",",
"str",
")",
":",
"data",
"=",
"_deserialize",
"(",
"config",
")",
"elif",
"isinstance",
"(",
"config",
",",
"dict",
")",
":",
"data",
"=",
"config",
"else",
":",
"ra... | 23.5 | 20.863636 |
def add(self, phrase, id=None):
"""
Adds a new phrase to the dictionary
:param phrase: the new phrase as a list of tokens
:param phrase_id: optionally the phrase_id can be set on addition. Beware, if you set one id you should set
them all as the auto-generated ids do not tak... | [
"def",
"add",
"(",
"self",
",",
"phrase",
",",
"id",
"=",
"None",
")",
":",
"phrase_id",
"=",
"id",
"if",
"id",
"is",
"not",
"None",
"else",
"self",
".",
"get_next_id",
"(",
")",
"PhraseDictionary",
".",
"_add_phrase",
"(",
"phrase",
",",
"phrase_id",
... | 51.727273 | 22.090909 |
def add_raw(self, length_tag, value_tag):
"""Define the tags used for a private raw data field.
:param length_tag: tag number of length field.
:param value_tag: tag number of value field.
Data fields are not terminated by the SOH character as is usual for
FIX, but instead have ... | [
"def",
"add_raw",
"(",
"self",
",",
"length_tag",
",",
"value_tag",
")",
":",
"self",
".",
"raw_len_tags",
".",
"append",
"(",
"length_tag",
")",
"self",
".",
"raw_data_tags",
".",
"append",
"(",
"value_tag",
")",
"return"
] | 44.375 | 22.4375 |
def readline(self, prompt='', use_raw=None):
"""Read a line of input. Prompt and use_raw exist to be
compatible with other input routines and are ignored.
EOFError will be raised on EOF.
"""
line = self.input.readline()
if not line: raise EOFError
return line.rstr... | [
"def",
"readline",
"(",
"self",
",",
"prompt",
"=",
"''",
",",
"use_raw",
"=",
"None",
")",
":",
"line",
"=",
"self",
".",
"input",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"raise",
"EOFError",
"return",
"line",
".",
"rstrip",
"(",
"\"\... | 40.125 | 5.375 |
def _find_titles(self, row_index, column_index):
'''
Helper method to find all titles for a particular cell.
'''
titles = []
for column_search in range(self.start[1], column_index):
cell = self.table[row_index][column_search]
if cell == None or (isinstanc... | [
"def",
"_find_titles",
"(",
"self",
",",
"row_index",
",",
"column_index",
")",
":",
"titles",
"=",
"[",
"]",
"for",
"column_search",
"in",
"range",
"(",
"self",
".",
"start",
"[",
"1",
"]",
",",
"column_index",
")",
":",
"cell",
"=",
"self",
".",
"t... | 33.64 | 21.16 |
def private_config_content(self, private_config):
"""
Update the private config
:param private_config: content of the private configuration file
"""
try:
private_config_path = os.path.join(self.working_dir, "private-config.cfg")
if private_config is Non... | [
"def",
"private_config_content",
"(",
"self",
",",
"private_config",
")",
":",
"try",
":",
"private_config_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"\"private-config.cfg\"",
")",
"if",
"private_config",
"is",
"None",
":... | 36.92 | 23.24 |
def register_aggregations():
"""Register sample aggregations."""
return [dict(
aggregation_name='file-download-agg',
templates='invenio_stats.contrib.aggregations.aggr_file_download',
aggregator_class=StatAggregator,
aggregator_config=dict(
client=current_search_clien... | [
"def",
"register_aggregations",
"(",
")",
":",
"return",
"[",
"dict",
"(",
"aggregation_name",
"=",
"'file-download-agg'",
",",
"templates",
"=",
"'invenio_stats.contrib.aggregations.aggr_file_download'",
",",
"aggregator_class",
"=",
"StatAggregator",
",",
"aggregator_conf... | 38 | 11.475 |
def local_attr(self, name, context=None):
"""Get the list of assign nodes associated to the given name.
Assignments are looked for in both this class and in parents.
:returns: The list of assignments to the given name.
:rtype: list(NodeNG)
:raises AttributeInferenceError: If n... | [
"def",
"local_attr",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"if",
"name",
"in",
"self",
".",
"locals",
":",
"result",
"=",
"self",
".",
"locals",
"[",
"name",
"]",
"else",
":",
"class_node",
"=",
... | 37.25 | 20 |
def get_asset_contents(self):
"""Gets the content of this asset.
return: (osid.repository.AssetContentList) - the asset contents
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from templ... | [
"def",
"get_asset_contents",
"(",
"self",
")",
":",
"# Implemented from template for osid.repository.Asset.get_asset_contents_template",
"return",
"AssetContentList",
"(",
"self",
".",
"_my_map",
"[",
"'assetContents'",
"]",
",",
"runtime",
"=",
"self",
".",
"_runtime",
"... | 39 | 18.769231 |
def round_teff_luminosity(cluster):
"""
Returns rounded teff and luminosity lists.
"""
temps = [round(t, -1) for t in teff(cluster)]
lums = [round(l, 3) for l in luminosity(cluster)]
return temps, lums | [
"def",
"round_teff_luminosity",
"(",
"cluster",
")",
":",
"temps",
"=",
"[",
"round",
"(",
"t",
",",
"-",
"1",
")",
"for",
"t",
"in",
"teff",
"(",
"cluster",
")",
"]",
"lums",
"=",
"[",
"round",
"(",
"l",
",",
"3",
")",
"for",
"l",
"in",
"lumin... | 31.285714 | 7.285714 |
def find_pyqt5(python):
"""Search for PyQt5 automatically"""
pyqt5 = (
_state.get("pyqt5") or
os.getenv("PYBLISH_QML_PYQT5")
)
# If not registered, ask Python for it explicitly
# This avoids having to expose PyQt5 on PYTHONPATH
# where it may otherwise get picked up by bystander... | [
"def",
"find_pyqt5",
"(",
"python",
")",
":",
"pyqt5",
"=",
"(",
"_state",
".",
"get",
"(",
"\"pyqt5\"",
")",
"or",
"os",
".",
"getenv",
"(",
"\"PYBLISH_QML_PYQT5\"",
")",
")",
"# If not registered, ask Python for it explicitly",
"# This avoids having to expose PyQt5 ... | 27.592593 | 18.925926 |
def remove_text_inside_brackets(s, brackets="()[]"):
"""
From http://stackoverflow.com/a/14603508/610569
"""
count = [0] * (len(brackets) // 2) # count open/close brackets
saved_chars = []
for character in s:
for i, b in enumerate(brackets):
if character == b: # found bracket... | [
"def",
"remove_text_inside_brackets",
"(",
"s",
",",
"brackets",
"=",
"\"()[]\"",
")",
":",
"count",
"=",
"[",
"0",
"]",
"*",
"(",
"len",
"(",
"brackets",
")",
"//",
"2",
")",
"# count open/close brackets",
"saved_chars",
"=",
"[",
"]",
"for",
"character",... | 39.277778 | 10.722222 |
def fullname(self):
""" includes the full path with parent names """
prefix = ""
if self.parent:
if self.parent.fullname:
prefix = self.parent.fullname + ":"
else:
# Only the root does not have a parent. In that case we also don't need a name.
... | [
"def",
"fullname",
"(",
"self",
")",
":",
"prefix",
"=",
"\"\"",
"if",
"self",
".",
"parent",
":",
"if",
"self",
".",
"parent",
".",
"fullname",
":",
"prefix",
"=",
"self",
".",
"parent",
".",
"fullname",
"+",
"\":\"",
"else",
":",
"# Only the root doe... | 32.909091 | 19.818182 |
def request(self, uri, method=GET, headers=None, cookies=None, params=None, data=None, post_files=None,**kwargs):
"""Makes a request using requests
@param uri: The uri to send request
@param method: Method to use to send request
@param headers: Any headers to send with request
@... | [
"def",
"request",
"(",
"self",
",",
"uri",
",",
"method",
"=",
"GET",
",",
"headers",
"=",
"None",
",",
"cookies",
"=",
"None",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"post_files",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":... | 31.382979 | 20.489362 |
def _parse_properties(response, result_class):
'''
Extracts out resource properties and metadata information.
Ignores the standard http headers.
'''
if response is None or response.headers is None:
return None
props = result_class()
for key, value in response.headers.items():
... | [
"def",
"_parse_properties",
"(",
"response",
",",
"result_class",
")",
":",
"if",
"response",
"is",
"None",
"or",
"response",
".",
"headers",
"is",
"None",
":",
"return",
"None",
"props",
"=",
"result_class",
"(",
")",
"for",
"key",
",",
"value",
"in",
"... | 35.454545 | 23 |
def _createDataStructure(self, content):
"""
This method receives a response, including headers, and creates the appropriate structure.
:param url: The URL to be recovered.
:param content: The content of the response.
:return: A json. ... | [
"def",
"_createDataStructure",
"(",
"self",
",",
"content",
")",
":",
"aux",
"=",
"{",
"}",
"aux",
"[",
"\"headers\"",
"]",
"=",
"{",
"}",
"aux",
"[",
"\"content\"",
"]",
"=",
"\"\"",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"content",
".",
... | 38.12 | 18.2 |
def get_ids(search_term, **kwargs):
"""Search Pubmed for paper IDs given a search term.
Search options can be passed as keyword arguments, some of which are
custom keywords identified by this function, while others are passed on
as parameters for the request to the PubMed web service
For details on... | [
"def",
"get_ids",
"(",
"search_term",
",",
"*",
"*",
"kwargs",
")",
":",
"use_text_word",
"=",
"kwargs",
".",
"pop",
"(",
"'use_text_word'",
",",
"True",
")",
"if",
"use_text_word",
":",
"search_term",
"+=",
"'[tw]'",
"params",
"=",
"{",
"'term'",
":",
"... | 43.68254 | 20.730159 |
async def result(self, timeout: Optional[float] = None, *, pole_delay: float = 0.5) -> Any:
"""
Get the result of the job, including waiting if it's not yet available. If the job raised an exception,
it will be raised here.
:param timeout: maximum time to wait for the job result before ... | [
"async",
"def",
"result",
"(",
"self",
",",
"timeout",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
",",
"*",
",",
"pole_delay",
":",
"float",
"=",
"0.5",
")",
"->",
"Any",
":",
"async",
"for",
"delay",
"in",
"poll",
"(",
"pole_delay",
")",
":"... | 44.333333 | 20.333333 |
def _advapi32_generate_pair(algorithm, bit_size=None):
"""
Generates a public/private key pair using CryptoAPI
:param algorithm:
The key algorithm - "rsa" or "dsa"
:param bit_size:
An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024,
2048, 3072 or 4096. For ... | [
"def",
"_advapi32_generate_pair",
"(",
"algorithm",
",",
"bit_size",
"=",
"None",
")",
":",
"if",
"algorithm",
"==",
"'rsa'",
":",
"provider",
"=",
"Advapi32Const",
".",
"MS_ENH_RSA_AES_PROV",
"algorithm_id",
"=",
"Advapi32Const",
".",
"CALG_RSA_SIGN",
"struct_type"... | 32.553571 | 22.785714 |
def _push(self, undoObj: QtmacsUndoCommand):
"""
The actual method that adds the command object onto the stack.
This method also toggles the ``nextIsRedo`` flag in the
command object and, depending on its value, executes either
the ``commit`` or ``reverseCommit`` method of the o... | [
"def",
"_push",
"(",
"self",
",",
"undoObj",
":",
"QtmacsUndoCommand",
")",
":",
"self",
".",
"_qteStack",
".",
"append",
"(",
"undoObj",
")",
"if",
"undoObj",
".",
"nextIsRedo",
":",
"undoObj",
".",
"commit",
"(",
")",
"else",
":",
"undoObj",
".",
"re... | 46.869565 | 20.173913 |
def _find_child(self, tag):
"""Find the child C{etree.Element} with the matching C{tag}.
@raises L{WSDLParseError}: If more than one such elements are found.
"""
tag = self._get_namespace_tag(tag)
children = self._root.findall(tag)
if len(children) > 1:
raise... | [
"def",
"_find_child",
"(",
"self",
",",
"tag",
")",
":",
"tag",
"=",
"self",
".",
"_get_namespace_tag",
"(",
"tag",
")",
"children",
"=",
"self",
".",
"_root",
".",
"findall",
"(",
"tag",
")",
"if",
"len",
"(",
"children",
")",
">",
"1",
":",
"rais... | 36.166667 | 13.75 |
def createEvent(self, physicalInterfaceId, eventTypeId, eventId):
"""
Create an event mapping for a physical interface.
Parameters:
physicalInterfaceId (string) - value returned by the platform when creating the physical interface
eventTypeId (string) - value returned by the ... | [
"def",
"createEvent",
"(",
"self",
",",
"physicalInterfaceId",
",",
"eventTypeId",
",",
"eventId",
")",
":",
"req",
"=",
"ApiClient",
".",
"allEventsUrl",
"%",
"(",
"self",
".",
"host",
",",
"\"/draft\"",
",",
"physicalInterfaceId",
")",
"body",
"=",
"{",
... | 57.055556 | 27.833333 |
def as_json(data, **kwargs):
"""Writes data as json.
:param dict data: data to convert to json
:param kwargs kwargs: kwargs for json dumps
:return: json string
:rtype: str
"""
if 'sort_keys' not in kwargs:
kwargs['sort_keys'] = False
if 'ensure_ascii' not in kwargs:
kwa... | [
"def",
"as_json",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'sort_keys'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'sort_keys'",
"]",
"=",
"False",
"if",
"'ensure_ascii'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'ensure_ascii'",
"]",
... | 22.764706 | 15.941176 |
def state(self, metric=None, index=None, params=None):
"""
Get a comprehensive state information of the whole cluster.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-state.html>`_
:arg metric: Limit the information returned to the specified metrics
:arg... | [
"def",
"state",
"(",
"self",
",",
"metric",
"=",
"None",
",",
"index",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"index",
"and",
"not",
"metric",
":",
"metric",
"=",
"'_all'",
"return",
"self",
".",
"transport",
".",
"perform_request",
... | 57.72 | 24.92 |
def read_sampling_params_from_config(cp, section_group=None,
section='sampling_params'):
"""Reads sampling parameters from the given config file.
Parameters are read from the `[({section_group}_){section}]` section.
The options should list the variable args to transform... | [
"def",
"read_sampling_params_from_config",
"(",
"cp",
",",
"section_group",
"=",
"None",
",",
"section",
"=",
"'sampling_params'",
")",
":",
"if",
"section_group",
"is",
"not",
"None",
":",
"section_prefix",
"=",
"'{}_'",
".",
"format",
"(",
"section_group",
")"... | 39.019608 | 21.745098 |
def get_tile_info_id(tile_id):
""" Get basic information about image tile
:param tile_id: original tile identification string provided by ESA (e.g.
'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01')
:type tile_id: str
:return: dictionary with info provided by Opensear... | [
"def",
"get_tile_info_id",
"(",
"tile_id",
")",
":",
"result_list",
"=",
"list",
"(",
"search_iter",
"(",
"tile_id",
"=",
"tile_id",
")",
")",
"if",
"not",
"result_list",
":",
"raise",
"TileMissingException",
"if",
"len",
"(",
"result_list",
")",
">",
"1",
... | 39.789474 | 27.947368 |
def add_asset(self, asset_id, composition_id):
"""Appends an asset to a composition.
arg: asset_id (osid.id.Id): ``Id`` of the ``Asset``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
raise: AlreadyExists - ``asset_id`` already part
... | [
"def",
"add_asset",
"(",
"self",
",",
"asset_id",
",",
"composition_id",
")",
":",
"self",
".",
"_provider_session",
".",
"add_asset",
"(",
"self",
",",
"asset_id",
",",
"composition_id",
")"
] | 44.882353 | 19.352941 |
def ranker(self, X, meta):
"""
Sort the place features list by the score of its relevance.
"""
# total score is just a sum of each row
total_score = X.sum(axis=1).transpose()
total_score = np.squeeze(np.asarray(total_score)) # matrix to array
ranks = total_score.... | [
"def",
"ranker",
"(",
"self",
",",
"X",
",",
"meta",
")",
":",
"# total score is just a sum of each row",
"total_score",
"=",
"X",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
".",
"transpose",
"(",
")",
"total_score",
"=",
"np",
".",
"squeeze",
"(",
"np",
... | 39.307692 | 10.692308 |
def location_name(self, name):
""" location.name """
response = self._request(
'location.name',
input=name)
return _get_node(response, 'LocationList', 'StopLocation') | [
"def",
"location_name",
"(",
"self",
",",
"name",
")",
":",
"response",
"=",
"self",
".",
"_request",
"(",
"'location.name'",
",",
"input",
"=",
"name",
")",
"return",
"_get_node",
"(",
"response",
",",
"'LocationList'",
",",
"'StopLocation'",
")"
] | 34.833333 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.