text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def user_id(self):
"""
Return the ID of the current request's user
"""
# This needs flask-login to be installed
if not has_flask_login:
return
# and the actual login manager installed
if not hasattr(current_app, 'login_manager'):
return
... | [
"def",
"user_id",
"(",
"self",
")",
":",
"# This needs flask-login to be installed",
"if",
"not",
"has_flask_login",
":",
"return",
"# and the actual login manager installed",
"if",
"not",
"hasattr",
"(",
"current_app",
",",
"'login_manager'",
")",
":",
"return",
"# fai... | 29.214286 | 0.002367 |
def merge(self, df: pd.DataFrame, on: str, how: str="outer", **kwargs):
"""
Set the main dataframe from the current dataframe and the passed
dataframe
:param df: the pandas dataframe to merge
:type df: pd.DataFrame
:param on: param for ``pd.merge``
:type on: str
... | [
"def",
"merge",
"(",
"self",
",",
"df",
":",
"pd",
".",
"DataFrame",
",",
"on",
":",
"str",
",",
"how",
":",
"str",
"=",
"\"outer\"",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"df",
"=",
"pd",
".",
"merge",
"(",
"self",
".",
"df",
",",
... | 37.055556 | 0.005848 |
def guess_labels(self, doc):
"""
return a prediction of label names
"""
doc = doc.clone() # make sure it can be serialized safely
return self.index.guess_labels(doc) | [
"def",
"guess_labels",
"(",
"self",
",",
"doc",
")",
":",
"doc",
"=",
"doc",
".",
"clone",
"(",
")",
"# make sure it can be serialized safely",
"return",
"self",
".",
"index",
".",
"guess_labels",
"(",
"doc",
")"
] | 33.5 | 0.009709 |
def _add_agents(self, agent_definitions):
"""Add specified agents to the client. Set up their shared memory and sensor linkages.
Does not spawn an agent in the Holodeck, this is only for documenting and accessing already existing agents.
This is an internal function.
Positional Arguments... | [
"def",
"_add_agents",
"(",
"self",
",",
"agent_definitions",
")",
":",
"if",
"not",
"isinstance",
"(",
"agent_definitions",
",",
"list",
")",
":",
"agent_definitions",
"=",
"[",
"agent_definitions",
"]",
"prepared_agents",
"=",
"self",
".",
"_prepare_agents",
"(... | 53.375 | 0.005754 |
def help_box():
"""A simple HTML help dialog box using the distribution data files."""
style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
dialog_box = wx.Dialog(None, wx.ID_ANY, HELP_TITLE,
style=style, size=(620, 450))
html_widget = HtmlHelp(dialog_box, wx.ID_ANY)
html_wi... | [
"def",
"help_box",
"(",
")",
":",
"style",
"=",
"wx",
".",
"DEFAULT_DIALOG_STYLE",
"|",
"wx",
".",
"RESIZE_BORDER",
"dialog_box",
"=",
"wx",
".",
"Dialog",
"(",
"None",
",",
"wx",
".",
"ID_ANY",
",",
"HELP_TITLE",
",",
"style",
"=",
"style",
",",
"size... | 43.666667 | 0.002494 |
def force_process_ordered(self):
"""
Take any messages from replica that have been ordered and process
them, this should be done rarely, like before catchup starts
so a more current LedgerStatus can be sent.
can be called either
1. when node is participating, this happens... | [
"def",
"force_process_ordered",
"(",
"self",
")",
":",
"for",
"instance_id",
",",
"messages",
"in",
"self",
".",
"replicas",
".",
"take_ordereds_out_of_turn",
"(",
")",
":",
"num_processed",
"=",
"0",
"for",
"message",
"in",
"messages",
":",
"self",
".",
"tr... | 50.136364 | 0.001779 |
def _execute(self, sql, params):
"""Execute statement with reconnecting by connection closed error codes.
2006 (CR_SERVER_GONE_ERROR): MySQL server has gone away
2013 (CR_SERVER_LOST): Lost connection to MySQL server during query
2055 (CR_SERVER_LOST_EXTENDED): Lost connection to MySQL ... | [
"def",
"_execute",
"(",
"self",
",",
"sql",
",",
"params",
")",
":",
"try",
":",
"return",
"self",
".",
"_execute_unsafe",
"(",
"sql",
",",
"params",
")",
"except",
"MySQLdb",
".",
"OperationalError",
"as",
"ex",
":",
"if",
"ex",
".",
"args",
"[",
"0... | 46.666667 | 0.007003 |
def _TTA(learn:Learner, beta:float=0.4, scale:float=1.35, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False) -> Tensors:
"Applies TTA to predict on `ds_type` dataset."
preds,y = learn.get_preds(ds_type)
all_preds = list(learn.tta_only(scale=scale, ds_type=ds_type))
avg_preds = torch.stack(all_... | [
"def",
"_TTA",
"(",
"learn",
":",
"Learner",
",",
"beta",
":",
"float",
"=",
"0.4",
",",
"scale",
":",
"float",
"=",
"1.35",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Valid",
",",
"with_loss",
":",
"bool",
"=",
"False",
")",
"->",... | 51.75 | 0.036392 |
def temp_filename(self):
"""Return a unique tempfile name.
"""
# TODO: it would be nice to get this to behave more like a
# context so we can make sure these temporary files are
# removed, regardless of whether an error occurs or the
# program is terminated.
handl... | [
"def",
"temp_filename",
"(",
"self",
")",
":",
"# TODO: it would be nice to get this to behave more like a",
"# context so we can make sure these temporary files are",
"# removed, regardless of whether an error occurs or the",
"# program is terminated.",
"handle",
",",
"filename",
"=",
"... | 39.2 | 0.004988 |
def get_by_id(self, id_networkv6):
"""Get IPv6 network
:param id_networkv4: ID for NetworkIPv6
:return: IPv6 Network
"""
uri = 'api/networkv4/%s/' % id_networkv6
return super(ApiNetworkIPv6, self).get(uri) | [
"def",
"get_by_id",
"(",
"self",
",",
"id_networkv6",
")",
":",
"uri",
"=",
"'api/networkv4/%s/'",
"%",
"id_networkv6",
"return",
"super",
"(",
"ApiNetworkIPv6",
",",
"self",
")",
".",
"get",
"(",
"uri",
")"
] | 24.7 | 0.007813 |
def add_sub_resource(self, relative_id, sub_resource):
"""Add sub resource"""
existing_sub_resources = self.resources.get(sub_resource.RELATIVE_PATH_TEMPLATE, defaultdict(list))
existing_sub_resources[relative_id].append(sub_resource)
self.resources.update({sub_resource.RELATIVE_PATH_TEM... | [
"def",
"add_sub_resource",
"(",
"self",
",",
"relative_id",
",",
"sub_resource",
")",
":",
"existing_sub_resources",
"=",
"self",
".",
"resources",
".",
"get",
"(",
"sub_resource",
".",
"RELATIVE_PATH_TEMPLATE",
",",
"defaultdict",
"(",
"list",
")",
")",
"existi... | 69.4 | 0.011396 |
def search_report_event_for_facets(self, **kwargs): # noqa: E501
"""Lists the values of one or more facets over the customer's events # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... | [
"def",
"search_report_event_for_facets",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"search_repor... | 46.142857 | 0.002022 |
def ping(self):
"""Attempt to detect if a device at this address is present on the I2C
bus. Will send out the device's address for writing and verify an ACK
is received. Returns true if the ACK is received, and false if not.
"""
self._idle()
self._transaction_start()
... | [
"def",
"ping",
"(",
"self",
")",
":",
"self",
".",
"_idle",
"(",
")",
"self",
".",
"_transaction_start",
"(",
")",
"self",
".",
"_i2c_start",
"(",
")",
"self",
".",
"_i2c_write_bytes",
"(",
"[",
"self",
".",
"_address_byte",
"(",
"False",
")",
"]",
"... | 45.785714 | 0.004587 |
def create_sensor(sensor_id, sensor, async_set_state_callback):
"""Simplify creating sensor by not needing to know type."""
if sensor['type'] in CONSUMPTION:
return Consumption(sensor_id, sensor)
if sensor['type'] in CARBONMONOXIDE:
return CarbonMonoxide(sensor_id, sensor)
if sensor['typ... | [
"def",
"create_sensor",
"(",
"sensor_id",
",",
"sensor",
",",
"async_set_state_callback",
")",
":",
"if",
"sensor",
"[",
"'type'",
"]",
"in",
"CONSUMPTION",
":",
"return",
"Consumption",
"(",
"sensor_id",
",",
"sensor",
")",
"if",
"sensor",
"[",
"'type'",
"]... | 40.888889 | 0.000664 |
def _remove_empty_items(d, required):
"""Return a new dict with any empty items removed.
Note that this is not a deep check. If d contains a dictionary which
itself contains empty items, those are never checked.
This method exists to make to_serializable() functions cleaner.
We could revisit this some day, ... | [
"def",
"_remove_empty_items",
"(",
"d",
",",
"required",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"required",
":",
"new_dict",
"[",
"k",
"]",
"=",
"v",
"elif",
"isinstance... | 28.821429 | 0.009592 |
def remove_ipv4addr(self, ipv4addr):
"""Remove an IPv4 address from the host.
:param str ipv4addr: The IP address to remove
"""
for addr in self.ipv4addrs:
if ((isinstance(addr, dict) and addr['ipv4addr'] == ipv4addr) or
(isinstance(addr, HostIPv4) and addr.... | [
"def",
"remove_ipv4addr",
"(",
"self",
",",
"ipv4addr",
")",
":",
"for",
"addr",
"in",
"self",
".",
"ipv4addrs",
":",
"if",
"(",
"(",
"isinstance",
"(",
"addr",
",",
"dict",
")",
"and",
"addr",
"[",
"'ipv4addr'",
"]",
"==",
"ipv4addr",
")",
"or",
"("... | 36.272727 | 0.007335 |
def calc_datastore(request, job_id):
"""
Download a full datastore file.
:param request:
`django.http.HttpRequest` object.
:param job_id:
The id of the requested datastore
:returns:
A `django.http.HttpResponse` containing the content
of the requested artifact, if pre... | [
"def",
"calc_datastore",
"(",
"request",
",",
"job_id",
")",
":",
"job",
"=",
"logs",
".",
"dbcmd",
"(",
"'get_job'",
",",
"int",
"(",
"job_id",
")",
")",
"if",
"job",
"is",
"None",
":",
"return",
"HttpResponseNotFound",
"(",
")",
"if",
"not",
"utils",... | 33.6 | 0.001157 |
def decode(self, descriptor):
""" Produce a list of dictionaries for each dimension in this transcoder """
i = iter(descriptor)
n = len(self._schema)
# Add the name key to our schema
schema = self._schema + ('name',)
# For each dimensions, generator takes n items off ite... | [
"def",
"decode",
"(",
"self",
",",
"descriptor",
")",
":",
"i",
"=",
"iter",
"(",
"descriptor",
")",
"n",
"=",
"len",
"(",
"self",
".",
"_schema",
")",
"# Add the name key to our schema",
"schema",
"=",
"self",
".",
"_schema",
"+",
"(",
"'name'",
",",
... | 43.2 | 0.009063 |
def ssgsea(data, gene_sets, outdir="ssGSEA_", sample_norm_method='rank', min_size=15, max_size=2000,
permutation_num=0, weighted_score_type=0.25, scale=True, ascending=False, processes=1,
figsize=(7,6), format='pdf', graph_num=20, no_plot=False, seed=None, verbose=False):
"""Run Gene Set Enric... | [
"def",
"ssgsea",
"(",
"data",
",",
"gene_sets",
",",
"outdir",
"=",
"\"ssGSEA_\"",
",",
"sample_norm_method",
"=",
"'rank'",
",",
"min_size",
"=",
"15",
",",
"max_size",
"=",
"2000",
",",
"permutation_num",
"=",
"0",
",",
"weighted_score_type",
"=",
"0.25",
... | 62.622642 | 0.008009 |
def keras_dropout(layer, rate):
'''keras dropout layer.
'''
from keras import layers
input_dim = len(layer.input.shape)
if input_dim == 2:
return layers.SpatialDropout1D(rate)
elif input_dim == 3:
return layers.SpatialDropout2D(rate)
elif input_dim == 4:
return laye... | [
"def",
"keras_dropout",
"(",
"layer",
",",
"rate",
")",
":",
"from",
"keras",
"import",
"layers",
"input_dim",
"=",
"len",
"(",
"layer",
".",
"input",
".",
"shape",
")",
"if",
"input_dim",
"==",
"2",
":",
"return",
"layers",
".",
"SpatialDropout1D",
"(",... | 25.133333 | 0.002558 |
def _compare_replication(current, desired, region, key, keyid, profile):
'''
Replication accepts a non-ARN role name, but always returns an ARN
'''
if desired is not None and desired.get('Role'):
desired = copy.deepcopy(desired)
desired['Role'] = _get_role_arn(desired['Role'],
... | [
"def",
"_compare_replication",
"(",
"current",
",",
"desired",
",",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
":",
"if",
"desired",
"is",
"not",
"None",
"and",
"desired",
".",
"get",
"(",
"'Role'",
")",
":",
"desired",
"=",
"copy",
".",
... | 50.222222 | 0.006522 |
def _get_unique_child_value(xtag, eltname):
"""Get the text content of the unique child element under xtag with name eltname"""
xelt = _get_unique_child(xtag, eltname)
if xelt is None:
return None
else:
return xelt.text | [
"def",
"_get_unique_child_value",
"(",
"xtag",
",",
"eltname",
")",
":",
"xelt",
"=",
"_get_unique_child",
"(",
"xtag",
",",
"eltname",
")",
"if",
"xelt",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"xelt",
".",
"text"
] | 35 | 0.007968 |
def app_main(self, experiment=None, last=False, new=False,
verbose=False, verbosity_level=None, no_modification=False,
match=False):
"""
The main function for parsing global arguments
Parameters
----------
experiment: str
The id of t... | [
"def",
"app_main",
"(",
"self",
",",
"experiment",
"=",
"None",
",",
"last",
"=",
"False",
",",
"new",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"verbosity_level",
"=",
"None",
",",
"no_modification",
"=",
"False",
",",
"match",
"=",
"False",
")... | 41.533333 | 0.001568 |
def get_canvas_image(self):
"""Get canvas image object.
Returns
-------
imgobj : `~ginga.canvas.types.image.NormImage`
Normalized image sitting on the canvas.
"""
if self._imgobj is not None:
return self._imgobj
try:
# See if... | [
"def",
"get_canvas_image",
"(",
"self",
")",
":",
"if",
"self",
".",
"_imgobj",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_imgobj",
"try",
":",
"# See if there is an image on the canvas",
"self",
".",
"_imgobj",
"=",
"self",
".",
"canvas",
".",
"get_... | 36.382353 | 0.001575 |
def getPlatformsByName(platformNames=['all'], mode=None, tags=[], excludePlatformNames=[]):
"""Method that recovers the names of the <Platforms> in a given list.
:param platformNames: List of strings containing the possible platforms.
:param mode: The mode of the search. The following can be ... | [
"def",
"getPlatformsByName",
"(",
"platformNames",
"=",
"[",
"'all'",
"]",
",",
"mode",
"=",
"None",
",",
"tags",
"=",
"[",
"]",
",",
"excludePlatformNames",
"=",
"[",
"]",
")",
":",
"allPlatformsList",
"=",
"getAllPlatformObjects",
"(",
"mode",
")",
"plat... | 43.306122 | 0.004147 |
def dispatch_submission(self, raw_msg):
"""Dispatch job submission to appropriate handlers."""
# ensure targets up to date:
self.notifier_stream.flush()
try:
idents, msg = self.session.feed_identities(raw_msg, copy=False)
msg = self.session.unserialize(msg, conten... | [
"def",
"dispatch_submission",
"(",
"self",
",",
"raw_msg",
")",
":",
"# ensure targets up to date:",
"self",
".",
"notifier_stream",
".",
"flush",
"(",
")",
"try",
":",
"idents",
",",
"msg",
"=",
"self",
".",
"session",
".",
"feed_identities",
"(",
"raw_msg",
... | 37.921348 | 0.005487 |
def add(self, items):
"""Add messages to be managed by the leaser."""
for item in items:
# Add the ack ID to the set of managed ack IDs, and increment
# the size counter.
if item.ack_id not in self._leased_messages:
self._leased_messages[item.ack_id] =... | [
"def",
"add",
"(",
"self",
",",
"items",
")",
":",
"for",
"item",
"in",
"items",
":",
"# Add the ack ID to the set of managed ack IDs, and increment",
"# the size counter.",
"if",
"item",
".",
"ack_id",
"not",
"in",
"self",
".",
"_leased_messages",
":",
"self",
".... | 46.083333 | 0.005319 |
def effective_nsamples(self):
"""The effective number of samples post burn-in that the sampler has
acquired so far."""
try:
act = numpy.array(list(self.acts.values())).max()
except (AttributeError, TypeError):
act = numpy.inf
if self.burn_in is None:
... | [
"def",
"effective_nsamples",
"(",
"self",
")",
":",
"try",
":",
"act",
"=",
"numpy",
".",
"array",
"(",
"list",
"(",
"self",
".",
"acts",
".",
"values",
"(",
")",
")",
")",
".",
"max",
"(",
")",
"except",
"(",
"AttributeError",
",",
"TypeError",
")... | 41.470588 | 0.002774 |
def _parse_req(self, req):
'''Parses a request object for relevant debugging information. Only works
if DEBUG is enabled.
Args:
req requests req object
'''
if DEBUG:
if req.status_code != requests.codes.ok:
print(("code: {}".format(req.status_code)))
print(("response {}".format(req.json())))
... | [
"def",
"_parse_req",
"(",
"self",
",",
"req",
")",
":",
"if",
"DEBUG",
":",
"if",
"req",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"print",
"(",
"(",
"\"code: {}\"",
".",
"format",
"(",
"req",
".",
"status_code",
")",
")",
... | 34.833333 | 0.030303 |
def supports_spatial_unit_record_type(self, spatial_unit_record_type):
"""Tests if the given spatial unit record type is supported.
arg: spatial_unit_record_type (osid.type.Type): a spatial
unit record Type
return: (boolean) - ``true`` if the type is supported, ``false``
... | [
"def",
"supports_spatial_unit_record_type",
"(",
"self",
",",
"spatial_unit_record_type",
")",
":",
"# Implemented from template for osid.Metadata.supports_coordinate_type",
"if",
"self",
".",
"_kwargs",
"[",
"'syntax'",
"]",
"not",
"in",
"[",
"'``SPATIALUNIT``'",
"]",
":",... | 50.125 | 0.002448 |
def apply_patch(self, filename, arch, build_dir=None):
"""
Apply a patch from the current recipe directory into the current
build directory.
.. versionchanged:: 0.6.0
Add ability to apply patch from any dir via kwarg `build_dir`'''
"""
info("Applying patch {}... | [
"def",
"apply_patch",
"(",
"self",
",",
"filename",
",",
"arch",
",",
"build_dir",
"=",
"None",
")",
":",
"info",
"(",
"\"Applying patch {}\"",
".",
"format",
"(",
"filename",
")",
")",
"build_dir",
"=",
"build_dir",
"if",
"build_dir",
"else",
"self",
".",... | 42.692308 | 0.003527 |
def get_valid_times_for_job_legacy(self, num_job):
""" Get the times for which the job num_job will be valid, using the method
use in inspiral hipe.
"""
# All of this should be integers, so no rounding factors needed.
shift_dur = self.curr_seg[0] + int(self.job_time_shift * num_j... | [
"def",
"get_valid_times_for_job_legacy",
"(",
"self",
",",
"num_job",
")",
":",
"# All of this should be integers, so no rounding factors needed.",
"shift_dur",
"=",
"self",
".",
"curr_seg",
"[",
"0",
"]",
"+",
"int",
"(",
"self",
".",
"job_time_shift",
"*",
"num_job"... | 46.866667 | 0.005579 |
def _convertPyval(self, oself, pyval):
"""
Convert a Python value to a value suitable for inserting into the
database.
@param oself: The object on which this descriptor is an attribute.
@param pyval: The value to be converted.
@return: A value legal for this column in th... | [
"def",
"_convertPyval",
"(",
"self",
",",
"oself",
",",
"pyval",
")",
":",
"# convert to dbval later, I guess?",
"if",
"pyval",
"is",
"None",
"and",
"not",
"self",
".",
"allowNone",
":",
"raise",
"TypeError",
"(",
"\"attribute [%s.%s = %s()] must not be None\"",
"%"... | 42.066667 | 0.003101 |
def get_rectangle(self):
"""Gets the coordinates of the rectangle, in which the tree can be put.
Returns:
tupel: (x1, y1, x2, y2)
"""
rec = [self.pos[0], self.pos[1]]*2
for age in self.nodes:
for node in age:
# Check max/min for x/y coords... | [
"def",
"get_rectangle",
"(",
"self",
")",
":",
"rec",
"=",
"[",
"self",
".",
"pos",
"[",
"0",
"]",
",",
"self",
".",
"pos",
"[",
"1",
"]",
"]",
"*",
"2",
"for",
"age",
"in",
"self",
".",
"nodes",
":",
"for",
"node",
"in",
"age",
":",
"# Check... | 34.75 | 0.003503 |
def get_period_queryset(self, request, period):
"""
Computes the queryset for a specific period and, perhaps, a request.
:param request: current request being processed.
:param period: current requested period.
:return: a queryset
"""
qs = self.get_queryset(reque... | [
"def",
"get_period_queryset",
"(",
"self",
",",
"request",
",",
"period",
")",
":",
"qs",
"=",
"self",
".",
"get_queryset",
"(",
"request",
")",
"if",
"not",
"period",
":",
"return",
"qs",
"if",
"self",
".",
"tracked_stamps",
"==",
"'create'",
":",
"retu... | 40.473684 | 0.003812 |
def name(self):
"""
Algo name.
"""
if self._name is None:
self._name = self.__class__.__name__
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name",
"is",
"None",
":",
"self",
".",
"_name",
"=",
"self",
".",
"__class__",
".",
"__name__",
"return",
"self",
".",
"_name"
] | 22.571429 | 0.012195 |
def _interpretMdriztabPars(rec):
"""
Collect task parameters from the MDRIZTAB record and
update the master parameters list with those values
Note that parameters read from the MDRIZTAB record must
be cleaned up in a similar way that parameters read
from the user interface are.
"""
tabd... | [
"def",
"_interpretMdriztabPars",
"(",
"rec",
")",
":",
"tabdict",
"=",
"{",
"}",
"# for each entry in the record...",
"for",
"indx",
"in",
"range",
"(",
"len",
"(",
"rec",
".",
"array",
".",
"names",
")",
")",
":",
"# ... get the name, format, and value.",
"_nam... | 34.739726 | 0.009202 |
def aperture_select(self, ra, dec, kwargs_aperture):
"""
returns a bool list if the coordinate is within the aperture (list)
:param ra:
:param dec:
:return:
"""
if self._aperture_type == 'shell':
bool_list = self.shell_select(ra, dec, **kwargs_aperture... | [
"def",
"aperture_select",
"(",
"self",
",",
"ra",
",",
"dec",
",",
"kwargs_aperture",
")",
":",
"if",
"self",
".",
"_aperture_type",
"==",
"'shell'",
":",
"bool_list",
"=",
"self",
".",
"shell_select",
"(",
"ra",
",",
"dec",
",",
"*",
"*",
"kwargs_apertu... | 39.142857 | 0.005348 |
def filter_humphrey(mesh,
alpha=0.1,
beta=0.5,
iterations=10,
laplacian_operator=None):
"""
Smooth a mesh in-place using laplacian smoothing
and Humphrey filtering.
Articles
"Improved Laplacian Smoothing of Noisy Surfac... | [
"def",
"filter_humphrey",
"(",
"mesh",
",",
"alpha",
"=",
"0.1",
",",
"beta",
"=",
"0.5",
",",
"iterations",
"=",
"10",
",",
"laplacian_operator",
"=",
"None",
")",
":",
"# if the laplacian operator was not passed create it here",
"if",
"laplacian_operator",
"is",
... | 31.588235 | 0.000602 |
def set_rate_BC(self, pores, values):
r"""
Apply constant rate boundary conditons to the specified pore
locations. This is similar to a Neumann boundary condition, but is
slightly different since it's the conductance multiplied by the
gradient, while Neumann conditions specify ju... | [
"def",
"set_rate_BC",
"(",
"self",
",",
"pores",
",",
"values",
")",
":",
"self",
".",
"_set_BC",
"(",
"pores",
"=",
"pores",
",",
"bctype",
"=",
"'rate'",
",",
"bcvalues",
"=",
"values",
",",
"mode",
"=",
"'merge'",
")"
] | 42.304348 | 0.00201 |
def show_text(self, text):
"""A drawing operator that generates the shape from a string text,
rendered according to the current
font :meth:`face <set_font_face>`,
font :meth:`size <set_font_size>`
(font :meth:`matrix <set_font_matrix>`),
and font :meth:`options <set_font_... | [
"def",
"show_text",
"(",
"self",
",",
"text",
")",
":",
"cairo",
".",
"cairo_show_text",
"(",
"self",
".",
"_pointer",
",",
"_encode_string",
"(",
"text",
")",
")",
"self",
".",
"_check_status",
"(",
")"
] | 41.945946 | 0.001259 |
def compile_regex_from_str(self, ft_str):
"""Given a string describing features masks for a sequence of segments,
return a regex matching the corresponding strings.
Args:
ft_str (str): feature masks, each enclosed in square brackets, in
which the features are delimited b... | [
"def",
"compile_regex_from_str",
"(",
"self",
",",
"ft_str",
")",
":",
"sequence",
"=",
"[",
"]",
"for",
"m",
"in",
"re",
".",
"finditer",
"(",
"r'\\[([^]]+)\\]'",
",",
"ft_str",
")",
":",
"ft_mask",
"=",
"fts",
"(",
"m",
".",
"group",
"(",
"1",
")",... | 37 | 0.002509 |
def rand_elem(seq, n=None):
"""returns a random element from seq n times. If n is None, it continues indefinitly"""
return map(random.choice, repeat(seq, n) if n is not None else repeat(seq)) | [
"def",
"rand_elem",
"(",
"seq",
",",
"n",
"=",
"None",
")",
":",
"return",
"map",
"(",
"random",
".",
"choice",
",",
"repeat",
"(",
"seq",
",",
"n",
")",
"if",
"n",
"is",
"not",
"None",
"else",
"repeat",
"(",
"seq",
")",
")"
] | 65.666667 | 0.01005 |
def handleNotification(self, handle, raw_data): # pylint: disable=unused-argument,invalid-name
""" gets called by the bluepy backend when using wait_for_notification
"""
if raw_data is None:
return
data = raw_data.decode("utf-8").strip(' \n\t')
self._cache = data
... | [
"def",
"handleNotification",
"(",
"self",
",",
"handle",
",",
"raw_data",
")",
":",
"# pylint: disable=unused-argument,invalid-name",
"if",
"raw_data",
"is",
"None",
":",
"return",
"data",
"=",
"raw_data",
".",
"decode",
"(",
"\"utf-8\"",
")",
".",
"strip",
"(",... | 43.214286 | 0.004854 |
def expect_all(a, b):
"""\
Asserts that two iterables contain the same values.
"""
assert all(_a == _b for _a, _b in zip_longest(a, b)) | [
"def",
"expect_all",
"(",
"a",
",",
"b",
")",
":",
"assert",
"all",
"(",
"_a",
"==",
"_b",
"for",
"_a",
",",
"_b",
"in",
"zip_longest",
"(",
"a",
",",
"b",
")",
")"
] | 29.4 | 0.006623 |
def vulnerability_section_header_element(feature, parent):
"""Retrieve vulnerability section header string from definitions."""
_ = feature, parent # NOQA
header = vulnerability_section_header['string_format']
return header.capitalize() | [
"def",
"vulnerability_section_header_element",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"header",
"=",
"vulnerability_section_header",
"[",
"'string_format'",
"]",
"return",
"header",
".",
"capitalize",
"(",
")"
] | 49.8 | 0.003953 |
def remove(self, oid):
"""
Remove a faked HBA resource.
This method also updates the 'hba-uris' property in the parent
Partition resource, by removing the URI for the faked HBA resource.
Parameters:
oid (string):
The object ID of the faked HBA resource.
... | [
"def",
"remove",
"(",
"self",
",",
"oid",
")",
":",
"hba",
"=",
"self",
".",
"lookup_by_oid",
"(",
"oid",
")",
"partition",
"=",
"self",
".",
"parent",
"devno",
"=",
"hba",
".",
"properties",
".",
"get",
"(",
"'device-number'",
",",
"None",
")",
"if"... | 33.583333 | 0.002413 |
def all(cls, include_deactivated=False):
"""
Get all resources
:param include_deactivated: Include deactivated resources in response
:returns: list of Document instances
:raises: SocketError, CouchException
"""
if include_deactivated:
resources = yiel... | [
"def",
"all",
"(",
"cls",
",",
"include_deactivated",
"=",
"False",
")",
":",
"if",
"include_deactivated",
":",
"resources",
"=",
"yield",
"cls",
".",
"view",
".",
"get",
"(",
"include_docs",
"=",
"True",
")",
"else",
":",
"resources",
"=",
"yield",
"cls... | 38.846154 | 0.005803 |
def enqueue(self, future):
"""
Enqueue a future to be processed by one of the threads in the pool.
The future must be bound to a worker and not have been started yet.
"""
future.enqueue()
with self._lock:
if self._shutdown:
raise RuntimeError('ThreadPool has been shut down and can... | [
"def",
"enqueue",
"(",
"self",
",",
"future",
")",
":",
"future",
".",
"enqueue",
"(",
")",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_shutdown",
":",
"raise",
"RuntimeError",
"(",
"'ThreadPool has been shut down and can no '",
"'longer accept futur... | 32.533333 | 0.011952 |
def markdown_editor(selector):
""" Enable markdown editor for given textarea.
:returns: Editor template context.
"""
return dict(
selector=selector,
extra_settings=mark_safe(simplejson.dumps(
dict(previewParserPath=reverse('django_markdown_preview'))))) | [
"def",
"markdown_editor",
"(",
"selector",
")",
":",
"return",
"dict",
"(",
"selector",
"=",
"selector",
",",
"extra_settings",
"=",
"mark_safe",
"(",
"simplejson",
".",
"dumps",
"(",
"dict",
"(",
"previewParserPath",
"=",
"reverse",
"(",
"'django_markdown_previ... | 29 | 0.003344 |
def _rollout_metadata(batch_env):
"""Metadata for rollouts."""
batch_env_shape = batch_env.observ.get_shape().as_list()
batch_size = [batch_env_shape[0]]
shapes_types_names = [
# TODO(piotrmilos): possibly retrieve the observation type for batch_env
(batch_size + batch_env_shape[1:], batch_env.obser... | [
"def",
"_rollout_metadata",
"(",
"batch_env",
")",
":",
"batch_env_shape",
"=",
"batch_env",
".",
"observ",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"batch_size",
"=",
"[",
"batch_env_shape",
"[",
"0",
"]",
"]",
"shapes_types_names",
"=",
"[",
... | 41.466667 | 0.011006 |
def get_activity_ids_by_objective_banks(self, objective_bank_ids):
"""Gets the list of ``Activity Ids`` corresponding to a list of ``ObjectiveBanks``.
arg: objective_bank_ids (osid.id.IdList): list of objective
bank ``Ids``
return: (osid.id.IdList) - list of activity ``Ids``
... | [
"def",
"get_activity_ids_by_objective_banks",
"(",
"self",
",",
"objective_bank_ids",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinSession.get_resource_ids_by_bins",
"id_list",
"=",
"[",
"]",
"for",
"activity",
"in",
"self",
".",
"get_activities_by_o... | 47.611111 | 0.004577 |
def assign_power_curve(self, wake_losses_model='power_efficiency_curve',
smoothing=False, block_width=0.5,
standard_deviation_method='turbulence_intensity',
smoothing_order='wind_farm_power_curves',
turbulence_in... | [
"def",
"assign_power_curve",
"(",
"self",
",",
"wake_losses_model",
"=",
"'power_efficiency_curve'",
",",
"smoothing",
"=",
"False",
",",
"block_width",
"=",
"0.5",
",",
"standard_deviation_method",
"=",
"'turbulence_intensity'",
",",
"smoothing_order",
"=",
"'wind_farm... | 53.321678 | 0.000772 |
def disable_avatar(self):
"""
Temporarily disable the avatar.
If :attr:`synchronize_vcard` is true, the vCard avatar is
disabled (even if disabling the PEP avatar fails).
This is done by setting the avatar metadata node empty and if
:attr:`synchronize_vcard` is true, do... | [
"def",
"disable_avatar",
"(",
"self",
")",
":",
"with",
"(",
"yield",
"from",
"self",
".",
"_publish_lock",
")",
":",
"todo",
"=",
"[",
"]",
"if",
"self",
".",
"_synchronize_vcard",
":",
"todo",
".",
"append",
"(",
"self",
".",
"_disable_vcard_avatar",
"... | 34.862069 | 0.001925 |
def kill_pid(self, pid):
"""Kill process by pid
Args:
pid (int)
"""
try:
p = psutil.Process(pid)
p.terminate()
self.info_log('Killed [pid:%s][name:%s]' % (p.pid, p.name()))
except psutil.NoSuchProcess:
self.error_log... | [
"def",
"kill_pid",
"(",
"self",
",",
"pid",
")",
":",
"try",
":",
"p",
"=",
"psutil",
".",
"Process",
"(",
"pid",
")",
"p",
".",
"terminate",
"(",
")",
"self",
".",
"info_log",
"(",
"'Killed [pid:%s][name:%s]'",
"%",
"(",
"p",
".",
"pid",
",",
"p",... | 22.733333 | 0.005634 |
def options(self, parser, env):
"""Register commandline options.
Implement this method for normal options behavior with protection from
OptionConflictErrors. If you override this method and want the default
--with-$name option to be registered, be sure to call super().
"""
... | [
"def",
"options",
"(",
"self",
",",
"parser",
",",
"env",
")",
":",
"env_opt",
"=",
"'NOSE_WITH_%s'",
"%",
"self",
".",
"name",
".",
"upper",
"(",
")",
"env_opt",
"=",
"env_opt",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"parser",
".",
"add_option... | 48.666667 | 0.002688 |
def pattern_input(self, question, message='Invalid entry', pattern='^[a-zA-Z0-9_ ]+$', default='',required=True):
'''
Method for input disallowing special characters, with optionally
specifiable regex pattern and error message.
'''
result = ''
requiredFlag = True
... | [
"def",
"pattern_input",
"(",
"self",
",",
"question",
",",
"message",
"=",
"'Invalid entry'",
",",
"pattern",
"=",
"'^[a-zA-Z0-9_ ]+$'",
",",
"default",
"=",
"''",
",",
"required",
"=",
"True",
")",
":",
"result",
"=",
"''",
"requiredFlag",
"=",
"True",
"w... | 42.73913 | 0.00398 |
def p_base_type(self, p): # noqa
'''base_type : BOOL annotations
| BYTE annotations
| I8 annotations
| I16 annotations
| I32 annotations
| I64 annotations
| DOUBLE annotations
... | [
"def",
"p_base_type",
"(",
"self",
",",
"p",
")",
":",
"# noqa",
"name",
"=",
"p",
"[",
"1",
"]",
"if",
"name",
"==",
"'i8'",
":",
"name",
"=",
"'byte'",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"PrimitiveType",
"(",
"name",
",",
"p",
"[",
"2",
"... | 31.25 | 0.003883 |
def lookup(self):
"""
Prints name, author, size and age
"""
print "%s by %s, size: %s, uploaded %s ago" % (self.name, self.author,
self.size, self.age) | [
"def",
"lookup",
"(",
"self",
")",
":",
"print",
"\"%s by %s, size: %s, uploaded %s ago\"",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"author",
",",
"self",
".",
"size",
",",
"self",
".",
"age",
")"
] | 38.833333 | 0.008403 |
def validatefeatures(self,features):
"""Returns features in validated form, or raises an Exception. Mostly for internal use"""
validatedfeatures = []
for feature in features:
if isinstance(feature, int) or isinstance(feature, float):
validatedfeatures.append( str(feat... | [
"def",
"validatefeatures",
"(",
"self",
",",
"features",
")",
":",
"validatedfeatures",
"=",
"[",
"]",
"for",
"feature",
"in",
"features",
":",
"if",
"isinstance",
"(",
"feature",
",",
"int",
")",
"or",
"isinstance",
"(",
"feature",
",",
"float",
")",
":... | 53.538462 | 0.012712 |
def run_reaction_production_check(self, model, solver, threshold,
implicit_sinks=True):
"""Run reaction production check method."""
prob = solver.create_problem()
# Create flux variables
v = prob.namespace()
for reaction_id in model.reaction... | [
"def",
"run_reaction_production_check",
"(",
"self",
",",
"model",
",",
"solver",
",",
"threshold",
",",
"implicit_sinks",
"=",
"True",
")",
":",
"prob",
"=",
"solver",
".",
"create_problem",
"(",
")",
"# Create flux variables",
"v",
"=",
"prob",
".",
"namespa... | 41.59322 | 0.001194 |
def extract_all(zipfile, dest_folder):
"""
reads the zip file, determines compression
and unzips recursively until source files
are extracted
"""
z = ZipFile(zipfile)
print(z)
z.extract(dest_folder) | [
"def",
"extract_all",
"(",
"zipfile",
",",
"dest_folder",
")",
":",
"z",
"=",
"ZipFile",
"(",
"zipfile",
")",
"print",
"(",
"z",
")",
"z",
".",
"extract",
"(",
"dest_folder",
")"
] | 24.888889 | 0.012931 |
def reduce_path(path):
"""Reduce absolute path to relative (if shorter) for easier readability."""
relative_path = os.path.relpath(path)
if len(relative_path) < len(path):
return relative_path
else:
return path | [
"def",
"reduce_path",
"(",
"path",
")",
":",
"relative_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
")",
"if",
"len",
"(",
"relative_path",
")",
"<",
"len",
"(",
"path",
")",
":",
"return",
"relative_path",
"else",
":",
"return",
"path"
... | 33.714286 | 0.004132 |
def get_server_api(token=None, site=None, cls=None, config=None, **kwargs):
"""
Get the anaconda server api class
"""
if not cls:
from binstar_client import Binstar
cls = Binstar
config = config if config is not None else get_config(site=site)
url = config.get('url', DEFAULT_UR... | [
"def",
"get_server_api",
"(",
"token",
"=",
"None",
",",
"site",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"config",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"cls",
":",
"from",
"binstar_client",
"import",
"Binstar",
"cls",
"=",
... | 33.464286 | 0.002075 |
def _read_config(self, filename=None):
"""
Read the user configuration
"""
if filename:
self._config_filename = filename
else:
try:
import appdirs
except ImportError:
raise Exception("Missing dependency for deter... | [
"def",
"_read_config",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
":",
"self",
".",
"_config_filename",
"=",
"filename",
"else",
":",
"try",
":",
"import",
"appdirs",
"except",
"ImportError",
":",
"raise",
"Exception",
"(",
"\"M... | 40.235294 | 0.005714 |
def api_method(self):
""" Returns the api method to `send` the current API Object type """
if not self._api_method:
raise NotImplementedError()
return getattr(self.api, self._api_method) | [
"def",
"api_method",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_api_method",
":",
"raise",
"NotImplementedError",
"(",
")",
"return",
"getattr",
"(",
"self",
".",
"api",
",",
"self",
".",
"_api_method",
")"
] | 43.6 | 0.009009 |
def append_dynamics(self, t, dynamics, canvas=0, separate=False, color='blue'):
"""!
@brief Append several dynamics to canvas or canvases (defined by 'canvas' and 'separate' arguments).
@param[in] t (list): Time points that corresponds to dynamic values and considered on a X axis.
... | [
"def",
"append_dynamics",
"(",
"self",
",",
"t",
",",
"dynamics",
",",
"canvas",
"=",
"0",
",",
"separate",
"=",
"False",
",",
"color",
"=",
"'blue'",
")",
":",
"description",
"=",
"dynamic_descr",
"(",
"canvas",
",",
"t",
",",
"dynamics",
",",
"separa... | 72.111111 | 0.010646 |
def _get_level(current_level, new_intention):
"""
Map GreyNoise intentions to Cortex maliciousness levels.
Accept a Cortex level and a GreyNoise intention, the return the more malicious of the two.
:param current_level: A Cortex maliciousness level
https://github.com/TheHive... | [
"def",
"_get_level",
"(",
"current_level",
",",
"new_intention",
")",
":",
"intention_level_map",
"=",
"OrderedDict",
"(",
"[",
"(",
"'info'",
",",
"'info'",
")",
",",
"(",
"'benign'",
",",
"'safe'",
")",
",",
"(",
"'suspicious'",
",",
"'suspicious'",
")",
... | 42 | 0.00321 |
def seek(self, pos, whence=_SEEK_SET):
"""Set the current position of this file.
:Parameters:
- `pos`: the position (or offset if using relative
positioning) to seek to
- `whence` (optional): where to seek
from. :attr:`os.SEEK_SET` (``0``) for absolute file
... | [
"def",
"seek",
"(",
"self",
",",
"pos",
",",
"whence",
"=",
"_SEEK_SET",
")",
":",
"if",
"whence",
"==",
"_SEEK_SET",
":",
"new_pos",
"=",
"pos",
"elif",
"whence",
"==",
"_SEEK_CUR",
":",
"new_pos",
"=",
"self",
".",
"__position",
"+",
"pos",
"elif",
... | 36 | 0.002081 |
def _prt_results(self, goea_results):
"""Print GOEA results to the screen."""
min_ratio = self.args.ratio
if min_ratio is not None:
assert 1 <= min_ratio <= 2
self.objgoea.print_date(min_ratio=min_ratio, pval=self.args.pval)
results_adj = self.objgoea.get_adj_records(... | [
"def",
"_prt_results",
"(",
"self",
",",
"goea_results",
")",
":",
"min_ratio",
"=",
"self",
".",
"args",
".",
"ratio",
"if",
"min_ratio",
"is",
"not",
"None",
":",
"assert",
"1",
"<=",
"min_ratio",
"<=",
"2",
"self",
".",
"objgoea",
".",
"print_date",
... | 47.153846 | 0.0064 |
def draw(self, pen, contours=True, components=True):
"""
Draw the glyph's outline data (contours and components) to
the given :ref:`type-pen`.
>>> glyph.draw(pen)
If ``contours`` is set to ``False``, the glyph's
contours will not be drawn.
>>> glyph.dra... | [
"def",
"draw",
"(",
"self",
",",
"pen",
",",
"contours",
"=",
"True",
",",
"components",
"=",
"True",
")",
":",
"if",
"contours",
":",
"for",
"contour",
"in",
"self",
":",
"contour",
".",
"draw",
"(",
"pen",
")",
"if",
"components",
":",
"for",
"co... | 29.304348 | 0.002874 |
def _get_key_by_keyid(keyid):
"""Get a key via HTTPS from the Ubuntu keyserver.
Different key ID formats are supported by SKS keyservers (the longer ones
are more secure, see "dead beef attack" and https://evil32.com/). Since
HTTPS is used, if SSLBump-like HTTPS proxies are in place, they will
imper... | [
"def",
"_get_key_by_keyid",
"(",
"keyid",
")",
":",
"# options=mr - machine-readable output (disables html wrappers)",
"keyserver_url",
"=",
"(",
"'https://keyserver.ubuntu.com'",
"'/pks/lookup?op=get&options=mr&exact=on&search=0x{}'",
")",
"curl_cmd",
"=",
"[",
"'curl'",
",",
"k... | 53.823529 | 0.000537 |
def nvmlDeviceGetTotalEccErrors(handle, errorType, counterType):
r"""
/**
* Retrieves the total ECC error counts for the device.
*
* For Fermi &tm; or newer fully supported devices.
* Only applicable to devices with ECC.
* Requires \a NVML_INFOROM_ECC version 1.0 or higher.
* Requi... | [
"def",
"nvmlDeviceGetTotalEccErrors",
"(",
"handle",
",",
"errorType",
",",
"counterType",
")",
":",
"c_count",
"=",
"c_ulonglong",
"(",
")",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlDeviceGetTotalEccErrors\"",
")",
"ret",
"=",
"fn",
"(",
"handle",
",",
... | 53 | 0.007601 |
def _run_chunk(self, chunk, kernel_options, device_options, tuning_options):
"""Benchmark a single kernel instance in the parameter space"""
#detect language and create high-level device interface
self.dev = DeviceInterface(kernel_options.kernel_string, iterations=tuning_options.iterations, **d... | [
"def",
"_run_chunk",
"(",
"self",
",",
"chunk",
",",
"kernel_options",
",",
"device_options",
",",
"tuning_options",
")",
":",
"#detect language and create high-level device interface",
"self",
".",
"dev",
"=",
"DeviceInterface",
"(",
"kernel_options",
".",
"kernel_stri... | 37 | 0.007684 |
def get_routertypes(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
"""Lists defined router types."""
pass | [
"def",
"get_routertypes",
"(",
"self",
",",
"context",
",",
"filters",
"=",
"None",
",",
"fields",
"=",
"None",
",",
"sorts",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"page_reverse",
"=",
"False",
")",
":",
"pass"
] | 43.6 | 0.018018 |
def require_condition(cls, expr, message, *format_args, **format_kwds):
"""
used to assert a certain state. If the expression renders a false
value, an exception will be raised with the supplied message
:param: message: The failure message to attach to the raised Buzz
:param... | [
"def",
"require_condition",
"(",
"cls",
",",
"expr",
",",
"message",
",",
"*",
"format_args",
",",
"*",
"*",
"format_kwds",
")",
":",
"if",
"not",
"expr",
":",
"raise",
"cls",
"(",
"message",
",",
"*",
"format_args",
",",
"*",
"*",
"format_kwds",
")"
] | 51.916667 | 0.003155 |
def update(self, callback=None, errback=None, parent=True, **kwargs):
"""
Update address configuration. Pass a list of keywords and their values to
update. For the list of keywords available for address configuration, see :attr:`ns1.rest.ipam.Addresses.INT_FIELDS` and :attr:`ns1.rest.ipam.Addres... | [
"def",
"update",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"parent",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"data",
":",
"raise",
"AddressException",
"(",
"'Address not loaded'",
")"... | 47.1875 | 0.004543 |
def session(self):
"""
This is what you should use to make requests. It sill authenticate for you.
:return: requests.sessions.Session
"""
if not self._session:
self._session = requests.Session()
self._session.headers.update(dict(Authorization='Bearer {0}'... | [
"def",
"session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_session",
":",
"self",
".",
"_session",
"=",
"requests",
".",
"Session",
"(",
")",
"self",
".",
"_session",
".",
"headers",
".",
"update",
"(",
"dict",
"(",
"Authorization",
"=",
"'... | 40.222222 | 0.010811 |
def uniqify(list_):
"inefficient on long lists; short lists only. preserves order."
a=[]
for x in list_:
if x not in a: a.append(x)
return a | [
"def",
"uniqify",
"(",
"list_",
")",
":",
"a",
"=",
"[",
"]",
"for",
"x",
"in",
"list_",
":",
"if",
"x",
"not",
"in",
"a",
":",
"a",
".",
"append",
"(",
"x",
")",
"return",
"a"
] | 24.5 | 0.046053 |
def get_times_from_utterance(utterance: str,
char_offset_to_token_index: Dict[int, int],
indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]:
"""
Given an utterance, we get the numbers that correspond to times and convert them to
values t... | [
"def",
"get_times_from_utterance",
"(",
"utterance",
":",
"str",
",",
"char_offset_to_token_index",
":",
"Dict",
"[",
"int",
",",
"int",
"]",
",",
"indices_of_approximate_words",
":",
"Set",
"[",
"int",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
... | 49.243902 | 0.003885 |
def check(cls, model, require_extra=False):
"""Check whether the provided model has this capability.
By default, uses isinstance. If `require_extra`, also requires that an
instance check be present in `model.extra_capability_checks`.
"""
class_capable = isinstance(model, cls)
... | [
"def",
"check",
"(",
"cls",
",",
"model",
",",
"require_extra",
"=",
"False",
")",
":",
"class_capable",
"=",
"isinstance",
"(",
"model",
",",
"cls",
")",
"f_name",
"=",
"model",
".",
"extra_capability_checks",
".",
"get",
"(",
"cls",
",",
"None",
")",
... | 35.45 | 0.002747 |
def is_local_source(filename, modname, experiment_path):
"""Check if a module comes from the given experiment path.
Check if a module, given by name and filename, is from (a subdirectory of )
the given experiment path.
This is used to determine if the module is a local source file, or rather
a pack... | [
"def",
"is_local_source",
"(",
"filename",
",",
"modname",
",",
"experiment_path",
")",
":",
"if",
"not",
"is_subdir",
"(",
"filename",
",",
"experiment_path",
")",
":",
"return",
"False",
"rel_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"filename",
... | 34.72973 | 0.000757 |
def _get_method_wrappers(cls):
"""
Find the appropriate operation-wrappers to use when defining flex/special
arithmetic, boolean, and comparison operations with the given class.
Parameters
----------
cls : class
Returns
-------
arith_flex : function or None
comp_flex : function... | [
"def",
"_get_method_wrappers",
"(",
"cls",
")",
":",
"if",
"issubclass",
"(",
"cls",
",",
"ABCSparseSeries",
")",
":",
"# Be sure to catch this before ABCSeries and ABCSparseArray,",
"# as they will both come see SparseSeries as a subclass",
"arith_flex",
"=",
"_flex_method_SERIE... | 36.403509 | 0.000469 |
def match(self, p_todo):
"""
Performs a match on a key:value tag in the todo.
First it tries to convert the value and the user-entered expression to
a date and makes a comparison if it succeeds, based on the given
operator (default ==).
Upon failure, it falls back to con... | [
"def",
"match",
"(",
"self",
",",
"p_todo",
")",
":",
"def",
"resort_to_grep_filter",
"(",
")",
":",
"grep",
"=",
"GrepFilter",
"(",
"self",
".",
"expression",
")",
"return",
"grep",
".",
"match",
"(",
"p_todo",
")",
"if",
"not",
"self",
".",
"key",
... | 37.139535 | 0.00122 |
def linefeed(self):
"""Perform an index and, if :data:`~pyte.modes.LNM` is set, a
carriage return.
"""
self.index()
if mo.LNM in self.mode:
self.carriage_return() | [
"def",
"linefeed",
"(",
"self",
")",
":",
"self",
".",
"index",
"(",
")",
"if",
"mo",
".",
"LNM",
"in",
"self",
".",
"mode",
":",
"self",
".",
"carriage_return",
"(",
")"
] | 26 | 0.009302 |
def delete_table_rate_rule_by_id(cls, table_rate_rule_id, **kwargs):
"""Delete TableRateRule
Delete an instance of TableRateRule by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.dele... | [
"def",
"delete_table_rate_rule_by_id",
"(",
"cls",
",",
"table_rate_rule_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_delete... | 45.238095 | 0.006186 |
def as_items(self, decode=False):
"""
Return a list of 2-tuples consisting of key/score.
"""
items = self.database.zrange(self.key, 0, -1, withscores=True)
if decode:
items = [(_decode(k), score) for k, score in items]
return items | [
"def",
"as_items",
"(",
"self",
",",
"decode",
"=",
"False",
")",
":",
"items",
"=",
"self",
".",
"database",
".",
"zrange",
"(",
"self",
".",
"key",
",",
"0",
",",
"-",
"1",
",",
"withscores",
"=",
"True",
")",
"if",
"decode",
":",
"items",
"=",... | 35.5 | 0.006873 |
def _add_externalData(self):
"""
Always add a ``<c:autoUpdate val="0"/>`` child so auto-updating
behavior is off by default.
"""
externalData = self._new_externalData()
externalData._add_autoUpdate(val=False)
self._insert_externalData(externalData)
return ... | [
"def",
"_add_externalData",
"(",
"self",
")",
":",
"externalData",
"=",
"self",
".",
"_new_externalData",
"(",
")",
"externalData",
".",
"_add_autoUpdate",
"(",
"val",
"=",
"False",
")",
"self",
".",
"_insert_externalData",
"(",
"externalData",
")",
"return",
... | 36 | 0.006024 |
def create_map(self, pix):
"""Create a new map with reference pixel coordinates shifted
to the pixel coordinates ``pix``.
Parameters
----------
pix : `~numpy.ndarray`
Reference pixel of new map.
Returns
-------
out_map : `~numpy.ndarray`
... | [
"def",
"create_map",
"(",
"self",
",",
"pix",
")",
":",
"k0",
"=",
"self",
".",
"_m0",
".",
"shift_to_coords",
"(",
"pix",
")",
"k1",
"=",
"self",
".",
"_m1",
".",
"shift_to_coords",
"(",
"pix",
")",
"k0",
"[",
"np",
".",
"isfinite",
"(",
"k1",
"... | 26.65 | 0.005435 |
def validate_qubit_list(qubit_list):
"""
Check the validity of qubits for the payload.
:param list|range qubit_list: List of qubits to be validated.
"""
if not isinstance(qubit_list, (list, range)):
raise TypeError("run_items must be a list")
if any(not isinstance(i, integer_types) or i... | [
"def",
"validate_qubit_list",
"(",
"qubit_list",
")",
":",
"if",
"not",
"isinstance",
"(",
"qubit_list",
",",
"(",
"list",
",",
"range",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"run_items must be a list\"",
")",
"if",
"any",
"(",
"not",
"isinstance",
"("... | 39.727273 | 0.002237 |
def assert_is_lon(val):
"""
Checks it the given value is a feasible decimal longitude
:param val: value to be checked
:type val: int of float
:returns: `None`
:raises: *ValueError* if value is out of longitude boundaries, *AssertionError* if type is wrong
"""
assert type(val) is float... | [
"def",
"assert_is_lon",
"(",
"val",
")",
":",
"assert",
"type",
"(",
"val",
")",
"is",
"float",
"or",
"type",
"(",
"val",
")",
"is",
"int",
",",
"\"Value must be a number\"",
"if",
"val",
"<",
"-",
"180.0",
"or",
"val",
">",
"180.0",
":",
"raise",
"V... | 35.615385 | 0.004211 |
def duplicate_line(self):
"""
Duplicates the line under the cursor. If multiple lines are selected,
only the last one is duplicated.
"""
cursor = self.textCursor()
assert isinstance(cursor, QtGui.QTextCursor)
has_selection = True
if not cursor.hasSelection... | [
"def",
"duplicate_line",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"assert",
"isinstance",
"(",
"cursor",
",",
"QtGui",
".",
"QTextCursor",
")",
"has_selection",
"=",
"True",
"if",
"not",
"cursor",
".",
"hasSelection",
"(",... | 35.583333 | 0.002281 |
def get_object_ids(model, meteor_ids):
"""Return all object IDs for the given meteor_ids."""
if model is ObjectMapping:
# this doesn't make sense - raise TypeError
raise TypeError("Can't map ObjectMapping instances through self.")
# Django model._meta is now public API -> pylint: disable=W02... | [
"def",
"get_object_ids",
"(",
"model",
",",
"meteor_ids",
")",
":",
"if",
"model",
"is",
"ObjectMapping",
":",
"# this doesn't make sense - raise TypeError",
"raise",
"TypeError",
"(",
"\"Can't map ObjectMapping instances through self.\"",
")",
"# Django model._meta is now publ... | 36.741935 | 0.000855 |
def _perform_validation(self, path, value, results):
"""
Validates a given value against the schema and configured validation rules.
:param path: a dot notation path to the value.
:param value: a value to be validated.
:param results: a list with validation results to add new ... | [
"def",
"_perform_validation",
"(",
"self",
",",
"path",
",",
"value",
",",
"results",
")",
":",
"name",
"=",
"path",
"if",
"path",
"!=",
"None",
"else",
"\"value\"",
"value",
"=",
"ObjectReader",
".",
"get_value",
"(",
"value",
")",
"super",
"(",
"MapSch... | 34.771429 | 0.007194 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'deployment') and self.deployment is not None:
_dict['deployment'] = self.deployment
if hasattr(self, 'user_id') and self.user_id is not None:
_dict['user_id'] ... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'deployment'",
")",
"and",
"self",
".",
"deployment",
"is",
"not",
"None",
":",
"_dict",
"[",
"'deployment'",
"]",
"=",
"self",
".",
"deployment",
"... | 43.5 | 0.005634 |
def adjoin(space: int, *lists: Sequence[str]) -> str:
"""Glue together two sets of strings using `space`."""
lengths = [max(map(len, x)) + space for x in lists[:-1]]
# not the last one
lengths.append(max(map(len, lists[-1])))
max_len = max(map(len, lists))
chains = (
itertools.chain(
... | [
"def",
"adjoin",
"(",
"space",
":",
"int",
",",
"*",
"lists",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"str",
":",
"lengths",
"=",
"[",
"max",
"(",
"map",
"(",
"len",
",",
"x",
")",
")",
"+",
"space",
"for",
"x",
"in",
"lists",
"[",
":",
... | 34.866667 | 0.001862 |
def hasnew(self,allowempty=False):
"""Does the correction define new corrected annotations?"""
for e in self.select(New,None,False, False):
if not allowempty and len(e) == 0: continue
return True
return False | [
"def",
"hasnew",
"(",
"self",
",",
"allowempty",
"=",
"False",
")",
":",
"for",
"e",
"in",
"self",
".",
"select",
"(",
"New",
",",
"None",
",",
"False",
",",
"False",
")",
":",
"if",
"not",
"allowempty",
"and",
"len",
"(",
"e",
")",
"==",
"0",
... | 42 | 0.027237 |
def next_window(self, widget, data=None):
"""
Function opens the run Window who executes the
assistant project creation
"""
# check whether deps-only is selected
deps_only = ('deps_only' in self.args and self.args['deps_only']['checkbox'].get_active())
# preserve... | [
"def",
"next_window",
"(",
"self",
",",
"widget",
",",
"data",
"=",
"None",
")",
":",
"# check whether deps-only is selected",
"deps_only",
"=",
"(",
"'deps_only'",
"in",
"self",
".",
"args",
"and",
"self",
".",
"args",
"[",
"'deps_only'",
"]",
"[",
"'checkb... | 45.516667 | 0.002867 |
def rankagg_R(df, method="stuart"):
"""Return aggregated ranks as implemented in the RobustRankAgg R package.
This function is now deprecated.
References:
Kolde et al., 2012, DOI: 10.1093/bioinformatics/btr709
Stuart et al., 2003, DOI: 10.1126/science.1087447
Parameters
--------... | [
"def",
"rankagg_R",
"(",
"df",
",",
"method",
"=",
"\"stuart\"",
")",
":",
"tmpdf",
"=",
"NamedTemporaryFile",
"(",
")",
"tmpscript",
"=",
"NamedTemporaryFile",
"(",
"mode",
"=",
"\"w\"",
")",
"tmpranks",
"=",
"NamedTemporaryFile",
"(",
")",
"df",
".",
"to... | 30.051282 | 0.01405 |
def rhochange(self):
"""Re-factorise matrix when rho changes"""
self.lu, self.piv = sl.lu_factor(self.Z, self.rho)
self.lu = np.asarray(self.lu, dtype=self.dtype) | [
"def",
"rhochange",
"(",
"self",
")",
":",
"self",
".",
"lu",
",",
"self",
".",
"piv",
"=",
"sl",
".",
"lu_factor",
"(",
"self",
".",
"Z",
",",
"self",
".",
"rho",
")",
"self",
".",
"lu",
"=",
"np",
".",
"asarray",
"(",
"self",
".",
"lu",
","... | 36.6 | 0.010695 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.