text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_best_match(text_log_error):
"""
Get the best TextLogErrorMatch for a given TextLogErrorMatch.
Matches are further filtered by the score cut off.
"""
score_cut_off = 0.7
return (text_log_error.matches.filter(score__gt=score_cut_off)
.order_by("-score", "... | [
"def",
"get_best_match",
"(",
"text_log_error",
")",
":",
"score_cut_off",
"=",
"0.7",
"return",
"(",
"text_log_error",
".",
"matches",
".",
"filter",
"(",
"score__gt",
"=",
"score_cut_off",
")",
".",
"order_by",
"(",
"\"-score\"",
",",
"\"-classified_failure_id\"... | 40.909091 | 18.181818 |
def observableFractionCMD(self, mask, distance_modulus, mass_min=0.1):
"""
Compute observable fraction of stars with masses greater than mass_min in each
pixel in the interior region of the mask.
ADW: Careful, this function is fragile! The selection here should
be the same... | [
"def",
"observableFractionCMD",
"(",
"self",
",",
"mask",
",",
"distance_modulus",
",",
"mass_min",
"=",
"0.1",
")",
":",
"if",
"distance_modulus",
"is",
"None",
":",
"distance_modulus",
"=",
"self",
".",
"distance_modulus",
"mass_init",
",",
"mass_pdf",
",",
... | 51.486486 | 29.324324 |
def get_new_names_by_old():
"""Return dictionary, new label name indexed by old label name."""
newdict = {}
for label_type, label_names in Labels.LABEL_NAMES.items():
for oldname in label_names[1:]:
newdict[oldname] = Labels.LABEL_NAMES[label_type][0]
return ... | [
"def",
"get_new_names_by_old",
"(",
")",
":",
"newdict",
"=",
"{",
"}",
"for",
"label_type",
",",
"label_names",
"in",
"Labels",
".",
"LABEL_NAMES",
".",
"items",
"(",
")",
":",
"for",
"oldname",
"in",
"label_names",
"[",
"1",
":",
"]",
":",
"newdict",
... | 40 | 18.5 |
def add_validator(validator, base_tag, tag=None):
"""
Add a validator for the given tag, which defines a subset of base_tag.
If tag is None, it is automatically constructed as
u'!~' + validator.__name__
Validator is a function that accepts a document node (in the form of a
Python object), a sche... | [
"def",
"add_validator",
"(",
"validator",
",",
"base_tag",
",",
"tag",
"=",
"None",
")",
":",
"if",
"not",
"tag",
":",
"tag",
"=",
"u'!~'",
"+",
"validator",
".",
"__name__",
"for",
"xid",
",",
"opts",
"in",
"_VALIDATOR_MODES",
".",
"iteritems",
"(",
"... | 46.416667 | 19.75 |
def append_transformed_structures(self, tstructs_or_transmuter):
"""
Method is overloaded to accept either a list of transformed structures
or transmuter, it which case it appends the second transmuter"s
structures.
Args:
tstructs_or_transmuter: A list of transformed... | [
"def",
"append_transformed_structures",
"(",
"self",
",",
"tstructs_or_transmuter",
")",
":",
"if",
"isinstance",
"(",
"tstructs_or_transmuter",
",",
"self",
".",
"__class__",
")",
":",
"self",
".",
"transformed_structures",
".",
"extend",
"(",
"tstructs_or_transmuter... | 44.470588 | 22.941176 |
def nvlist_to_dict(nvlist):
'''Convert a CORBA namevalue list into a dictionary.'''
result = {}
for item in nvlist :
result[item.name] = item.value.value()
return result | [
"def",
"nvlist_to_dict",
"(",
"nvlist",
")",
":",
"result",
"=",
"{",
"}",
"for",
"item",
"in",
"nvlist",
":",
"result",
"[",
"item",
".",
"name",
"]",
"=",
"item",
".",
"value",
".",
"value",
"(",
")",
"return",
"result"
] | 32.166667 | 16.833333 |
def _write(self, context, report_dir, report_name, assets_dir=None,
template=None):
"""Writes the data in `context` in the report's template to
`report_name` in `report_dir`.
If `assets_dir` is supplied, copies all assets for this report
to the specified directory.
... | [
"def",
"_write",
"(",
"self",
",",
"context",
",",
"report_dir",
",",
"report_name",
",",
"assets_dir",
"=",
"None",
",",
"template",
"=",
"None",
")",
":",
"if",
"template",
"is",
"None",
":",
"template",
"=",
"self",
".",
"_get_template",
"(",
")",
"... | 41.03125 | 17.09375 |
def split_points(self, point_cloud):
"""Split a point cloud into two along this plane.
Parameters
----------
point_cloud : :obj:`PointCloud`
The PointCloud to divide in two.
Returns
-------
:obj:`tuple` of :obj:`PointCloud`
Two new PointC... | [
"def",
"split_points",
"(",
"self",
",",
"point_cloud",
")",
":",
"if",
"not",
"isinstance",
"(",
"point_cloud",
",",
"PointCloud",
")",
":",
"raise",
"ValueError",
"(",
"'Can only split point clouds'",
")",
"# compute indices above and below",
"above_plane",
"=",
"... | 40.225806 | 23.387097 |
def _bind_posix_socket(socket_name=None):
"""
Find a socket to listen on and return it.
Returns (socket_name, sock_obj)
"""
assert socket_name is None or isinstance(socket_name, six.text_type)
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if socket_name:
s.bind(socket_name... | [
"def",
"_bind_posix_socket",
"(",
"socket_name",
"=",
"None",
")",
":",
"assert",
"socket_name",
"is",
"None",
"or",
"isinstance",
"(",
"socket_name",
",",
"six",
".",
"text_type",
")",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_UNIX",
",",... | 31.241379 | 18.758621 |
def currentPanel(self):
"""
Returns the currently active panel based on whether or not it has \
focus.
:return <XViewPanel> || None
"""
focus_widget = QtGui.QApplication.instance().focusWidget()
focus_panel = projexui.ancestor(focus_widget, XViewPane... | [
"def",
"currentPanel",
"(",
"self",
")",
":",
"focus_widget",
"=",
"QtGui",
".",
"QApplication",
".",
"instance",
"(",
")",
".",
"focusWidget",
"(",
")",
"focus_panel",
"=",
"projexui",
".",
"ancestor",
"(",
"focus_widget",
",",
"XViewPanel",
")",
"panels",
... | 29.176471 | 17.647059 |
def group(self, groupId):
"""
The group's content provides access to the items that are shared
with the group.
Group items are stored by reference and are not physically stored
in a group. Rather, they are stored as links to the original item
in the item resource (/conten... | [
"def",
"group",
"(",
"self",
",",
"groupId",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/groups/%s\"",
"%",
"groupId",
"return",
"Group",
"(",
"groupId",
"=",
"groupId",
",",
"contentURL",
"=",
"url",
",",
"securityHandler",
"=",
"self",
".",
"... | 42.894737 | 16.789474 |
def tags(self):
'''List tags (py_version, abi, platform) supported by this wheel.'''
return itertools.product(
self.py_version.split('.'),
self.abi.split('.'),
self.platform.split('.'),
) | [
"def",
"tags",
"(",
"self",
")",
":",
"return",
"itertools",
".",
"product",
"(",
"self",
".",
"py_version",
".",
"split",
"(",
"'.'",
")",
",",
"self",
".",
"abi",
".",
"split",
"(",
"'.'",
")",
",",
"self",
".",
"platform",
".",
"split",
"(",
"... | 34.428571 | 15.857143 |
def ensure_no_set_overlap(train: Sequence[str], valid: Sequence[str], test: Sequence[str]) -> None:
""" Ensures no test set data has creeped into the training set."""
logger.debug("Ensuring that the training, validation and test data sets have no overlap")
train_s = set(train)
valid_s = set(valid)
... | [
"def",
"ensure_no_set_overlap",
"(",
"train",
":",
"Sequence",
"[",
"str",
"]",
",",
"valid",
":",
"Sequence",
"[",
"str",
"]",
",",
"test",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"\"Ensuring that the train... | 58.470588 | 37.529412 |
def get_port(self):
""" Return a port to use to talk to this cluster. """
if len(self.client_nodes) > 0:
node = self.client_nodes[0]
else:
node = self.nodes[0]
return node.get_port() | [
"def",
"get_port",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"client_nodes",
")",
">",
"0",
":",
"node",
"=",
"self",
".",
"client_nodes",
"[",
"0",
"]",
"else",
":",
"node",
"=",
"self",
".",
"nodes",
"[",
"0",
"]",
"return",
"node",... | 33.142857 | 9.857143 |
def AddArguments(cls, argument_group):
"""Adds command line arguments the helper supports to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argparse._ArgumentGroup|arg... | [
"def",
"AddArguments",
"(",
"cls",
",",
"argument_group",
")",
":",
"argument_group",
".",
"add_argument",
"(",
"'--user'",
",",
"dest",
"=",
"'username'",
",",
"type",
"=",
"str",
",",
"action",
"=",
"'store'",
",",
"default",
"=",
"cls",
".",
"_DEFAULT_U... | 45.541667 | 21.416667 |
def expand_counts(df, column, values=None):
"""
expand a column containing value:count dictionaries
"""
d = counts_to_dicts(df, column)
if len(d) > 0:
if values is None:
values = set(np.concatenate(d.apply(lambda c: c.keys()).values))
for value in values:
name... | [
"def",
"expand_counts",
"(",
"df",
",",
"column",
",",
"values",
"=",
"None",
")",
":",
"d",
"=",
"counts_to_dicts",
"(",
"df",
",",
"column",
")",
"if",
"len",
"(",
"d",
")",
">",
"0",
":",
"if",
"values",
"is",
"None",
":",
"values",
"=",
"set"... | 40.615385 | 13.846154 |
def add(buffer, entropy):
"""
Mix bytes from *string* into the PRNG state.
The *entropy* argument is (the lower bound of) an estimate of how much
randomness is contained in *string*, measured in bytes.
For more information, see e.g. :rfc:`1750`.
This function is only relevant if you are forki... | [
"def",
"add",
"(",
"buffer",
",",
"entropy",
")",
":",
"if",
"not",
"isinstance",
"(",
"buffer",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"buffer must be a byte string\"",
")",
"if",
"not",
"isinstance",
"(",
"entropy",
",",
"int",
")",
":",
... | 31.083333 | 20.333333 |
def reanimate(self, _time=None):
""" Move dead proxies to unchecked if a backoff timeout passes """
n_reanimated = 0
now = _time or time.time()
for proxy in list(self.dead):
state = self.proxies[proxy]
assert state.next_check is not None
if state.next_... | [
"def",
"reanimate",
"(",
"self",
",",
"_time",
"=",
"None",
")",
":",
"n_reanimated",
"=",
"0",
"now",
"=",
"_time",
"or",
"time",
".",
"time",
"(",
")",
"for",
"proxy",
"in",
"list",
"(",
"self",
".",
"dead",
")",
":",
"state",
"=",
"self",
".",... | 38.833333 | 5.333333 |
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dim... | [
"def",
"h1_mhe",
"(",
"simulated_array",
",",
"observed_array",
",",
"replace_nan",
"=",
"None",
",",
"replace_inf",
"=",
"None",
",",
"remove_neg",
"=",
"False",
",",
"remove_zero",
"=",
"False",
")",
":",
"# Treats data",
"simulated_array",
",",
"observed_arra... | 32.082192 | 26.657534 |
async def shutdown(self):
"Force stop the output stream, if there are more data to download, shutdown the connection"
if self.stream:
if not self.stream.dataeof and not self.stream.dataerror:
self.stream.close(self.scheduler)
await self.connection.shutdown()
... | [
"async",
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"self",
".",
"stream",
":",
"if",
"not",
"self",
".",
"stream",
".",
"dataeof",
"and",
"not",
"self",
".",
"stream",
".",
"dataerror",
":",
"self",
".",
"stream",
".",
"close",
"(",
"self",
"... | 45.444444 | 19.888889 |
def read_problematic_samples(file_name):
"""Reads a file with sample IDs.
:param file_name: the name of the file containing problematic samples after
sex check.
:type file_name: str
:returns: a set of problematic samples (tuple containing the family ID as
first ele... | [
"def",
"read_problematic_samples",
"(",
"file_name",
")",
":",
"problematic_samples",
"=",
"set",
"(",
")",
"open_func",
"=",
"open",
"if",
"file_name",
".",
"endswith",
"(",
"\".gz\"",
")",
":",
"open_func",
"=",
"gzip",
".",
"open",
"with",
"open_func",
"(... | 34.259259 | 23.62963 |
def _get_points_for_series(self, series):
"""Return generator of dict from columns and values of a series.
:param series: One series
:return: Generator of dicts
"""
for point in series.get('values', []):
yield self.point_from_cols_vals(
series['column... | [
"def",
"_get_points_for_series",
"(",
"self",
",",
"series",
")",
":",
"for",
"point",
"in",
"series",
".",
"get",
"(",
"'values'",
",",
"[",
"]",
")",
":",
"yield",
"self",
".",
"point_from_cols_vals",
"(",
"series",
"[",
"'columns'",
"]",
",",
"point",... | 31.818182 | 10.454545 |
def nexus(network, before_state, after_state,
direction=Direction.BIDIRECTIONAL):
"""Return a tuple of all irreducible nexus of the network."""
validate.is_network(network)
sias = (sia(transition, direction) for transition in
transitions(network, before_state, after_state))
return... | [
"def",
"nexus",
"(",
"network",
",",
"before_state",
",",
"after_state",
",",
"direction",
"=",
"Direction",
".",
"BIDIRECTIONAL",
")",
":",
"validate",
".",
"is_network",
"(",
"network",
")",
"sias",
"=",
"(",
"sia",
"(",
"transition",
",",
"direction",
"... | 45.125 | 14 |
def getkey(stype, site_id=None, key=None):
'Returns the cache key depending on its type.'
base = '{0}.feedjack'.format(settings.CACHE_MIDDLEWARE_KEY_PREFIX)
if stype == T_HOST: return '{0}.hostcache'.format(base)
elif stype == T_ITEM: return '{0}.{1}.item.{2}'.format(base, site_id, str2md5(key))
elif stype == T_ME... | [
"def",
"getkey",
"(",
"stype",
",",
"site_id",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"base",
"=",
"'{0}.feedjack'",
".",
"format",
"(",
"settings",
".",
"CACHE_MIDDLEWARE_KEY_PREFIX",
")",
"if",
"stype",
"==",
"T_HOST",
":",
"return",
"'{0}.hostc... | 63 | 23 |
def _isint(string):
"""
>>> _isint("123")
True
>>> _isint("123.45")
False
"""
return type(string) is int or \
(isinstance(string, _binary_type) or
isinstance(string, string_types)) and \
_isconvertible(int, string) | [
"def",
"_isint",
"(",
"string",
")",
":",
"return",
"type",
"(",
"string",
")",
"is",
"int",
"or",
"(",
"isinstance",
"(",
"string",
",",
"_binary_type",
")",
"or",
"isinstance",
"(",
"string",
",",
"string_types",
")",
")",
"and",
"_isconvertible",
"(",... | 23.363636 | 12.818182 |
def advance(self):
"""Carry out one iteration of Arnoldi."""
if self.iter >= self.maxiter:
raise ArgumentError('Maximum number of iterations reached.')
if self.invariant:
raise ArgumentError('Krylov subspace was found to be invariant '
'in ... | [
"def",
"advance",
"(",
"self",
")",
":",
"if",
"self",
".",
"iter",
">=",
"self",
".",
"maxiter",
":",
"raise",
"ArgumentError",
"(",
"'Maximum number of iterations reached.'",
")",
"if",
"self",
".",
"invariant",
":",
"raise",
"ArgumentError",
"(",
"'Krylov s... | 41.045455 | 16.488636 |
def result(self, timeout=None):
"""Return the value returned by the call. If the call hasn't yet
completed then this method will wait up to ''timeout'' seconds. More
information in the :doc:`usage` page. If the call hasn't completed in
timeout seconds then a TimeoutError will be raised. ... | [
"def",
"result",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_ended",
"(",
")",
":",
"return",
"scoop",
".",
"futures",
".",
"_join",
"(",
"self",
")",
"if",
"self",
".",
"exceptionValue",
"is",
"not",
"None",
":"... | 43.947368 | 21.684211 |
def delete_detail(self, request):
"""
Implements the Delete Detail (delete an object)
maps to DELETE /api/object_name/:id/ in rest semantics
:param request: rip.Request
:return: rip.Response
"""
pipeline = crud_pipeline_factory.delete_detail_pipeline(
... | [
"def",
"delete_detail",
"(",
"self",
",",
"request",
")",
":",
"pipeline",
"=",
"crud_pipeline_factory",
".",
"delete_detail_pipeline",
"(",
"configuration",
"=",
"self",
".",
"configuration",
")",
"return",
"pipeline",
"(",
"request",
"=",
"request",
")"
] | 35 | 11.727273 |
def p_args(self, p):
"""args : LPAR pos_args_list COMMA kw_args RPAR
| LPAR pos_args_list RPAR
| LPAR kw_args RPAR
| LPAR RPAR
| empty"""
if len(p) > 3:
if p[3] == ',':
p[0] = (p[2], p[4])
elif isinst... | [
"def",
"p_args",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
">",
"3",
":",
"if",
"p",
"[",
"3",
"]",
"==",
"','",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"p",
"[",
"2",
"]",
",",
"p",
"[",
"4",
"]",
")",
"elif",
"isinstan... | 30.066667 | 10.133333 |
def unique(self, col_or_col_list):
"""
Return a list of unique values of a column or a list of lists of column list
:param col_or_col_list: a column or a list of columns
:return:
"""
if isinstance(col_or_col_list, list):
col_is_list = True
col_li... | [
"def",
"unique",
"(",
"self",
",",
"col_or_col_list",
")",
":",
"if",
"isinstance",
"(",
"col_or_col_list",
",",
"list",
")",
":",
"col_is_list",
"=",
"True",
"col_list",
"=",
"col_or_col_list",
"else",
":",
"col_is_list",
"=",
"False",
"col_list",
"=",
"[",... | 30.230769 | 19.666667 |
def _replace_envvar(s, _):
"""env:KEY or env:KEY:DEFAULT"""
e = s.split(":")
if len(e) > 3 or len(e) == 1 or e[0] != "env":
raise ValueError()
elif len(e) == 2:
# Note: this can/should raise a KeyError (according to spec).
return os.environ[e[1]]
else: # len(e) == 3
... | [
"def",
"_replace_envvar",
"(",
"s",
",",
"_",
")",
":",
"e",
"=",
"s",
".",
"split",
"(",
"\":\"",
")",
"if",
"len",
"(",
"e",
")",
">",
"3",
"or",
"len",
"(",
"e",
")",
"==",
"1",
"or",
"e",
"[",
"0",
"]",
"!=",
"\"env\"",
":",
"raise",
... | 34.4 | 13.2 |
def capabilities(self):
"""A tuple of capabilities this device supports.
Returns:
(~libinput.constant.DeviceCapability): Device capabilities.
"""
caps = []
for cap in DeviceCapability:
if self._libinput.libinput_device_has_capability(self._handle, cap):
caps.append(cap)
return tuple(caps) | [
"def",
"capabilities",
"(",
"self",
")",
":",
"caps",
"=",
"[",
"]",
"for",
"cap",
"in",
"DeviceCapability",
":",
"if",
"self",
".",
"_libinput",
".",
"libinput_device_has_capability",
"(",
"self",
".",
"_handle",
",",
"cap",
")",
":",
"caps",
".",
"appe... | 25.166667 | 21.583333 |
def forecast(stl, fc_func, steps=10, seasonal=False, **fc_func_kwargs):
"""Forecast the given decomposition ``stl`` forward by ``steps`` steps using the forecasting
function ``fc_func``, optionally including the calculated seasonality.
This is an additive model, Y[t] = T[t] + S[t] + e[t]
Args:
... | [
"def",
"forecast",
"(",
"stl",
",",
"fc_func",
",",
"steps",
"=",
"10",
",",
"seasonal",
"=",
"False",
",",
"*",
"*",
"fc_func_kwargs",
")",
":",
"# container for forecast values",
"forecast_array",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"# forecast ... | 48.592105 | 23.355263 |
def __analizar_observaciones(self, ret):
"Comprueba y extrae observaciones si existen en la respuesta XML"
self.Observaciones = [obs["codigoDescripcion"] for obs in ret.get('arrayObservaciones', [])]
self.Obs = '\n'.join(["%(codigo)s: %(descripcion)s" % obs for obs in self.Observaciones]) | [
"def",
"__analizar_observaciones",
"(",
"self",
",",
"ret",
")",
":",
"self",
".",
"Observaciones",
"=",
"[",
"obs",
"[",
"\"codigoDescripcion\"",
"]",
"for",
"obs",
"in",
"ret",
".",
"get",
"(",
"'arrayObservaciones'",
",",
"[",
"]",
")",
"]",
"self",
"... | 77.5 | 37.5 |
def get_deviation_content(self, deviationid):
"""Fetch full data that is not included in the main devaition object
The endpoint works with journals and literatures. Deviation objects returned from API contain only excerpt of a journal, use this endpoint to load full content.
Any custom CSS ru... | [
"def",
"get_deviation_content",
"(",
"self",
",",
"deviationid",
")",
":",
"response",
"=",
"self",
".",
"_req",
"(",
"'/deviation/content'",
",",
"{",
"'deviationid'",
":",
"deviationid",
"}",
")",
"content",
"=",
"{",
"}",
"if",
"\"html\"",
"in",
"response... | 32.230769 | 26.5 |
def set(self, key: URIRef, value: Union[Literal, BNode, URIRef, str, int], lang: Optional[str]=None):
""" Set the VALUE for KEY predicate in the Metadata Graph
:param key: Predicate to be set (eg. DCT.creator)
:param value: Value to be stored (eg. "Cicero")
:param lang: [Optional] Langu... | [
"def",
"set",
"(",
"self",
",",
"key",
":",
"URIRef",
",",
"value",
":",
"Union",
"[",
"Literal",
",",
"BNode",
",",
"URIRef",
",",
"str",
",",
"int",
"]",
",",
"lang",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"if",
"not",
"isin... | 47.5625 | 17.3125 |
def _create_dynamic_xml(self, cmdname, tag_name, mode, subelements=None):
"""Create RIBCL XML to send to iLO.
This function creates the dynamic xml required to be sent
to the ILO for all the APIs.
:param cmdname: the API which needs to be implemented.
:param tag_name: the tag i... | [
"def",
"_create_dynamic_xml",
"(",
"self",
",",
"cmdname",
",",
"tag_name",
",",
"mode",
",",
"subelements",
"=",
"None",
")",
":",
"root",
"=",
"etree",
".",
"Element",
"(",
"'RIBCL'",
",",
"VERSION",
"=",
"\"2.0\"",
")",
"login",
"=",
"etree",
".",
"... | 37.09375 | 18.84375 |
def increment(self, name, count=1, rate=1):
# type: (str, int, float) -> None
"""Increment a Counter metric"""
if self._should_send_metric(name, rate):
self._request(
Counter(
self._create_metric_name_for_request(name),
int(cou... | [
"def",
"increment",
"(",
"self",
",",
"name",
",",
"count",
"=",
"1",
",",
"rate",
"=",
"1",
")",
":",
"# type: (str, int, float) -> None",
"if",
"self",
".",
"_should_send_metric",
"(",
"name",
",",
"rate",
")",
":",
"self",
".",
"_request",
"(",
"Count... | 31.916667 | 13.916667 |
def _flatten_listener(listener):
"""
from
{
"Listener": {
"InstancePort": 80,
"LoadBalancerPort": 80,
"Protocol": "HTTP",
"InstanceProtocol": "HTTP"
},
"PolicyNames": []
},
to
{
"InstancePort": 80,
"LoadBalancerPort": 80,
... | [
"def",
"_flatten_listener",
"(",
"listener",
")",
":",
"result",
"=",
"dict",
"(",
")",
"if",
"set",
"(",
"listener",
".",
"keys",
"(",
")",
")",
"==",
"set",
"(",
"[",
"'Listener'",
",",
"'PolicyNames'",
"]",
")",
":",
"result",
".",
"update",
"(",
... | 20.419355 | 20.16129 |
def find_base(path):
"""Find the base of a glob."""
result = _pattern.match(path)
if result:
base = result.group(0)
else:
base = "./"
if base.endswith('/') or base.endswith('\\'):
return os.path.abspath(base)
else:
return os.path.dirname(os.path.abspath(base)) | [
"def",
"find_base",
"(",
"path",
")",
":",
"result",
"=",
"_pattern",
".",
"match",
"(",
"path",
")",
"if",
"result",
":",
"base",
"=",
"result",
".",
"group",
"(",
"0",
")",
"else",
":",
"base",
"=",
"\"./\"",
"if",
"base",
".",
"endswith",
"(",
... | 20.307692 | 21 |
def _check_exists(database: Database, table: LdapObjectClass, key: str, value: str):
""" Check if a given LDAP object exists. """
try:
get_one(table, Q(**{key: value}), database=database)
return True
except ObjectDoesNotExist:
return False | [
"def",
"_check_exists",
"(",
"database",
":",
"Database",
",",
"table",
":",
"LdapObjectClass",
",",
"key",
":",
"str",
",",
"value",
":",
"str",
")",
":",
"try",
":",
"get_one",
"(",
"table",
",",
"Q",
"(",
"*",
"*",
"{",
"key",
":",
"value",
"}",... | 38.428571 | 21 |
def _load_wm_map(exclude_auto=None):
"""Load an ontology map for world models.
exclude_auto : None or list[tuple]
A list of ontology mappings for which automated mappings should be
excluded, e.g. [(HUME, UN)] would result in not using mappings
from HUME to UN.
"""
exclude_auto =... | [
"def",
"_load_wm_map",
"(",
"exclude_auto",
"=",
"None",
")",
":",
"exclude_auto",
"=",
"[",
"]",
"if",
"not",
"exclude_auto",
"else",
"exclude_auto",
"path_here",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__fi... | 39.675439 | 13.587719 |
def symlink(self, link_target, path, dir_fd=None):
"""Creates the specified symlink, pointed at the specified link target.
Args:
link_target: The target of the symlink.
path: Path to the symlink to create.
dir_fd: If not `None`, the file descriptor of a directory,
... | [
"def",
"symlink",
"(",
"self",
",",
"link_target",
",",
"path",
",",
"dir_fd",
"=",
"None",
")",
":",
"link_target",
"=",
"self",
".",
"_path_with_dir_fd",
"(",
"link_target",
",",
"self",
".",
"symlink",
",",
"dir_fd",
")",
"self",
".",
"filesystem",
".... | 41.4375 | 18.1875 |
def dateint_difference(dateint1, dateint2):
"""Return the difference between two dateints in days.
Arguments
---------
dateint1 : int
An integer object decipting a specific calendaric day; e.g. 20161225.
dateint2 : int
An integer object decipting a specific calendaric day; e.g. 2016... | [
"def",
"dateint_difference",
"(",
"dateint1",
",",
"dateint2",
")",
":",
"dt1",
"=",
"dateint_to_datetime",
"(",
"dateint1",
")",
"dt2",
"=",
"dateint_to_datetime",
"(",
"dateint2",
")",
"delta",
"=",
"dt1",
"-",
"dt2",
"return",
"abs",
"(",
"delta",
".",
... | 28.421053 | 21.210526 |
def convert_to_qutip(expr, full_space=None, mapping=None):
"""Convert a QNET expression to a qutip object
Args:
expr: a QNET expression
full_space (HilbertSpace): The
Hilbert space in which `expr` is defined. If not given,
``expr.space`` is used. The Hilbert space must h... | [
"def",
"convert_to_qutip",
"(",
"expr",
",",
"full_space",
"=",
"None",
",",
"mapping",
"=",
"None",
")",
":",
"if",
"full_space",
"is",
"None",
":",
"full_space",
"=",
"expr",
".",
"space",
"if",
"not",
"expr",
".",
"space",
".",
"is_tensor_factor_of",
... | 44.88 | 18.786667 |
def addError(self, test, err, capt=None):
"""
Since Skip, Blocked, and Deprecated are all technically errors, but not
error states, we want to make sure that they don't show up in
the nose output as errors.
"""
if (err[0] == errors.BlockedTest or (
err[0] ... | [
"def",
"addError",
"(",
"self",
",",
"test",
",",
"err",
",",
"capt",
"=",
"None",
")",
":",
"if",
"(",
"err",
"[",
"0",
"]",
"==",
"errors",
".",
"BlockedTest",
"or",
"(",
"err",
"[",
"0",
"]",
"==",
"errors",
".",
"SkipTest",
")",
"or",
"(",
... | 45.8125 | 16.8125 |
def delete_alias(self, alias_name):
"""Delete the alias."""
for aliases in self.key_to_aliases.values():
if alias_name in aliases:
aliases.remove(alias_name) | [
"def",
"delete_alias",
"(",
"self",
",",
"alias_name",
")",
":",
"for",
"aliases",
"in",
"self",
".",
"key_to_aliases",
".",
"values",
"(",
")",
":",
"if",
"alias_name",
"in",
"aliases",
":",
"aliases",
".",
"remove",
"(",
"alias_name",
")"
] | 39.4 | 4.4 |
def confusion_matrix(self, metrics=None, thresholds=None):
"""
Get the confusion matrix for the specified metric
:param metrics: A string (or list of strings) among metrics listed in :const:`max_metrics`. Defaults to 'f1'.
:param thresholds: A value (or list of values) between 0 and 1.
... | [
"def",
"confusion_matrix",
"(",
"self",
",",
"metrics",
"=",
"None",
",",
"thresholds",
"=",
"None",
")",
":",
"# make lists out of metrics and thresholds arguments",
"if",
"metrics",
"is",
"None",
"and",
"thresholds",
"is",
"None",
":",
"metrics",
"=",
"[",
"'f... | 42.909091 | 24.757576 |
def _extract_archive(archive_fpath, archive_file, archive_namelist, output_dir,
force_commonprefix=True, prefix=None,
dryrun=False, verbose=not QUIET, overwrite=None):
"""
archive_fpath = zip_fpath
archive_file = zip_file
"""
# force extracted components int... | [
"def",
"_extract_archive",
"(",
"archive_fpath",
",",
"archive_file",
",",
"archive_namelist",
",",
"output_dir",
",",
"force_commonprefix",
"=",
"True",
",",
"prefix",
"=",
"None",
",",
"dryrun",
"=",
"False",
",",
"verbose",
"=",
"not",
"QUIET",
",",
"overwr... | 38.363636 | 16.121212 |
def on_connection_open_error(self, connection, error):
"""Invoked if the connection to RabbitMQ can not be made.
:type connection: pika.TornadoConnection
:param Exception error: The exception indicating failure
"""
LOGGER.critical('Could not connect to RabbitMQ (%s): %r',
... | [
"def",
"on_connection_open_error",
"(",
"self",
",",
"connection",
",",
"error",
")",
":",
"LOGGER",
".",
"critical",
"(",
"'Could not connect to RabbitMQ (%s): %r'",
",",
"connection",
",",
"error",
")",
"self",
".",
"state",
"=",
"self",
".",
"STATE_CLOSED",
"... | 37.454545 | 15.454545 |
def get_execution_state(self, topologyName, callback=None):
"""
Get execution state
"""
if callback:
self.execution_state_watchers[topologyName].append(callback)
else:
execution_state_path = self.get_execution_state_path(topologyName)
with open(execution_state_path) as f:
d... | [
"def",
"get_execution_state",
"(",
"self",
",",
"topologyName",
",",
"callback",
"=",
"None",
")",
":",
"if",
"callback",
":",
"self",
".",
"execution_state_watchers",
"[",
"topologyName",
"]",
".",
"append",
"(",
"callback",
")",
"else",
":",
"execution_state... | 33.769231 | 14.230769 |
def create_config_headers_dicts(self):
"""
Creates the config_headers_to_widgets and config_widgets_to_headers and config_headers_to_categories dicts
"""
self.config_headers_to_widgets = {
# blue stuff
'Bot Loadout': {
'team_color_id': (self.blue_p... | [
"def",
"create_config_headers_dicts",
"(",
"self",
")",
":",
"self",
".",
"config_headers_to_widgets",
"=",
"{",
"# blue stuff",
"'Bot Loadout'",
":",
"{",
"'team_color_id'",
":",
"(",
"self",
".",
"blue_primary_spinbox",
",",
")",
",",
"'custom_color_id'",
":",
"... | 59.625 | 29.053571 |
def get_proxy_for_requests(self, url):
"""
Get proxy configuration for a given URL, in a form ready to use with the Requests library.
:param str url: The URL for which to obtain proxy configuration.
:returns: Proxy configuration in a form recognized by Requests, for use with the ``proxi... | [
"def",
"get_proxy_for_requests",
"(",
"self",
",",
"url",
")",
":",
"proxy",
"=",
"self",
".",
"get_proxy",
"(",
"url",
")",
"if",
"not",
"proxy",
":",
"raise",
"ProxyConfigExhaustedError",
"(",
"url",
")",
"return",
"proxy_parameter_for_requests",
"(",
"proxy... | 46.714286 | 23.142857 |
def file_list(package, **kwargs):
'''
List the files that belong to a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list nginx
'''
ret = file_dict(package)
files = []
for pkg_files in six.itervalues(ret['files']):
files.extend(pkg_files)
ret['files'... | [
"def",
"file_list",
"(",
"package",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"file_dict",
"(",
"package",
")",
"files",
"=",
"[",
"]",
"for",
"pkg_files",
"in",
"six",
".",
"itervalues",
"(",
"ret",
"[",
"'files'",
"]",
")",
":",
"files",
"."... | 20.5625 | 21.1875 |
def move_recursive(self, dest_path):
"""See DAVResource.move_recursive() """
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
fpDest = self.provider._loc_to_file_path(dest_path, self.environ)
assert not util.is_equal_or_child_uri(self.path, dest_path)
assert ... | [
"def",
"move_recursive",
"(",
"self",
",",
"dest_path",
")",
":",
"if",
"self",
".",
"provider",
".",
"readonly",
":",
"raise",
"DAVError",
"(",
"HTTP_FORBIDDEN",
")",
"fpDest",
"=",
"self",
".",
"provider",
".",
"_loc_to_file_path",
"(",
"dest_path",
",",
... | 46.368421 | 12.736842 |
def attach(gandi, ip, vm, background, force):
"""Attach an ip to a vm.
ip can be an ip id or ip
vm can be a vm id or name.
"""
try:
ip_ = gandi.ip.info(ip)
vm_ = gandi.iaas.info(vm)
except UsageError:
gandi.error("Can't find this ip %s" % ip)
iface = gandi.iface.inf... | [
"def",
"attach",
"(",
"gandi",
",",
"ip",
",",
"vm",
",",
"background",
",",
"force",
")",
":",
"try",
":",
"ip_",
"=",
"gandi",
".",
"ip",
".",
"info",
"(",
"ip",
")",
"vm_",
"=",
"gandi",
".",
"iaas",
".",
"info",
"(",
"vm",
")",
"except",
... | 30.615385 | 18.038462 |
def draw_annotation(img, boxes, klass, is_crowd=None):
"""Will not modify img"""
labels = []
assert len(boxes) == len(klass)
if is_crowd is not None:
assert len(boxes) == len(is_crowd)
for cls, crd in zip(klass, is_crowd):
clsname = cfg.DATA.CLASS_NAMES[cls]
if cr... | [
"def",
"draw_annotation",
"(",
"img",
",",
"boxes",
",",
"klass",
",",
"is_crowd",
"=",
"None",
")",
":",
"labels",
"=",
"[",
"]",
"assert",
"len",
"(",
"boxes",
")",
"==",
"len",
"(",
"klass",
")",
"if",
"is_crowd",
"is",
"not",
"None",
":",
"asse... | 33.25 | 11.5625 |
def get_git_revision(repopath):
"""
Return Git revision for the repository located at repopath
Result is a tuple (latest commit hash, branch), with None values on
error
"""
try:
git = programs.find_program('git')
assert git is not None and osp.isdir(osp.join(repopat... | [
"def",
"get_git_revision",
"(",
"repopath",
")",
":",
"try",
":",
"git",
"=",
"programs",
".",
"find_program",
"(",
"'git'",
")",
"assert",
"git",
"is",
"not",
"None",
"and",
"osp",
".",
"isdir",
"(",
"osp",
".",
"join",
"(",
"repopath",
",",
"'.git'",... | 37.121212 | 20.515152 |
def exposure_summary_table(
aggregate_hazard, exposure_summary=None, callback=None):
"""Compute the summary from the aggregate hazard to analysis.
Source layer :
| haz_id | haz_class | aggr_id | aggr_name | exposure_count |
Output layer :
| exp_type | count_hazard_class | total |
:par... | [
"def",
"exposure_summary_table",
"(",
"aggregate_hazard",
",",
"exposure_summary",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"output_layer_name",
"=",
"summary_4_exposure_summary_table_steps",
"[",
"'output_layer_name'",
"]",
"source_fields",
"=",
"aggregate_ha... | 35.610619 | 18.840708 |
def resizeEvent(self, event):
"""
Reimplements the :meth:`*.resizeEvent` method.
:param event: QEvent.
:type event: QEvent
"""
super(type(self), self).resizeEvent(event)
self.__notifier.refresh_position() | [
"def",
"resizeEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"type",
"(",
"self",
")",
",",
"self",
")",
".",
"resizeEvent",
"(",
"event",
")",
"self",
".",
"__notifier",
".",
"refresh_position",
"(",
")"
] | 23 | 16.454545 |
def create_function_f_y(self):
"""output function"""
return ca.Function(
'y',
[self.t, self.x, self.m, self.p, self.c, self.ng, self.nu],
[self.y_rhs],
['t', 'x', 'm', 'p', 'c', 'ng', 'nu'], ['y'], self.func_opt) | [
"def",
"create_function_f_y",
"(",
"self",
")",
":",
"return",
"ca",
".",
"Function",
"(",
"'y'",
",",
"[",
"self",
".",
"t",
",",
"self",
".",
"x",
",",
"self",
".",
"m",
",",
"self",
".",
"p",
",",
"self",
".",
"c",
",",
"self",
".",
"ng",
... | 38.571429 | 17.857143 |
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.",
")",
":",
"Rz",
"=",
"R",
"**",
"2.",
"+",
"z",
"**",
"2.",
"sqrtRz",
"=",
"numpy",
".",
"sqrt",
"(",
"Rz",
")",
"return",
"R",
"*",
"(",
"1.",... | 27.684211 | 16.105263 |
def read_text(self): # type: () ->Dict[str,str]
"""
Get version out of ad-hoc version.txt
:return:
"""
found = {}
for file in self.file_inventory.text_files:
if not os.path.isfile(file):
continue
with self.file_opener.open_this(fil... | [
"def",
"read_text",
"(",
"self",
")",
":",
"# type: () ->Dict[str,str]",
"found",
"=",
"{",
"}",
"for",
"file",
"in",
"self",
".",
"file_inventory",
".",
"text_files",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file",
")",
":",
"continue",... | 33.230769 | 10.307692 |
def six_frame(genome, table, minimum = 10):
"""
translate each sequence into six reading frames
"""
for seq in parse_fasta(genome):
dna = Seq(seq[1].upper().replace('U', 'T'), IUPAC.ambiguous_dna)
counter = 0
for sequence in ['f', dna], ['rc', dna.reverse_complement()]:
... | [
"def",
"six_frame",
"(",
"genome",
",",
"table",
",",
"minimum",
"=",
"10",
")",
":",
"for",
"seq",
"in",
"parse_fasta",
"(",
"genome",
")",
":",
"dna",
"=",
"Seq",
"(",
"seq",
"[",
"1",
"]",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"'U'",
... | 44.95 | 13.85 |
def _walk_paths(self, base: pathlib.PurePath) \
-> Iterator[pathlib.PurePath]:
"""
Internal helper for walking paths. This is required to exclude the name
of the root entity from the walk.
:param base: The base path to prepend to the entity name.
:return: An iterator... | [
"def",
"_walk_paths",
"(",
"self",
",",
"base",
":",
"pathlib",
".",
"PurePath",
")",
"->",
"Iterator",
"[",
"pathlib",
".",
"PurePath",
"]",
":",
"return",
"self",
".",
"walk_paths",
"(",
"base",
")"
] | 37 | 12 |
def get_class(self, id=None, uri=None, match=None):
"""
get the saved-class with given ID or via other methods...
Note: it tries to guess what is being passed..
In [1]: g.get_class(uri='http://www.w3.org/2000/01/rdf-schema#Resource')
Out[1]: <Class *http://www.w3.org/2000/01/rd... | [
"def",
"get_class",
"(",
"self",
",",
"id",
"=",
"None",
",",
"uri",
"=",
"None",
",",
"match",
"=",
"None",
")",
":",
"if",
"not",
"id",
"and",
"not",
"uri",
"and",
"not",
"match",
":",
"return",
"None",
"if",
"type",
"(",
"id",
")",
"==",
"ty... | 32.734694 | 18.163265 |
def _file_iter(input_stream, size, offset=0):
"""读取输入流:
Args:
input_stream: 待读取文件的二进制流
size: 二进制流的大小
Raises:
IOError: 文件流读取失败
"""
input_stream.seek(offset)
d = input_stream.read(size)
while d:
yield d
d = input_stream.read(size) | [
"def",
"_file_iter",
"(",
"input_stream",
",",
"size",
",",
"offset",
"=",
"0",
")",
":",
"input_stream",
".",
"seek",
"(",
"offset",
")",
"d",
"=",
"input_stream",
".",
"read",
"(",
"size",
")",
"while",
"d",
":",
"yield",
"d",
"d",
"=",
"input_stre... | 19.466667 | 17.2 |
def delay(self, n, start_time):
"""Calculate delay before the next retry.
Args:
n: the number of current attempt. The first attempt should be 1.
start_time: the time when retry started in unix time.
Returns:
Number of seconds to wait before next retry. -1 if retry should give up.
"""... | [
"def",
"delay",
"(",
"self",
",",
"n",
",",
"start_time",
")",
":",
"if",
"(",
"n",
">",
"self",
".",
"max_retries",
"or",
"(",
"n",
">",
"self",
".",
"min_retries",
"and",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
">",
"self",
".",
"max_... | 32.470588 | 21.294118 |
def _measure(self, weighted):
"""_BaseMeasure subclass representing primary measure for this cube.
If the cube response includes a means measure, the return value is
means. Otherwise it is counts, with the choice between weighted or
unweighted determined by *weighted*.
Note tha... | [
"def",
"_measure",
"(",
"self",
",",
"weighted",
")",
":",
"return",
"(",
"self",
".",
"_measures",
".",
"means",
"if",
"self",
".",
"_measures",
".",
"means",
"is",
"not",
"None",
"else",
"self",
".",
"_measures",
".",
"weighted_counts",
"if",
"weighted... | 39.666667 | 18.388889 |
def delete_mappings_in_network(network_id, network_2_id=None, **kwargs):
"""
Delete all the resource attribute mappings in a network. If another network
is specified, only delete the mappings between the two networks.
"""
qry = db.DBSession.query(ResourceAttrMap).filter(or_(ResourceAttrMap.n... | [
"def",
"delete_mappings_in_network",
"(",
"network_id",
",",
"network_2_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ResourceAttrMap",
")",
".",
"filter",
"(",
"or_",
"(",
"ResourceAttrMap",
"... | 38.235294 | 31.882353 |
def find_zone_name(data, zone_id):
"""
Find on the HTML document the zone name.
# expected result
<span class="more_info" \
title="Zone can be renamed on Setup tab">1 - zone1</span>,
:param data: BeautifulSoup object
:param zone: zone id
:return: zone name
:rtype: string
:r... | [
"def",
"find_zone_name",
"(",
"data",
",",
"zone_id",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"BeautifulSoup",
")",
":",
"raise",
"TypeError",
"(",
"\"Function requires BeautilSoup HTML element.\"",
")",
"table",
"=",
"data",
".",
"find",
"(",
"... | 33.56 | 17.32 |
def eigenvectors_rev(T, right=True, mu=None):
r"""Compute eigenvectors of reversible transition matrix.
Parameters
----------
T : (d, d) ndarray
Transition matrix (stochastic matrix)
right : bool, optional
If right=True compute right eigenvectors, left eigenvectors
otherwise... | [
"def",
"eigenvectors_rev",
"(",
"T",
",",
"right",
"=",
"True",
",",
"mu",
"=",
"None",
")",
":",
"if",
"mu",
"is",
"None",
":",
"mu",
"=",
"stationary_distribution",
"(",
"T",
")",
"\"\"\" symmetrize T \"\"\"",
"smu",
"=",
"np",
".",
"sqrt",
"(",
"mu"... | 27.212121 | 15.727273 |
def loadings(self):
"""Loadings = eigenvectors times sqrt(eigenvalues)."""
loadings = self.v[:, : self.keep] * np.sqrt(self.eigenvalues)
cols = ["PC%s" % i for i in range(1, self.keep + 1)]
loadings = pd.DataFrame(
loadings, columns=cols, index=self.feature_names
... | [
"def",
"loadings",
"(",
"self",
")",
":",
"loadings",
"=",
"self",
".",
"v",
"[",
":",
",",
":",
"self",
".",
"keep",
"]",
"*",
"np",
".",
"sqrt",
"(",
"self",
".",
"eigenvalues",
")",
"cols",
"=",
"[",
"\"PC%s\"",
"%",
"i",
"for",
"i",
"in",
... | 42.625 | 18.25 |
def add_label_to_table(self, row, col, txt):
"""Add a label to specified cell in table."""
label = QLabel(txt)
label.setMargin(5)
label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.table.setCellWidget(row, col, label) | [
"def",
"add_label_to_table",
"(",
"self",
",",
"row",
",",
"col",
",",
"txt",
")",
":",
"label",
"=",
"QLabel",
"(",
"txt",
")",
"label",
".",
"setMargin",
"(",
"5",
")",
"label",
".",
"setAlignment",
"(",
"Qt",
".",
"AlignLeft",
"|",
"Qt",
".",
"A... | 42.833333 | 9.666667 |
def _index_iterator(column_size, max_size, mix_index=False):
"""
This will iterate over the indexes and return a list of indexes
:param column_size: list of int of the size of each list
:param max_size: int of the max number of iterations
:param mix_index: bool if True will g... | [
"def",
"_index_iterator",
"(",
"column_size",
",",
"max_size",
",",
"mix_index",
"=",
"False",
")",
":",
"# todo implement a proper partial factorial design",
"indexes",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"column_size",
")",
"index_order",
"=",
"[",
"0",
"]",
... | 37.3125 | 16.625 |
def check_error(response, expect_status=200):
"""
Youku error should return in json form, like:
HTTP 400
{
"error":{
"code":120010223,
"type":"UploadsException",
"description":"Expired upload token"
}
}
But error also maybe in response url par... | [
"def",
"check_error",
"(",
"response",
",",
"expect_status",
"=",
"200",
")",
":",
"json",
"=",
"None",
"try",
":",
"json",
"=",
"response",
".",
"json",
"(",
")",
"except",
":",
"pass",
"if",
"(",
"response",
".",
"status_code",
"!=",
"expect_status",
... | 30.051282 | 18.769231 |
def delete(network):
"""libvirt network cleanup.
@raise: libvirt.libvirtError.
"""
try:
network.destroy()
except libvirt.libvirtError as error:
raise RuntimeError("Unable to destroy network: {}".format(error)) | [
"def",
"delete",
"(",
"network",
")",
":",
"try",
":",
"network",
".",
"destroy",
"(",
")",
"except",
"libvirt",
".",
"libvirtError",
"as",
"error",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to destroy network: {}\"",
".",
"format",
"(",
"error",
")",
")"... | 23.8 | 18.8 |
def metadata(sceneid, pmin=2, pmax=98, **kwargs):
"""
Retrieve image bounds and band statistics.
Attributes
----------
sceneid : str
Landsat sceneid. For scenes after May 2017,
sceneid have to be LANDSAT_PRODUCT_ID.
pmin : int, optional, (default: 2)
Histogram minimum cu... | [
"def",
"metadata",
"(",
"sceneid",
",",
"pmin",
"=",
"2",
",",
"pmax",
"=",
"98",
",",
"*",
"*",
"kwargs",
")",
":",
"scene_params",
"=",
"_landsat_parse_scene_id",
"(",
"sceneid",
")",
"meta_data",
"=",
"_landsat_get_mtl",
"(",
"sceneid",
")",
".",
"get... | 27.705882 | 20.764706 |
def get_user_ip(request):
"""Return user ip
:param request: Django request object
:return: user ip
"""
ip = get_real_ip(request)
if ip is None:
ip = get_ip(request)
if ip is None:
ip = '127.0.0.1'
return ip | [
"def",
"get_user_ip",
"(",
"request",
")",
":",
"ip",
"=",
"get_real_ip",
"(",
"request",
")",
"if",
"ip",
"is",
"None",
":",
"ip",
"=",
"get_ip",
"(",
"request",
")",
"if",
"ip",
"is",
"None",
":",
"ip",
"=",
"'127.0.0.1'",
"return",
"ip"
] | 21 | 14.833333 |
def _fast_shake(self, x, normals, values, error):
'''Take an efficient (not always robust) step towards the constraints.
Arguments:
| ``x`` -- The unknowns.
| ``normals`` -- A numpy array with the gradients of the active
constraints. Each row is o... | [
"def",
"_fast_shake",
"(",
"self",
",",
"x",
",",
"normals",
",",
"values",
",",
"error",
")",
":",
"# filter out the degrees of freedom that do not feel the constraints.",
"mask",
"=",
"(",
"normals",
"!=",
"0",
")",
".",
"any",
"(",
"axis",
"=",
"0",
")",
... | 45.117647 | 20.215686 |
def minion_sign_in_payload(self):
'''
Generates the payload used to authenticate with the master
server. This payload consists of the passed in id_ and the ssh
public key to encrypt the AES key sent back from the master.
:return: Payload dictionary
:rtype: dict
'... | [
"def",
"minion_sign_in_payload",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"}",
"payload",
"[",
"'cmd'",
"]",
"=",
"'_auth'",
"payload",
"[",
"'id'",
"]",
"=",
"self",
".",
"opts",
"[",
"'id'",
"]",
"if",
"'autosign_grains'",
"in",
"self",
".",
"opts... | 39.466667 | 19.2 |
def addExpression(self, datafields):
"""
Adds an Expression to the db. Datafields is a tuple in the order:
id, rna_quantification_id, name, expression,
is_normalized, raw_read_count, score, units, conf_low, conf_hi
"""
self._expressionValueList.append(datafields)
... | [
"def",
"addExpression",
"(",
"self",
",",
"datafields",
")",
":",
"self",
".",
"_expressionValueList",
".",
"append",
"(",
"datafields",
")",
"if",
"len",
"(",
"self",
".",
"_expressionValueList",
")",
">=",
"self",
".",
"_batchSize",
":",
"self",
".",
"ba... | 44.888889 | 12.888889 |
def close(self):
"""Closes the ssh connection."""
if 'isLive' in self.__dict__ and self.isLive:
self.transport.close()
self.isLive = False | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"'isLive'",
"in",
"self",
".",
"__dict__",
"and",
"self",
".",
"isLive",
":",
"self",
".",
"transport",
".",
"close",
"(",
")",
"self",
".",
"isLive",
"=",
"False"
] | 34.8 | 10.4 |
def match(self, fsys_view):
'''
Compare potentially partial criteria against built filesystems entry dictionary
'''
evalue_dict = fsys_view[1]
for key, value in six.viewitems(self.criteria):
if key in evalue_dict:
if evalue_dict[key] != value:
... | [
"def",
"match",
"(",
"self",
",",
"fsys_view",
")",
":",
"evalue_dict",
"=",
"fsys_view",
"[",
"1",
"]",
"for",
"key",
",",
"value",
"in",
"six",
".",
"viewitems",
"(",
"self",
".",
"criteria",
")",
":",
"if",
"key",
"in",
"evalue_dict",
":",
"if",
... | 33.333333 | 17.833333 |
def parallel_bulk(client, actions, thread_count=4, chunk_size=500,
max_chunk_bytes=100 * 1014 * 1024,
expand_action_callback=expand_action, **kwargs):
"""
Parallel version of the bulk helper run in multiple threads at once.
:arg client: instance of :class:`~elasticsearch.Elasticsearch` to us... | [
"def",
"parallel_bulk",
"(",
"client",
",",
"actions",
",",
"thread_count",
"=",
"4",
",",
"chunk_size",
"=",
"500",
",",
"max_chunk_bytes",
"=",
"100",
"*",
"1014",
"*",
"1024",
",",
"expand_action_callback",
"=",
"expand_action",
",",
"*",
"*",
"kwargs",
... | 48.558824 | 25.382353 |
def Repository(self, *dirs):
"""Specify Repository directories to search."""
for d in dirs:
if not isinstance(d, SCons.Node.Node):
d = self.Dir(d)
self.Top.addRepository(d) | [
"def",
"Repository",
"(",
"self",
",",
"*",
"dirs",
")",
":",
"for",
"d",
"in",
"dirs",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",
"SCons",
".",
"Node",
".",
"Node",
")",
":",
"d",
"=",
"self",
".",
"Dir",
"(",
"d",
")",
"self",
".",
"Top... | 37.166667 | 8.666667 |
def MERGE(*args):
"""
Wipe repeated dependencies from a list of (Analysis, id, filename) tuples,
supplied as argument. Replace id with the correct filename.
"""
# Get the longest common path
common_prefix = os.path.dirname(os.path.commonprefix([os.path.abspath(a.scripts[-1][1]) for a, _, _ in a... | [
"def",
"MERGE",
"(",
"*",
"args",
")",
":",
"# Get the longest common path",
"common_prefix",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"commonprefix",
"(",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"a",
".",
"scripts",
"[... | 39.913043 | 18.347826 |
def get(self, key):
"""Get a value from the cache.
Returns None if the key is not in the cache.
"""
value = redis_conn.get(key)
if value is not None:
value = pickle.loads(value)
return value | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"value",
"=",
"redis_conn",
".",
"get",
"(",
"key",
")",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"pickle",
".",
"loads",
"(",
"value",
")",
"return",
"value"
] | 22.090909 | 17.272727 |
def splitDataset(dataset, groupby):
"""
Split the given dataset into multiple datasets grouped by the given groupby
function. For example::
# Split mnist dataset into 10 datasets, one dataset for each label
splitDataset(mnist, groupby=lambda x: x[1])
# Split mnist dataset into 5 datasets, one ... | [
"def",
"splitDataset",
"(",
"dataset",
",",
"groupby",
")",
":",
"# Split dataset based on the group by function and keep track of indices",
"indicesByGroup",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"k",
",",
"g",
"in",
"itertools",
".",
"grou... | 41.75 | 24.083333 |
def rename(self, req, parent, name, newparent, newname):
"""Rename a file
Valid replies:
reply_err
"""
self.reply_err(req, errno.EROFS) | [
"def",
"rename",
"(",
"self",
",",
"req",
",",
"parent",
",",
"name",
",",
"newparent",
",",
"newname",
")",
":",
"self",
".",
"reply_err",
"(",
"req",
",",
"errno",
".",
"EROFS",
")"
] | 24.857143 | 13.285714 |
def save_resource(self, resource_form, *args, **kwargs):
"""Pass through to provider ResourceAdminSession.update_resource"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.update_resource
if resource_form.is_for_update():
return self.update_res... | [
"def",
"save_resource",
"(",
"self",
",",
"resource_form",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Implemented from kitosid template for -",
"# osid.resource.ResourceAdminSession.update_resource",
"if",
"resource_form",
".",
"is_for_update",
"(",
")",
":... | 54.5 | 16.875 |
def redirect(self, url):
'''Used when you need to redirect to another view, and you only
have the final plugin:// url.'''
# TODO: Should we be overriding self.request with the new request?
new_request = self._parse_request(url=url, handle=self.request.handle)
log.debug('Redirecti... | [
"def",
"redirect",
"(",
"self",
",",
"url",
")",
":",
"# TODO: Should we be overriding self.request with the new request?",
"new_request",
"=",
"self",
".",
"_parse_request",
"(",
"url",
"=",
"url",
",",
"handle",
"=",
"self",
".",
"request",
".",
"handle",
")",
... | 58.857143 | 23.428571 |
def unbind (self, event, callback):
"""
Unbind the callback from the event and ensure that it is never called
:param event: the event that should be unbound
:type event: str
:param callback: the function that should be unbound
:rtype callback: function
"""
... | [
"def",
"unbind",
"(",
"self",
",",
"event",
",",
"callback",
")",
":",
"if",
"self",
".",
"_events",
".",
"has_key",
"(",
"event",
")",
"and",
"len",
"(",
"self",
".",
"_events",
"[",
"event",
"]",
")",
">",
"0",
":",
"for",
"_callback",
"in",
"s... | 43.928571 | 12.071429 |
def handler(self):
""" The current imported serialization handler module.
:return: The imported handler
:rtype: module
"""
if not hasattr(self, "_handler"):
self._handler = sys.modules[self.imported]
return self._handler | [
"def",
"handler",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_handler\"",
")",
":",
"self",
".",
"_handler",
"=",
"sys",
".",
"modules",
"[",
"self",
".",
"imported",
"]",
"return",
"self",
".",
"_handler"
] | 27.3 | 15 |
def snapshots(self, owner=None, restorable_by=None):
"""
Get all snapshots related to this volume. Note that this requires
that all available snapshots for the account be retrieved from EC2
first and then the list is filtered client-side to contain only
those for this volume.
... | [
"def",
"snapshots",
"(",
"self",
",",
"owner",
"=",
"None",
",",
"restorable_by",
"=",
"None",
")",
":",
"rs",
"=",
"self",
".",
"connection",
".",
"get_all_snapshots",
"(",
"owner",
"=",
"owner",
",",
"restorable_by",
"=",
"restorable_by",
")",
"mine",
... | 40.703704 | 21.666667 |
def _get_metadata_path(self, key):
""" return the metadata pathname for this key """
return "{group}/meta/{key}/meta".format(group=self.group._v_pathname,
key=key) | [
"def",
"_get_metadata_path",
"(",
"self",
",",
"key",
")",
":",
"return",
"\"{group}/meta/{key}/meta\"",
".",
"format",
"(",
"group",
"=",
"self",
".",
"group",
".",
"_v_pathname",
",",
"key",
"=",
"key",
")"
] | 56 | 14.75 |
def parse_selinux(parts):
"""
Parse part of an ls output line that is selinux.
Args:
parts (list): A four element list of strings representing the initial
parts of an ls line after the permission bits. The parts are owner
group, selinux info, and the path.
Returns:
... | [
"def",
"parse_selinux",
"(",
"parts",
")",
":",
"owner",
",",
"group",
"=",
"parts",
"[",
":",
"2",
"]",
"selinux",
"=",
"parts",
"[",
"2",
"]",
".",
"split",
"(",
"\":\"",
")",
"lsel",
"=",
"len",
"(",
"selinux",
")",
"path",
",",
"link",
"=",
... | 29.548387 | 21.290323 |
def postfix_to_optree(nodes):
"""Convert a list of nodes in postfix order to an Optree."""
while len(nodes) > 1:
nodes = _reduce(nodes)
if len(nodes) == 0:
raise OperatorError("Empty node list")
node = nodes[0]
if isinstance(node, OperatorNode):
raise OperatorError("Operator without operands")
... | [
"def",
"postfix_to_optree",
"(",
"nodes",
")",
":",
"while",
"len",
"(",
"nodes",
")",
">",
"1",
":",
"nodes",
"=",
"_reduce",
"(",
"nodes",
")",
"if",
"len",
"(",
"nodes",
")",
"==",
"0",
":",
"raise",
"OperatorError",
"(",
"\"Empty node list\"",
")",... | 23.058824 | 19.882353 |
def return_search_summary(start_time=0, end_time=0, nevents=0,
ifos=None, **kwargs):
"""
Function to create a SearchSummary object where all columns are populated
but all are set to values that test False (ie. strings to '', floats/ints
to 0, ...). This avoids errors when you t... | [
"def",
"return_search_summary",
"(",
"start_time",
"=",
"0",
",",
"end_time",
"=",
"0",
",",
"nevents",
"=",
"0",
",",
"ifos",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ifos",
"is",
"None",
":",
"ifos",
"=",
"[",
"]",
"# create an empty ... | 39.254902 | 18.470588 |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the DerivationParameters struct to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a Bytearra... | [
"def",
"write",
"(",
"self",
",",
"output_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"local_stream",
"=",
"BytearrayStream",
"(",
")",
"if",
"self",
".",
"_cryptographic_parameters",
":",
"self",
".",
"_cryptogra... | 34.23913 | 15.021739 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.