text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def three_d_effect(img, **kwargs):
"""Create 3D effect using convolution"""
w = kwargs.get('weight', 1)
LOG.debug("Applying 3D effect with weight %.2f", w)
kernel = np.array([[-w, 0, w],
[-w, 1, w],
[-w, 0, w]])
mode = kwargs.get('convolve_mode', 'same')... | [
"def",
"three_d_effect",
"(",
"img",
",",
"*",
"*",
"kwargs",
")",
":",
"w",
"=",
"kwargs",
".",
"get",
"(",
"'weight'",
",",
"1",
")",
"LOG",
".",
"debug",
"(",
"\"Applying 3D effect with weight %.2f\"",
",",
"w",
")",
"kernel",
"=",
"np",
".",
"array... | 38.529412 | 20.882353 |
def config_attributes(self):
"""
Helper method used by TorConfig when generating a torrc file.
"""
rtn = [('HiddenServiceDir', str(self.dir))]
if self.conf._supports['HiddenServiceDirGroupReadable'] \
and self.group_readable:
rtn.append(('HiddenServiceDirG... | [
"def",
"config_attributes",
"(",
"self",
")",
":",
"rtn",
"=",
"[",
"(",
"'HiddenServiceDir'",
",",
"str",
"(",
"self",
".",
"dir",
")",
")",
"]",
"if",
"self",
".",
"conf",
".",
"_supports",
"[",
"'HiddenServiceDirGroupReadable'",
"]",
"and",
"self",
".... | 40.5 | 17.125 |
def get_logical_plan(cluster, environ, topology, role=None):
'''
Get the logical plan state of a topology in a cluster
:param cluster:
:param environ:
:param topology:
:param role:
:return:
'''
params = dict(cluster=cluster, environ=environ, topology=topology)
if role is not None:
params['role']... | [
"def",
"get_logical_plan",
"(",
"cluster",
",",
"environ",
",",
"topology",
",",
"role",
"=",
"None",
")",
":",
"params",
"=",
"dict",
"(",
"cluster",
"=",
"cluster",
",",
"environ",
"=",
"environ",
",",
"topology",
"=",
"topology",
")",
"if",
"role",
... | 31.466667 | 21.733333 |
def get_default_jvm_opts(tmp_dir=None, parallel_gc=False):
"""Retrieve default JVM tuning options
Avoids issues with multiple spun up Java processes running into out of memory errors.
Parallel GC can use a lot of cores on big machines and primarily helps reduce task latency
and responsiveness which are... | [
"def",
"get_default_jvm_opts",
"(",
"tmp_dir",
"=",
"None",
",",
"parallel_gc",
"=",
"False",
")",
":",
"opts",
"=",
"[",
"\"-XX:+UseSerialGC\"",
"]",
"if",
"not",
"parallel_gc",
"else",
"[",
"]",
"if",
"tmp_dir",
":",
"opts",
".",
"append",
"(",
"\"-Djava... | 57.8125 | 31 |
def validate_id(tx_body):
"""Validate the transaction ID of a transaction
Args:
tx_body (dict): The Transaction to be transformed.
"""
# NOTE: Remove reference to avoid side effects
# tx_body = deepcopy(tx_body)
tx_body = rapidjson.loads(rapidjson.dum... | [
"def",
"validate_id",
"(",
"tx_body",
")",
":",
"# NOTE: Remove reference to avoid side effects",
"# tx_body = deepcopy(tx_body)",
"tx_body",
"=",
"rapidjson",
".",
"loads",
"(",
"rapidjson",
".",
"dumps",
"(",
"tx_body",
")",
")",
"try",
":",
"proposed_tx_id",
"=",
... | 35.083333 | 20.416667 |
def bresenham_line(self, x0, y0, x1, y1, color=None, colorFunc=None):
"""
Draw line from point x0, y0 to x1, y1 using Bresenham's algorithm.
Will draw beyond matrix bounds.
"""
md.bresenham_line(self.set, x0, y0, x1, y1, color, colorFunc) | [
"def",
"bresenham_line",
"(",
"self",
",",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
",",
"color",
"=",
"None",
",",
"colorFunc",
"=",
"None",
")",
":",
"md",
".",
"bresenham_line",
"(",
"self",
".",
"set",
",",
"x0",
",",
"y0",
",",
"x1",
",",
"y... | 39 | 19 |
def evaluate(self, values):
''' Evaluates the expression to an integer
values is a dictionnary that associates n-bit variables to integer
values. Every symbolic variables used in the expression must be
represented.
For instance, let x and y 4-bit variables, and e = x+y:
... | [
"def",
"evaluate",
"(",
"self",
",",
"values",
")",
":",
"ret",
"=",
"self",
".",
"mba",
".",
"evaluate",
"(",
"self",
".",
"vec",
",",
"values",
")",
"if",
"isinstance",
"(",
"ret",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"ret",
"ret... | 29.769231 | 22.461538 |
def clear_mappers():
"""
Clears all mappers set up by SA and also clears all custom "id" and
"slug" attributes inserted by the :func:`mapper` function in this module.
This should only ever be needed in a testing context.
"""
# Remove our hybrid property constructs.
for mpr, is_primary in _m... | [
"def",
"clear_mappers",
"(",
")",
":",
"# Remove our hybrid property constructs.",
"for",
"mpr",
",",
"is_primary",
"in",
"_mapper_registry",
".",
"items",
"(",
")",
":",
"if",
"is_primary",
":",
"for",
"attr_name",
"in",
"(",
"'id'",
",",
"'slug'",
")",
":",
... | 40.095238 | 17.047619 |
def matching(self, packages):
"""Message for matching packages
"""
print("\nNot found package with the name [ {0}{1}{2} ]. "
"Matching packages:\nNOTE: Not dependenc"
"ies are resolved\n".format(self.meta.color["CYAN"],
"".joi... | [
"def",
"matching",
"(",
"self",
",",
"packages",
")",
":",
"print",
"(",
"\"\\nNot found package with the name [ {0}{1}{2} ]. \"",
"\"Matching packages:\\nNOTE: Not dependenc\"",
"\"ies are resolved\\n\"",
".",
"format",
"(",
"self",
".",
"meta",
".",
"color",
"[",
"\"CYA... | 49.125 | 15.5 |
def getobjpath(obj, path):
"""Returns an item or attribute of the object recursively.
Item names are specified between brackets, eg: [item].
Attribute names are prefixed with a dot (the first one is optional), eg: .attr
Example: getobjpath(obj, "attr1.attr2[item].attr3")
"""
if not path:
... | [
"def",
"getobjpath",
"(",
"obj",
",",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"obj",
"if",
"path",
".",
"startswith",
"(",
"\"[\"",
")",
":",
"item",
"=",
"path",
"[",
"1",
":",
"path",
".",
"index",
"(",
"\"]\"",
")",
"]",
"return"... | 35.6 | 13.96 |
def _get_traceback_no_io():
"""
Return a version of L{traceback} that doesn't do I/O.
"""
try:
module = load_module(str("_traceback_no_io"), traceback)
except NotImplementedError:
# Can't fix the I/O problem, oh well:
return traceback
class FakeLineCache(object):
... | [
"def",
"_get_traceback_no_io",
"(",
")",
":",
"try",
":",
"module",
"=",
"load_module",
"(",
"str",
"(",
"\"_traceback_no_io\"",
")",
",",
"traceback",
")",
"except",
"NotImplementedError",
":",
"# Can't fix the I/O problem, oh well:",
"return",
"traceback",
"class",
... | 25.045455 | 17.409091 |
def configure_user(self, user, attributes, attribute_mapping):
"""Configures a user after creation and returns the updated user.
By default, returns the user with his attributes updated.
"""
user.set_unusable_password()
return self.update_user(user, attributes, attribute_mapping... | [
"def",
"configure_user",
"(",
"self",
",",
"user",
",",
"attributes",
",",
"attribute_mapping",
")",
":",
"user",
".",
"set_unusable_password",
"(",
")",
"return",
"self",
".",
"update_user",
"(",
"user",
",",
"attributes",
",",
"attribute_mapping",
",",
"forc... | 45.375 | 15.875 |
def _load_string_from_native_memory(self, addr_):
"""
Load zero terminated UTF-8 string from native memory.
:param addr_: Native load address.
:return: Loaded string.
"""
# check if addr is symbolic
if self.state.solver.symbolic(addr_):
l.error("... | [
"def",
"_load_string_from_native_memory",
"(",
"self",
",",
"addr_",
")",
":",
"# check if addr is symbolic",
"if",
"self",
".",
"state",
".",
"solver",
".",
"symbolic",
"(",
"addr_",
")",
":",
"l",
".",
"error",
"(",
"\"Loading strings from symbolic addresses is no... | 37.444444 | 16.333333 |
def user_id(self):
"""Who created the event (:class:`~hangups.user.UserID`)."""
return user.UserID(chat_id=self._event.sender_id.chat_id,
gaia_id=self._event.sender_id.gaia_id) | [
"def",
"user_id",
"(",
"self",
")",
":",
"return",
"user",
".",
"UserID",
"(",
"chat_id",
"=",
"self",
".",
"_event",
".",
"sender_id",
".",
"chat_id",
",",
"gaia_id",
"=",
"self",
".",
"_event",
".",
"sender_id",
".",
"gaia_id",
")"
] | 54 | 18 |
def open(self):
"""Retrieve this file's attributes from the server.
Returns a Future.
.. versionchanged:: 2.0
No longer accepts a callback argument.
.. versionchanged:: 0.2
:class:`~motor.MotorGridOut` now opens itself on demand, calling
``open`` expli... | [
"def",
"open",
"(",
"self",
")",
":",
"return",
"self",
".",
"_framework",
".",
"chain_return_value",
"(",
"self",
".",
"_ensure_file",
"(",
")",
",",
"self",
".",
"get_io_loop",
"(",
")",
",",
"self",
")"
] | 35.866667 | 20.266667 |
def generate_VJ_junction_transfer_matrices(self):
"""Compute the transfer matrices for the VJ junction.
Sets the attributes Tvj, Svj, Dvj, lTvj, and lDvj.
"""
nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
#Compute Tvj
Tv... | [
"def",
"generate_VJ_junction_transfer_matrices",
"(",
"self",
")",
":",
"nt2num",
"=",
"{",
"'A'",
":",
"0",
",",
"'C'",
":",
"1",
",",
"'G'",
":",
"2",
",",
"'T'",
":",
"3",
"}",
"#Compute Tvj",
"Tvj",
"=",
"{",
"}",
"for",
"aa",
"in",
"self",
"."... | 39.627119 | 22.949153 |
def hazard_class_style(layer, classification, display_null=False):
"""Set colors to the layer according to the hazard.
:param layer: The layer to style.
:type layer: QgsVectorLayer
:param display_null: If we should display the null hazard zone. Default to
False.
:type display_null: bool
... | [
"def",
"hazard_class_style",
"(",
"layer",
",",
"classification",
",",
"display_null",
"=",
"False",
")",
":",
"categories",
"=",
"[",
"]",
"# Conditional styling",
"attribute_table_styles",
"=",
"[",
"]",
"for",
"hazard_class",
",",
"(",
"color",
",",
"label",
... | 35.673913 | 18.847826 |
def generate_folds(node_label_matrix, labelled_node_indices, number_of_categories, percentage, number_of_folds=10):
"""
Form the seed nodes for training and testing.
Inputs: - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format.
- labelled_node_indices: A NumPy arra... | [
"def",
"generate_folds",
"(",
"node_label_matrix",
",",
"labelled_node_indices",
",",
"number_of_categories",
",",
"percentage",
",",
"number_of_folds",
"=",
"10",
")",
":",
"number_of_labeled_nodes",
"=",
"labelled_node_indices",
".",
"size",
"training_set_size",
"=",
... | 49.03125 | 29.65625 |
def compare_orderings(info_frags_records, linkage_orderings):
"""Given linkage groups and info_frags records, link pseudo-chromosomes to
scaffolds based on the initial contig composition of each group. Because
info_frags records are usually richer and may contain contigs not found
in linkage groups, th... | [
"def",
"compare_orderings",
"(",
"info_frags_records",
",",
"linkage_orderings",
")",
":",
"scaffolds",
"=",
"info_frags_records",
".",
"keys",
"(",
")",
"linkage_groups",
"=",
"linkage_orderings",
".",
"keys",
"(",
")",
"best_matching_table",
"=",
"dict",
"(",
")... | 36.683673 | 18.204082 |
def configure_crud(graph, ns, mappings):
"""
Register CRUD endpoints for a resource object.
:param mappings: a dictionary from operations to tuple, where each tuple contains
the target function and zero or more marshmallow schemas according
to the signature of the ... | [
"def",
"configure_crud",
"(",
"graph",
",",
"ns",
",",
"mappings",
")",
":",
"convention",
"=",
"CRUDConvention",
"(",
"graph",
")",
"convention",
".",
"configure",
"(",
"ns",
",",
"mappings",
")"
] | 37.2 | 25.1 |
def _delete(
self, sock_info, criteria, multi,
write_concern=None, op_id=None, ordered=True,
collation=None, session=None, retryable_write=False):
"""Internal delete helper."""
common.validate_is_mapping("filter", criteria)
write_concern = write_concern or sel... | [
"def",
"_delete",
"(",
"self",
",",
"sock_info",
",",
"criteria",
",",
"multi",
",",
"write_concern",
"=",
"None",
",",
"op_id",
"=",
"None",
",",
"ordered",
"=",
"True",
",",
"collation",
"=",
"None",
",",
"session",
"=",
"None",
",",
"retryable_write",... | 43.555556 | 12.6 |
def pop(self):
"""Pop the next future from the queue;
in progress futures have priority over those that have not yet started;
higher level futures have priority over lower level ones; """
self.updateQueue()
# If our buffer is underflowing, request more Futures
if self.ti... | [
"def",
"pop",
"(",
"self",
")",
":",
"self",
".",
"updateQueue",
"(",
")",
"# If our buffer is underflowing, request more Futures",
"if",
"self",
".",
"timelen",
"(",
"self",
")",
"<",
"self",
".",
"lowwatermark",
":",
"self",
".",
"requestFuture",
"(",
")",
... | 38.482759 | 12.793103 |
def execute_and_recommend(self, drop_doses=False):
"""
Execute and recommend a best-fitting model. If drop_doses and no model
is recommended, drop the highest dose-group and repeat until either:
1. a model is recommended, or
2. the dataset is exhausted (i.e., only 3 dose-groups ... | [
"def",
"execute_and_recommend",
"(",
"self",
",",
"drop_doses",
"=",
"False",
")",
":",
"self",
".",
"execute",
"(",
")",
"self",
".",
"recommend",
"(",
")",
"if",
"not",
"drop_doses",
":",
"return",
"while",
"self",
".",
"recommended_model",
"is",
"None",... | 37.869565 | 23.695652 |
def resize(mountpoint, size):
'''
Resize filesystem.
General options:
* **mountpoint**: Specify the BTRFS mountpoint to resize.
* **size**: ([+/-]<newsize>[kKmMgGtTpPeE]|max) Specify the new size of the target.
CLI Example:
.. code-block:: bash
salt '*' btrfs.resize /mountpoint ... | [
"def",
"resize",
"(",
"mountpoint",
",",
"size",
")",
":",
"if",
"size",
"==",
"'max'",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_is_device",
"(",
"mountpoint",
")",
":",
"raise",
"CommandExecutionError",
"(",
"\"Mountpoint \\\"{0}\\\" s... | 36.030303 | 30.515152 |
def cancel_scheduled_hangup(self, call_params):
"""REST Cancel a Scheduled Hangup Helper
"""
path = '/' + self.api_version + '/CancelScheduledHangup/'
method = 'POST'
return self.request(path, method, call_params) | [
"def",
"cancel_scheduled_hangup",
"(",
"self",
",",
"call_params",
")",
":",
"path",
"=",
"'/'",
"+",
"self",
".",
"api_version",
"+",
"'/CancelScheduledHangup/'",
"method",
"=",
"'POST'",
"return",
"self",
".",
"request",
"(",
"path",
",",
"method",
",",
"c... | 41.333333 | 10.5 |
def put(self, request, bot_id, id, format=None):
"""
Update existing Messenger chat state
---
serializer: MessengerChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid reque... | [
"def",
"put",
"(",
"self",
",",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
"=",
"None",
")",
":",
"return",
"super",
"(",
"MessengerChatStateDetail",
",",
"self",
")",
".",
"put",
"(",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
")"
... | 34.083333 | 11.916667 |
def _setup(app, *, schema, title=None, app_key=APP_KEY, db=None):
"""Initialize the admin-on-rest admin"""
admin = web.Application(loop=app.loop)
app[app_key] = admin
loader = jinja2.FileSystemLoader([TEMPLATES_ROOT, ])
aiohttp_jinja2.setup(admin, loader=loader, app_key=TEMPLATE_APP_KEY)
if t... | [
"def",
"_setup",
"(",
"app",
",",
"*",
",",
"schema",
",",
"title",
"=",
"None",
",",
"app_key",
"=",
"APP_KEY",
",",
"db",
"=",
"None",
")",
":",
"admin",
"=",
"web",
".",
"Application",
"(",
"loop",
"=",
"app",
".",
"loop",
")",
"app",
"[",
"... | 25.888889 | 21.814815 |
def formatTimeFromNow(secs=None):
""" Properly Format Time that is `x` seconds in the future
:param int secs: Seconds to go in the future (`x>0`) or the
past (`x<0`)
:return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`)
:rtype: str
"""
return d... | [
"def",
"formatTimeFromNow",
"(",
"secs",
"=",
"None",
")",
":",
"return",
"datetime",
".",
"utcfromtimestamp",
"(",
"time",
".",
"time",
"(",
")",
"+",
"int",
"(",
"secs",
"or",
"0",
")",
")",
".",
"strftime",
"(",
"timeFormat",
")"
] | 38.6 | 21.9 |
def dataset_exists(self, dataset):
"""Returns whether the given dataset exists.
If regional location is specified for the dataset, that is also checked
to be compatible with the remote dataset, otherwise an exception is thrown.
:param dataset:
:type dataset: BQDataset
... | [
"def",
"dataset_exists",
"(",
"self",
",",
"dataset",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"client",
".",
"datasets",
"(",
")",
".",
"get",
"(",
"projectId",
"=",
"dataset",
".",
"project_id",
",",
"datasetId",
"=",
"dataset",
".",
"data... | 41.72 | 24.48 |
def flatten_list(list_):
"""
Banana banana
"""
res = []
for elem in list_:
if isinstance(elem, list):
res.extend(flatten_list(elem))
else:
res.append(elem)
return res | [
"def",
"flatten_list",
"(",
"list_",
")",
":",
"res",
"=",
"[",
"]",
"for",
"elem",
"in",
"list_",
":",
"if",
"isinstance",
"(",
"elem",
",",
"list",
")",
":",
"res",
".",
"extend",
"(",
"flatten_list",
"(",
"elem",
")",
")",
"else",
":",
"res",
... | 16.923077 | 18.307692 |
def _put_model(D, name, dat, m):
"""
Place the model data given, into the location (m) given.
:param dict D: Metadata (dataset)
:param str name: Model name (ex: chron0model0)
:param dict dat: Model data
:param regex m: Model name regex groups
:return dict D: Metadata (dataset)
"""
t... | [
"def",
"_put_model",
"(",
"D",
",",
"name",
",",
"dat",
",",
"m",
")",
":",
"try",
":",
"# print(\"Placing model: {}\".format(name))",
"_pc",
"=",
"m",
".",
"group",
"(",
"1",
")",
"+",
"\"Data\"",
"_section",
"=",
"m",
".",
"group",
"(",
"1",
")",
"... | 42.416667 | 16.583333 |
def err_write(self, msg, **kwargs):
r"""Print `msg` as an error message.
The message is buffered (won't display) until linefeed ("\n").
"""
if self._thread_invalid():
# special case: if a non-main thread writes to stderr
# i.e. due to an uncaught exception, pass ... | [
"def",
"err_write",
"(",
"self",
",",
"msg",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_thread_invalid",
"(",
")",
":",
"# special case: if a non-main thread writes to stderr",
"# i.e. due to an uncaught exception, pass it through",
"# without raising an additi... | 42.75 | 17 |
def ReadClientFullInfo(self, client_id):
"""Reads full client information for a single client.
Args:
client_id: A GRR client id string, e.g. "C.ea3b2b71840d6fa7".
Returns:
A `ClientFullInfo` instance for given client.
Raises:
UnknownClientError: if no client with such id was found.
... | [
"def",
"ReadClientFullInfo",
"(",
"self",
",",
"client_id",
")",
":",
"result",
"=",
"self",
".",
"MultiReadClientFullInfo",
"(",
"[",
"client_id",
"]",
")",
"try",
":",
"return",
"result",
"[",
"client_id",
"]",
"except",
"KeyError",
":",
"raise",
"UnknownC... | 27.588235 | 20.294118 |
def _item_to_database(self, iterator, database_pb):
"""Convert a database protobuf to the native object.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type database_pb: :class:`~google.spanner.admin.database.v1... | [
"def",
"_item_to_database",
"(",
"self",
",",
"iterator",
",",
"database_pb",
")",
":",
"return",
"Database",
".",
"from_pb",
"(",
"database_pb",
",",
"self",
",",
"pool",
"=",
"BurstyPool",
"(",
")",
")"
] | 44.615385 | 23.769231 |
def connect(host='localhost', port=21050, database=None, timeout=None,
use_ssl=False, ca_cert=None, auth_mechanism='NOSASL', user=None,
password=None, kerberos_service_name='impala', use_ldap=None,
ldap_user=None, ldap_password=None, use_kerberos=None,
protocol=None, krb_... | [
"def",
"connect",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"21050",
",",
"database",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"use_ssl",
"=",
"False",
",",
"ca_cert",
"=",
"None",
",",
"auth_mechanism",
"=",
"'NOSASL'",
",",
"user",
"="... | 35.633028 | 20.12844 |
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
... | [
"def",
"create_cache_cluster",
"(",
"name",
",",
"wait",
"=",
"600",
",",
"security_groups",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
... | 54.571429 | 33.214286 |
def disconnect(self, message=""):
"""Hang up the connection.
Arguments:
message -- Quit message.
"""
try:
del self.connected
except AttributeError:
return
self.quit(message)
self.transport.close()
self._handle_event(... | [
"def",
"disconnect",
"(",
"self",
",",
"message",
"=",
"\"\"",
")",
":",
"try",
":",
"del",
"self",
".",
"connected",
"except",
"AttributeError",
":",
"return",
"self",
".",
"quit",
"(",
"message",
")",
"self",
".",
"transport",
".",
"close",
"(",
")",... | 22.0625 | 20.125 |
def hill_climbing(data, graph, **kwargs):
"""Hill Climbing optimization: a greedy exploration algorithm."""
nodelist = list(data.columns)
data = scale(data.values).astype('float32')
tested_candidates = [nx.adj_matrix(graph, nodelist=nodelist, weight=None)]
best_score = parallel_graph_evaluation(data... | [
"def",
"hill_climbing",
"(",
"data",
",",
"graph",
",",
"*",
"*",
"kwargs",
")",
":",
"nodelist",
"=",
"list",
"(",
"data",
".",
"columns",
")",
"data",
"=",
"scale",
"(",
"data",
".",
"values",
")",
".",
"astype",
"(",
"'float32'",
")",
"tested_cand... | 51.36 | 18.68 |
def _setLearningMode(self):
"""
Sets the learning mode.
"""
for region in self.L4Regions:
region.setParameter("learn", True)
for region in self.L2Regions:
region.setParameter("learningMode", True) | [
"def",
"_setLearningMode",
"(",
"self",
")",
":",
"for",
"region",
"in",
"self",
".",
"L4Regions",
":",
"region",
".",
"setParameter",
"(",
"\"learn\"",
",",
"True",
")",
"for",
"region",
"in",
"self",
".",
"L2Regions",
":",
"region",
".",
"setParameter",
... | 27.625 | 5.875 |
def load_all(stream, Loader=None):
"""
Parse all YAML documents in a stream
and produce corresponding Python objects.
"""
if Loader is None:
load_warning('load_all')
Loader = FullLoader
loader = Loader(stream)
try:
while loader.check_data():
yield loader.... | [
"def",
"load_all",
"(",
"stream",
",",
"Loader",
"=",
"None",
")",
":",
"if",
"Loader",
"is",
"None",
":",
"load_warning",
"(",
"'load_all'",
")",
"Loader",
"=",
"FullLoader",
"loader",
"=",
"Loader",
"(",
"stream",
")",
"try",
":",
"while",
"loader",
... | 23.6 | 12.666667 |
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if th... | [
"def",
"treat_values",
"(",
"simulated_array",
",",
"observed_array",
",",
"replace_nan",
"=",
"None",
",",
"replace_inf",
"=",
"None",
",",
"remove_neg",
"=",
"False",
",",
"remove_zero",
"=",
"False",
")",
":",
"sim_copy",
"=",
"np",
".",
"copy",
"(",
"s... | 48.084906 | 25.509434 |
def get_counter(self, redis_conn=None, host='localhost', port=6379,
key='counter', cycle_time=5, start_time=None,
window=SECONDS_1_HOUR, roll=True, keep_max=12, start_at=0):
'''
Generate a new Counter
Useful for generic distributed counters
@param... | [
"def",
"get_counter",
"(",
"self",
",",
"redis_conn",
"=",
"None",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"6379",
",",
"key",
"=",
"'counter'",
",",
"cycle_time",
"=",
"5",
",",
"start_time",
"=",
"None",
",",
"window",
"=",
"SECONDS_1_HOUR",... | 49.8 | 22.04 |
def dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=(-1,), normalize=False, verbosity=1):
"""Compose a pybrain.dataset from a pandas DataFrame
Arguments:
delays (list of int): sample delays to use for the input tapped delay line
Positive and negative values are treated the... | [
"def",
"dataset_from_dataframe",
"(",
"df",
",",
"delays",
"=",
"(",
"1",
",",
"2",
",",
"3",
")",
",",
"inputs",
"=",
"(",
"1",
",",
"2",
",",
"-",
"1",
")",
",",
"outputs",
"=",
"(",
"-",
"1",
",",
")",
",",
"normalize",
"=",
"False",
",",
... | 48.35 | 28.4875 |
def get_expiration_date(self):
"""
Get the expiration date from the database.
:return: The expiration date from the database.
:rtype: str|None
"""
if self._authorization() and self.is_in_database() and not self.is_time_older():
# * We are authorized to work.... | [
"def",
"get_expiration_date",
"(",
"self",
")",
":",
"if",
"self",
".",
"_authorization",
"(",
")",
"and",
"self",
".",
"is_in_database",
"(",
")",
"and",
"not",
"self",
".",
"is_time_older",
"(",
")",
":",
"# * We are authorized to work.",
"# and",
"# * The e... | 32.482759 | 21.172414 |
def _shouldConnect(self, node):
"""
Check whether this node should initiate a connection to another node
:param node: the other node
:type node: Node
"""
return isinstance(node, TCPNode) and node not in self._preventConnectNodes and (self._selfIsReadonlyNode or self._se... | [
"def",
"_shouldConnect",
"(",
"self",
",",
"node",
")",
":",
"return",
"isinstance",
"(",
"node",
",",
"TCPNode",
")",
"and",
"node",
"not",
"in",
"self",
".",
"_preventConnectNodes",
"and",
"(",
"self",
".",
"_selfIsReadonlyNode",
"or",
"self",
".",
"_sel... | 38 | 28.888889 |
def transform(self, data):
"""
Transforms the data.
"""
if not self._get("fitted"):
raise RuntimeError("`transform` called before `fit` or `fit_transform`.")
data = data.copy()
output_column_prefix = self._get("output_column_prefix")
if output_colum... | [
"def",
"transform",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"self",
".",
"_get",
"(",
"\"fitted\"",
")",
":",
"raise",
"RuntimeError",
"(",
"\"`transform` called before `fit` or `fit_transform`.\"",
")",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"... | 28.48 | 22.56 |
def connect(cls, database: str, user: str, password: str, host: str, port: int, *, use_pool: bool=True,
enable_ssl: bool=False, minsize=1, maxsize=50, keepalives_idle=5, keepalives_interval=4, echo=False,
**kwargs):
"""
Sets connection parameters
For more informat... | [
"def",
"connect",
"(",
"cls",
",",
"database",
":",
"str",
",",
"user",
":",
"str",
",",
"password",
":",
"str",
",",
"host",
":",
"str",
",",
"port",
":",
"int",
",",
"*",
",",
"use_pool",
":",
"bool",
"=",
"True",
",",
"enable_ssl",
":",
"bool"... | 53.619048 | 19.047619 |
def create_for_collection_items(item_type, hint):
"""
Helper method for collection items
:param item_type:
:return:
"""
# this leads to infinite loops
# try:
# prt_type = get_pretty_type_str(item_type)
# except:
# prt_type = str(it... | [
"def",
"create_for_collection_items",
"(",
"item_type",
",",
"hint",
")",
":",
"# this leads to infinite loops",
"# try:",
"# prt_type = get_pretty_type_str(item_type)",
"# except:",
"# prt_type = str(item_type)",
"return",
"TypeInformationRequiredError",
"(",
"\"Cannot parse... | 45.6875 | 25.6875 |
def all(user, groupby='week', summary='default', network=False,
split_week=False, split_day=False, filter_empty=True, attributes=True,
flatten=False):
"""
Returns a dictionary containing all bandicoot indicators for the user,
as well as reporting variables.
Relevant indicators are defin... | [
"def",
"all",
"(",
"user",
",",
"groupby",
"=",
"'week'",
",",
"summary",
"=",
"'default'",
",",
"network",
"=",
"False",
",",
"split_week",
"=",
"False",
",",
"split_day",
"=",
"False",
",",
"filter_empty",
"=",
"True",
",",
"attributes",
"=",
"True",
... | 48.457627 | 25.485876 |
def to_string(self, buf=None, format_abs_ref_as='string',
upper_triangle=True, header=True, index=True, **kwargs):
"""Render a DataFrame to a console-friendly tabular output.
Wrapper around the :meth:`pandas.DataFrame.to_string` method.
"""
out = self._sympy_formatter(... | [
"def",
"to_string",
"(",
"self",
",",
"buf",
"=",
"None",
",",
"format_abs_ref_as",
"=",
"'string'",
",",
"upper_triangle",
"=",
"True",
",",
"header",
"=",
"True",
",",
"index",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"self",
"."... | 46.428571 | 17.761905 |
def find(self, instance_id):
""" find an instance
Create a new instance and populate it with data stored if it exists.
Args:
instance_id (str): UUID of the instance
Returns:
AtlasServiceInstance.Instance: An instance
"""
... | [
"def",
"find",
"(",
"self",
",",
"instance_id",
")",
":",
"instance",
"=",
"AtlasServiceInstance",
".",
"Instance",
"(",
"instance_id",
",",
"self",
".",
"backend",
")",
"self",
".",
"backend",
".",
"storage",
".",
"populate",
"(",
"instance",
")",
"return... | 31.857143 | 19.928571 |
def _finalize(self, chain=-1):
"""Finalize the chain for all tallyable objects."""
chain = range(self.chains)[chain]
for name in self.trace_names[chain]:
self._traces[name]._finalize(chain)
self.commit() | [
"def",
"_finalize",
"(",
"self",
",",
"chain",
"=",
"-",
"1",
")",
":",
"chain",
"=",
"range",
"(",
"self",
".",
"chains",
")",
"[",
"chain",
"]",
"for",
"name",
"in",
"self",
".",
"trace_names",
"[",
"chain",
"]",
":",
"self",
".",
"_traces",
"[... | 40.333333 | 6.833333 |
def tournament(self,individuals,tourn_size, num_selections=None):
"""conducts tournament selection of size tourn_size"""
winners = []
locs = []
if num_selections is None:
num_selections = len(individuals)
for i in np.arange(num_selections):
# sample pool ... | [
"def",
"tournament",
"(",
"self",
",",
"individuals",
",",
"tourn_size",
",",
"num_selections",
"=",
"None",
")",
":",
"winners",
"=",
"[",
"]",
"locs",
"=",
"[",
"]",
"if",
"num_selections",
"is",
"None",
":",
"num_selections",
"=",
"len",
"(",
"individ... | 37.5 | 17.722222 |
def roll_dice(roll, *, functions=True, floats=True):
"""
Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice
:param roll: Roll in dice notation
:return: Result of roll, and an explanation string
"""
roll = ''.join(roll.split())
roll = regex.sub(r'(?<=d)%', ... | [
"def",
"roll_dice",
"(",
"roll",
",",
"*",
",",
"functions",
"=",
"True",
",",
"floats",
"=",
"True",
")",
":",
"roll",
"=",
"''",
".",
"join",
"(",
"roll",
".",
"split",
"(",
")",
")",
"roll",
"=",
"regex",
".",
"sub",
"(",
"r'(?<=d)%'",
",",
... | 49.420543 | 30.170543 |
def open(self):
"""Create a connection to the AWS API server. This can be reused for
sending multiple emails.
"""
if self.connection:
return False
try:
self.connection = SESConnection(
aws_access_key_id=self._access_key_id,
... | [
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"connection",
":",
"return",
"False",
"try",
":",
"self",
".",
"connection",
"=",
"SESConnection",
"(",
"aws_access_key_id",
"=",
"self",
".",
"_access_key_id",
",",
"aws_secret_access_key",
"=",
"self... | 32.45 | 12.4 |
def set_actuator_control_target_send(self, time_usec, group_mlx, target_system, target_component, controls, force_mavlink1=False):
'''
Set the vehicle attitude and body angular rates.
time_usec : Timestamp (micros since boot or Unix epoch) (uint64_t)
... | [
"def",
"set_actuator_control_target_send",
"(",
"self",
",",
"time_usec",
",",
"group_mlx",
",",
"target_system",
",",
"target_component",
",",
"controls",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"set_actua... | 102.75 | 83.083333 |
def replicate_global_dbs(cloud_url=None, local_url=None):
"""
Set up replication of the global databases from the cloud server to the
local server.
:param str cloud_url: Used to override the cloud url from the global
configuration in case the calling function is in the process of
initializing t... | [
"def",
"replicate_global_dbs",
"(",
"cloud_url",
"=",
"None",
",",
"local_url",
"=",
"None",
")",
":",
"local_url",
"=",
"local_url",
"or",
"config",
"[",
"\"local_server\"",
"]",
"[",
"\"url\"",
"]",
"cloud_url",
"=",
"cloud_url",
"or",
"config",
"[",
"\"cl... | 41.684211 | 20.210526 |
def update(self, reference, field_updates, option=None):
"""Add a "change" to update a document.
See
:meth:`~.firestore_v1beta1.document.DocumentReference.update` for
more information on ``field_updates`` and ``option``.
Args:
reference (~.firestore_v1beta1.document... | [
"def",
"update",
"(",
"self",
",",
"reference",
",",
"field_updates",
",",
"option",
"=",
"None",
")",
":",
"if",
"option",
".",
"__class__",
".",
"__name__",
"==",
"\"ExistsOption\"",
":",
"raise",
"ValueError",
"(",
"\"you must not pass an explicit write option ... | 46.454545 | 23.636364 |
def decimal_to_digits(decimal, min_digits=None):
"""
Return the number of digits to the first nonzero decimal.
Parameters
-----------
decimal: float
min_digits: int, minimum number of digits to return
Returns
-----------
digits: int, number of digits to the first nonzero decima... | [
"def",
"decimal_to_digits",
"(",
"decimal",
",",
"min_digits",
"=",
"None",
")",
":",
"digits",
"=",
"abs",
"(",
"int",
"(",
"np",
".",
"log10",
"(",
"decimal",
")",
")",
")",
"if",
"min_digits",
"is",
"not",
"None",
":",
"digits",
"=",
"np",
".",
... | 25.055556 | 19.5 |
def as_dict(self):
"""
Returns a copy of the configuration dictionary. Changes in this should not reflect on the original
object.
:return: Configuration dictionary.
:rtype: dict
"""
self.clean()
d = OrderedDict()
all_props = self.__class__.CONFIG_... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"self",
".",
"clean",
"(",
")",
"d",
"=",
"OrderedDict",
"(",
")",
"all_props",
"=",
"self",
".",
"__class__",
".",
"CONFIG_PROPERTIES",
"for",
"attr_name",
",",
"attr_config",
"in",
"six",
".",
"iteritems",
"(",
... | 37.307692 | 16 |
def _update_ctx(self, attrs):
"""
Update the state of the Styler.
Collects a mapping of {index_label: ['<property>: <value>']}.
attrs : Series or DataFrame
should contain strings of '<property>: <value>;<prop2>: <val2>'
Whitespace shouldn't matter and the final trailing... | [
"def",
"_update_ctx",
"(",
"self",
",",
"attrs",
")",
":",
"for",
"row_label",
",",
"v",
"in",
"attrs",
".",
"iterrows",
"(",
")",
":",
"for",
"col_label",
",",
"col",
"in",
"v",
".",
"iteritems",
"(",
")",
":",
"i",
"=",
"self",
".",
"index",
".... | 39.235294 | 17 |
def _private_notes(self, key, value):
"""Populate the ``_private_notes`` key.
Also populates the ``_export_to`` key through side effects.
"""
def _is_for_cds(value):
normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
return 'CDS' in normalized_c_values
def _is_... | [
"def",
"_private_notes",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"def",
"_is_for_cds",
"(",
"value",
")",
":",
"normalized_c_values",
"=",
"[",
"el",
".",
"upper",
"(",
")",
"for",
"el",
"in",
"force_list",
"(",
"value",
".",
"get",
"(",
"'c... | 32.342105 | 17.184211 |
def select_hits(hits_array, condition=None):
'''Selects the hits with condition.
E.g.: condition = 'rel_BCID == 7 & event_number < 1000'
Parameters
----------
hits_array : numpy.array
condition : string
A condition that is applied to the hits in numexpr. Only if the expression evaluates... | [
"def",
"select_hits",
"(",
"hits_array",
",",
"condition",
"=",
"None",
")",
":",
"if",
"condition",
"is",
"None",
":",
"return",
"hits_array",
"for",
"variable",
"in",
"set",
"(",
"re",
".",
"findall",
"(",
"r'[a-zA-Z_]+'",
",",
"condition",
")",
")",
"... | 29.136364 | 24.5 |
def institutes(self, institute_ids=None):
"""Fetch all institutes.
Args:
institute_ids(list(str))
Returns:
res(pymongo.Cursor)
"""
query = {}
if institute_ids:
query['_id'] = {'$in': institute_ids}
LOG.debug("F... | [
"def",
"institutes",
"(",
"self",
",",
"institute_ids",
"=",
"None",
")",
":",
"query",
"=",
"{",
"}",
"if",
"institute_ids",
":",
"query",
"[",
"'_id'",
"]",
"=",
"{",
"'$in'",
":",
"institute_ids",
"}",
"LOG",
".",
"debug",
"(",
"\"Fetching all institu... | 27.428571 | 13.642857 |
def _add_implied_commands(self):
"""
Add the commands that are implied by the blueprint.
"""
if len(self.get_added_columns()) and not self._creating():
self._commands.insert(0, self._create_command("add"))
if len(self.get_changed_columns()) and not self._creating():
... | [
"def",
"_add_implied_commands",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"get_added_columns",
"(",
")",
")",
"and",
"not",
"self",
".",
"_creating",
"(",
")",
":",
"self",
".",
"_commands",
".",
"insert",
"(",
"0",
",",
"self",
".",
"_cr... | 38.272727 | 19.545455 |
def list_event_types(self, filter=market_filter(), locale=None, session=None, lightweight=None):
"""
Returns a list of Event Types (i.e. Sports) associated with the markets
selected by the MarketFilter.
:param dict filter: The filter to select desired markets
:param str locale: ... | [
"def",
"list_event_types",
"(",
"self",
",",
"filter",
"=",
"market_filter",
"(",
")",
",",
"locale",
"=",
"None",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"met... | 50.4375 | 24.5625 |
def verify(self, string_version=None):
"""
Check that the version information is consistent with the VCS
before doing a release. If supplied with a string version,
this is also checked against the current version. Should be
called from setup.py with the declared package version b... | [
"def",
"verify",
"(",
"self",
",",
"string_version",
"=",
"None",
")",
":",
"if",
"string_version",
"and",
"string_version",
"!=",
"str",
"(",
"self",
")",
":",
"raise",
"Exception",
"(",
"\"Supplied string version does not match current version.\"",
")",
"if",
"s... | 44.454545 | 25.363636 |
def workbench_scenarios(cls):
"""
Gather scenarios to be displayed in the workbench
"""
module = cls.__module__
module = module.split('.')[0]
directory = pkg_resources.resource_filename(module, 'scenarios')
files = _find_files(directory)
scenarios = _read_... | [
"def",
"workbench_scenarios",
"(",
"cls",
")",
":",
"module",
"=",
"cls",
".",
"__module__",
"module",
"=",
"module",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"directory",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"module",
",",
"'scenarios... | 34.8 | 9.2 |
def cluster_nodes(self, state=None, healthy=None):
"""
With the Nodes API, you can obtain a collection of resources, each of
which represents a node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.er... | [
"def",
"cluster_nodes",
"(",
"self",
",",
"state",
"=",
"None",
",",
"healthy",
"=",
"None",
")",
":",
"path",
"=",
"'/ws/v1/cluster/nodes'",
"# TODO: validate state argument",
"legal_healthy",
"=",
"[",
"'true'",
",",
"'false'",
"]",
"if",
"healthy",
"is",
"n... | 34.12 | 17.24 |
def addPathway(
self, pathway_id, pathway_label, pathway_type=None,
pathway_description=None):
"""
Adds a pathway as a class. If no specific type is specified, it will
default to a subclass of "GO:cellular_process" and "PW:pathway".
:param pathway_id:
:pa... | [
"def",
"addPathway",
"(",
"self",
",",
"pathway_id",
",",
"pathway_label",
",",
"pathway_type",
"=",
"None",
",",
"pathway_description",
"=",
"None",
")",
":",
"if",
"pathway_type",
"is",
"None",
":",
"pathway_type",
"=",
"self",
".",
"globaltt",
"[",
"'cell... | 35.15 | 19.25 |
def validate(self):
"""
Perform some basic checks to help ensure that the specification is valid.
Throws an exception if an invalid value is found.
Returns true if all checks were passed.
:return: boolean
"""
# Check all values for None
for attr in self.__... | [
"def",
"validate",
"(",
"self",
")",
":",
"# Check all values for None",
"for",
"attr",
"in",
"self",
".",
"__dict__",
":",
"if",
"self",
".",
"__dict__",
"[",
"attr",
"]",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"attr",
"+",
"\" is not set\"",
")",... | 37.02381 | 21.595238 |
def create(cls, name, abr_type='cisco', auto_cost_bandwidth=100,
deprecated_algorithm=False, initial_delay=200,
initial_hold_time=1000, max_hold_time=10000,
shutdown_max_metric_lsa=0, startup_max_metric_lsa=0):
"""
Create custom Domain Settings
Domai... | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"abr_type",
"=",
"'cisco'",
",",
"auto_cost_bandwidth",
"=",
"100",
",",
"deprecated_algorithm",
"=",
"False",
",",
"initial_delay",
"=",
"200",
",",
"initial_hold_time",
"=",
"1000",
",",
"max_hold_time",
"=",
... | 44.848485 | 15.636364 |
def seek(self, offset, whence):
"""Changes the current file position of this file.
The file current position always applies to the :py:func:`IFile.read`
method. Same for the :py:func:`IFile.write` method it except when
the :py:func:`IFile.access_mode` is :py:attr:`FileAccess... | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"offset can only be an instance of type baseinteger\"",
")",
"if",
"not",
"isinstance",
"(",
... | 43.28 | 22.2 |
def _get_sv_callers(items):
"""
return a sorted list of all of the structural variant callers run
"""
callers = []
for data in items:
for sv in data.get("sv", []):
callers.append(sv["variantcaller"])
return list(set([x for x in callers if x != "sv-ensemble"])).sort() | [
"def",
"_get_sv_callers",
"(",
"items",
")",
":",
"callers",
"=",
"[",
"]",
"for",
"data",
"in",
"items",
":",
"for",
"sv",
"in",
"data",
".",
"get",
"(",
"\"sv\"",
",",
"[",
"]",
")",
":",
"callers",
".",
"append",
"(",
"sv",
"[",
"\"variantcaller... | 33.666667 | 13.888889 |
def connect(self, port=None, baud_rate=115200):
'''
Parameters
----------
port : str or list-like, optional
Port (or list of ports) to try to connect to as a DMF Control
Board.
baud_rate : int, optional
Returns
-------
str
... | [
"def",
"connect",
"(",
"self",
",",
"port",
"=",
"None",
",",
"baud_rate",
"=",
"115200",
")",
":",
"if",
"isinstance",
"(",
"port",
",",
"types",
".",
"StringTypes",
")",
":",
"ports",
"=",
"[",
"port",
"]",
"else",
":",
"ports",
"=",
"port",
"if"... | 35.268908 | 21.722689 |
def plot_pot(self, colorbar=True, cb_orientation='vertical',
cb_label='Potential, m$^2$ s$^{-2}$', ax=None, show=True,
fname=None, **kwargs):
"""
Plot the gravitational potential.
Usage
-----
x.plot_pot([tick_interval, xlabel, ylabel, ax, colorb... | [
"def",
"plot_pot",
"(",
"self",
",",
"colorbar",
"=",
"True",
",",
"cb_orientation",
"=",
"'vertical'",
",",
"cb_label",
"=",
"'Potential, m$^2$ s$^{-2}$'",
",",
"ax",
"=",
"None",
",",
"show",
"=",
"True",
",",
"fname",
"=",
"None",
",",
"*",
"*",
"kwar... | 42.078431 | 18.862745 |
def list_tables(self, limit=None, start_table=None):
"""
Return a list of table names associated with the current account
and endpoint.
:type limit: int
:param limit: The maximum number of tables to return.
:type start_table: str
:param limit: The name of the ta... | [
"def",
"list_tables",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"start_table",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"limit",
":",
"data",
"[",
"'Limit'",
"]",
"=",
"limit",
"if",
"start_table",
":",
"data",
"[",
"'ExclusiveStartTableN... | 37.136364 | 17.772727 |
def setup_signing(self, secret_key, sign_outgoing=True, allow_unsigned_callback=None, initial_timestamp=None, link_id=None):
'''setup for MAVLink2 signing'''
self.mav.signing.secret_key = secret_key
self.mav.signing.sign_outgoing = sign_outgoing
self.mav.signing.allow_unsigned_callback =... | [
"def",
"setup_signing",
"(",
"self",
",",
"secret_key",
",",
"sign_outgoing",
"=",
"True",
",",
"allow_unsigned_callback",
"=",
"None",
",",
"initial_timestamp",
"=",
"None",
",",
"link_id",
"=",
"None",
")",
":",
"self",
".",
"mav",
".",
"signing",
".",
"... | 51.263158 | 14.421053 |
def vel_term_floc(ConcAl, ConcClay, coag, material, DIM_FRACTAL,
DiamTarget, Temp):
"""Calculate floc terminal velocity."""
WaterDensity = pc.density_water(Temp).magnitude
return (((pc.gravity.magnitude * material.Diameter**2)
/ (18 * PHI_FLOC * pc.viscosity_kinematic(Temp).ma... | [
"def",
"vel_term_floc",
"(",
"ConcAl",
",",
"ConcClay",
",",
"coag",
",",
"material",
",",
"DIM_FRACTAL",
",",
"DiamTarget",
",",
"Temp",
")",
":",
"WaterDensity",
"=",
"pc",
".",
"density_water",
"(",
"Temp",
")",
".",
"magnitude",
"return",
"(",
"(",
"... | 41.642857 | 19.285714 |
def _get_dynamic_field_for(cls, field_name):
"""
Return the dynamic field within this class that match the given name.
Keep an internal cache to speed up future calls wieh same field name.
(The cache store the field for each individual class and subclasses, to
keep the link betwe... | [
"def",
"_get_dynamic_field_for",
"(",
"cls",
",",
"field_name",
")",
":",
"from",
".",
"fields",
"import",
"DynamicFieldMixin",
"# here to avoid circular import",
"if",
"cls",
"not",
"in",
"ModelWithDynamicFieldMixin",
".",
"_dynamic_fields_cache",
":",
"ModelWithDynamicF... | 48 | 29.461538 |
def handler(self, reply):
"""Upper level handler of keyboard events."""
data = reply.data
while len(data):
event, data = rq.EventField(None).parse_binary_value(data, self.display.display, None, None)
if self.escape(event): # Quit if this returns True
self... | [
"def",
"handler",
"(",
"self",
",",
"reply",
")",
":",
"data",
"=",
"reply",
".",
"data",
"while",
"len",
"(",
"data",
")",
":",
"event",
",",
"data",
"=",
"rq",
".",
"EventField",
"(",
"None",
")",
".",
"parse_binary_value",
"(",
"data",
",",
"sel... | 41.111111 | 19.666667 |
def intersect(self, *queries):
'''Return a new :class:`Query` obtained form the intersection of this
:class:`Query` with one or more *queries*. Workds the same way as
the :meth:`union` method.'''
q = self._clone()
q.intersections += queries
return q | [
"def",
"intersect",
"(",
"self",
",",
"*",
"queries",
")",
":",
"q",
"=",
"self",
".",
"_clone",
"(",
")",
"q",
".",
"intersections",
"+=",
"queries",
"return",
"q"
] | 40.142857 | 18.142857 |
def get(key, profile=None): # pylint: disable=W0613
'''
Get a value from the dictionary
'''
data = _get_values(profile)
# Decrypt SDB data if specified in the profile
if profile and profile.get('gpg', False):
return salt.utils.data.traverse_dict_and_list(_decrypt(data), key, None)
... | [
"def",
"get",
"(",
"key",
",",
"profile",
"=",
"None",
")",
":",
"# pylint: disable=W0613",
"data",
"=",
"_get_values",
"(",
"profile",
")",
"# Decrypt SDB data if specified in the profile",
"if",
"profile",
"and",
"profile",
".",
"get",
"(",
"'gpg'",
",",
"Fals... | 33.909091 | 23 |
def update(self, callback=None, errback=None, **kwargs):
"""
Update Network configuration. Pass a list of keywords and their values to update.
For the list of keywords available for zone configuration, see :attr:`ns1.rest.ipam.Networks.INT_FIELDS` and :attr:`ns1.rest.ipam.Networks.PASSTHRU_FIELD... | [
"def",
"update",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"data",
":",
"raise",
"NetworkException",
"(",
"'Network not loaded'",
")",
"def",
"success",
"(",
"re... | 41.15 | 21.35 |
def _evaluate(self,*args,**kwargs):
"""
NAME:
__call__ (_evaluate)
PURPOSE:
evaluate the actions (jr,lz,jz)
INPUT:
Either:
a) R,vR,vT,z,vz[,phi]:
1) floats: phase-space value for single object (phi is optional) (each can be ... | [
"def",
"_evaluate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"delta",
"=",
"kwargs",
".",
"pop",
"(",
"'delta'",
",",
"self",
".",
"_delta",
")",
"order",
"=",
"kwargs",
".",
"get",
"(",
"'order'",
",",
"self",
".",
"_ord... | 49.747475 | 21.282828 |
def convert_dict_to_option_dict(input_dict):
"""Convert a simple key-value dictionary to a dictionary of options tuples"""
ret_dict = {}
for key, value in input_dict.items():
ret_dict[key] = convert_value_to_option_tuple(value)
return ret_dict | [
"def",
"convert_dict_to_option_dict",
"(",
"input_dict",
")",
":",
"ret_dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"input_dict",
".",
"items",
"(",
")",
":",
"ret_dict",
"[",
"key",
"]",
"=",
"convert_value_to_option_tuple",
"(",
"value",
")",
... | 43.666667 | 11.5 |
def get_serializable_data_for_fields(model):
"""
Return a serialised version of the model's fields which exist as local database
columns (i.e. excluding m2m and incoming foreign key relations)
"""
pk_field = model._meta.pk
# If model is a child via multitable inheritance, use parent's pk
whi... | [
"def",
"get_serializable_data_for_fields",
"(",
"model",
")",
":",
"pk_field",
"=",
"model",
".",
"_meta",
".",
"pk",
"# If model is a child via multitable inheritance, use parent's pk",
"while",
"pk_field",
".",
"remote_field",
"and",
"pk_field",
".",
"remote_field",
"."... | 36.294118 | 20.647059 |
def get_rating_metadata(self):
"""Gets the metadata for a rating.
return: (osid.Metadata) - metadata for the rating
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template
met... | [
"def",
"get_rating_metadata",
"(",
"self",
")",
":",
"# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template",
"metadata",
"=",
"dict",
"(",
"self",
".",
"_mdata",
"[",
"'rating'",
"]",
")",
"metadata",
".",
"update",
"(",
"{",
"'existing... | 41.363636 | 21.090909 |
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs) | [
"def",
"info",
"(",
"self",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_log",
"(",
"logging",
".",
"INFO",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 42.25 | 4.5 |
def read(self, symbol, as_of=None, date_range=None, from_version=None, allow_secondary=None, **kwargs):
"""
Read data for the named symbol. Returns a VersionedItem object with
a data and metdata element (as passed into write).
Parameters
----------
symbol : `str`
... | [
"def",
"read",
"(",
"self",
",",
"symbol",
",",
"as_of",
"=",
"None",
",",
"date_range",
"=",
"None",
",",
"from_version",
"=",
"None",
",",
"allow_secondary",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"read_preference",
"=",
"self",
... | 54.804348 | 27.326087 |
def getObjectsAspecting(self, point, aspList):
""" Returns a list of objects aspecting a point
considering a list of possible aspects.
"""
res = []
for obj in self:
if obj.isPlanet() and aspects.isAspecting(obj, point, aspList):
res.append(ob... | [
"def",
"getObjectsAspecting",
"(",
"self",
",",
"point",
",",
"aspList",
")",
":",
"res",
"=",
"[",
"]",
"for",
"obj",
"in",
"self",
":",
"if",
"obj",
".",
"isPlanet",
"(",
")",
"and",
"aspects",
".",
"isAspecting",
"(",
"obj",
",",
"point",
",",
"... | 34.4 | 13.9 |
def _fit_island(self, island_data):
"""
Take an Island, do all the parameter estimation and fitting.
Parameters
----------
island_data : :class:`AegeanTools.models.IslandFittingData`
The island to be fit.
Returns
-------
sources : list
... | [
"def",
"_fit_island",
"(",
"self",
",",
"island_data",
")",
":",
"global_data",
"=",
"self",
".",
"global_data",
"# global data",
"dcurve",
"=",
"global_data",
".",
"dcurve",
"rmsimg",
"=",
"global_data",
".",
"rmsimg",
"# island data",
"isle_num",
"=",
"island_... | 38.534653 | 22.871287 |
def get_preorder_burn_info( outputs ):
"""
Given the set of outputs, find the fee sent
to our burn address. This is always the third output.
Return the fee and burn address on success as {'op_fee': ..., 'burn_address': ...}
Return None if not found
"""
if len(outputs) != 3:
... | [
"def",
"get_preorder_burn_info",
"(",
"outputs",
")",
":",
"if",
"len",
"(",
"outputs",
")",
"!=",
"3",
":",
"# not a well-formed preorder ",
"return",
"None",
"op_fee",
"=",
"outputs",
"[",
"2",
"]",
"[",
"'value'",
"]",
"burn_address",
"=",
"None",
"try",
... | 29.5 | 22.333333 |
def do_unthrottle(self, *args):
"""
Remove the throughput limits for DQL that were set with 'throttle'
# Remove all limits
> unthrottle
# Remove the limit on total allowed throughput
> unthrottle total
# Remove the default limit
> unthrottle default
... | [
"def",
"do_unthrottle",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"not",
"args",
":",
"if",
"promptyn",
"(",
"\"Are you sure you want to clear all throttles?\"",
")",
":",
"self",
".",
"throttle",
".",
"load",
"(",
"{",
"}",
")",
"elif",
"len",
"(",
... | 34.117647 | 13.294118 |
def to_json(self):
"""
Serialize object to json dict
:return: dict
"""
data = dict()
data['InterlocutorId'] = self.id_
data['Text'] = self.text
data['Username'] = self.username
data['FirstName'] = self.first_name
data['LastName'] = self.la... | [
"def",
"to_json",
"(",
"self",
")",
":",
"data",
"=",
"dict",
"(",
")",
"data",
"[",
"'InterlocutorId'",
"]",
"=",
"self",
".",
"id_",
"data",
"[",
"'Text'",
"]",
"=",
"self",
".",
"text",
"data",
"[",
"'Username'",
"]",
"=",
"self",
".",
"username... | 25.769231 | 10.538462 |
def set_setting(key, value, qsettings=None):
"""Set value to QSettings based on key in InaSAFE scope.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defined, it will
... | [
"def",
"set_setting",
"(",
"key",
",",
"value",
",",
"qsettings",
"=",
"None",
")",
":",
"full_key",
"=",
"'%s/%s'",
"%",
"(",
"APPLICATION_NAME",
",",
"key",
")",
"set_general_setting",
"(",
"full_key",
",",
"value",
",",
"qsettings",
")"
] | 32.466667 | 15.6 |
def keep_types_s(s, types):
"""
Keep the given types from a string
Same as :meth:`keep_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list of str
Th... | [
"def",
"keep_types_s",
"(",
"s",
",",
"types",
")",
":",
"patt",
"=",
"'|'",
".",
"join",
"(",
"'(?<=\\n)'",
"+",
"s",
"+",
"'\\n(?s).+?\\n(?=\\S+|$)'",
"for",
"s",
"in",
"types",
")",
"return",
"''",
".",
"join",
"(",
"re",
".",
"findall",
"(",
"pat... | 29.095238 | 22.142857 |
def measure(function, xs, ys, popt, weights):
"""
measure the quality of a fit
"""
m = 0
n = 0
for x in xs:
try:
if len(popt) == 2:
m += (ys[n] - function(x, popt[0], popt[1]))**2 * weights[n]
elif len(popt) == 3:
m += (ys[n] - func... | [
"def",
"measure",
"(",
"function",
",",
"xs",
",",
"ys",
",",
"popt",
",",
"weights",
")",
":",
"m",
"=",
"0",
"n",
"=",
"0",
"for",
"x",
"in",
"xs",
":",
"try",
":",
"if",
"len",
"(",
"popt",
")",
"==",
"2",
":",
"m",
"+=",
"(",
"ys",
"[... | 29.631579 | 21.210526 |
def get_metadata(url, validate_cert=True):
"""
Gets the metadata XML from the provided URL
:param url: Url where the XML of the Identity Provider Metadata is published.
:type url: string
:param validate_cert: If the url uses https schema, that flag enables or not the verificati... | [
"def",
"get_metadata",
"(",
"url",
",",
"validate_cert",
"=",
"True",
")",
":",
"valid",
"=",
"False",
"if",
"validate_cert",
":",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"else",
":",
"ctx",
"=",
"ssl",
".",
"create_default_context",
... | 32.527778 | 21.527778 |
def get_points(recording):
"""
Get one point for each stroke in a recording. The point represents the
strokes spacial position (e.g. the center of the bounding box).
Parameters
----------
recording : list of strokes
Returns
-------
list :
points
"""
points = []
... | [
"def",
"get_points",
"(",
"recording",
")",
":",
"points",
"=",
"[",
"]",
"for",
"stroke",
"in",
"recording",
":",
"point",
"=",
"geometry",
".",
"get_bounding_box",
"(",
"stroke",
")",
".",
"get_center",
"(",
")",
"points",
".",
"append",
"(",
"point",
... | 22.947368 | 22.315789 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.