text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _ParseRecord(self, parser_mediator, file_object):
"""Parses an event record.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.
Raises:
ParseError: if t... | [
"def",
"_ParseRecord",
"(",
"self",
",",
"parser_mediator",
",",
"file_object",
")",
":",
"header_record_offset",
"=",
"file_object",
".",
"tell",
"(",
")",
"# Check the header token type before reading the token data to prevent",
"# variable size tokens to consume a large amount... | 37.466667 | 22.013333 |
def image_channel_compress_top(body_output, targets, model_hparams, vocab_size):
"""Transforms body output to return logits.
Args:
body_output: Tensor of shape [batch, img_len, img_len, depth].
targets:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
... | [
"def",
"image_channel_compress_top",
"(",
"body_output",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"del",
"targets",
"# unused arg",
"with",
"tf",
".",
"variable_scope",
"(",
"\"image_channel_compress_modality\"",
")",
":",
"hidden_size",
"=",... | 34.166667 | 16.555556 |
def _set_cache_(self, attr):
"""Retrieve object information"""
if attr == "size":
oinfo = self.repo.odb.info(self.binsha)
self.size = oinfo.size
# assert oinfo.type == self.type, _assertion_msg_format % (self.binsha, oinfo.type, self.type)
else:
su... | [
"def",
"_set_cache_",
"(",
"self",
",",
"attr",
")",
":",
"if",
"attr",
"==",
"\"size\"",
":",
"oinfo",
"=",
"self",
".",
"repo",
".",
"odb",
".",
"info",
"(",
"self",
".",
"binsha",
")",
"self",
".",
"size",
"=",
"oinfo",
".",
"size",
"# assert oi... | 43.5 | 18.125 |
def children_types( record, index, key='refs', stop_types=STOP_TYPES ):
"""Produce dictionary mapping type-key to instances for all children"""
types = {}
for child in children( record, index, key, stop_types=stop_types ):
types.setdefault(child['type'],[]).append( child )
return types | [
"def",
"children_types",
"(",
"record",
",",
"index",
",",
"key",
"=",
"'refs'",
",",
"stop_types",
"=",
"STOP_TYPES",
")",
":",
"types",
"=",
"{",
"}",
"for",
"child",
"in",
"children",
"(",
"record",
",",
"index",
",",
"key",
",",
"stop_types",
"=",
... | 50.833333 | 21.666667 |
def squish_infinite(x, range=(0, 1)):
"""
Truncate infinite values to a range.
Parameters
----------
x : array_like
Values that should have infinities squished.
range : tuple
The range onto which to squish the infinites.
Must be of size 2.
Returns
-------
ou... | [
"def",
"squish_infinite",
"(",
"x",
",",
"range",
"=",
"(",
"0",
",",
"1",
")",
")",
":",
"xtype",
"=",
"type",
"(",
"x",
")",
"if",
"not",
"hasattr",
"(",
"x",
",",
"'dtype'",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"x",
"... | 21.857143 | 19.628571 |
def _adaptive(self, gamma=1.0, relative_tolerance=1.0e-8, maximum_iterations=1000, verbose=True, print_warning=True):
"""
Determine dimensionless free energies by a combination of Newton-Raphson iteration and self-consistent iteration.
Picks whichever method gives the lowest gradient.
Is... | [
"def",
"_adaptive",
"(",
"self",
",",
"gamma",
"=",
"1.0",
",",
"relative_tolerance",
"=",
"1.0e-8",
",",
"maximum_iterations",
"=",
"1000",
",",
"verbose",
"=",
"True",
",",
"print_warning",
"=",
"True",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"\"... | 45.069767 | 27.813953 |
def clear(self):
"""
Reset the config object to its initial state
"""
with self._lock:
self._config = {
CacheConfig.Morlist: {'last': defaultdict(float), 'intl': {}},
CacheConfig.Metadata: {'last': defaultdict(float), 'intl': {}},
} | [
"def",
"clear",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_config",
"=",
"{",
"CacheConfig",
".",
"Morlist",
":",
"{",
"'last'",
":",
"defaultdict",
"(",
"float",
")",
",",
"'intl'",
":",
"{",
"}",
"}",
",",
"CacheConf... | 34.666667 | 18.666667 |
def shift(self, time: int) -> 'Timeslot':
"""Return a new Timeslot shifted by `time`.
Args:
time: time to be shifted
"""
return Timeslot(self.interval.shift(time), self.channel) | [
"def",
"shift",
"(",
"self",
",",
"time",
":",
"int",
")",
"->",
"'Timeslot'",
":",
"return",
"Timeslot",
"(",
"self",
".",
"interval",
".",
"shift",
"(",
"time",
")",
",",
"self",
".",
"channel",
")"
] | 30.857143 | 13.714286 |
def eas2tas(eas, h):
""" Equivalent airspeed to true airspeed """
rho = density(h)
tas = eas * np.sqrt(rho0 / rho)
return tas | [
"def",
"eas2tas",
"(",
"eas",
",",
"h",
")",
":",
"rho",
"=",
"density",
"(",
"h",
")",
"tas",
"=",
"eas",
"*",
"np",
".",
"sqrt",
"(",
"rho0",
"/",
"rho",
")",
"return",
"tas"
] | 27.4 | 14.2 |
def _async_route(self, msg, in_stream=None):
"""
Arrange for `msg` to be forwarded towards its destination. If its
destination is the local context, then arrange for it to be dispatched
using the local handlers.
This is a lower overhead version of :meth:`route` that may only be
... | [
"def",
"_async_route",
"(",
"self",
",",
"msg",
",",
"in_stream",
"=",
"None",
")",
":",
"_vv",
"and",
"IOLOG",
".",
"debug",
"(",
"'%r._async_route(%r, %r)'",
",",
"self",
",",
"msg",
",",
"in_stream",
")",
"if",
"len",
"(",
"msg",
".",
"data",
")",
... | 39.650794 | 22.126984 |
def openpty():
"""openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible."""
try:
return os.openpty()
except (AttributeError, OSError):
pass
master_fd, slave_name = _open_terminal()
slave_fd = slave_open(slave_name)
return master_fd, ... | [
"def",
"openpty",
"(",
")",
":",
"try",
":",
"return",
"os",
".",
"openpty",
"(",
")",
"except",
"(",
"AttributeError",
",",
"OSError",
")",
":",
"pass",
"master_fd",
",",
"slave_name",
"=",
"_open_terminal",
"(",
")",
"slave_fd",
"=",
"slave_open",
"(",... | 28.909091 | 14.454545 |
def flatten(l, unique=True):
"""flatten a list of lists
Parameters
----------
l : list
of lists
unique : boolean
whether or not only unique items are wanted (default=True)
Returns
-------
list
of single items
Examples
----... | [
"def",
"flatten",
"(",
"l",
",",
"unique",
"=",
"True",
")",
":",
"l",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"y",
",",
"l",
")",
"if",
"not",
"unique",
":",
"return",
"list",
"(",
"l",
")",
"return",
"list",
"(",
"set",
... | 18.28125 | 24 |
def _gei8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand >= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True)
output.append('call __LEI8')... | [
"def",
"_gei8",
"(",
"ins",
")",
":",
"output",
"=",
"_8bit_oper",
"(",
"ins",
".",
"quad",
"[",
"2",
"]",
",",
"ins",
".",
"quad",
"[",
"3",
"]",
",",
"reversed_",
"=",
"True",
")",
"output",
".",
"append",
"(",
"'call __LEI8'",
")",
"output",
"... | 29.615385 | 17 |
def itemStyle(self):
"""
Returns the item style information for this item.
:return <XGanttWidgetItem.ItemStyle>
"""
if ( self.useGroupStyleWithChildren() and self.childCount() ):
return XGanttWidgetItem.ItemStyle.Group
return sel... | [
"def",
"itemStyle",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"useGroupStyleWithChildren",
"(",
")",
"and",
"self",
".",
"childCount",
"(",
")",
")",
":",
"return",
"XGanttWidgetItem",
".",
"ItemStyle",
".",
"Group",
"return",
"self",
".",
"_itemStyle... | 32.3 | 16.1 |
def needs(self):
"""Returns a unique list of module names that this module depends on."""
result = []
for dep in self.dependencies:
module = dep.split(".")[0].lower()
if module not in result:
result.append(module)
return result | [
"def",
"needs",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"dep",
"in",
"self",
".",
"dependencies",
":",
"module",
"=",
"dep",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"if",
"module",
"not",
"in",
"re... | 32.444444 | 13.333333 |
def tuples_as_dict(_list):
"""Translate a list of tuples to OrderedDict with key and val as strings.
Parameters
----------
_list : list of tuples
Returns
-------
collections.OrderedDict
Example
-------
::
>>> tuples_as_dict([('cmd', 'val'), ('cmd2', 'val2')])
... | [
"def",
"tuples_as_dict",
"(",
"_list",
")",
":",
"_dict",
"=",
"OrderedDict",
"(",
")",
"for",
"key",
",",
"val",
"in",
"_list",
":",
"key",
"=",
"str",
"(",
"key",
")",
"val",
"=",
"str",
"(",
"val",
")",
"_dict",
"[",
"key",
"]",
"=",
"val",
... | 19.72 | 23.4 |
def view(self):
"""A list of view specs"""
spec = []
for k, v in six.iteritems(self._p4dict):
if k.startswith('view'):
match = RE_FILESPEC.search(v)
if match:
spec.append(FileSpec(v[:match.end() - 1], v[match.end():]))
retu... | [
"def",
"view",
"(",
"self",
")",
":",
"spec",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_p4dict",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"'view'",
")",
":",
"match",
"=",
"RE_FILESPEC",
".",
"s... | 31.8 | 18 |
def accel_toggle_hide_on_lose_focus(self, *args):
"""Callback toggle whether the window should hide when it loses
focus. Called by the accel key.
"""
if self.settings.general.get_boolean('window-losefocus'):
self.settings.general.set_boolean('window-losefocus', False)
... | [
"def",
"accel_toggle_hide_on_lose_focus",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"settings",
".",
"general",
".",
"get_boolean",
"(",
"'window-losefocus'",
")",
":",
"self",
".",
"settings",
".",
"general",
".",
"set_boolean",
"(",
"'win... | 45.555556 | 16.222222 |
def ds_add(ds, days):
"""
Add or subtract days from a YYYY-MM-DD
:param ds: anchor date in ``YYYY-MM-DD`` format to add to
:type ds: str
:param days: number of days to add to the ds, you can use negative values
:type days: int
>>> ds_add('2015-01-01', 5)
'2015-01-06'
>>> ds_add('20... | [
"def",
"ds_add",
"(",
"ds",
",",
"days",
")",
":",
"ds",
"=",
"datetime",
".",
"strptime",
"(",
"ds",
",",
"'%Y-%m-%d'",
")",
"if",
"days",
":",
"ds",
"=",
"ds",
"+",
"timedelta",
"(",
"days",
")",
"return",
"ds",
".",
"isoformat",
"(",
")",
"[",... | 24.368421 | 18.684211 |
def transpose(vari):
"""
Transpose a shapeable quantety.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Quantety of interest.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari``.
Examples:
>>> P = chaospy.reshape(chaospy.pra... | [
"def",
"transpose",
"(",
"vari",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"core",
"=",
"vari",
".",
"A",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"vari",
".",
"keys",
":",
"core",
"[",
"key",
"]",
"=",
"transpose",
"(... | 26.038462 | 16.576923 |
def random_id(size=8, chars=string.ascii_letters + string.digits):
"""Generates a random string of given size from the given chars.
@param size: The size of the random string.
@param chars: Constituent pool of characters to draw random characters from.
@type size: number
@type chars: string
@rtype: str... | [
"def",
"random_id",
"(",
"size",
"=",
"8",
",",
"chars",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
":",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"chars",
")",
"for",
"_",
"in",
"range",
"(",
"siz... | 38.636364 | 17.272727 |
def routing_solution_to_ding0_graph(graph, solution):
""" Insert `solution` from routing into `graph`
Args
----
graph: :networkx:`NetworkX Graph Obj< >`
NetworkX graph object with nodes
solution: BaseSolution
Instance of `BaseSolution` or child class (e.g. `LocalSearchSolution`) (=s... | [
"def",
"routing_solution_to_ding0_graph",
"(",
"graph",
",",
"solution",
")",
":",
"# TODO: Bisherige Herangehensweise (diese Funktion): Branches werden nach Routing erstellt um die Funktionsfähigkeit",
"# TODO: des Routing-Tools auch für die TestCases zu erhalten. Es wird ggf. notwendig, diese di... | 49.227273 | 28.454545 |
def to_string(self, cart_coords=False):
"""
Return GaussianInput string
Option: whe cart_coords sets to True return the cartesian coordinates
instead of the z-matrix
"""
def para_dict_to_string(para, joiner=" "):
para_str = []
# sorted is... | [
"def",
"to_string",
"(",
"self",
",",
"cart_coords",
"=",
"False",
")",
":",
"def",
"para_dict_to_string",
"(",
"para",
",",
"joiner",
"=",
"\" \"",
")",
":",
"para_str",
"=",
"[",
"]",
"# sorted is only done to make unittests work reliably",
"for",
"par",
",",
... | 40.108696 | 15.978261 |
async def restart(request):
"""
Returns OK, then waits approximately 1 second and restarts container
"""
def wait_and_restart():
log.info('Restarting server')
sleep(1)
os.system('kill 1')
Thread(target=wait_and_restart).start()
return web.json_response({"message": "restar... | [
"async",
"def",
"restart",
"(",
"request",
")",
":",
"def",
"wait_and_restart",
"(",
")",
":",
"log",
".",
"info",
"(",
"'Restarting server'",
")",
"sleep",
"(",
"1",
")",
"os",
".",
"system",
"(",
"'kill 1'",
")",
"Thread",
"(",
"target",
"=",
"wait_a... | 31.8 | 11.6 |
def get_geometry_from_name(self, name):
"""
Returns the coordination geometry of the given name.
:param name: The name of the coordination geometry.
"""
for gg in self.cg_list:
if gg.name == name or name in gg.alternative_names:
return gg
raise... | [
"def",
"get_geometry_from_name",
"(",
"self",
",",
"name",
")",
":",
"for",
"gg",
"in",
"self",
".",
"cg_list",
":",
"if",
"gg",
".",
"name",
"==",
"name",
"or",
"name",
"in",
"gg",
".",
"alternative_names",
":",
"return",
"gg",
"raise",
"LookupError",
... | 38.454545 | 13.181818 |
def match_tweet(self, tweet, user_stream):
"""
Check if a tweet matches the defined criteria
:param tweet: The tweet in question
:type tweet: :class:`~responsebot.models.Tweet`
:return: True if matched, False otherwise
"""
if user_stream:
if len(self.... | [
"def",
"match_tweet",
"(",
"self",
",",
"tweet",
",",
"user_stream",
")",
":",
"if",
"user_stream",
":",
"if",
"len",
"(",
"self",
".",
"track",
")",
">",
"0",
":",
"return",
"self",
".",
"is_tweet_match_track",
"(",
"tweet",
")",
"return",
"True",
"re... | 32.266667 | 17.333333 |
def has_no_dangling_branch(neuron):
'''Check if the neuron has dangling neurites'''
soma_center = neuron.soma.points[:, COLS.XYZ].mean(axis=0)
recentered_soma = neuron.soma.points[:, COLS.XYZ] - soma_center
radius = np.linalg.norm(recentered_soma, axis=1)
soma_max_radius = radius.max()
def is_d... | [
"def",
"has_no_dangling_branch",
"(",
"neuron",
")",
":",
"soma_center",
"=",
"neuron",
".",
"soma",
".",
"points",
"[",
":",
",",
"COLS",
".",
"XYZ",
"]",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"recentered_soma",
"=",
"neuron",
".",
"soma",
".",
"... | 41.222222 | 21.814815 |
def get_tempdir():
""" Get the temporary directory where pyelastix stores its temporary
files. The directory is specific to the current process and the
calling thread. Generally, the user does not need this; directories
are automatically cleaned up. Though Elastix log files are also
written here.
... | [
"def",
"get_tempdir",
"(",
")",
":",
"tempdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"'pyelastix'",
")",
"# Make sure it exists",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"tempdir",
")",
":",... | 38.205882 | 18.294118 |
def insert_value(self, agg, value, idx, name=''):
"""
Insert *value* into member number *idx* from aggregate.
"""
if not isinstance(idx, (tuple, list)):
idx = [idx]
instr = instructions.InsertValue(self.block, agg, value, idx, name=name)
self._insert(instr)
... | [
"def",
"insert_value",
"(",
"self",
",",
"agg",
",",
"value",
",",
"idx",
",",
"name",
"=",
"''",
")",
":",
"if",
"not",
"isinstance",
"(",
"idx",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"idx",
"=",
"[",
"idx",
"]",
"instr",
"=",
"instru... | 36.666667 | 14.222222 |
def create_namespaced_resource_quota(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_resource_quota # noqa: E501
create a ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_re... | [
"def",
"create_namespaced_resource_quota",
"(",
"self",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"... | 62.68 | 35.56 |
def has_permission(self, user):
"""
Returns True if the given request has permission to use the tool.
Can be overriden by the user in subclasses.
"""
return user.has_perm(
self.model._meta.app_label + '.' + self.get_permission()
) | [
"def",
"has_permission",
"(",
"self",
",",
"user",
")",
":",
"return",
"user",
".",
"has_perm",
"(",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
"+",
"'.'",
"+",
"self",
".",
"get_permission",
"(",
")",
")"
] | 35.375 | 15.375 |
def read_resp_data(service_name, implementation_name, url, response):
"""
Read the (DELETE, PATCH, POST, PUT) response body and header if exist.
"""
RR = _mockdata_path_root(service_name, implementation_name)
for resource_dir in app_resource_dirs:
path = os.path.join(resource_dir['path'],
... | [
"def",
"read_resp_data",
"(",
"service_name",
",",
"implementation_name",
",",
"url",
",",
"response",
")",
":",
"RR",
"=",
"_mockdata_path_root",
"(",
"service_name",
",",
"implementation_name",
")",
"for",
"resource_dir",
"in",
"app_resource_dirs",
":",
"path",
... | 41.8 | 13 |
def all_properties(self):
"""Get all properties of a given index"""
properties = {}
r = self.requests.get(self.index_url + "/_mapping", headers=HEADER_JSON, verify=False)
try:
r.raise_for_status()
r_json = r.json()
if 'items' not in r_json[self.index... | [
"def",
"all_properties",
"(",
"self",
")",
":",
"properties",
"=",
"{",
"}",
"r",
"=",
"self",
".",
"requests",
".",
"get",
"(",
"self",
".",
"index_url",
"+",
"\"/_mapping\"",
",",
"headers",
"=",
"HEADER_JSON",
",",
"verify",
"=",
"False",
")",
"try"... | 34.454545 | 25.136364 |
def set_result(self, result):
"""
Sets the result of the Future.
:param result: Result of the Future.
"""
if result is None:
self._result = NONE_RESULT
else:
self._result = result
self._event.set()
self._invoke_callbacks() | [
"def",
"set_result",
"(",
"self",
",",
"result",
")",
":",
"if",
"result",
"is",
"None",
":",
"self",
".",
"_result",
"=",
"NONE_RESULT",
"else",
":",
"self",
".",
"_result",
"=",
"result",
"self",
".",
"_event",
".",
"set",
"(",
")",
"self",
".",
... | 25 | 10.833333 |
def to_postfix(tokens):
"""
Convert a list of evaluatable tokens to postfix format.
"""
precedence = {
'/': 4,
'*': 4,
'+': 3,
'-': 3,
'^': 2,
'(': 1
}
postfix = []
opstack = []
for token in tokens:
if is_int(token):
p... | [
"def",
"to_postfix",
"(",
"tokens",
")",
":",
"precedence",
"=",
"{",
"'/'",
":",
"4",
",",
"'*'",
":",
"4",
",",
"'+'",
":",
"3",
",",
"'-'",
":",
"3",
",",
"'^'",
":",
"2",
",",
"'('",
":",
"1",
"}",
"postfix",
"=",
"[",
"]",
"opstack",
"... | 25.023256 | 16.325581 |
def dispatch(self, args):
"""
Calls proper method depending on command-line arguments.
"""
if not args.list and not args.group:
if not args.font and not args.char and not args.block:
self.info()
return
else:
args.lis... | [
"def",
"dispatch",
"(",
"self",
",",
"args",
")",
":",
"if",
"not",
"args",
".",
"list",
"and",
"not",
"args",
".",
"group",
":",
"if",
"not",
"args",
".",
"font",
"and",
"not",
"args",
".",
"char",
"and",
"not",
"args",
".",
"block",
":",
"self"... | 35.1 | 14.2 |
def invert(self):
""" Invert the transform """
libfn = utils.get_lib_fn('inverseTransform%s' % (self._libsuffix))
inv_tx_ptr = libfn(self.pointer)
new_tx = ANTsTransform(precision=self.precision, dimension=self.dimension,
transform_type=self.transform_typ... | [
"def",
"invert",
"(",
"self",
")",
":",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'inverseTransform%s'",
"%",
"(",
"self",
".",
"_libsuffix",
")",
")",
"inv_tx_ptr",
"=",
"libfn",
"(",
"self",
".",
"pointer",
")",
"new_tx",
"=",
"ANTsTransform",
"(... | 39.666667 | 27.222222 |
def sorted_enums(self) -> List[Tuple[str, int]]:
"""Return list of enum items sorted by value."""
return sorted(self.enum.items(), key=lambda x: x[1]) | [
"def",
"sorted_enums",
"(",
"self",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"int",
"]",
"]",
":",
"return",
"sorted",
"(",
"self",
".",
"enum",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
")"
] | 54.666667 | 9.333333 |
def read_sizes(self):
"""
read the memory ussage
"""
command = const.CMD_GET_FREE_SIZES
response_size = 1024
cmd_response = self.__send_command(command,b'', response_size)
if cmd_response.get('status'):
if self.verbose: print(codecs.encode(self.__data,... | [
"def",
"read_sizes",
"(",
"self",
")",
":",
"command",
"=",
"const",
".",
"CMD_GET_FREE_SIZES",
"response_size",
"=",
"1024",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"command",
",",
"b''",
",",
"response_size",
")",
"if",
"cmd_response",
".",
... | 40.677419 | 8.935484 |
def heartbeat_timeout(self):
""" Called by heartbeat_monitor on timeout """
assert not self._closed, "Did we not stop heartbeat_monitor on close?"
log.error("Heartbeat time out")
poison_exc = ConnectionLostError('Heartbeat timed out')
poison_frame = frames.PoisonPillFrame(poison_... | [
"def",
"heartbeat_timeout",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"_closed",
",",
"\"Did we not stop heartbeat_monitor on close?\"",
"log",
".",
"error",
"(",
"\"Heartbeat time out\"",
")",
"poison_exc",
"=",
"ConnectionLostError",
"(",
"'Heartbeat timed ... | 51.555556 | 17.333333 |
def _set_capabilities(self, v, load=False):
"""
Setter method for capabilities, mapped from YANG variable /capabilities (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_capabilities is considered as a private
method. Backends looking to populate this varia... | [
"def",
"_set_capabilities",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | 75.818182 | 34.727273 |
def Render(self, rdf_data):
"""Processes data according to formatting rules."""
report_data = rdf_data[:self.max_results]
results = [self.hinter.Render(rdf) for rdf in report_data]
extra = len(rdf_data) - len(report_data)
if extra > 0:
results.append("...plus another %d issues." % extra)
r... | [
"def",
"Render",
"(",
"self",
",",
"rdf_data",
")",
":",
"report_data",
"=",
"rdf_data",
"[",
":",
"self",
".",
"max_results",
"]",
"results",
"=",
"[",
"self",
".",
"hinter",
".",
"Render",
"(",
"rdf",
")",
"for",
"rdf",
"in",
"report_data",
"]",
"e... | 40.75 | 13.375 |
def _set_circuit_type(self, v, load=False):
"""
Setter method for circuit_type, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/circuit_type (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_circuit_type is considered as a priv... | [
"def",
"_set_circuit_type",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | 99.363636 | 47.863636 |
def view_extreme_groups(token, dstore):
"""
Show the source groups contributing the most to the highest IML
"""
data = dstore['disagg_by_grp'].value
data.sort(order='extreme_poe')
return rst_table(data[::-1]) | [
"def",
"view_extreme_groups",
"(",
"token",
",",
"dstore",
")",
":",
"data",
"=",
"dstore",
"[",
"'disagg_by_grp'",
"]",
".",
"value",
"data",
".",
"sort",
"(",
"order",
"=",
"'extreme_poe'",
")",
"return",
"rst_table",
"(",
"data",
"[",
":",
":",
"-",
... | 32.285714 | 6 |
def tx_max(tasmax, freq='YS'):
r"""Highest max temperature
The maximum value of daily maximum temperature.
Parameters
----------
tasmax : xarray.DataArray
Maximum daily temperature [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
... | [
"def",
"tx_max",
"(",
"tasmax",
",",
"freq",
"=",
"'YS'",
")",
":",
"return",
"tasmax",
".",
"resample",
"(",
"time",
"=",
"freq",
")",
".",
"max",
"(",
"dim",
"=",
"'time'",
",",
"keep_attrs",
"=",
"True",
")"
] | 23.107143 | 24.75 |
def decodebytes(input):
"""Decode base64 string to byte array."""
py_version = sys.version_info[0]
if py_version >= 3:
return _decodebytes_py3(input)
return _decodebytes_py2(input) | [
"def",
"decodebytes",
"(",
"input",
")",
":",
"py_version",
"=",
"sys",
".",
"version_info",
"[",
"0",
"]",
"if",
"py_version",
">=",
"3",
":",
"return",
"_decodebytes_py3",
"(",
"input",
")",
"return",
"_decodebytes_py2",
"(",
"input",
")"
] | 33.166667 | 7.666667 |
def example_metadata(study_name, draft_name):
"""Example of building a metadata doc"""
odm = ODM("SYSTEM_NAME", filetype=ODM.FILETYPE_SNAPSHOT)
study = Study(study_name, project_type=Study.PROJECT)
# Push study element into odm
odm << study
# Create global variables and set them into study.
... | [
"def",
"example_metadata",
"(",
"study_name",
",",
"draft_name",
")",
":",
"odm",
"=",
"ODM",
"(",
"\"SYSTEM_NAME\"",
",",
"filetype",
"=",
"ODM",
".",
"FILETYPE_SNAPSHOT",
")",
"study",
"=",
"Study",
"(",
"study_name",
",",
"project_type",
"=",
"Study",
"."... | 35.708333 | 25.422619 |
def all_status(self):
"""Return names, hall numbers, and the washers/dryers available for all
rooms in the system
>>> all_laundry = l.all_status()
"""
laundry_rooms = {}
for room in self.hall_to_link:
laundry_rooms[room] = self.parse_a_hall(room)
ret... | [
"def",
"all_status",
"(",
"self",
")",
":",
"laundry_rooms",
"=",
"{",
"}",
"for",
"room",
"in",
"self",
".",
"hall_to_link",
":",
"laundry_rooms",
"[",
"room",
"]",
"=",
"self",
".",
"parse_a_hall",
"(",
"room",
")",
"return",
"laundry_rooms"
] | 29.727273 | 14.272727 |
def auto_decompress_stream(src):
"""Decompress data from `src` if required.
If the first block of `src` appears to be compressed, then the entire
stream will be uncompressed. Otherwise the stream will be passed along
as-is.
Args:
src (iterable): iterable that yields blocks of data
Yie... | [
"def",
"auto_decompress_stream",
"(",
"src",
")",
":",
"block",
"=",
"next",
"(",
"src",
")",
"compression",
"=",
"guess_compression",
"(",
"block",
")",
"if",
"compression",
"==",
"'bz2'",
":",
"src",
"=",
"bz2_decompress_stream",
"(",
"chain",
"(",
"[",
... | 26.76 | 21.68 |
def set_mute(self, mute):
"""Send mute command."""
req_url = ENDPOINTS["setMute"].format(self.ip_address, self.zone_id)
params = {"enable": "true" if mute else "false"}
return request(req_url, params=params) | [
"def",
"set_mute",
"(",
"self",
",",
"mute",
")",
":",
"req_url",
"=",
"ENDPOINTS",
"[",
"\"setMute\"",
"]",
".",
"format",
"(",
"self",
".",
"ip_address",
",",
"self",
".",
"zone_id",
")",
"params",
"=",
"{",
"\"enable\"",
":",
"\"true\"",
"if",
"mute... | 47 | 14.6 |
def firmware_download_output_cluster_output_fwdl_status(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
output = ET.SubElement(firmware_download, "output")
clu... | [
"def",
"firmware_download_output_cluster_output_fwdl_status",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"firmware_download",
"=",
"ET",
".",
"Element",
"(",
"\"firmware_download\"",
")",
"config",
... | 44 | 15.923077 |
def _toggle_transparency(self, changed_from_config_window=False, force_value=None):
""" Toggles theme trasparency.
changed_from_config_window is used to inhibit toggling from within
Config Window when 'T' is pressed.
force_value will set trasparency if True or False,
... | [
"def",
"_toggle_transparency",
"(",
"self",
",",
"changed_from_config_window",
"=",
"False",
",",
"force_value",
"=",
"None",
")",
":",
"if",
"self",
".",
"window_mode",
"==",
"CONFIG_MODE",
"and",
"not",
"changed_from_config_window",
":",
"return",
"self",
".",
... | 49.565217 | 23.26087 |
def DefaultSelector(sock):
"Return the best selector for the platform"
global _DEFAULT_SELECTOR
if _DEFAULT_SELECTOR is None:
if has_selector('poll'):
_DEFAULT_SELECTOR = PollSelector
elif hasattr(select, 'select'):
_DEFAULT_SELECTOR = SelectSelector
else:
... | [
"def",
"DefaultSelector",
"(",
"sock",
")",
":",
"global",
"_DEFAULT_SELECTOR",
"if",
"_DEFAULT_SELECTOR",
"is",
"None",
":",
"if",
"has_selector",
"(",
"'poll'",
")",
":",
"_DEFAULT_SELECTOR",
"=",
"PollSelector",
"elif",
"hasattr",
"(",
"select",
",",
"'select... | 37.545455 | 11.181818 |
def cache_file(app_name=APPNAME, app_author=APPAUTHOR, filename=DATABASENAME):
"""Returns the filename (including path) for the data cache.
The path will depend on the operating system, certain environmental
variables and whether it is being run inside a virtual environment.
See `homebase <https://gith... | [
"def",
"cache_file",
"(",
"app_name",
"=",
"APPNAME",
",",
"app_author",
"=",
"APPAUTHOR",
",",
"filename",
"=",
"DATABASENAME",
")",
":",
"user_data_dir",
"=",
"homebase",
".",
"user_data_dir",
"(",
"app_name",
"=",
"app_name",
",",
"app_author",
"=",
"app_au... | 40.814815 | 25.518519 |
def monitored(name, **params):
'''
Makes sure an URL is monitored by uptime. Checks if URL is already
monitored, and if not, adds it.
'''
ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''}
if __salt__['uptime.check_exists'](name=name):
ret['result'] = True
ret['... | [
"def",
"monitored",
"(",
"name",
",",
"*",
"*",
"params",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"if",
"__salt__",
"[",
"'uptime.check_exists'... | 35.37931 | 19.655172 |
def fetch(self, start=False, full_data=True):
""" Get the current job data and possibly flag it as started. """
if self.id is None:
return self
if full_data is True:
fields = None
elif isinstance(full_data, dict):
fields = full_data
else:
... | [
"def",
"fetch",
"(",
"self",
",",
"start",
"=",
"False",
",",
"full_data",
"=",
"True",
")",
":",
"if",
"self",
".",
"id",
"is",
"None",
":",
"return",
"self",
"if",
"full_data",
"is",
"True",
":",
"fields",
"=",
"None",
"elif",
"isinstance",
"(",
... | 28.730769 | 19.25 |
def _function(self):
"""
Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click.
"""
start_time = datetime.datetime.now()
# calculate stop time
if self.settings['wait_mode'] == 'absolute':
stop_time = start_time... | [
"def",
"_function",
"(",
"self",
")",
":",
"start_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"# calculate stop time",
"if",
"self",
".",
"settings",
"[",
"'wait_mode'",
"]",
"==",
"'absolute'",
":",
"stop_time",
"=",
"start_time",
"+",
... | 36.921053 | 20.973684 |
def build_toc_line_without_indentation(header: dict,
ordered: bool = False,
no_links: bool = False,
index: int = 1,
parser: str = 'github',
... | [
"def",
"build_toc_line_without_indentation",
"(",
"header",
":",
"dict",
",",
"ordered",
":",
"bool",
"=",
"False",
",",
"no_links",
":",
"bool",
"=",
"False",
",",
"index",
":",
"int",
"=",
"1",
",",
"parser",
":",
"str",
"=",
"'github'",
",",
"list_mar... | 40.9375 | 19 |
def launch(url, wait=False, locate=False):
"""This function launches the given URL (or filename) in the default
viewer application for this file type. If this is an executable, it
might launch the executable in a new session. The return value is
the exit code of the launched application. Usually, ``0... | [
"def",
"launch",
"(",
"url",
",",
"wait",
"=",
"False",
",",
"locate",
"=",
"False",
")",
":",
"from",
".",
"_termui_impl",
"import",
"open_url",
"return",
"open_url",
"(",
"url",
",",
"wait",
"=",
"wait",
",",
"locate",
"=",
"locate",
")"
] | 42.125 | 21.916667 |
def joint(self, table, fields,
join_table, join_fields,
condition_field, condition_join_field,
join_method='left_join'):
""".. :py:method::
Usage::
>>> joint('user', 'name, id_number', 'medical_card', 'number', 'id', 'user_id', 'i... | [
"def",
"joint",
"(",
"self",
",",
"table",
",",
"fields",
",",
"join_table",
",",
"join_fields",
",",
"condition_field",
",",
"condition_join_field",
",",
"join_method",
"=",
"'left_join'",
")",
":",
"import",
"string",
"fields",
"=",
"map",
"(",
"string",
"... | 52.142857 | 28.964286 |
def callback(self, request, **kwargs):
"""
Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template
"""
access_token = request.session['oauth_token'] + "#... | [
"def",
"callback",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"access_token",
"=",
"request",
".",
"session",
"[",
"'oauth_token'",
"]",
"+",
"\"#TH#\"",
"access_token",
"+=",
"str",
"(",
"request",
".",
"session",
"[",
"'oauth_id'",
... | 44.454545 | 11.363636 |
def build_sdist(sdist_directory, config_settings=None):
"""Builds an sdist, places it in sdist_directory"""
poetry = Poetry.create(".")
path = SdistBuilder(poetry, SystemEnv(Path(sys.prefix)), NullIO()).build(
Path(sdist_directory)
)
return unicode(path.name) | [
"def",
"build_sdist",
"(",
"sdist_directory",
",",
"config_settings",
"=",
"None",
")",
":",
"poetry",
"=",
"Poetry",
".",
"create",
"(",
"\".\"",
")",
"path",
"=",
"SdistBuilder",
"(",
"poetry",
",",
"SystemEnv",
"(",
"Path",
"(",
"sys",
".",
"prefix",
... | 31.222222 | 22 |
def cleanup(self):
"Remove the directory containin the clone and virtual environment."
log.info('Removing temp dir %s', self._tempdir.name)
self._tempdir.cleanup() | [
"def",
"cleanup",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Removing temp dir %s'",
",",
"self",
".",
"_tempdir",
".",
"name",
")",
"self",
".",
"_tempdir",
".",
"cleanup",
"(",
")"
] | 46 | 21.5 |
def sflow_source_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
sflow = ET.SubElement(config, "sflow", xmlns="urn:brocade.com:mgmt:brocade-sflow")
source_ip = ET.SubElement(sflow, "source-ip")
source_ip.text = kwargs.pop('source_ip')
... | [
"def",
"sflow_source_ip",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"sflow",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"sflow\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:brocad... | 39.3 | 14.4 |
def _request_status(self):
""" Checks the api endpoint to check if the async job progress """
if self.item_id:
return True
response = self.con.get(self.monitor_url)
if not response:
return False
data = response.json()
self.status = data.get('sta... | [
"def",
"_request_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"item_id",
":",
"return",
"True",
"response",
"=",
"self",
".",
"con",
".",
"get",
"(",
"self",
".",
"monitor_url",
")",
"if",
"not",
"response",
":",
"return",
"False",
"data",
"=",
... | 32.529412 | 19.941176 |
def is_valid(self, t: URIRef) -> bool:
"""
Raise an exception if 't' is unrecognized
:param t: metadata URI
"""
if not self.has_type(t):
raise TypeError("Unrecognized FHIR type: {}".format(t))
return True | [
"def",
"is_valid",
"(",
"self",
",",
"t",
":",
"URIRef",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"has_type",
"(",
"t",
")",
":",
"raise",
"TypeError",
"(",
"\"Unrecognized FHIR type: {}\"",
".",
"format",
"(",
"t",
")",
")",
"return",
"True"
... | 32.125 | 9.625 |
def validate_inputs(u_kn, N_k, f_k):
"""Check types and return inputs for MBAR calculations.
Parameters
----------
u_kn or q_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies or unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='in... | [
"def",
"validate_inputs",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
":",
"n_states",
",",
"n_samples",
"=",
"u_kn",
".",
"shape",
"u_kn",
"=",
"ensure_type",
"(",
"u_kn",
",",
"'float'",
",",
"2",
",",
"\"u_kn or Q_kn\"",
",",
"shape",
"=",
"(",
"n_sta... | 45.321429 | 26.75 |
def _do_anchor(self, anchor):
""" Collects preposition anchors and attachments in a dictionary.
Once the dictionary has an entry for both the anchor and the attachment, they are linked.
"""
if anchor:
for x in anchor.split("-"):
A, P = None, None
... | [
"def",
"_do_anchor",
"(",
"self",
",",
"anchor",
")",
":",
"if",
"anchor",
":",
"for",
"x",
"in",
"anchor",
".",
"split",
"(",
"\"-\"",
")",
":",
"A",
",",
"P",
"=",
"None",
",",
"None",
"if",
"x",
".",
"startswith",
"(",
"\"A\"",
")",
"and",
"... | 52.647059 | 17.235294 |
def compat_get_paginated_response(view, page):
""" get_paginated_response is unknown to DRF 3.0 """
if DRFVLIST[0] == 3 and DRFVLIST[1] >= 1:
from rest_messaging.serializers import ComplexMessageSerializer # circular import
serializer = ComplexMessageSerializer(page, many=True)
return v... | [
"def",
"compat_get_paginated_response",
"(",
"view",
",",
"page",
")",
":",
"if",
"DRFVLIST",
"[",
"0",
"]",
"==",
"3",
"and",
"DRFVLIST",
"[",
"1",
"]",
">=",
"1",
":",
"from",
"rest_messaging",
".",
"serializers",
"import",
"ComplexMessageSerializer",
"# c... | 51.555556 | 16.666667 |
def _get_indexes(self, schema, **kwargs):
"""return all the indexes for the given schema"""
# http://www.sqlite.org/pragma.html#schema
# http://www.mail-archive.com/sqlite-users@sqlite.org/msg22055.html
# http://stackoverflow.com/questions/604939/
ret = {}
rs = self._quer... | [
"def",
"_get_indexes",
"(",
"self",
",",
"schema",
",",
"*",
"*",
"kwargs",
")",
":",
"# http://www.sqlite.org/pragma.html#schema",
"# http://www.mail-archive.com/sqlite-users@sqlite.org/msg22055.html",
"# http://stackoverflow.com/questions/604939/",
"ret",
"=",
"{",
"}",
"rs",... | 43.875 | 20.0625 |
def badnick(self, me=None, nick=None, **kw):
"""Use alt nick on nick error"""
if me == '*':
self.bot.set_nick(self.bot.nick + '_')
self.bot.log.debug('Trying to regain nickname in 30s...')
self.nick_handle = self.bot.loop.call_later(
30, self.bot.set_nick, self.bo... | [
"def",
"badnick",
"(",
"self",
",",
"me",
"=",
"None",
",",
"nick",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"me",
"==",
"'*'",
":",
"self",
".",
"bot",
".",
"set_nick",
"(",
"self",
".",
"bot",
".",
"nick",
"+",
"'_'",
")",
"self",
... | 47.142857 | 12.571429 |
def get(self, key, namespace=None):
"""Retrieve value for key."""
# Short-circuit to reduce overhead.
if not _CONFIG_OVERRIDE:
return NO_VALUE
full_key = generate_uppercase_key(key, namespace)
logger.debug('Searching %s for %s', self, full_key)
return get_key_... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"namespace",
"=",
"None",
")",
":",
"# Short-circuit to reduce overhead.",
"if",
"not",
"_CONFIG_OVERRIDE",
":",
"return",
"NO_VALUE",
"full_key",
"=",
"generate_uppercase_key",
"(",
"key",
",",
"namespace",
")",
"logg... | 45 | 11.875 |
def is_method(arg):
"""Checks whether given object is a method."""
if inspect.ismethod(arg):
return True
if isinstance(arg, NonInstanceMethod):
return True
# Unfortunately, there is no disctinction between instance methods
# that are yet to become part of a class, and regular functi... | [
"def",
"is_method",
"(",
"arg",
")",
":",
"if",
"inspect",
".",
"ismethod",
"(",
"arg",
")",
":",
"return",
"True",
"if",
"isinstance",
"(",
"arg",
",",
"NonInstanceMethod",
")",
":",
"return",
"True",
"# Unfortunately, there is no disctinction between instance me... | 40.0625 | 22.8125 |
def run(self):
"""
Writes data in JSON format into the task's output target.
The data objects have the following attributes:
* `_id` is the default Elasticsearch id field,
* `text`: the text,
* `date`: the day when the data was created.
"""
today = date... | [
"def",
"run",
"(",
"self",
")",
":",
"today",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"with",
"self",
".",
"output",
"(",
")",
".",
"open",
"(",
"'w'",
")",
"as",
"output",
":",
"for",
"i",
"in",
"range",
"(",
"5",
")",
":",
"ou... | 33.529412 | 17.882353 |
def _last_commit(self):
"""
Retrieve the most recent commit message (with ``svn log -l1``)
Returns:
tuple: (datestr, (revno, user, None, desc))
::
$ svn log -l1
------------------------------------------------------------------------
r25701 | bhendrix | 2010-08-02 12:14:25 ... | [
"def",
"_last_commit",
"(",
"self",
")",
":",
"cmd",
"=",
"[",
"'svn'",
",",
"'log'",
"'-l1'",
"]",
"op",
"=",
"self",
".",
"sh",
"(",
"cmd",
",",
"shell",
"=",
"False",
")",
"data",
",",
"rest",
"=",
"op",
".",
"split",
"(",
"'\\n'",
",",
"2",... | 35.08 | 19.96 |
def insertBlock(self):
"""
API to insert a block into DBS
:param blockObj: Block object
:type blockObj: dict
:key open_for_writing: Open For Writing (1/0) (Optional, default 1)
:key block_size: Block Size (Optional, default 0)
:key file_count: File Count (Optiona... | [
"def",
"insertBlock",
"(",
"self",
")",
":",
"try",
":",
"body",
"=",
"request",
".",
"body",
".",
"read",
"(",
")",
"indata",
"=",
"cjson",
".",
"decode",
"(",
"body",
")",
"indata",
"=",
"validateJSONInputNoCopy",
"(",
"\"block\"",
",",
"indata",
")"... | 47.576923 | 22.269231 |
def get_selected(self):
"""return the current selected option as a tuple: (option, index)
or as a list of tuples (in case multi_select==True)
"""
if self.multi_select:
return_tuples = []
for selected in self.all_selected:
return_tuples.append((s... | [
"def",
"get_selected",
"(",
"self",
")",
":",
"if",
"self",
".",
"multi_select",
":",
"return_tuples",
"=",
"[",
"]",
"for",
"selected",
"in",
"self",
".",
"all_selected",
":",
"return_tuples",
".",
"append",
"(",
"(",
"self",
".",
"options",
"[",
"selec... | 40.545455 | 13.454545 |
def cut_gmail_quote(html_message):
''' Cuts the outermost block element with class gmail_quote. '''
gmail_quote = cssselect('div.gmail_quote', html_message)
if gmail_quote and (gmail_quote[0].text is None or not RE_FWD.match(gmail_quote[0].text)):
gmail_quote[0].getparent().remove(gmail_quote[0])
... | [
"def",
"cut_gmail_quote",
"(",
"html_message",
")",
":",
"gmail_quote",
"=",
"cssselect",
"(",
"'div.gmail_quote'",
",",
"html_message",
")",
"if",
"gmail_quote",
"and",
"(",
"gmail_quote",
"[",
"0",
"]",
".",
"text",
"is",
"None",
"or",
"not",
"RE_FWD",
"."... | 55.333333 | 24.333333 |
def import_from_filename(obj, filename, silent=False): # pragma: no cover
"""If settings_module is a filename path import it."""
if filename in [item.filename for item in inspect.stack()]:
raise ImportError(
"Looks like you are loading dynaconf "
"from inside the {} file and the... | [
"def",
"import_from_filename",
"(",
"obj",
",",
"filename",
",",
"silent",
"=",
"False",
")",
":",
"# pragma: no cover",
"if",
"filename",
"in",
"[",
"item",
".",
"filename",
"for",
"item",
"in",
"inspect",
".",
"stack",
"(",
")",
"]",
":",
"raise",
"Imp... | 38.243243 | 19.054054 |
def _get_assistive_access():
'''
Get a list of all of the assistive access applications installed,
returns as a ternary showing whether each app is enabled or not.
'''
cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "SELECT * FROM access"'
call = __salt__['cmd.run_all'](
... | [
"def",
"_get_assistive_access",
"(",
")",
":",
"cmd",
"=",
"'sqlite3 \"/Library/Application Support/com.apple.TCC/TCC.db\" \"SELECT * FROM access\"'",
"call",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"output_loglevel",
"=",
"'debug'",
",",
"python_shell"... | 33 | 24.826087 |
def _handle_indent_between_paren(self, column, line, parent_impl, tc):
"""
Handle indent between symbols such as parenthesis, braces,...
"""
pre, post = parent_impl
next_char = self._get_next_char(tc)
prev_char = self._get_prev_char(tc)
prev_open = prev_char in ['... | [
"def",
"_handle_indent_between_paren",
"(",
"self",
",",
"column",
",",
"line",
",",
"parent_impl",
",",
"tc",
")",
":",
"pre",
",",
"post",
"=",
"parent_impl",
"next_char",
"=",
"self",
".",
"_get_next_char",
"(",
"tc",
")",
"prev_char",
"=",
"self",
".",... | 42.38 | 14.54 |
def _join_sequence(seq, last_separator=''):
"""Join a sequence into a string."""
count = len(seq)
return ', '.join(_format_element(element, count, i, last_separator)
for i, element in enumerate(seq)) | [
"def",
"_join_sequence",
"(",
"seq",
",",
"last_separator",
"=",
"''",
")",
":",
"count",
"=",
"len",
"(",
"seq",
")",
"return",
"', '",
".",
"join",
"(",
"_format_element",
"(",
"element",
",",
"count",
",",
"i",
",",
"last_separator",
")",
"for",
"i"... | 45.6 | 13.6 |
def service_enable(s_name, **connection_args):
'''
Enable a service
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_enable 'serviceName'
'''
ret = True
service = _service_get(s_name, **connection_args)
if service is None:
return False
nitro = _connect... | [
"def",
"service_enable",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"service",
"=",
"_service_get",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
"if",
"service",
"is",
"None",
":",
"return",
"False",
"nitro",
... | 23.32 | 22.76 |
async def update_offer(self, **params):
"""Updates offer after transaction confirmation
Accepts:
- transaction id
- coinid
- confirmed (boolean flag)
"""
logging.debug("\n\n -- Update offer. ")
if params.get("message"):
params = json.loads(params.get("message", "{}"))
if not params:
return... | [
"async",
"def",
"update_offer",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"logging",
".",
"debug",
"(",
"\"\\n\\n -- Update offer. \"",
")",
"if",
"params",
".",
"get",
"(",
"\"message\"",
")",
":",
"params",
"=",
"json",
".",
"loads",
"(",
"params... | 25.829268 | 18.02439 |
def GenerateKeys(config, overwrite_keys=False):
"""Generate the keys we need for a GRR server."""
if not hasattr(key_utils, "MakeCACert"):
raise OpenSourceKeyUtilsRequiredError(
"Generate keys can only run with open source key_utils.")
if (config.Get("PrivateKeys.server_key", default=None) and
n... | [
"def",
"GenerateKeys",
"(",
"config",
",",
"overwrite_keys",
"=",
"False",
")",
":",
"if",
"not",
"hasattr",
"(",
"key_utils",
",",
"\"MakeCACert\"",
")",
":",
"raise",
"OpenSourceKeyUtilsRequiredError",
"(",
"\"Generate keys can only run with open source key_utils.\"",
... | 43.6 | 15.971429 |
def create_namespaced_controller_revision(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_controller_revision # noqa: E501
create a ControllerRevision # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, pleas... | [
"def",
"create_namespaced_controller_revision",
"(",
"self",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":"... | 64.28 | 36.56 |
def getClassInModuleFromName(className, module):
"""
get a class from name within a module
"""
n = getAvClassNamesInModule(module)
i = n.index(className)
c = getAvailableClassesInModule(module)
return c[i] | [
"def",
"getClassInModuleFromName",
"(",
"className",
",",
"module",
")",
":",
"n",
"=",
"getAvClassNamesInModule",
"(",
"module",
")",
"i",
"=",
"n",
".",
"index",
"(",
"className",
")",
"c",
"=",
"getAvailableClassesInModule",
"(",
"module",
")",
"return",
... | 28.25 | 6.5 |
def _from_args(args):
"""Factory method to create a new instance from command line args.
:param args: instance of :class:`argparse.Namespace`
"""
return bugzscout.BugzScout(args.url, args.user, args.project, args.area) | [
"def",
"_from_args",
"(",
"args",
")",
":",
"return",
"bugzscout",
".",
"BugzScout",
"(",
"args",
".",
"url",
",",
"args",
".",
"user",
",",
"args",
".",
"project",
",",
"args",
".",
"area",
")"
] | 38.333333 | 18.5 |
def HelloWorld(handler, t):
"""
This is the traditional "Hello, World" function. The idiom is used throughout the API. We construct a Tropo object, and then flesh out that object by calling "action" functions (in this case, tropo.say). Then call tropo.Render, which translates the Tropo object into JSON format. ... | [
"def",
"HelloWorld",
"(",
"handler",
",",
"t",
")",
":",
"t",
".",
"say",
"(",
"[",
"\"Hello, World\"",
",",
"\"How ya doing?\"",
"]",
")",
"json",
"=",
"t",
".",
"RenderJson",
"(",
")",
"logging",
".",
"info",
"(",
"\"HelloWorld json: %s\"",
"%",
"json"... | 72.375 | 48.625 |
def _le_annot_parms(self, annot, p1, p2):
"""Get common parameters for making line end symbols.
"""
w = annot.border["width"] # line width
sc = annot.colors["stroke"] # stroke color
if not sc: sc = (0,0,0)
scol = " ".join(map(str, sc)) + " RG\n"
fc... | [
"def",
"_le_annot_parms",
"(",
"self",
",",
"annot",
",",
"p1",
",",
"p2",
")",
":",
"w",
"=",
"annot",
".",
"border",
"[",
"\"width\"",
"]",
"# line width",
"sc",
"=",
"annot",
".",
"colors",
"[",
"\"stroke\"",
"]",
"# stroke color",
"if",
"not",
"sc"... | 47.318182 | 15.863636 |
def deleteEvent(self, physicalInterfaceId, eventId):
"""
Delete an event mapping from a physical interface.
Parameters: physicalInterfaceId (string), eventId (string).
Throws APIException on failure.
"""
req = ApiClient.oneEventUrl % (self.host, "/draft", physicalInterfac... | [
"def",
"deleteEvent",
"(",
"self",
",",
"physicalInterfaceId",
",",
"eventId",
")",
":",
"req",
"=",
"ApiClient",
".",
"oneEventUrl",
"%",
"(",
"self",
".",
"host",
",",
"\"/draft\"",
",",
"physicalInterfaceId",
",",
"eventId",
")",
"resp",
"=",
"requests",
... | 48.076923 | 20.846154 |
def _has_ipv6(host):
""" Returns True if the system can bind an IPv6 address. """
sock = None
has_ipv6 = False
# App Engine doesn't support IPV6 sockets and actually has a quota on the
# number of sockets that can be used, so just early out here instead of
# creating a socket needlessly.
# ... | [
"def",
"_has_ipv6",
"(",
"host",
")",
":",
"sock",
"=",
"None",
"has_ipv6",
"=",
"False",
"# App Engine doesn't support IPV6 sockets and actually has a quota on the",
"# number of sockets that can be used, so just early out here instead of",
"# creating a socket needlessly.",
"# See ht... | 34.5 | 21.071429 |
def occupy(self, address, size, sort):
"""
Include a block, specified by (address, size), in this segment list.
:param int address: The starting address of the block.
:param int size: Size of the block.
:param str sort: Type of the block.
:return: None
... | [
"def",
"occupy",
"(",
"self",
",",
"address",
",",
"size",
",",
"sort",
")",
":",
"if",
"size",
"is",
"None",
"or",
"size",
"<=",
"0",
":",
"# Cannot occupy a non-existent block",
"return",
"# l.debug(\"Occpuying 0x%08x-0x%08x\", address, address + size)",
"if",
"no... | 33.375 | 18.125 |
def merge_section(key, prnt_sec, child_sec):
""" Synthesize a output numpy docstring section.
Parameters
----------
key: str
The numpy-section being merged.
prnt_sec: Optional[str]
The docstring section from the parent's attribute.
child_sec: Optional... | [
"def",
"merge_section",
"(",
"key",
",",
"prnt_sec",
",",
"child_sec",
")",
":",
"if",
"prnt_sec",
"is",
"None",
"and",
"child_sec",
"is",
"None",
":",
"return",
"None",
"if",
"key",
"==",
"\"Short Summary\"",
":",
"header",
"=",
"''",
"else",
":",
"head... | 26.758621 | 20.137931 |
def node_to_evenly_discretized(node):
"""
Parses the evenly discretized mfd node to an instance of the
:class: openquake.hazardlib.mfd.evenly_discretized.EvenlyDiscretizedMFD,
or to None if not all parameters are available
"""
if not all([node.attrib["minMag"], node.attrib["binWidth"],
... | [
"def",
"node_to_evenly_discretized",
"(",
"node",
")",
":",
"if",
"not",
"all",
"(",
"[",
"node",
".",
"attrib",
"[",
"\"minMag\"",
"]",
",",
"node",
".",
"attrib",
"[",
"\"binWidth\"",
"]",
",",
"node",
".",
"nodes",
"[",
"0",
"]",
".",
"text",
"]",... | 38.8 | 13.6 |
def pstdev(data):
"""Calculates the population standard deviation."""
n = len(data)
if n < 2:
return 0
# raise ValueError('variance requires at least two data points')
ss = TableExtraction._ss(data)
pvar = ss/n # the population variance
return pvar... | [
"def",
"pstdev",
"(",
"data",
")",
":",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"<",
"2",
":",
"return",
"0",
"# raise ValueError('variance requires at least two data points')",
"ss",
"=",
"TableExtraction",
".",
"_ss",
"(",
"data",
")",
"pvar",
"=",
... | 35.222222 | 16 |
async def mount(self, mount_point, *, mount_options=None):
"""Mount this partition."""
self._data = await self._handler.mount(
system_id=self.block_device.node.system_id,
device_id=self.block_device.id, id=self.id,
mount_point=mount_point,
mount_options=mo... | [
"async",
"def",
"mount",
"(",
"self",
",",
"mount_point",
",",
"*",
",",
"mount_options",
"=",
"None",
")",
":",
"self",
".",
"_data",
"=",
"await",
"self",
".",
"_handler",
".",
"mount",
"(",
"system_id",
"=",
"self",
".",
"block_device",
".",
"node",... | 46.571429 | 8.428571 |
def render(self, file_path, **kwargs):
""" Save the content of the .text file in the PDF.
Parameters
----------
file_path: str
Path to the output file.
"""
temp = get_tempfile(suffix='.tex')
self.save_content(temp.name)
try:
self.... | [
"def",
"render",
"(",
"self",
",",
"file_path",
",",
"*",
"*",
"kwargs",
")",
":",
"temp",
"=",
"get_tempfile",
"(",
"suffix",
"=",
"'.tex'",
")",
"self",
".",
"save_content",
"(",
"temp",
".",
"name",
")",
"try",
":",
"self",
".",
"_render_function",
... | 29.8125 | 19 |
def add_path_segment(self, value):
"""
Add a new path segment to the end of the current string
:param string value: the new path segment to use
Example::
>>> u = URL('http://example.com/foo/')
>>> u.add_path_segment('bar').as_string()
'http://exampl... | [
"def",
"add_path_segment",
"(",
"self",
",",
"value",
")",
":",
"segments",
"=",
"self",
".",
"path_segments",
"(",
")",
"+",
"(",
"to_unicode",
"(",
"value",
")",
",",
")",
"return",
"self",
".",
"path_segments",
"(",
"segments",
")"
] | 31.428571 | 16.857143 |
def makevAndvPfuncs(self,policyFunc):
'''
Constructs the marginal value function for this period.
Parameters
----------
policyFunc : function
Consumption and medical care function for this period, defined over
market resources, permanent income level, and... | [
"def",
"makevAndvPfuncs",
"(",
"self",
",",
"policyFunc",
")",
":",
"# Get state dimension sizes",
"mCount",
"=",
"self",
".",
"aXtraGrid",
".",
"size",
"pCount",
"=",
"self",
".",
"pLvlGrid",
".",
"size",
"MedCount",
"=",
"self",
".",
"MedShkVals",
".",
"si... | 49.819277 | 28.46988 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.