text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def number_arg(ctx, obj):
'''
Handles LiteralObjects as well as computable arguments
'''
if hasattr(obj, 'compute'):
obj = next(obj.compute(ctx), False)
return to_number(obj) | [
"def",
"number_arg",
"(",
"ctx",
",",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'compute'",
")",
":",
"obj",
"=",
"next",
"(",
"obj",
".",
"compute",
"(",
"ctx",
")",
",",
"False",
")",
"return",
"to_number",
"(",
"obj",
")"
] | 28 | 18 |
def process(in_path, annot_beats=False, feature="mfcc", framesync=False,
boundaries_id="gt", labels_id=None, n_jobs=4, config=None):
"""Sweeps parameters across the specified algorithm."""
results_file = "results_sweep_boundsE%s_labelsE%s.csv" % (boundaries_id,
... | [
"def",
"process",
"(",
"in_path",
",",
"annot_beats",
"=",
"False",
",",
"feature",
"=",
"\"mfcc\"",
",",
"framesync",
"=",
"False",
",",
"boundaries_id",
"=",
"\"gt\"",
",",
"labels_id",
"=",
"None",
",",
"n_jobs",
"=",
"4",
",",
"config",
"=",
"None",
... | 46.092784 | 20.639175 |
def fetch(self):
"""Fetch the data for the model from Redis and assign the values.
:rtype: bool
"""
raw = yield gen.Task(self._redis_client.get, self._key)
if raw:
self.loads(base64.b64decode(raw))
raise gen.Return(True)
raise gen.Return(False) | [
"def",
"fetch",
"(",
"self",
")",
":",
"raw",
"=",
"yield",
"gen",
".",
"Task",
"(",
"self",
".",
"_redis_client",
".",
"get",
",",
"self",
".",
"_key",
")",
"if",
"raw",
":",
"self",
".",
"loads",
"(",
"base64",
".",
"b64decode",
"(",
"raw",
")"... | 28 | 17.454545 |
def _connect(self):
"""
Connect to the graphite server
"""
if (self.proto == 'udp'):
stream = socket.SOCK_DGRAM
else:
stream = socket.SOCK_STREAM
if (self.proto[-1] == '4'):
family = socket.AF_INET
connection_struct = (self... | [
"def",
"_connect",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"proto",
"==",
"'udp'",
")",
":",
"stream",
"=",
"socket",
".",
"SOCK_DGRAM",
"else",
":",
"stream",
"=",
"socket",
".",
"SOCK_STREAM",
"if",
"(",
"self",
".",
"proto",
"[",
"-",
"1"... | 40.910448 | 16.880597 |
def RqueryBM(query_filter,query_items,query_attributes,dataset,database,host=rbiomart_host):
"""
Queries BioMart.
:param query_filtery: one BioMart filter associated with the items being queried
:param query_items: list of items to be queried (must assoiate with given filter)
:param query_attribute... | [
"def",
"RqueryBM",
"(",
"query_filter",
",",
"query_items",
",",
"query_attributes",
",",
"dataset",
",",
"database",
",",
"host",
"=",
"rbiomart_host",
")",
":",
"biomaRt",
"=",
"importr",
"(",
"\"biomaRt\"",
")",
"ensemblMart",
"=",
"biomaRt",
".",
"useMart"... | 42.956522 | 25.565217 |
def _transform_item(self, content_metadata_item):
"""
Transform the provided content metadata item to the schema expected by the integrated channel.
"""
content_metadata_type = content_metadata_item['content_type']
transformed_item = {}
for integrated_channel_schema_key, ... | [
"def",
"_transform_item",
"(",
"self",
",",
"content_metadata_item",
")",
":",
"content_metadata_type",
"=",
"content_metadata_item",
"[",
"'content_type'",
"]",
"transformed_item",
"=",
"{",
"}",
"for",
"integrated_channel_schema_key",
",",
"edx_data_schema_key",
"in",
... | 46.478261 | 24.434783 |
def visit_dictcomp(self, node, parent):
"""visit a DictComp node by returning a fresh instance of it"""
newnode = nodes.DictComp(node.lineno, node.col_offset, parent)
newnode.postinit(
self.visit(node.key, newnode),
self.visit(node.value, newnode),
[self.visit... | [
"def",
"visit_dictcomp",
"(",
"self",
",",
"node",
",",
"parent",
")",
":",
"newnode",
"=",
"nodes",
".",
"DictComp",
"(",
"node",
".",
"lineno",
",",
"node",
".",
"col_offset",
",",
"parent",
")",
"newnode",
".",
"postinit",
"(",
"self",
".",
"visit",... | 43.555556 | 14.555556 |
def get(self, number):
"""
Return a pattern for a number.
@param number (int) Number of pattern
@return (set) Indices of on bits
"""
if not number in self._patterns:
raise IndexError("Invalid number")
return self._patterns[number] | [
"def",
"get",
"(",
"self",
",",
"number",
")",
":",
"if",
"not",
"number",
"in",
"self",
".",
"_patterns",
":",
"raise",
"IndexError",
"(",
"\"Invalid number\"",
")",
"return",
"self",
".",
"_patterns",
"[",
"number",
"]"
] | 21.333333 | 13.333333 |
def command(state, args):
"""Watch an anime."""
if len(args) < 2:
print(f'Usage: {args[0]} {{ID|aid:AID}} [EPISODE]')
return
aid = state.results.parse_aid(args[1], default_key='db')
anime = query.select.lookup(state.db, aid)
if len(args) < 3:
episode = anime.watched_episodes ... | [
"def",
"command",
"(",
"state",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"print",
"(",
"f'Usage: {args[0]} {{ID|aid:AID}} [EPISODE]'",
")",
"return",
"aid",
"=",
"state",
".",
"results",
".",
"parse_aid",
"(",
"args",
"[",
"1"... | 32.296296 | 16.407407 |
def _find_path(start, end, path=tuple()):
"""Return the path from start to end.
If no path exists, return None.
"""
path = path + (start, )
if start is end:
return path
else:
ret = None
if start.lo is not None:
ret = _find_path(start.lo, end, path)
if... | [
"def",
"_find_path",
"(",
"start",
",",
"end",
",",
"path",
"=",
"tuple",
"(",
")",
")",
":",
"path",
"=",
"path",
"+",
"(",
"start",
",",
")",
"if",
"start",
"is",
"end",
":",
"return",
"path",
"else",
":",
"ret",
"=",
"None",
"if",
"start",
"... | 27.533333 | 13.933333 |
def iterate(self, max_number_of_files=None):
"""iterate([max_number_of_files]) -> image, bounding_boxes, image_file
Yields the image and the bounding boxes stored in the training set as an iterator.
This function loads the images and converts them to gray-scale.
It yields the image, the list of boundi... | [
"def",
"iterate",
"(",
"self",
",",
"max_number_of_files",
"=",
"None",
")",
":",
"indices",
"=",
"quasi_random_indices",
"(",
"len",
"(",
"self",
")",
",",
"max_number_of_files",
")",
"for",
"index",
"in",
"indices",
":",
"image",
"=",
"bob",
".",
"io",
... | 39.548387 | 26.290323 |
def rhymes(word):
"""Get words rhyming with a given word.
This function may return an empty list if no rhyming words are found in
the dictionary, or if the word you pass to the function is itself not
found in the dictionary.
.. doctest::
>>> import pronouncing
>>> pronouncing.rhym... | [
"def",
"rhymes",
"(",
"word",
")",
":",
"phones",
"=",
"phones_for_word",
"(",
"word",
")",
"combined_rhymes",
"=",
"[",
"]",
"if",
"phones",
":",
"for",
"element",
"in",
"phones",
":",
"combined_rhymes",
".",
"append",
"(",
"[",
"w",
"for",
"w",
"in",... | 33.259259 | 21.333333 |
def setCurrentQuery(self, query):
"""
Sets the query for the current container widget. This will only change
the active container, not parent containers. You should use the
setQuery method to completely assign a query to this widget.
:param query | <orb.Quer... | [
"def",
"setCurrentQuery",
"(",
"self",
",",
"query",
")",
":",
"container",
"=",
"self",
".",
"currentContainer",
"(",
")",
"if",
"container",
":",
"container",
".",
"setQuery",
"(",
"query",
")"
] | 39.272727 | 14.909091 |
def element_tree_oai_records(tree, header_subs=None):
"""Take an ElementTree and converts the nodes into BibRecord records.
This expects a clean OAI response with the tree root as ListRecords
or GetRecord and record as the subtag like so:
<ListRecords|GetRecord>
<record>
<header>
... | [
"def",
"element_tree_oai_records",
"(",
"tree",
",",
"header_subs",
"=",
"None",
")",
":",
"from",
".",
"bibrecord",
"import",
"record_add_field",
",",
"create_record",
"if",
"not",
"header_subs",
":",
"header_subs",
"=",
"[",
"]",
"# Make it a tuple, this informati... | 36.566667 | 18.2 |
def get_page_object_by_name(context, name):
"""
**Arguments**
``name`
name for object selection
:return selected object
"""
selected_object = None
try:
for obj_type in context['page']['content']:
for obj in context['page']['content'][obj_type]:
... | [
"def",
"get_page_object_by_name",
"(",
"context",
",",
"name",
")",
":",
"selected_object",
"=",
"None",
"try",
":",
"for",
"obj_type",
"in",
"context",
"[",
"'page'",
"]",
"[",
"'content'",
"]",
":",
"for",
"obj",
"in",
"context",
"[",
"'page'",
"]",
"[... | 27.807692 | 16.038462 |
def init_validator(required, cls, *additional_validators):
"""
Create an attrs validator based on the cls provided and required setting.
:param bool required: whether the field is required in a given model.
:param cls: the expected class type of object value.
:return: attrs validator chained correct... | [
"def",
"init_validator",
"(",
"required",
",",
"cls",
",",
"*",
"additional_validators",
")",
":",
"validator",
"=",
"validators",
".",
"instance_of",
"(",
"cls",
")",
"if",
"additional_validators",
":",
"additional_validators",
"=",
"list",
"(",
"additional_valid... | 43.466667 | 20 |
def mremove(self, class_name, names):
"""
Removes multiple components from the network.
Removes them from component DataFrames.
Parameters
----------
class_name : string
Component class name
name : list-like
Component names
Examp... | [
"def",
"mremove",
"(",
"self",
",",
"class_name",
",",
"names",
")",
":",
"if",
"class_name",
"not",
"in",
"self",
".",
"components",
":",
"logger",
".",
"error",
"(",
"\"Component class {} not found\"",
".",
"format",
"(",
"class_name",
")",
")",
"return",
... | 24.470588 | 20.470588 |
def closeContentsWidget( self ):
"""
Closes the current contents widget.
"""
widget = self.currentContentsWidget()
if ( not widget ):
return
widget.close()
widget.setParent(None)
widget.deleteLater() | [
"def",
"closeContentsWidget",
"(",
"self",
")",
":",
"widget",
"=",
"self",
".",
"currentContentsWidget",
"(",
")",
"if",
"(",
"not",
"widget",
")",
":",
"return",
"widget",
".",
"close",
"(",
")",
"widget",
".",
"setParent",
"(",
"None",
")",
"widget",
... | 26.181818 | 10.545455 |
def to(self, target: typing.Union[types.Message, types.Chat, types.base.Integer, types.base.String]):
"""
Send to chat
:param target: message or chat or id
:return:
"""
if isinstance(target, types.Message):
chat_id = target.chat.id
elif isinstance(tar... | [
"def",
"to",
"(",
"self",
",",
"target",
":",
"typing",
".",
"Union",
"[",
"types",
".",
"Message",
",",
"types",
".",
"Chat",
",",
"types",
".",
"base",
".",
"Integer",
",",
"types",
".",
"base",
".",
"String",
"]",
")",
":",
"if",
"isinstance",
... | 31.777778 | 16.888889 |
def _generate_url(self, regex, arguments):
"""
Uses the regex (of the type defined in Django's url patterns) and the arguments to return a relative URL
For example, if the regex is '^/api/shreddr/job/(?P<id>[\d]+)$' and arguments is ['23']
then return would be '/api/shreddr/job/23'
... | [
"def",
"_generate_url",
"(",
"self",
",",
"regex",
",",
"arguments",
")",
":",
"regex_tokens",
"=",
"_split_regex",
"(",
"regex",
")",
"result",
"=",
"''",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"arguments",
")",
")",
":",
"result",
"=",
"result",... | 45.846154 | 16.923077 |
def visualRect(self, index):
"""
Returns the visual rectangle for the inputed index.
:param index | <QModelIndex>
:return <QtCore.QRect>
"""
rect = super(XTreeWidget, self).visualRect(index)
item = self.itemFromIndex(index)
... | [
"def",
"visualRect",
"(",
"self",
",",
"index",
")",
":",
"rect",
"=",
"super",
"(",
"XTreeWidget",
",",
"self",
")",
".",
"visualRect",
"(",
"index",
")",
"item",
"=",
"self",
".",
"itemFromIndex",
"(",
"index",
")",
"if",
"not",
"rect",
".",
"isNul... | 35.1875 | 14.0625 |
def clear_commentarea_cache(comment):
"""
Clean the plugin output cache of a rendered plugin.
"""
parent = comment.content_object
for instance in CommentsAreaItem.objects.parent(parent):
instance.clear_cache() | [
"def",
"clear_commentarea_cache",
"(",
"comment",
")",
":",
"parent",
"=",
"comment",
".",
"content_object",
"for",
"instance",
"in",
"CommentsAreaItem",
".",
"objects",
".",
"parent",
"(",
"parent",
")",
":",
"instance",
".",
"clear_cache",
"(",
")"
] | 33 | 7.571429 |
def _verify_any(self):
"""
Verify that an initial request has been made, or failing that, that
the request is in the session
:raises: LTIException
"""
log.debug('verify_any enter')
# Check to see if there is a new LTI launch request incoming
newrequest = ... | [
"def",
"_verify_any",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'verify_any enter'",
")",
"# Check to see if there is a new LTI launch request incoming",
"newrequest",
"=",
"False",
"if",
"flask_request",
".",
"method",
"==",
"'POST'",
":",
"params",
"=",
"f... | 37.37037 | 13.888889 |
def bs_values_df(run_list, estimator_list, estimator_names, n_simulate,
**kwargs):
"""Computes a data frame of bootstrap resampled values.
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
estimator_list: list of functions
Estimators t... | [
"def",
"bs_values_df",
"(",
"run_list",
",",
"estimator_list",
",",
"estimator_names",
",",
"n_simulate",
",",
"*",
"*",
"kwargs",
")",
":",
"tqdm_kwargs",
"=",
"kwargs",
".",
"pop",
"(",
"'tqdm_kwargs'",
",",
"{",
"'desc'",
":",
"'bs values'",
"}",
")",
"... | 40.833333 | 18.309524 |
def get(self, key=NOT_SET, index=NOT_SET, d=None):
"""Return value with given key or index.
If no value is found, return d (None by default).
"""
if index is NOT_SET and key is not NOT_SET:
try:
index, value = self._dict[key]
except KeyError:
return d
else:
return value
elif index is not... | [
"def",
"get",
"(",
"self",
",",
"key",
"=",
"NOT_SET",
",",
"index",
"=",
"NOT_SET",
",",
"d",
"=",
"None",
")",
":",
"if",
"index",
"is",
"NOT_SET",
"and",
"key",
"is",
"not",
"NOT_SET",
":",
"try",
":",
"index",
",",
"value",
"=",
"self",
".",
... | 22.285714 | 19.285714 |
def setup_menus():
'''setup console menus'''
menu = MPMenuTop([])
menu.add(MPMenuSubMenu('MAVExplorer',
items=[MPMenuItem('Settings', 'Settings', 'menuSettings'),
MPMenuItem('Map', 'Map', '# map'),
MPMenuItem('Sav... | [
"def",
"setup_menus",
"(",
")",
":",
"menu",
"=",
"MPMenuTop",
"(",
"[",
"]",
")",
"menu",
".",
"add",
"(",
"MPMenuSubMenu",
"(",
"'MAVExplorer'",
",",
"items",
"=",
"[",
"MPMenuItem",
"(",
"'Settings'",
",",
"'Settings'",
",",
"'menuSettings'",
")",
","... | 47.5 | 24.5 |
def data_item(self) -> DataItem:
"""Return the data item associated with this display panel.
.. versionadded:: 1.0
Scriptable: Yes
"""
display_panel = self.__display_panel
if not display_panel:
return None
data_item = display_panel.data_item
... | [
"def",
"data_item",
"(",
"self",
")",
"->",
"DataItem",
":",
"display_panel",
"=",
"self",
".",
"__display_panel",
"if",
"not",
"display_panel",
":",
"return",
"None",
"data_item",
"=",
"display_panel",
".",
"data_item",
"return",
"DataItem",
"(",
"data_item",
... | 29.833333 | 14 |
def safe_import_module(module_name):
"""
Like :func:`importlib.import_module`, except it does not raise ``ImportError``
if the requested ``module_name`` was not found.
"""
try:
return import_module(module_name)
except ImportError as e:
m = re.match(r"No module named '([\w\.]+)'",... | [
"def",
"safe_import_module",
"(",
"module_name",
")",
":",
"try",
":",
"return",
"import_module",
"(",
"module_name",
")",
"except",
"ImportError",
"as",
"e",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r\"No module named '([\\w\\.]+)'\"",
",",
"str",
"(",
"e",
... | 36.181818 | 14.727273 |
def binned_pixelrange(self, waverange, **kwargs):
"""Calculate the number of pixels within the given wavelength
range and `binset`.
Parameters
----------
waverange : tuple of float or `~astropy.units.quantity.Quantity`
Lower and upper limits of the desired wavelength... | [
"def",
"binned_pixelrange",
"(",
"self",
",",
"waverange",
",",
"*",
"*",
"kwargs",
")",
":",
"x",
"=",
"units",
".",
"validate_quantity",
"(",
"waverange",
",",
"self",
".",
"_internal_wave_unit",
",",
"equivalencies",
"=",
"u",
".",
"spectral",
"(",
")",... | 33.590909 | 22.954545 |
def sendmail(self, msg_from, msg_to, msg):
"""Remember the recipients."""
SMTP_dummy.msg_from = msg_from
SMTP_dummy.msg_to = msg_to
SMTP_dummy.msg = msg | [
"def",
"sendmail",
"(",
"self",
",",
"msg_from",
",",
"msg_to",
",",
"msg",
")",
":",
"SMTP_dummy",
".",
"msg_from",
"=",
"msg_from",
"SMTP_dummy",
".",
"msg_to",
"=",
"msg_to",
"SMTP_dummy",
".",
"msg",
"=",
"msg"
] | 36 | 4.4 |
def format_python2_stmts(python_stmts, show_tokens=False, showast=False,
showgrammar=False, compile_mode='exec'):
"""
formats python2 statements
"""
parser_debug = {'rules': False, 'transition': False,
'reduce': showgrammar,
'errorstack':... | [
"def",
"format_python2_stmts",
"(",
"python_stmts",
",",
"show_tokens",
"=",
"False",
",",
"showast",
"=",
"False",
",",
"showgrammar",
"=",
"False",
",",
"compile_mode",
"=",
"'exec'",
")",
":",
"parser_debug",
"=",
"{",
"'rules'",
":",
"False",
",",
"'tran... | 34.227273 | 21.590909 |
def _addsub_int_array(self, other, op):
"""
Add or subtract array-like of integers equivalent to applying
`_time_shift` pointwise.
Parameters
----------
other : Index, ExtensionArray, np.ndarray
integer-dtype
op : {operator.add, operator.sub}
... | [
"def",
"_addsub_int_array",
"(",
"self",
",",
"other",
",",
"op",
")",
":",
"# _addsub_int_array is overriden by PeriodArray",
"assert",
"not",
"is_period_dtype",
"(",
"self",
")",
"assert",
"op",
"in",
"[",
"operator",
".",
"add",
",",
"operator",
".",
"sub",
... | 31.75 | 16.25 |
def showtraceback(self, *args, **kwargs):
"""Display the exception that just occurred.
We remove the first stack item because it is our own code.
The output is written by self.write(), below.
"""
try:
type, value, tb = sys.exc_info()
sys.last_type = typ... | [
"def",
"showtraceback",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"type",
",",
"value",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"sys",
".",
"last_type",
"=",
"type",
"sys",
".",
"last_value",
"=",
"va... | 33.590909 | 16.727273 |
def prefix_all(self, prefix='#', *lines):
"""
Same as :func:`~prefix`, for multiple lines.
:param prefix: Dockerfile command to use, e.g. ``ENV`` or ``RUN``.
:type prefix: unicode | str
:param lines: Lines with arguments to be prefixed.
:type lines: collections.Iterable[... | [
"def",
"prefix_all",
"(",
"self",
",",
"prefix",
"=",
"'#'",
",",
"*",
"lines",
")",
":",
"for",
"line",
"in",
"lines",
":",
"if",
"isinstance",
"(",
"line",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"self",
".",
"prefix",
"(",
"prefix",
","... | 35.0625 | 12.6875 |
def __process_parameter(self, param_name, param_type, ancestry=None):
"""Collect values for a given web service operation input parameter."""
assert self.active()
param_optional = param_type.optional()
has_argument, value = self.__get_param_value(param_name)
if has_argument:
... | [
"def",
"__process_parameter",
"(",
"self",
",",
"param_name",
",",
"param_type",
",",
"ancestry",
"=",
"None",
")",
":",
"assert",
"self",
".",
"active",
"(",
")",
"param_optional",
"=",
"param_type",
".",
"optional",
"(",
")",
"has_argument",
",",
"value",
... | 53.727273 | 15.454545 |
def list_symbols(self, all_symbols=False, snapshot=None, regex=None, **kwargs):
"""
Return the symbols in this library.
Parameters
----------
all_symbols : `bool`
If True returns all symbols under all snapshots, even if the symbol has been deleted
in the ... | [
"def",
"list_symbols",
"(",
"self",
",",
"all_symbols",
"=",
"False",
",",
"snapshot",
"=",
"None",
",",
"regex",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"{",
"}",
"if",
"regex",
"is",
"not",
"None",
":",
"query",
"[",
"'symbo... | 46.071429 | 26.928571 |
def grey_transmittance(extinction_coefficient, molar_density, length, base=e):
r'''Calculates the transmittance of a grey body, given the extinction
coefficient of the material, its molar density, and the path length of the
radiation.
.. math::
\tau = base^{(-\epsilon \cdot l\cdot \rho_m )... | [
"def",
"grey_transmittance",
"(",
"extinction_coefficient",
",",
"molar_density",
",",
"length",
",",
"base",
"=",
"e",
")",
":",
"transmittance",
"=",
"molar_density",
"*",
"extinction_coefficient",
"*",
"length",
"return",
"base",
"**",
"(",
"-",
"transmittance"... | 37.392157 | 27.117647 |
def set_sticker_position_in_set(self, sticker, position):
"""
Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.
:param sticker:
:param position:
:return:
"""
return apihelper.set_sticker_position_in_set... | [
"def",
"set_sticker_position_in_set",
"(",
"self",
",",
"sticker",
",",
"position",
")",
":",
"return",
"apihelper",
".",
"set_sticker_position_in_set",
"(",
"self",
".",
"token",
",",
"sticker",
",",
"position",
")"
] | 43 | 24.5 |
def changes(since, out_file, eager):
"""Show changes since a specific date."""
root = get_root()
history_data = defaultdict(lambda: {'lines': deque(), 'releasers': set()})
with chdir(root):
result = run_command(
(
'git log "--pretty=format:%H %s" --date-order --date=... | [
"def",
"changes",
"(",
"since",
",",
"out_file",
",",
"eager",
")",
":",
"root",
"=",
"get_root",
"(",
")",
"history_data",
"=",
"defaultdict",
"(",
"lambda",
":",
"{",
"'lines'",
":",
"deque",
"(",
")",
",",
"'releasers'",
":",
"set",
"(",
")",
"}",... | 36.343137 | 21 |
def parse(self, request):
"""Parse incoming request and return an email instance.
Args:
request: an HttpRequest object, containing the forwarded email, as
per the SendGrid specification for inbound emails.
Returns:
an EmailMultiAlternatives instance, con... | [
"def",
"parse",
"(",
"self",
",",
"request",
")",
":",
"assert",
"isinstance",
"(",
"request",
",",
"HttpRequest",
")",
",",
"\"Invalid request type: %s\"",
"%",
"type",
"(",
"request",
")",
"try",
":",
"# from_email should never be a list (unless we change our API)",... | 38.797101 | 24.014493 |
def move_roles(self, roles):
"""
Moves roles to this role config group.
The roles can be moved from any role config group belonging
to the same service. The role type of the destination group
must match the role type of the roles.
@param roles: The names of the roles to move.
@return: List... | [
"def",
"move_roles",
"(",
"self",
",",
"roles",
")",
":",
"return",
"move_roles",
"(",
"self",
".",
"_get_resource_root",
"(",
")",
",",
"self",
".",
"serviceRef",
".",
"serviceName",
",",
"self",
".",
"name",
",",
"roles",
",",
"self",
".",
"serviceRef"... | 38 | 17.230769 |
def _set_defaults(self):
"""
Set configuration parameters for drawing guide
"""
valid_locations = {'top', 'bottom', 'left', 'right'}
horizontal_locations = {'left', 'right'}
get_property = self.theme.themeables.property
margin_location_lookup = {'t': 'b', 'b': 't'... | [
"def",
"_set_defaults",
"(",
"self",
")",
":",
"valid_locations",
"=",
"{",
"'top'",
",",
"'bottom'",
",",
"'left'",
",",
"'right'",
"}",
"horizontal_locations",
"=",
"{",
"'left'",
",",
"'right'",
"}",
"get_property",
"=",
"self",
".",
"theme",
".",
"them... | 34.426966 | 17.078652 |
def image_get(fingerprint,
remote_addr=None,
cert=None,
key=None,
verify_cert=True,
_raw=False):
''' Get an image by its fingerprint
fingerprint :
The fingerprint of the image to retrieve
remote_addr :
An... | [
"def",
"image_get",
"(",
"fingerprint",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
",",
"_raw",
"=",
"False",
")",
":",
"client",
"=",
"pylxd_client_get",
"(",
"remote_addr",
",",
... | 25.491525 | 22.033898 |
def equals(self, other):
"""Field-based equality for SSAEvents."""
if isinstance(other, SSAEvent):
return self.as_dict() == other.as_dict()
else:
raise TypeError("Cannot compare to non-SSAEvent object") | [
"def",
"equals",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"SSAEvent",
")",
":",
"return",
"self",
".",
"as_dict",
"(",
")",
"==",
"other",
".",
"as_dict",
"(",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Cannot ... | 40.833333 | 14 |
def stringify(self, string, phrases, parent=None):
"""
Stringifies phrases.
After parsing of the string via self.parse(), this method takes the
escaped string and the list of phrases returned by self.parse() and
replaces the original phrases (with tags) with the Phrase-objects in
the list and adds the app... | [
"def",
"stringify",
"(",
"self",
",",
"string",
",",
"phrases",
",",
"parent",
"=",
"None",
")",
":",
"last_tag",
"=",
"0",
"beauty",
"=",
"\"\"",
"for",
"phrase",
"in",
"phrases",
":",
"beauty",
"+=",
"string",
"[",
"last_tag",
":",
"phrase",
".",
"... | 28.365854 | 23.02439 |
def new_metric(self, meta):
"""
Create and register metric,
find subscribers for this metric (using meta as filter) and subscribe
Return:
metric (available_metrics[0]): one of Metric
"""
type_ = meta.get('type')
if not type_:
raise ValueEr... | [
"def",
"new_metric",
"(",
"self",
",",
"meta",
")",
":",
"type_",
"=",
"meta",
".",
"get",
"(",
"'type'",
")",
"if",
"not",
"type_",
":",
"raise",
"ValueError",
"(",
"'Metric type should be defined.'",
")",
"if",
"type_",
"in",
"available_metrics",
":",
"m... | 51.53125 | 29.15625 |
def update_monitor(self):
"""Update the monitor and monitor status from the ZM server."""
result = self._client.get_state(self._monitor_url)
self._raw_result = result['monitor'] | [
"def",
"update_monitor",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"self",
".",
"_monitor_url",
")",
"self",
".",
"_raw_result",
"=",
"result",
"[",
"'monitor'",
"]"
] | 49.5 | 9.25 |
def emit(self, span_datas):
"""
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit
"""
envelopes = [self.span_data_to_envelope(sd) for sd in span_d... | [
"def",
"emit",
"(",
"self",
",",
"span_datas",
")",
":",
"envelopes",
"=",
"[",
"self",
".",
"span_data_to_envelope",
"(",
"sd",
")",
"for",
"sd",
"in",
"span_datas",
"]",
"result",
"=",
"self",
".",
"_transmit",
"(",
"envelopes",
")",
"if",
"result",
... | 39 | 10.818182 |
def tell(self):
"""Returns the current position of read head.
"""
pos = ctypes.c_size_t()
check_call(_LIB.MXRecordIOReaderTell(self.handle, ctypes.byref(pos)))
return pos.value | [
"def",
"tell",
"(",
"self",
")",
":",
"pos",
"=",
"ctypes",
".",
"c_size_t",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXRecordIOReaderTell",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"pos",
")",
")",
")",
"return",
"pos",
".",
... | 35.166667 | 14.5 |
def toplevel(func):
"""A sync tasklet that sets a fresh default Context.
Use this for toplevel view functions such as
webapp.RequestHandler.get() or Django view functions.
"""
synctaskletfunc = synctasklet(func) # wrap at declaration time.
@utils.wrapping(func)
def add_context_wrapper(*args, **kwds):
... | [
"def",
"toplevel",
"(",
"func",
")",
":",
"synctaskletfunc",
"=",
"synctasklet",
"(",
"func",
")",
"# wrap at declaration time.",
"@",
"utils",
".",
"wrapping",
"(",
"func",
")",
"def",
"add_context_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"... | 30.869565 | 14.130435 |
def try_int(o:Any)->Any:
"Try to convert `o` to int, default to `o` if not possible."
# NB: single-item rank-1 array/tensor can be converted to int, but we don't want to do this
if isinstance(o, (np.ndarray,Tensor)): return o if o.ndim else int(o)
if isinstance(o, collections.Sized) or getattr(o,'__arra... | [
"def",
"try_int",
"(",
"o",
":",
"Any",
")",
"->",
"Any",
":",
"# NB: single-item rank-1 array/tensor can be converted to int, but we don't want to do this",
"if",
"isinstance",
"(",
"o",
",",
"(",
"np",
".",
"ndarray",
",",
"Tensor",
")",
")",
":",
"return",
"o",... | 55.571429 | 31 |
def get_requires(self, requires_types):
"""Extracts requires of given types from metadata file, filter windows
specific requires.
"""
if not isinstance(requires_types, list):
requires_types = list(requires_types)
extracted_requires = []
for requires_name in re... | [
"def",
"get_requires",
"(",
"self",
",",
"requires_types",
")",
":",
"if",
"not",
"isinstance",
"(",
"requires_types",
",",
"list",
")",
":",
"requires_types",
"=",
"list",
"(",
"requires_types",
")",
"extracted_requires",
"=",
"[",
"]",
"for",
"requires_name"... | 44.615385 | 10.538462 |
def pop_rule_nodes(self) -> bool:
"""Pop context variable that store rule nodes"""
self.rule_nodes = self.rule_nodes.parents
self.tag_cache = self.tag_cache.parents
self.id_cache = self.id_cache.parents
return True | [
"def",
"pop_rule_nodes",
"(",
"self",
")",
"->",
"bool",
":",
"self",
".",
"rule_nodes",
"=",
"self",
".",
"rule_nodes",
".",
"parents",
"self",
".",
"tag_cache",
"=",
"self",
".",
"tag_cache",
".",
"parents",
"self",
".",
"id_cache",
"=",
"self",
".",
... | 41.5 | 8.166667 |
def earthsun_distance(unixtime, delta_t, numthreads):
"""
Calculates the distance from the earth to the sun using the
NREL SPA algorithm described in [1].
Parameters
----------
unixtime : numpy array
Array of unix/epoch timestamps to calculate solar position for.
Unixtime is the... | [
"def",
"earthsun_distance",
"(",
"unixtime",
",",
"delta_t",
",",
"numthreads",
")",
":",
"R",
"=",
"solar_position",
"(",
"unixtime",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"delta_t",
",",
"0",
",",
"numthreads",
",",
"esd",
"=",
"... | 31.5 | 24.1875 |
def get_named_tensor(self, name):
"""
Returns a named tensor if available.
Returns:
valid: True if named tensor found, False otherwise
tensor: If valid, will be a tensor, otherwise None
"""
if name in self.named_tensors:
return True, self.name... | [
"def",
"get_named_tensor",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"named_tensors",
":",
"return",
"True",
",",
"self",
".",
"named_tensors",
"[",
"name",
"]",
"else",
":",
"return",
"False",
",",
"None"
] | 30.75 | 13.916667 |
def get_id_attr(self, value):
"""Check if value has id attribute and return it.
:param value: The value to get id from.
:return: The value.id.
"""
if not hasattr(value, "id") and hasattr(value, "value"):
value = value.value
return value.id | [
"def",
"get_id_attr",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"hasattr",
"(",
"value",
",",
"\"id\"",
")",
"and",
"hasattr",
"(",
"value",
",",
"\"value\"",
")",
":",
"value",
"=",
"value",
".",
"value",
"return",
"value",
".",
"id"
] | 32.444444 | 13.111111 |
def roundedSpecClass(self):
""" Spectral class with rounded class number ie A8.5V is A9 """
try:
classnumber = str(int(np.around(self.classNumber)))
except TypeError:
classnumber = str(self.classNumber)
return self.classLetter + classnumber | [
"def",
"roundedSpecClass",
"(",
"self",
")",
":",
"try",
":",
"classnumber",
"=",
"str",
"(",
"int",
"(",
"np",
".",
"around",
"(",
"self",
".",
"classNumber",
")",
")",
")",
"except",
"TypeError",
":",
"classnumber",
"=",
"str",
"(",
"self",
".",
"c... | 36.25 | 16.375 |
def open_image(fn):
""" Opens an image using OpenCV given the file path.
Arguments:
fn: the file path of the image
Returns:
The image in RGB format as numpy array of floats normalized to range between 0.0 - 1.0
"""
flags = cv2.IMREAD_UNCHANGED+cv2.IMREAD_ANYDEPTH+cv2.IMREAD_ANYCOLO... | [
"def",
"open_image",
"(",
"fn",
")",
":",
"flags",
"=",
"cv2",
".",
"IMREAD_UNCHANGED",
"+",
"cv2",
".",
"IMREAD_ANYDEPTH",
"+",
"cv2",
".",
"IMREAD_ANYCOLOR",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
"and",
"not",
"str",
"(",
"... | 46.769231 | 23.820513 |
def pad_to_multiple(self, factor):
"""
Pad the pianoroll with zeros at the end along the time axis with the
minimum length that makes the resulting pianoroll length a multiple of
`factor`.
Parameters
----------
factor : int
The value which the length ... | [
"def",
"pad_to_multiple",
"(",
"self",
",",
"factor",
")",
":",
"remainder",
"=",
"self",
".",
"pianoroll",
".",
"shape",
"[",
"0",
"]",
"%",
"factor",
"if",
"remainder",
":",
"pad_width",
"=",
"(",
"(",
"0",
",",
"(",
"factor",
"-",
"remainder",
")"... | 34.588235 | 22.235294 |
def setup_config(
config_directories=None,
config_file=None,
default_filename="opentc.yml"
):
"""Setup configuration
"""
config_found = False
config_file_path = None
if config_file:
config_file_path = config_file
if os.path.isfile(config_file_path) and os.acc... | [
"def",
"setup_config",
"(",
"config_directories",
"=",
"None",
",",
"config_file",
"=",
"None",
",",
"default_filename",
"=",
"\"opentc.yml\"",
")",
":",
"config_found",
"=",
"False",
"config_file_path",
"=",
"None",
"if",
"config_file",
":",
"config_file_path",
"... | 31.689655 | 18.206897 |
def best_motif_in_cluster(single_pwm, clus_pwm, clusters, fg_fa, background, stats=None, metrics=("roc_auc", "recall_at_fdr")):
"""Return the best motif per cluster for a clustering results.
The motif can be either the average motif or one of the clustered motifs.
Parameters
----------
single_pwm ... | [
"def",
"best_motif_in_cluster",
"(",
"single_pwm",
",",
"clus_pwm",
",",
"clusters",
",",
"fg_fa",
",",
"background",
",",
"stats",
"=",
"None",
",",
"metrics",
"=",
"(",
"\"roc_auc\"",
",",
"\"recall_at_fdr\"",
")",
")",
":",
"# combine original and clustered mot... | 30.625 | 21.055556 |
def _listify(collection):
"""This is a workaround where Collections are no longer iterable
when using JPype."""
new_list = []
for index in range(len(collection)):
new_list.append(collection[index])
return new_list | [
"def",
"_listify",
"(",
"collection",
")",
":",
"new_list",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"collection",
")",
")",
":",
"new_list",
".",
"append",
"(",
"collection",
"[",
"index",
"]",
")",
"return",
"new_list"
] | 37 | 8.714286 |
def add_module_plugin_filters(self, module_plugin_filters):
"""
Adds `module_plugin_filters` to the internal module filters.
May be a single object or an iterable.
Every module filters must be a callable and take in
a list of plugins and their associated names.
"""
... | [
"def",
"add_module_plugin_filters",
"(",
"self",
",",
"module_plugin_filters",
")",
":",
"module_plugin_filters",
"=",
"util",
".",
"return_list",
"(",
"module_plugin_filters",
")",
"self",
".",
"module_plugin_filters",
".",
"extend",
"(",
"module_plugin_filters",
")"
] | 44.2 | 18 |
def get_data(self, data_split="train"):
"""
Get specified split of data.
"""
if data_split == 'train':
return self._current_train_set
elif data_split == 'valid':
return self._current_valid_set
elif data_split == 'test':
return self._cur... | [
"def",
"get_data",
"(",
"self",
",",
"data_split",
"=",
"\"train\"",
")",
":",
"if",
"data_split",
"==",
"'train'",
":",
"return",
"self",
".",
"_current_train_set",
"elif",
"data_split",
"==",
"'valid'",
":",
"return",
"self",
".",
"_current_valid_set",
"elif... | 30 | 6 |
def _json_path_search(self, json_dict, expr):
"""
Scan JSON dictionary with using json-path passed sting of the format of $.element..element1[index] etc.
*Args:*\n
_json_dict_ - JSON dictionary;\n
_expr_ - string of fuzzy search for items within the directory;\n
*Return... | [
"def",
"_json_path_search",
"(",
"self",
",",
"json_dict",
",",
"expr",
")",
":",
"path",
"=",
"parse",
"(",
"expr",
")",
"results",
"=",
"path",
".",
"find",
"(",
"json_dict",
")",
"if",
"len",
"(",
"results",
")",
"is",
"0",
":",
"raise",
"JsonVali... | 35.68 | 24.8 |
def add_job(self, id, func, **kwargs):
"""
Add the given job to the job list and wakes up the scheduler if it's already running.
:param str id: explicit identifier for the job (for modifying it later)
:param func: callable (or a textual reference to one) to run at the given time
... | [
"def",
"add_job",
"(",
"self",
",",
"id",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"job_def",
"=",
"dict",
"(",
"kwargs",
")",
"job_def",
"[",
"'id'",
"]",
"=",
"id",
"job_def",
"[",
"'func'",
"]",
"=",
"func",
"job_def",
"[",
"'name'",
"]... | 33.25 | 22.875 |
def createGraph(self, name, createCollections = True, isSmart = False, numberOfShards = None, smartGraphAttribute = None) :
"""Creates a graph and returns it. 'name' must be the name of a class inheriting from Graph.
Checks will be performed to make sure that every collection mentionned in the edges def... | [
"def",
"createGraph",
"(",
"self",
",",
"name",
",",
"createCollections",
"=",
"True",
",",
"isSmart",
"=",
"False",
",",
"numberOfShards",
"=",
"None",
",",
"smartGraphAttribute",
"=",
"None",
")",
":",
"def",
"_checkCollectionList",
"(",
"lst",
")",
":",
... | 37.176471 | 24.294118 |
def get_upload_path(self, filename):
''' Override this in proxy subclass to customize upload path.
Default upload path is
:file:`/media/images/<user.id>/<filename>.<ext>`
or :file:`/media/images/common/<filename>.<ext>` if user is not set.
``<filename>`` is retur... | [
"def",
"get_upload_path",
"(",
"self",
",",
"filename",
")",
":",
"user_folder",
"=",
"str",
"(",
"self",
".",
"user",
".",
"pk",
")",
"if",
"self",
".",
"user",
"else",
"'common'",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
... | 47.8125 | 22.6875 |
def summary(processors, metrics, context):
"""Print the summary"""
# display aggregated metric values on language level
def display_header(processors, before='', after=''):
"""Display the header for the summary results."""
print(before, end=' ')
for processor in processors:
... | [
"def",
"summary",
"(",
"processors",
",",
"metrics",
",",
"context",
")",
":",
"# display aggregated metric values on language level",
"def",
"display_header",
"(",
"processors",
",",
"before",
"=",
"''",
",",
"after",
"=",
"''",
")",
":",
"\"\"\"Display the header ... | 34.77193 | 14.035088 |
def universal_transformer_encoder(encoder_input,
encoder_self_attention_bias,
hparams,
name="encoder",
nonpadding=None,
save_weights_to=None,
... | [
"def",
"universal_transformer_encoder",
"(",
"encoder_input",
",",
"encoder_self_attention_bias",
",",
"hparams",
",",
"name",
"=",
"\"encoder\"",
",",
"nonpadding",
"=",
"None",
",",
"save_weights_to",
"=",
"None",
",",
"make_image_summary",
"=",
"True",
")",
":",
... | 40.970149 | 19.701493 |
def _mod_run_check(cmd_kwargs, onlyif, unless):
'''
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
'''
if onlyif:
if __salt__['cmd.retcode'](onlyif, **cmd_kwargs) != 0:
retu... | [
"def",
"_mod_run_check",
"(",
"cmd_kwargs",
",",
"onlyif",
",",
"unless",
")",
":",
"if",
"onlyif",
":",
"if",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"onlyif",
",",
"*",
"*",
"cmd_kwargs",
")",
"!=",
"0",
":",
"return",
"{",
"'comment'",
":",
"'on... | 31.181818 | 16.818182 |
def unlock_queue_message(self, queue_name, sequence_number, lock_token):
'''
Unlocks a message for processing by other receivers on a given
queue. This operation deletes the lock object, causing the
message to be unlocked. A message must have first been locked by a
receiver befor... | [
"def",
"unlock_queue_message",
"(",
"self",
",",
"queue_name",
",",
"sequence_number",
",",
"lock_token",
")",
":",
"_validate_not_none",
"(",
"'queue_name'",
",",
"queue_name",
")",
"_validate_not_none",
"(",
"'sequence_number'",
",",
"sequence_number",
")",
"_valida... | 48.964286 | 22.392857 |
def output_stream_http(plugin, initial_streams, external=False, port=0):
"""Continuously output the stream over HTTP."""
global output
if not external:
if not args.player:
console.exit("The default player (VLC) does not seem to be "
"installed. You must specify ... | [
"def",
"output_stream_http",
"(",
"plugin",
",",
"initial_streams",
",",
"external",
"=",
"False",
",",
"port",
"=",
"0",
")",
":",
"global",
"output",
"if",
"not",
"external",
":",
"if",
"not",
"args",
".",
"player",
":",
"console",
".",
"exit",
"(",
... | 36.857143 | 20.442857 |
def create(self, repo_slug=None, key=None, label=None):
""" Associate an ssh key with your repo and return it.
"""
key = '%s' % key
repo_slug = repo_slug or self.bitbucket.repo_slug or ''
url = self.bitbucket.url('SET_DEPLOY_KEY',
username=self.bi... | [
"def",
"create",
"(",
"self",
",",
"repo_slug",
"=",
"None",
",",
"key",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"key",
"=",
"'%s'",
"%",
"key",
"repo_slug",
"=",
"repo_slug",
"or",
"self",
".",
"bitbucket",
".",
"repo_slug",
"or",
"''",
... | 48.846154 | 11.846154 |
def create_key_pair(self, key_name):
"""
Create a new key pair for your account.
This will create the key pair within the region you
are currently connected to.
:type key_name: string
:param key_name: The name of the new keypair
:rtype: :class:`boto.ec2.keypair.... | [
"def",
"create_key_pair",
"(",
"self",
",",
"key_name",
")",
":",
"params",
"=",
"{",
"'KeyName'",
":",
"key_name",
"}",
"return",
"self",
".",
"get_object",
"(",
"'CreateKeyPair'",
",",
"params",
",",
"KeyPair",
",",
"verb",
"=",
"'POST'",
")"
] | 41 | 17.375 |
def to_graphviz(booster, fmap='', num_trees=0, rankdir='UT',
yes_color='#0000FF', no_color='#FF0000',
condition_node_params=None, leaf_node_params=None, **kwargs):
"""Convert specified tree to graphviz instance. IPython can automatically plot the
returned graphiz instance. Otherw... | [
"def",
"to_graphviz",
"(",
"booster",
",",
"fmap",
"=",
"''",
",",
"num_trees",
"=",
"0",
",",
"rankdir",
"=",
"'UT'",
",",
"yes_color",
"=",
"'#0000FF'",
",",
"no_color",
"=",
"'#FF0000'",
",",
"condition_node_params",
"=",
"None",
",",
"leaf_node_params",
... | 32.155844 | 16.766234 |
def activate(name, lbn, target, profile='default', tgt_type='glob'):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Activate the named worker from the lbn load balancers at the targeted
minions
... | [
"def",
"activate",
"(",
"name",
",",
"lbn",
",",
"target",
",",
"profile",
"=",
"'default'",
",",
"tgt_type",
"=",
"'glob'",
")",
":",
"return",
"_talk2modjk",
"(",
"name",
",",
"lbn",
",",
"target",
",",
"'worker_activate'",
",",
"profile",
",",
"tgt_ty... | 29.809524 | 23.142857 |
def find_covalent_bonds(ampal, max_range=2.2, threshold=1.1, tag=True):
"""Finds all covalent bonds in the AMPAL object.
Parameters
----------
ampal : AMPAL Object
Any AMPAL object with a `get_atoms` method.
max_range : float, optional
Used to define the sector size, so interactions... | [
"def",
"find_covalent_bonds",
"(",
"ampal",
",",
"max_range",
"=",
"2.2",
",",
"threshold",
"=",
"1.1",
",",
"tag",
"=",
"True",
")",
":",
"sectors",
"=",
"gen_sectors",
"(",
"ampal",
".",
"get_atoms",
"(",
")",
",",
"max_range",
"*",
"1.1",
")",
"bond... | 38.459459 | 17.621622 |
def _get_enrollments_list_page(self, params=None):
"""
Submit request to retrieve enrollments list.
Args:
params (dict): Query parameters to use in the request. Valid parameters are:
* course_id: Filters the result to course enrollments for the course
... | [
"def",
"_get_enrollments_list_page",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"req_url",
"=",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"self",
".",
"enrollment_list_url",
")",
"resp",
"=",
"self",
".",
"requester",
".",
"get",
"(",
"req_url"... | 40.827586 | 19.517241 |
def bezier_unit_tangent(seg, t):
"""Returns the unit tangent of the segment at t.
Notes
-----
If you receive a RuntimeWarning, try the following:
>>> import numpy
>>> old_numpy_error_settings = numpy.seterr(invalid='raise')
This can be undone with:
>>> numpy.seterr(**old_numpy_error_set... | [
"def",
"bezier_unit_tangent",
"(",
"seg",
",",
"t",
")",
":",
"assert",
"0",
"<=",
"t",
"<=",
"1",
"dseg",
"=",
"seg",
".",
"derivative",
"(",
"t",
")",
"# Note: dseg might be numpy value, use np.seterr(invalid='raise')",
"try",
":",
"unit_tangent",
"=",
"dseg",... | 39.583333 | 18.777778 |
def _set_auth(self, v, load=False):
"""
Setter method for auth, mapped from YANG variable /rbridge_id/snmp_server/user/auth (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_auth is considered as a private
method. Backends looking to populate this variabl... | [
"def",
"_set_auth",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 92.136364 | 43.954545 |
def connect_get_namespaced_pod_attach(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_attach # noqa: E501
connect GET requests to attach of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, ple... | [
"def",
"connect_get_namespaced_pod_attach",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
... | 69.407407 | 42.185185 |
def invoke_hook_bolt_ack(self, heron_tuple, process_latency_ns):
"""invoke task hooks for every time bolt acks a tuple
:type heron_tuple: HeronTuple
:param heron_tuple: tuple that is acked
:type process_latency_ns: float
:param process_latency_ns: process latency in nano seconds
"""
if len(... | [
"def",
"invoke_hook_bolt_ack",
"(",
"self",
",",
"heron_tuple",
",",
"process_latency_ns",
")",
":",
"if",
"len",
"(",
"self",
".",
"task_hooks",
")",
">",
"0",
":",
"bolt_ack_info",
"=",
"BoltAckInfo",
"(",
"heron_tuple",
"=",
"heron_tuple",
",",
"acking_task... | 45.642857 | 15.5 |
def setup(self, level=None, log_file=None, json=None):
'''
Load everything up. Note that any arg here will override both
default and custom settings
@param level: the log level
@param log_file: boolean t/f whether to log to a file, else stdout
@param json: boolean t/f wh... | [
"def",
"setup",
"(",
"self",
",",
"level",
"=",
"None",
",",
"log_file",
"=",
"None",
",",
"json",
"=",
"None",
")",
":",
"self",
".",
"settings",
"=",
"self",
".",
"wrapper",
".",
"load",
"(",
"self",
".",
"settings_name",
")",
"my_level",
"=",
"l... | 47.081081 | 26.162162 |
def _setResult(self, result):
"""
Sets the result. If the result is already set, raises
C{AlreadyCalledError}.
@raise AlreadyCalledError: The result was already set.
@return: C{None}, if the result was successfully set.
"""
if self._result is not _NO_RESULT:
... | [
"def",
"_setResult",
"(",
"self",
",",
"result",
")",
":",
"if",
"self",
".",
"_result",
"is",
"not",
"_NO_RESULT",
":",
"raise",
"AlreadyCalledError",
"(",
")",
"self",
".",
"_result",
"=",
"result"
] | 31.166667 | 15 |
def packSeptets(octets, padBits=0):
""" Packs the specified octets into septets
Typically the output of encodeGsm7 would be used as input to this function. The resulting
bytearray contains the original GSM-7 characters packed into septets ready for transmission.
:rtype: bytearray
"""
r... | [
"def",
"packSeptets",
"(",
"octets",
",",
"padBits",
"=",
"0",
")",
":",
"result",
"=",
"bytearray",
"(",
")",
"if",
"type",
"(",
"octets",
")",
"==",
"str",
":",
"octets",
"=",
"iter",
"(",
"rawStrToByteArray",
"(",
"octets",
")",
")",
"elif",
"type... | 32.757576 | 17.484848 |
def create_issue(self, project_id, summary, issue_type_id, priority_id, extra_request_params={}):
"""
client = BacklogClient("your_space_name", "your_api_key")
project_key = "YOUR_PROJECT"
project_id = client.get_project_id(project_key)
issue_type_id = client.project_issue_types... | [
"def",
"create_issue",
"(",
"self",
",",
"project_id",
",",
"summary",
",",
"issue_type_id",
",",
"priority_id",
",",
"extra_request_params",
"=",
"{",
"}",
")",
":",
"request_params",
"=",
"extra_request_params",
"request_params",
"[",
"\"projectId\"",
"]",
"=",
... | 41.125 | 15.291667 |
def to_team(team):
"""Serializes team to id string
:param team: object to serialize
:return: string id
"""
from sevenbridges.models.team import Team
if not team:
raise SbgError('Team is required!')
elif isinstance(team, Team):
return team.i... | [
"def",
"to_team",
"(",
"team",
")",
":",
"from",
"sevenbridges",
".",
"models",
".",
"team",
"import",
"Team",
"if",
"not",
"team",
":",
"raise",
"SbgError",
"(",
"'Team is required!'",
")",
"elif",
"isinstance",
"(",
"team",
",",
"Team",
")",
":",
"retu... | 32.071429 | 11.071429 |
def __build_config_block(self, config_block_node):
"""parse `config_block` in each section
Args:
config_block_node (TreeNode): Description
Returns:
[line_node1, line_node2, ...]
"""
node_lists = []
for line_node in config_block_node:
... | [
"def",
"__build_config_block",
"(",
"self",
",",
"config_block_node",
")",
":",
"node_lists",
"=",
"[",
"]",
"for",
"line_node",
"in",
"config_block_node",
":",
"if",
"isinstance",
"(",
"line_node",
",",
"pegnode",
".",
"ConfigLine",
")",
":",
"node_lists",
".... | 39.578947 | 15 |
def index(self):
"""Retrieve the attribute index number.
Args::
no argument
Returns::
attribute index number (starting at 0)
C library equivalent : SDfindattr
"""
self._index = _C.SDfindattr(self._obj._id, sel... | [
"def",
"index",
"(",
"self",
")",
":",
"self",
".",
"_index",
"=",
"_C",
".",
"SDfindattr",
"(",
"self",
".",
"_obj",
".",
"_id",
",",
"self",
".",
"_name",
")",
"_checkErr",
"(",
"'find'",
",",
"self",
".",
"_index",
",",
"'illegal attribute name'",
... | 23.764706 | 23.588235 |
def _pretty_print_event(event, colored):
"""
Basic formatter to convert an event object to string
"""
event.timestamp = colored.yellow(event.timestamp)
event.log_stream_name = colored.cyan(event.log_stream_name)
return ' '.join([event.log_stream_name, event.timestamp, ev... | [
"def",
"_pretty_print_event",
"(",
"event",
",",
"colored",
")",
":",
"event",
".",
"timestamp",
"=",
"colored",
".",
"yellow",
"(",
"event",
".",
"timestamp",
")",
"event",
".",
"log_stream_name",
"=",
"colored",
".",
"cyan",
"(",
"event",
".",
"log_strea... | 40.75 | 18 |
def option_configure(debug=False, path=None):
"""
Summary:
Initiate configuration menu to customize metal runtime options.
Console script ```keyconfig``` invokes this option_configure directly
in debug mode to display the contents of the local config file (if exists)
Args:
:p... | [
"def",
"option_configure",
"(",
"debug",
"=",
"False",
",",
"path",
"=",
"None",
")",
":",
"if",
"CONFIG_SCRIPT",
"in",
"sys",
".",
"argv",
"[",
"0",
"]",
":",
"debug",
"=",
"True",
"# set debug mode if invoked from CONFIG_SCRIPT",
"if",
"path",
"is",
"None"... | 39.851852 | 20.962963 |
def recursive_index_decode(int_array, max=32767, min=-32768):
"""Unpack an array of integers using recursive indexing.
:param int_array: the input array of integers
:param max: the maximum integer size
:param min: the minimum integer size
:return the array of integers after recursive index decoding... | [
"def",
"recursive_index_decode",
"(",
"int_array",
",",
"max",
"=",
"32767",
",",
"min",
"=",
"-",
"32768",
")",
":",
"out_arr",
"=",
"[",
"]",
"decoded_val",
"=",
"0",
"for",
"item",
"in",
"int_array",
".",
"tolist",
"(",
")",
":",
"if",
"item",
"==... | 36.058824 | 11.529412 |
def _interpolate_missing_data(data, mask, method='cubic'):
"""
Interpolate missing data as identified by the ``mask`` keyword.
Parameters
----------
data : 2D `~numpy.ndarray`
An array containing the 2D image.
mask : 2D bool `~numpy.ndarray`
A 2D booleen mask array with the sam... | [
"def",
"_interpolate_missing_data",
"(",
"data",
",",
"mask",
",",
"method",
"=",
"'cubic'",
")",
":",
"from",
"scipy",
"import",
"interpolate",
"data_interp",
"=",
"np",
".",
"array",
"(",
"data",
",",
"copy",
"=",
"True",
")",
"if",
"len",
"(",
"data_i... | 30.709091 | 20.818182 |
def encode(B):
""" Encode data using Hamming(7, 4) code.
E.g.:
encode([0, 0, 1, 1])
encode([[0, 0, 0, 1],
[0, 1, 0, 1]])
:param array B: binary data to encode (must be shaped as (4, ) or (-1, 4)).
"""
B = array(B)
flatten = False
if len(B.shape) == 1:
... | [
"def",
"encode",
"(",
"B",
")",
":",
"B",
"=",
"array",
"(",
"B",
")",
"flatten",
"=",
"False",
"if",
"len",
"(",
"B",
".",
"shape",
")",
"==",
"1",
":",
"flatten",
"=",
"True",
"B",
"=",
"B",
".",
"reshape",
"(",
"1",
",",
"-",
"1",
")",
... | 18.714286 | 25 |
def init_argparser_working_dir(
self, argparser,
explanation='',
help_template=(
'the working directory; %(explanation)s'
'default is current working directory (%(cwd)s)'),
):
"""
Subclass could an extra expanation on how th... | [
"def",
"init_argparser_working_dir",
"(",
"self",
",",
"argparser",
",",
"explanation",
"=",
"''",
",",
"help_template",
"=",
"(",
"'the working directory; %(explanation)s'",
"'default is current working directory (%(cwd)s)'",
")",
",",
")",
":",
"cwd",
"=",
"self",
"."... | 30.6 | 17.96 |
def free (self):
""" Returns free properties which are not dependency properties.
"""
result = [p for p in self.lazy_properties
if not p.feature.incidental and p.feature.free]
result.extend(self.free_)
return result | [
"def",
"free",
"(",
"self",
")",
":",
"result",
"=",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"lazy_properties",
"if",
"not",
"p",
".",
"feature",
".",
"incidental",
"and",
"p",
".",
"feature",
".",
"free",
"]",
"result",
".",
"extend",
"(",
"self"... | 38.142857 | 12 |
def readline(self, size=-1):
"Ignore the `size` since a complete line must be processed."
try:
record = next(self.reader)
return self.outdel.join(self.process_line(record)) + '\n'
except StopIteration:
return '' | [
"def",
"readline",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"try",
":",
"record",
"=",
"next",
"(",
"self",
".",
"reader",
")",
"return",
"self",
".",
"outdel",
".",
"join",
"(",
"self",
".",
"process_line",
"(",
"record",
")",
")",
"+"... | 37.857143 | 18.428571 |
def translate_features_to_letter_annotations(protein, more_sites=None):
"""Store select uniprot features (sites) as letter annotations with the key as the
type of site and the values as a list of booleans"""
from ssbio.databases.uniprot import longname_sites
from collections import defau... | [
"def",
"translate_features_to_letter_annotations",
"(",
"protein",
",",
"more_sites",
"=",
"None",
")",
":",
"from",
"ssbio",
".",
"databases",
".",
"uniprot",
"import",
"longname_sites",
"from",
"collections",
"import",
"defaultdict",
"sites",
"=",
"longname_sites",
... | 46.155556 | 22.555556 |
def list_subscriptions(self, target_id=None, ids=None, query_flags=None):
"""ListSubscriptions.
[Preview API]
:param str target_id:
:param [str] ids:
:param str query_flags:
:rtype: [NotificationSubscription]
"""
query_parameters = {}
if target_id ... | [
"def",
"list_subscriptions",
"(",
"self",
",",
"target_id",
"=",
"None",
",",
"ids",
"=",
"None",
",",
"query_flags",
"=",
"None",
")",
":",
"query_parameters",
"=",
"{",
"}",
"if",
"target_id",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"'targetId... | 49.238095 | 20.571429 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.