text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _get_interpretation_function(interpretation, dtype):
"""
Retrieves the interpretation function used.
"""
type_string = dtype.__name__
name = "%s__%s" % (interpretation, type_string)
global _interpretations
if not hasattr(_interpretations, name):
raise ValueError("No transform ... | [
"def",
"_get_interpretation_function",
"(",
"interpretation",
",",
"dtype",
")",
":",
"type_string",
"=",
"dtype",
".",
"__name__",
"name",
"=",
"\"%s__%s\"",
"%",
"(",
"interpretation",
",",
"type_string",
")",
"global",
"_interpretations",
"if",
"not",
"hasattr"... | 30.533333 | 19.066667 |
def graded_submissions(self):
'''
Queryset for the graded submissions, which are worth closing.
'''
qs = self._valid_submissions().filter(state__in=[Submission.GRADED])
return qs | [
"def",
"graded_submissions",
"(",
"self",
")",
":",
"qs",
"=",
"self",
".",
"_valid_submissions",
"(",
")",
".",
"filter",
"(",
"state__in",
"=",
"[",
"Submission",
".",
"GRADED",
"]",
")",
"return",
"qs"
] | 36.166667 | 26.833333 |
def updateModel(self, X_all, Y_all, X_new, Y_new):
"""
Updates the model with new observations.
"""
if self.model is None:
self._create_model(X_all, Y_all)
else:
self.model.set_XY(X_all, Y_all)
# WARNING: Even if self.max_iters=0, the hyperparamet... | [
"def",
"updateModel",
"(",
"self",
",",
"X_all",
",",
"Y_all",
",",
"X_new",
",",
"Y_new",
")",
":",
"if",
"self",
".",
"model",
"is",
"None",
":",
"self",
".",
"_create_model",
"(",
"X_all",
",",
"Y_all",
")",
"else",
":",
"self",
".",
"model",
".... | 48.625 | 26 |
def _getSDRPairs(self,
pairs,
noise=None,
locationNoise=None,
includeRandomLocation=False,
numAmbiguousLocations=0):
"""
This method takes a list of (location, feature) index pairs (one pair per
cortical column), ... | [
"def",
"_getSDRPairs",
"(",
"self",
",",
"pairs",
",",
"noise",
"=",
"None",
",",
"locationNoise",
"=",
"None",
",",
"includeRandomLocation",
"=",
"False",
",",
"numAmbiguousLocations",
"=",
"0",
")",
":",
"sensations",
"=",
"{",
"}",
"numpy",
".",
"random... | 33.824561 | 14.701754 |
def make_benchark(n_train, n_test, n_dim=2):
""" Compute the benchmarks for Ordianry Kriging
Parameters
----------
n_train : int
number of points in the training set
n_test : int
number of points in the test set
n_dim : int
number of dimensions (default=2)
Returns
--... | [
"def",
"make_benchark",
"(",
"n_train",
",",
"n_test",
",",
"n_dim",
"=",
"2",
")",
":",
"X_train",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"n_train",
",",
"n_dim",
")",
"y_train",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"n_train",
")",
"X_... | 31.159091 | 20.636364 |
def get_words(data):
"""
Extracts the words from given string.
Usage::
>>> get_words("Users are: John Doe, Jane Doe, Z6PO.")
[u'Users', u'are', u'John', u'Doe', u'Jane', u'Doe', u'Z6PO']
:param data: Data to extract words from.
:type data: unicode
:return: Words.
:rtype: l... | [
"def",
"get_words",
"(",
"data",
")",
":",
"words",
"=",
"re",
".",
"findall",
"(",
"r\"\\w+\"",
",",
"data",
")",
"LOGGER",
".",
"debug",
"(",
"\"> Words: '{0}'\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"words",
")",
")",
")",
"return",
"w... | 23.833333 | 20.722222 |
def generate(declaration, headers=None, has_iterators=False):
"""Compile and load the reflection dictionary for a type.
If the requested dictionary has already been cached, then load that instead.
Parameters
----------
declaration : str
A type declaration (for example "vector<int>")
he... | [
"def",
"generate",
"(",
"declaration",
",",
"headers",
"=",
"None",
",",
"has_iterators",
"=",
"False",
")",
":",
"global",
"NEW_DICTS",
"# FIXME: _rootpy_dictionary_already_exists returns false positives",
"# if a third-party module provides \"incomplete\" dictionaries.",
"#if c... | 41.573034 | 19.303371 |
def create_db(name, owner=None, encoding=u'UTF-8', template='template1',
**kwargs):
"""Create a Postgres database."""
flags = u''
if encoding:
flags = u'-E %s' % encoding
if owner:
flags = u'%s -O %s' % (flags, owner)
if template and template != 'template1':
fl... | [
"def",
"create_db",
"(",
"name",
",",
"owner",
"=",
"None",
",",
"encoding",
"=",
"u'UTF-8'",
",",
"template",
"=",
"'template1'",
",",
"*",
"*",
"kwargs",
")",
":",
"flags",
"=",
"u''",
"if",
"encoding",
":",
"flags",
"=",
"u'-E %s'",
"%",
"encoding",... | 35.333333 | 18.416667 |
def validate_page(ctx, param, value):
"""Ensure that a valid value for page is chosen."""
# pylint: disable=unused-argument
if value == 0:
raise click.BadParameter(
"Page is not zero-based, please set a value to 1 or higher.", param=param
)
return value | [
"def",
"validate_page",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"# pylint: disable=unused-argument",
"if",
"value",
"==",
"0",
":",
"raise",
"click",
".",
"BadParameter",
"(",
"\"Page is not zero-based, please set a value to 1 or higher.\"",
",",
"param",
"=... | 36.25 | 16.875 |
def characterize_local_files(filedir, max_bytes=MAX_FILE_DEFAULT):
"""
Collate local file info as preperation for Open Humans upload.
Note: Files with filesize > max_bytes are not included in returned info.
:param filedir: This field is target directory to get files from.
:param max_bytes: This fi... | [
"def",
"characterize_local_files",
"(",
"filedir",
",",
"max_bytes",
"=",
"MAX_FILE_DEFAULT",
")",
":",
"file_data",
"=",
"{",
"}",
"logging",
".",
"info",
"(",
"'Characterizing files in {}'",
".",
"format",
"(",
"filedir",
")",
")",
"for",
"filename",
"in",
"... | 39.4 | 14.866667 |
def _raise_rpc_timeout_error(self, uuid):
"""Gather information and raise an Rpc exception.
:param str uuid: Rpc Identifier.
:return:
"""
requests = []
for key, value in self._request.items():
if value == uuid:
requests.append(key)
sel... | [
"def",
"_raise_rpc_timeout_error",
"(",
"self",
",",
"uuid",
")",
":",
"requests",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"self",
".",
"_request",
".",
"items",
"(",
")",
":",
"if",
"value",
"==",
"uuid",
":",
"requests",
".",
"append",
"("... | 27.526316 | 13.842105 |
def hill_climbing_stochastic(problem, iterations_limit=0, viewer=None):
'''
Stochastic hill climbing.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.... | [
"def",
"hill_climbing_stochastic",
"(",
"problem",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_random_best_expander",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fringe_size",... | 41.25 | 19.375 |
def update(self, current, values=[], exact=[], strict=[]):
"""
Updates the progress bar.
# Arguments
current: Index of current step.
values: List of tuples (name, value_for_last_step).
The progress bar will display averages for these values.
ex... | [
"def",
"update",
"(",
"self",
",",
"current",
",",
"values",
"=",
"[",
"]",
",",
"exact",
"=",
"[",
"]",
",",
"strict",
"=",
"[",
"]",
")",
":",
"for",
"k",
",",
"v",
"in",
"values",
":",
"if",
"k",
"not",
"in",
"self",
".",
"sum_values",
":"... | 38.573034 | 17.516854 |
def encode(*args, **kwargs):
"""
A helper function to encode an element.
@param args: The python data to be encoded.
@kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}.
@return: A L{util.BufferedByteStream} object that contains the data.
"""
encoding = kwargs.pop('encoding', DEFAU... | [
"def",
"encode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"encoding",
"=",
"kwargs",
".",
"pop",
"(",
"'encoding'",
",",
"DEFAULT_ENCODING",
")",
"encoder",
"=",
"get_encoder",
"(",
"encoding",
",",
"*",
"*",
"kwargs",
")",
"[",
"encoder",
... | 28 | 18.941176 |
def detect_palette_support(basic_palette=None):
''' Returns whether we think the terminal supports basic, extended, or
truecolor. None if not able to tell.
Returns:
None or str: 'basic', 'extended', 'truecolor'
'''
result = col_init = win_enabled = None
TERM = env.TERM or '... | [
"def",
"detect_palette_support",
"(",
"basic_palette",
"=",
"None",
")",
":",
"result",
"=",
"col_init",
"=",
"win_enabled",
"=",
"None",
"TERM",
"=",
"env",
".",
"TERM",
"or",
"''",
"if",
"os_name",
"==",
"'nt'",
":",
"from",
".",
"windows",
"import",
"... | 34.431818 | 21.159091 |
def after_func_accept_retry_state(fn):
"""Wrap "after" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_after_sleep_func(retry_state):
# func, trial_number, trial_time_taken
... | [
"def",
"after_func_accept_retry_state",
"(",
"fn",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"fn",
")",
":",
"return",
"fn",
"if",
"func_takes_retry_state",
"(",
"fn",
")",
":",
"return",
"fn",
"@",
"_utils",
".",
"wraps",
"(",
"fn",
")",
"de... | 31.705882 | 15 |
def _combine_costs(self, Npwl, Hpwl, Cpwl, fparm_pwl, any_pwl,
Npol, Hpol, Cpol, fparm_pol, npol, nw):
""" Combines pwl, polynomial and user-defined costs.
"""
NN = vstack([n for n in [Npwl, Npol] if n is not None], "csr")
if (Hpwl is not None) and (Hpol is not No... | [
"def",
"_combine_costs",
"(",
"self",
",",
"Npwl",
",",
"Hpwl",
",",
"Cpwl",
",",
"fparm_pwl",
",",
"any_pwl",
",",
"Npol",
",",
"Hpol",
",",
"Cpol",
",",
"fparm_pol",
",",
"npol",
",",
"nw",
")",
":",
"NN",
"=",
"vstack",
"(",
"[",
"n",
"for",
"... | 37 | 21.789474 |
def dump(self):
"""Saves state database."""
assert self.database is not None
cmd = "SELECT count from {} WHERE rowid={}"
self._execute(cmd.format(self.STATE_INFO_TABLE, self.STATE_INFO_ROW))
ret = self._fetchall()
assert len(ret) == 1
assert len(ret[0]) == 1
... | [
"def",
"dump",
"(",
"self",
")",
":",
"assert",
"self",
".",
"database",
"is",
"not",
"None",
"cmd",
"=",
"\"SELECT count from {} WHERE rowid={}\"",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_INFO_TABLE",
",",
"self",
".",
... | 30.423077 | 18.980769 |
def send_last_message(self, msg, connection_id=None):
"""
Should be used instead of send_message, when you want to close the
connection once the message is sent.
:param msg: protobuf validator_pb2.Message
"""
zmq_identity = None
if connection_id is not None and s... | [
"def",
"send_last_message",
"(",
"self",
",",
"msg",
",",
"connection_id",
"=",
"None",
")",
":",
"zmq_identity",
"=",
"None",
"if",
"connection_id",
"is",
"not",
"None",
"and",
"self",
".",
"_connections",
"is",
"not",
"None",
":",
"if",
"connection_id",
... | 38.258065 | 19.419355 |
def create_strategy(name=None):
"""
Create a strategy, or just returns it if it's already one.
:param name:
:return: Strategy
"""
import logging
from bonobo.execution.strategies.base import Strategy
if isinstance(name, Strategy):
return name
if name is None:
name ... | [
"def",
"create_strategy",
"(",
"name",
"=",
"None",
")",
":",
"import",
"logging",
"from",
"bonobo",
".",
"execution",
".",
"strategies",
".",
"base",
"import",
"Strategy",
"if",
"isinstance",
"(",
"name",
",",
"Strategy",
")",
":",
"return",
"name",
"if",... | 24.653846 | 23.730769 |
def deserialize(self, obj=None, ignore_non_existing=False):
"""
:type obj dict|None
:type ignore_non_existing bool
"""
if not isinstance(obj, dict):
if ignore_non_existing:
return
raise TypeError("Wrong data '{}' passed for '{}' deserialization".format(obj, self.__class__.__name... | [
"def",
"deserialize",
"(",
"self",
",",
"obj",
"=",
"None",
",",
"ignore_non_existing",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"if",
"ignore_non_existing",
":",
"return",
"raise",
"TypeError",
"(",
"\"Wrong da... | 37.5 | 25.462963 |
def parse_eff(filename):
"""
Parse through Jean-Marcs OSSSO .eff files.
The efficiency files comes in 'chunks' meant to be used at different 'rates' of motion.
"""
blocks = []
block = {}
with open(filename) as efile:
for line in efile.readlines():
if line.lstrip().... | [
"def",
"parse_eff",
"(",
"filename",
")",
":",
"blocks",
"=",
"[",
"]",
"block",
"=",
"{",
"}",
"with",
"open",
"(",
"filename",
")",
"as",
"efile",
":",
"for",
"line",
"in",
"efile",
".",
"readlines",
"(",
")",
":",
"if",
"line",
".",
"lstrip",
... | 28.913043 | 17.608696 |
def getExtensions(self):
"""returns objects for all map service extensions"""
extensions = []
if isinstance(self.supportedExtensions, list):
for ext in self.supportedExtensions:
extensionURL = self._url + "/exts/%s" % ext
if ext == "SchematicsServer":
... | [
"def",
"getExtensions",
"(",
"self",
")",
":",
"extensions",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"self",
".",
"supportedExtensions",
",",
"list",
")",
":",
"for",
"ext",
"in",
"self",
".",
"supportedExtensions",
":",
"extensionURL",
"=",
"self",
".",
... | 58.7 | 25.9 |
def draw_line(self, lx, ltor):
'''Draw a series of elements from left to right'''
tag = self.get_tag()
c = self.canvas
s = self.style
sep = s.h_sep
exx = 0
exy = 0
terms = lx if ltor else reversed(lx) # Reverse so we can draw left to right
for term in terms:
t, texx,... | [
"def",
"draw_line",
"(",
"self",
",",
"lx",
",",
"ltor",
")",
":",
"tag",
"=",
"self",
".",
"get_tag",
"(",
")",
"c",
"=",
"self",
".",
"canvas",
"s",
"=",
"self",
".",
"style",
"sep",
"=",
"s",
".",
"h_sep",
"exx",
"=",
"0",
"exy",
"=",
"0",... | 34.657143 | 24.2 |
def ext_from_filename(filename):
""" Scan a filename for it's extension.
:param filename: string of the filename
:return: the extension off the end (empty string if it can't find one)
"""
try:
base, ext = filename.lower().rsplit(".", 1)
except ValueError:
return ''
ext = ".{... | [
"def",
"ext_from_filename",
"(",
"filename",
")",
":",
"try",
":",
"base",
",",
"ext",
"=",
"filename",
".",
"lower",
"(",
")",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"except",
"ValueError",
":",
"return",
"''",
"ext",
"=",
"\".{0}\"",
".",
"for... | 31.95 | 16.75 |
def label_position(self):
'''
Find the largest region and position the label in that.
'''
reg_sizes = [(r.size(), r) for r in self.pieces]
reg_sizes.sort()
return reg_sizes[-1][1].label_position() | [
"def",
"label_position",
"(",
"self",
")",
":",
"reg_sizes",
"=",
"[",
"(",
"r",
".",
"size",
"(",
")",
",",
"r",
")",
"for",
"r",
"in",
"self",
".",
"pieces",
"]",
"reg_sizes",
".",
"sort",
"(",
")",
"return",
"reg_sizes",
"[",
"-",
"1",
"]",
... | 34 | 19.428571 |
def unpack(cls, msg, client, server, _):
"""Parse message and return an `OpKillCursors`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
# Leading 4 bytes are reserved.
num_of_cursor_ids, = _UNPACK_INT(msg[4:8])
... | [
"def",
"unpack",
"(",
"cls",
",",
"msg",
",",
"client",
",",
"server",
",",
"_",
")",
":",
"# Leading 4 bytes are reserved.",
"num_of_cursor_ids",
",",
"=",
"_UNPACK_INT",
"(",
"msg",
"[",
"4",
":",
"8",
"]",
")",
"cursor_ids",
"=",
"[",
"]",
"pos",
"=... | 38.866667 | 14.333333 |
async def _seek(self, ctx, *, time: str):
""" Seeks to a given position in a track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
seconds = time_rx.search(time)
if not seconds:
... | [
"async",
"def",
"_seek",
"(",
"self",
",",
"ctx",
",",
"*",
",",
"time",
":",
"str",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",... | 35.421053 | 20.052632 |
def _add_warc_action_log(self, path, url):
'''Add the action log to the WARC file.'''
_logger.debug('Adding action log record.')
actions = []
with open(path, 'r', encoding='utf-8', errors='replace') as file:
for line in file:
actions.append(json.loads(line))
... | [
"def",
"_add_warc_action_log",
"(",
"self",
",",
"path",
",",
"url",
")",
":",
"_logger",
".",
"debug",
"(",
"'Adding action log record.'",
")",
"actions",
"=",
"[",
"]",
"with",
"open",
"(",
"path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
",",
"err... | 38.181818 | 20.181818 |
def create_bucket(self, bucket_name, region_name=None):
"""
Creates an Amazon S3 bucket.
:param bucket_name: The name of the bucket
:type bucket_name: str
:param region_name: The name of the aws region in which to create the bucket.
:type region_name: str
"""
... | [
"def",
"create_bucket",
"(",
"self",
",",
"bucket_name",
",",
"region_name",
"=",
"None",
")",
":",
"s3_conn",
"=",
"self",
".",
"get_conn",
"(",
")",
"if",
"not",
"region_name",
":",
"region_name",
"=",
"s3_conn",
".",
"meta",
".",
"region_name",
"if",
... | 41.210526 | 16.157895 |
def _get_local_ip(self):
"""Try to determine the local IP address of the machine."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Use Google Public DNS server to determine own IP
sock.connect(('8.8.8.8', 80))
return sock.getsockname()[0... | [
"def",
"_get_local_ip",
"(",
"self",
")",
":",
"try",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"# Use Google Public DNS server to determine own IP",
"sock",
".",
"connect",
"(",
"(",
"'8.8... | 33.1875 | 17.875 |
def reset(self):
"""Resets the sampler to its initial state
Note
----
This will destroy the label cache and history of estimates.
"""
self._TP = np.zeros(self._n_class)
self._FP = np.zeros(self._n_class)
self._FN = np.zeros(self._n_class)
self._TN... | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_TP",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"_n_class",
")",
"self",
".",
"_FP",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"_n_class",
")",
"self",
".",
"_FN",
"=",
"np",
".",
"zeros",
... | 36.866667 | 16.933333 |
def _get_model_reference(self, model_id):
"""Constructs a ModelReference.
Args:
model_id (str): the ID of the model.
Returns:
google.cloud.bigquery.model.ModelReference:
A ModelReference for a model in this dataset.
"""
return ModelReference.from_api_repr(
{"pro... | [
"def",
"_get_model_reference",
"(",
"self",
",",
"model_id",
")",
":",
"return",
"ModelReference",
".",
"from_api_repr",
"(",
"{",
"\"projectId\"",
":",
"self",
".",
"project",
",",
"\"datasetId\"",
":",
"self",
".",
"dataset_id",
",",
"\"modelId\"",
":",
"mod... | 29.769231 | 19.461538 |
def last_seen(self):
"""Return mattress last seen time."""
"""
These values seem to be rarely updated correctly in the API.
Don't expect accurate results from this property.
"""
try:
if self.side == 'left':
lastseen = self.device.device_data['l... | [
"def",
"last_seen",
"(",
"self",
")",
":",
"\"\"\"\n These values seem to be rarely updated correctly in the API.\n Don't expect accurate results from this property.\n \"\"\"",
"try",
":",
"if",
"self",
".",
"side",
"==",
"'left'",
":",
"lastseen",
"=",
"self... | 35.941176 | 16 |
def lock(self, name, timeout=None, sleep=0.1):
"""
Return a new Lock object using key ``name`` that mimics
the behavior of threading.Lock.
If specified, ``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.
``sle... | [
"def",
"lock",
"(",
"self",
",",
"name",
",",
"timeout",
"=",
"None",
",",
"sleep",
"=",
"0.1",
")",
":",
"return",
"Lock",
"(",
"self",
",",
"name",
",",
"timeout",
"=",
"timeout",
",",
"sleep",
"=",
"sleep",
")"
] | 41.769231 | 21 |
def _copy(query_dict):
"""
Return a mutable copy of `query_dict`. This is a workaround to
Django bug #13572, which prevents QueryDict.copy from working.
"""
memo = { }
result = query_dict.__class__('',
encoding=query_dict.encoding,
mutable=True)
memo[id(query_dict)] = resu... | [
"def",
"_copy",
"(",
"query_dict",
")",
":",
"memo",
"=",
"{",
"}",
"result",
"=",
"query_dict",
".",
"__class__",
"(",
"''",
",",
"encoding",
"=",
"query_dict",
".",
"encoding",
",",
"mutable",
"=",
"True",
")",
"memo",
"[",
"id",
"(",
"query_dict",
... | 24 | 18.4 |
def split_at_single(text, sep, not_before=[], not_after=[]):
"""Works like text.split(sep) but separated fragments
cant end with not_before or start with not_after"""
n = 0
lt, s = len(text), len(sep)
last = 0
while n < lt:
if not s + n > lt:
if sep == text[n:n + s]:
... | [
"def",
"split_at_single",
"(",
"text",
",",
"sep",
",",
"not_before",
"=",
"[",
"]",
",",
"not_after",
"=",
"[",
"]",
")",
":",
"n",
"=",
"0",
"lt",
",",
"s",
"=",
"len",
"(",
"text",
")",
",",
"len",
"(",
"sep",
")",
"last",
"=",
"0",
"while... | 34.105263 | 16.105263 |
def reorderMAT(m, H=5000, cost='line'):
'''
This function reorders the connectivity matrix in order to place more
edges closer to the diagonal. This often helps in displaying community
structure, clusters, etc.
Parameters
----------
MAT : NxN np.ndarray
connection matrix
H : int... | [
"def",
"reorderMAT",
"(",
"m",
",",
"H",
"=",
"5000",
",",
"cost",
"=",
"'line'",
")",
":",
"from",
"scipy",
"import",
"linalg",
",",
"stats",
"m",
"=",
"m",
".",
"copy",
"(",
")",
"n",
"=",
"len",
"(",
"m",
")",
"np",
".",
"fill_diagonal",
"("... | 29.861111 | 19.833333 |
def equivalence_transform(compound, from_positions, to_positions, add_bond=True):
"""Computes an affine transformation that maps the from_positions to the
respective to_positions, and applies this transformation to the compound.
Parameters
----------
compound : mb.Compound
The Compound to b... | [
"def",
"equivalence_transform",
"(",
"compound",
",",
"from_positions",
",",
"to_positions",
",",
"add_bond",
"=",
"True",
")",
":",
"warn",
"(",
"'The `equivalence_transform` function is being phased out in favor of'",
"' `force_overlap`.'",
",",
"DeprecationWarning",
")",
... | 44.731707 | 24.804878 |
def delete(self, key):
"""Adds deletion of the entity with given key to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
key: key of the entity which should be deleted
"""
self._cur_batch.delet... | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_cur_batch",
".",
"delete",
"(",
"key",
")",
"self",
".",
"_num_mutations",
"+=",
"1",
"if",
"self",
".",
"_num_mutations",
">=",
"MAX_MUTATIONS_IN_BATCH",
":",
"self",
".",
"commit",
"(",... | 31.071429 | 18.642857 |
def _convert_a_header_to_a_h2_header(self, hdr_name, hdr_value, is_sensitive, should_index): # noqa: E501
# type: (str, str, Callable[[str, str], bool], Callable[[str], bool]) -> Tuple[HPackHeaders, int] # noqa: E501
""" _convert_a_header_to_a_h2_header builds a HPackHeaders from a header
name... | [
"def",
"_convert_a_header_to_a_h2_header",
"(",
"self",
",",
"hdr_name",
",",
"hdr_value",
",",
"is_sensitive",
",",
"should_index",
")",
":",
"# noqa: E501",
"# type: (str, str, Callable[[str, str], bool], Callable[[str], bool]) -> Tuple[HPackHeaders, int] # noqa: E501",
"# If both... | 37.297872 | 18.244681 |
def arg_to_json(arg):
"""
Perform necessary JSON conversion on the arg.
"""
conversion = json_conversions.get(type(arg))
if conversion:
return conversion(arg)
for type_ in subclass_conversions:
if isinstance(arg, type_):
return json_conversions[type_](arg)
return ... | [
"def",
"arg_to_json",
"(",
"arg",
")",
":",
"conversion",
"=",
"json_conversions",
".",
"get",
"(",
"type",
"(",
"arg",
")",
")",
"if",
"conversion",
":",
"return",
"conversion",
"(",
"arg",
")",
"for",
"type_",
"in",
"subclass_conversions",
":",
"if",
"... | 30.545455 | 7.818182 |
def get_report(host, userid, password,
port=443, auth_method='basic', client_timeout=60):
"""get iRMC report
This function returns iRMC report in XML format
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for ... | [
"def",
"get_report",
"(",
"host",
",",
"userid",
",",
"password",
",",
"port",
"=",
"443",
",",
"auth_method",
"=",
"'basic'",
",",
"client_timeout",
"=",
"60",
")",
":",
"auth_obj",
"=",
"None",
"try",
":",
"protocol",
"=",
"{",
"80",
":",
"'http'",
... | 34.921569 | 16.392157 |
def action_edit_save(self, courseid, taskid, path, content):
""" Save an edited file """
wanted_path = self.verify_path(courseid, taskid, path)
if wanted_path is None:
return json.dumps({"error": True})
try:
self.task_factory.get_task_fs(courseid, taskid).put(want... | [
"def",
"action_edit_save",
"(",
"self",
",",
"courseid",
",",
"taskid",
",",
"path",
",",
"content",
")",
":",
"wanted_path",
"=",
"self",
".",
"verify_path",
"(",
"courseid",
",",
"taskid",
",",
"path",
")",
"if",
"wanted_path",
"is",
"None",
":",
"retu... | 45.1 | 18 |
def handle_lock_expired(
payment_state: InitiatorPaymentState,
state_change: ReceiveLockExpired,
channelidentifiers_to_channels: ChannelMap,
block_number: BlockNumber,
) -> TransitionResult[InitiatorPaymentState]:
"""Initiator also needs to handle LockExpired messages when refund tra... | [
"def",
"handle_lock_expired",
"(",
"payment_state",
":",
"InitiatorPaymentState",
",",
"state_change",
":",
"ReceiveLockExpired",
",",
"channelidentifiers_to_channels",
":",
"ChannelMap",
",",
"block_number",
":",
"BlockNumber",
",",
")",
"->",
"TransitionResult",
"[",
... | 38.76087 | 19.652174 |
def WriteFileHash(self, path, hash_value):
"""Writes the file path and hash to file.
Args:
path (str): path of the file.
hash_value (str): message digest hash calculated over the file data.
"""
string = '{0:s}\t{1:s}\n'.format(hash_value, path)
encoded_string = self._EncodeString(strin... | [
"def",
"WriteFileHash",
"(",
"self",
",",
"path",
",",
"hash_value",
")",
":",
"string",
"=",
"'{0:s}\\t{1:s}\\n'",
".",
"format",
"(",
"hash_value",
",",
"path",
")",
"encoded_string",
"=",
"self",
".",
"_EncodeString",
"(",
"string",
")",
"self",
".",
"_... | 32.363636 | 16 |
def _cosine(a, b):
""" Return the len(a & b) / len(a) """
return 1. * len(a & b) / (math.sqrt(len(a)) * math.sqrt(len(b))) | [
"def",
"_cosine",
"(",
"a",
",",
"b",
")",
":",
"return",
"1.",
"*",
"len",
"(",
"a",
"&",
"b",
")",
"/",
"(",
"math",
".",
"sqrt",
"(",
"len",
"(",
"a",
")",
")",
"*",
"math",
".",
"sqrt",
"(",
"len",
"(",
"b",
")",
")",
")"
] | 42.666667 | 16.666667 |
def list_events(self, source=None, severity=None, text_filter=None,
start=None, stop=None, page_size=500, descending=False):
"""
Reads events between the specified start and stop time.
Events are sorted by generation time, source, then sequence number.
:param str so... | [
"def",
"list_events",
"(",
"self",
",",
"source",
"=",
"None",
",",
"severity",
"=",
"None",
",",
"text_filter",
"=",
"None",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"page_size",
"=",
"500",
",",
"descending",
"=",
"False",
")",
":"... | 45.477273 | 20.931818 |
def flatten(lst):
"""Flatten list.
Args:
lst (list): List to flatten
Returns:
generator
"""
for elm in lst:
if isinstance(elm, collections.Iterable) and not isinstance(
elm, string_types):
for sub in flatten(elm):
yield sub
... | [
"def",
"flatten",
"(",
"lst",
")",
":",
"for",
"elm",
"in",
"lst",
":",
"if",
"isinstance",
"(",
"elm",
",",
"collections",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"elm",
",",
"string_types",
")",
":",
"for",
"sub",
"in",
"flatten",
"(... | 23.857143 | 16.357143 |
def recent_activity(self, user_id):
"""Recent activity (actions) for a given user"""
M = models # noqa
if request.args.get('limit'):
limit = int(request.args.get('limit'))
else:
limit = 1000
qry = (
db.session.query(M.Log, M.Dashboard, M.Sli... | [
"def",
"recent_activity",
"(",
"self",
",",
"user_id",
")",
":",
"M",
"=",
"models",
"# noqa",
"if",
"request",
".",
"args",
".",
"get",
"(",
"'limit'",
")",
":",
"limit",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'limit'",
")",
")... | 30.957447 | 15.723404 |
def log_path(cls, project, log):
"""Return a fully-qualified log string."""
return google.api_core.path_template.expand(
"projects/{project}/logs/{log}", project=project, log=log
) | [
"def",
"log_path",
"(",
"cls",
",",
"project",
",",
"log",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/logs/{log}\"",
",",
"project",
"=",
"project",
",",
"log",
"=",
"log",
")"
] | 42.4 | 16 |
def centers_std(self):
"""The standardized centers for the kmeans model."""
o = self._model_json["output"]
cvals = o["centers_std"].cell_values
centers_std = [list(cval[1:]) for cval in cvals]
centers_std = [list(x) for x in zip(*centers_std)]
return centers_std | [
"def",
"centers_std",
"(",
"self",
")",
":",
"o",
"=",
"self",
".",
"_model_json",
"[",
"\"output\"",
"]",
"cvals",
"=",
"o",
"[",
"\"centers_std\"",
"]",
".",
"cell_values",
"centers_std",
"=",
"[",
"list",
"(",
"cval",
"[",
"1",
":",
"]",
")",
"for... | 43.428571 | 10.285714 |
def create_deamon(cmd, shell=False, root=False):
"""Usage:
Create servcice process.
"""
try:
if root:
cmd.insert(0, 'sudo')
LOG.info(cmd)
subproc = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE,
stderr=subprocess.PIPE... | [
"def",
"create_deamon",
"(",
"cmd",
",",
"shell",
"=",
"False",
",",
"root",
"=",
"False",
")",
":",
"try",
":",
"if",
"root",
":",
"cmd",
".",
"insert",
"(",
"0",
",",
"'sudo'",
")",
"LOG",
".",
"info",
"(",
"cmd",
")",
"subproc",
"=",
"subproce... | 28.357143 | 16.214286 |
def language(s):
""" Returns a (language, confidence)-tuple for the given string.
"""
s = decode_utf8(s)
s = set(w.strip(PUNCTUATION) for w in s.replace("'", "' ").split())
n = float(len(s) or 1)
p = {}
for xx in LANGUAGES:
lexicon = _module(xx).__dict__["lexicon"]
p[xx] = su... | [
"def",
"language",
"(",
"s",
")",
":",
"s",
"=",
"decode_utf8",
"(",
"s",
")",
"s",
"=",
"set",
"(",
"w",
".",
"strip",
"(",
"PUNCTUATION",
")",
"for",
"w",
"in",
"s",
".",
"replace",
"(",
"\"'\"",
",",
"\"' \"",
")",
".",
"split",
"(",
")",
... | 37.727273 | 16.727273 |
def create_user(email, password, active, confirmed_at, send_email):
"""
Create a new user.
"""
if confirmed_at == 'now':
confirmed_at = security.datetime_factory()
user = user_manager.create(email=email, password=password, active=active,
confirmed_at=confirmed_... | [
"def",
"create_user",
"(",
"email",
",",
"password",
",",
"active",
",",
"confirmed_at",
",",
"send_email",
")",
":",
"if",
"confirmed_at",
"==",
"'now'",
":",
"confirmed_at",
"=",
"security",
".",
"datetime_factory",
"(",
")",
"user",
"=",
"user_manager",
"... | 43.285714 | 17.714286 |
def hook_inform(self, inform_name, callback):
"""Hookup a function to be called when an inform is received.
Useful for interface-changed and sensor-status informs.
Parameters
----------
inform_name : str
The name of the inform.
callback : function
... | [
"def",
"hook_inform",
"(",
"self",
",",
"inform_name",
",",
"callback",
")",
":",
"# Do not hook the same callback multiple times",
"if",
"callback",
"not",
"in",
"self",
".",
"_inform_hooks",
"[",
"inform_name",
"]",
":",
"self",
".",
"_inform_hooks",
"[",
"infor... | 32.625 | 17.5 |
def enthalpy_Cpg_Hvap(self):
r'''Method to calculate the enthalpy of an ideal mixture (no pressure
effects). This routine is based on "route A", where only the gas heat
capacity and enthalpy of vaporization are used.
The reference temperature is a property of the class; it defau... | [
"def",
"enthalpy_Cpg_Hvap",
"(",
"self",
")",
":",
"H",
"=",
"0",
"T",
"=",
"self",
".",
"T",
"if",
"self",
".",
"phase",
"==",
"'g'",
":",
"for",
"i",
"in",
"self",
".",
"cmps",
":",
"H",
"+=",
"self",
".",
"zs",
"[",
"i",
"]",
"*",
"self",
... | 41.672414 | 26.465517 |
def coerce(self, value):
"""Convert text values into integer values.
Args:
value (str or int): The value to coerce.
Raises:
TypeError: If the value is not an int or string.
ValueError: If the value is not int or an acceptable value.
Return... | [
"def",
"coerce",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
"or",
"isinstance",
"(",
"value",
",",
"compat",
".",
"long",
")",
":",
"return",
"value",
"return",
"int",
"(",
"value",
")"
] | 27.444444 | 23.111111 |
def load(self, filepath):
"""Load configuration from existing file.
:param str filepath: Path to existing config file.
:raises: ValueError if supplied config file is invalid.
"""
try:
self._config.read(filepath)
self.long_running_operation_timeout = self.... | [
"def",
"load",
"(",
"self",
",",
"filepath",
")",
":",
"try",
":",
"self",
".",
"_config",
".",
"read",
"(",
"filepath",
")",
"self",
".",
"long_running_operation_timeout",
"=",
"self",
".",
"_config",
".",
"getint",
"(",
"\"Azure\"",
",",
"\"long_running_... | 41.0625 | 16.8125 |
def update_pulled_fields(instance, imported_instance, fields):
"""
Update instance fields based on imported from backend data.
Save changes to DB only one or more fields were changed.
"""
modified = False
for field in fields:
pulled_value = getattr(imported_instance, field)
curre... | [
"def",
"update_pulled_fields",
"(",
"instance",
",",
"imported_instance",
",",
"fields",
")",
":",
"modified",
"=",
"False",
"for",
"field",
"in",
"fields",
":",
"pulled_value",
"=",
"getattr",
"(",
"imported_instance",
",",
"field",
")",
"current_value",
"=",
... | 47.75 | 21.75 |
def _Close(self):
"""Closes the file-like object.
If the file-like object was passed in the init function the file
object-based file-like object does not control the file-like object
and should not actually close it.
"""
if not self._file_object_set_in_init:
try:
# TODO: fix close... | [
"def",
"_Close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_file_object_set_in_init",
":",
"try",
":",
"# TODO: fix close being called for the same object multiple times.",
"self",
".",
"_file_object",
".",
"close",
"(",
")",
"except",
"IOError",
":",
"pass"... | 32.571429 | 18.142857 |
def add_optional_arg_param(self, param_name, layer_index, blob_index):
"""Add an arg param. If there is no such param in .caffemodel fie, silently ignore it."""
blobs = self.layers[layer_index].blobs
if blob_index < len(blobs):
self.add_arg_param(param_name, layer_index, blob_index) | [
"def",
"add_optional_arg_param",
"(",
"self",
",",
"param_name",
",",
"layer_index",
",",
"blob_index",
")",
":",
"blobs",
"=",
"self",
".",
"layers",
"[",
"layer_index",
"]",
".",
"blobs",
"if",
"blob_index",
"<",
"len",
"(",
"blobs",
")",
":",
"self",
... | 63 | 13.6 |
def load_plugins(classprefix, plugin_list):
"""
loads the plugins specified in the list
:param classprefix: the class prefix
:param plugin_list: the list of plugins
"""
# classprefix "cmd3.plugins."
plugins = []
import_object = {}
# log.info(str(list))
for plugin in plugin_list:
... | [
"def",
"load_plugins",
"(",
"classprefix",
",",
"plugin_list",
")",
":",
"# classprefix \"cmd3.plugins.\"",
"plugins",
"=",
"[",
"]",
"import_object",
"=",
"{",
"}",
"# log.info(str(list))",
"for",
"plugin",
"in",
"plugin_list",
":",
"if",
"cygwin",
":",
"plugin",... | 34.914286 | 14.4 |
def create_oracle(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a oracle database using cx_oracle.
"""
return create_engine(
_create_oracle(username, password, host, port, database),
**kwargs
) | [
"def",
"create_oracle",
"(",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"return",
"create_engine",
"(",
"_create_oracle",
"(",
"username",
",",
"password",
",",
"host",
","... | 35.375 | 22.125 |
def call(self, name, *args, **kwargs):
"""Make a SoftLayer API call
:param service: the name of the SoftLayer API service
:param method: the method to call on the service
:param \\*args: same optional arguments that ``BaseClient.call`` takes
:param \\*\\*kwargs: same optional ke... | [
"def",
"call",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"client",
".",
"call",
"(",
"self",
".",
"name",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 37.684211 | 22.473684 |
def IV(abf,T1,T2,plotToo=True,color='b'):
"""
Given two time points (seconds) return IV data.
Optionally plots a fancy graph (with errorbars)
Returns [[AV],[SD]] for the given range.
"""
rangeData=abf.average_data([[T1,T2]]) #get the average data per sweep
AV,SD=rangeData[:,0,0],rangeData[:,... | [
"def",
"IV",
"(",
"abf",
",",
"T1",
",",
"T2",
",",
"plotToo",
"=",
"True",
",",
"color",
"=",
"'b'",
")",
":",
"rangeData",
"=",
"abf",
".",
"average_data",
"(",
"[",
"[",
"T1",
",",
"T2",
"]",
"]",
")",
"#get the average data per sweep",
"AV",
",... | 38.912281 | 16.912281 |
def add_filter(self, name, filter_values):
"""
Add a filter for a facet.
"""
# normalize the value into a list
if not isinstance(filter_values, (tuple, list)):
if filter_values is None:
return
filter_values = [filter_values, ]
# re... | [
"def",
"add_filter",
"(",
"self",
",",
"name",
",",
"filter_values",
")",
":",
"# normalize the value into a list",
"if",
"not",
"isinstance",
"(",
"filter_values",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"if",
"filter_values",
"is",
"None",
":",
"ret... | 30.157895 | 14.157895 |
def _listen(self):
"""Listen for messages passed from parent
This method distributes messages received via stdin to their
corresponding channel. Based on the format of the incoming
message, the message is forwarded to its corresponding channel
to be processed by its correspondin... | [
"def",
"_listen",
"(",
"self",
")",
":",
"def",
"_listen",
"(",
")",
":",
"\"\"\"This runs in a thread\"\"\"",
"for",
"line",
"in",
"iter",
"(",
"sys",
".",
"stdin",
".",
"readline",
",",
"b\"\"",
")",
":",
"try",
":",
"response",
"=",
"json",
".",
"lo... | 38.534884 | 22.232558 |
def replace(self, left=None, lower=None, upper=None, right=None, ignore_inf=True):
"""
Create a new interval based on the current one and the provided values.
Callable can be passed instead of values. In that case, it is called with the current
corresponding value except if ignore_inf i... | [
"def",
"replace",
"(",
"self",
",",
"left",
"=",
"None",
",",
"lower",
"=",
"None",
",",
"upper",
"=",
"None",
",",
"right",
"=",
"None",
",",
"ignore_inf",
"=",
"True",
")",
":",
"if",
"callable",
"(",
"left",
")",
":",
"left",
"=",
"left",
"(",... | 40.777778 | 25.833333 |
def check_cgroup_availability_in_thread(options):
"""
Run check_cgroup_availability() in a separate thread to detect the following problem:
If "cgexec --sticky" is used to tell cgrulesengd to not interfere
with our child processes, the sticky flag unfortunately works only
for processes spawned by th... | [
"def",
"check_cgroup_availability_in_thread",
"(",
"options",
")",
":",
"thread",
"=",
"_CheckCgroupsThread",
"(",
"options",
")",
"thread",
".",
"start",
"(",
")",
"thread",
".",
"join",
"(",
")",
"if",
"thread",
".",
"error",
":",
"raise",
"thread",
".",
... | 42 | 19.230769 |
def _set_logging(
logger_name="colin",
level=logging.INFO,
handler_class=logging.StreamHandler,
handler_kwargs=None,
format='%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s',
date_format='%H:%M:%S'):
"""
Set personal logger for this library.
... | [
"def",
"_set_logging",
"(",
"logger_name",
"=",
"\"colin\"",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"handler_class",
"=",
"logging",
".",
"StreamHandler",
",",
"handler_kwargs",
"=",
"None",
",",
"format",
"=",
"'%(asctime)s.%(msecs).03d %(filename)-17s %(l... | 40.966667 | 17.433333 |
def setup(self):
"""
Create mask list.
Consists of all tuples between which this filter accepts lines.
"""
# get start and end of the mask and set a start_limit
if not self.mask_source.start:
raise SystemExit("Can't parse format of %s. Is this a log file or "... | [
"def",
"setup",
"(",
"self",
")",
":",
"# get start and end of the mask and set a start_limit",
"if",
"not",
"self",
".",
"mask_source",
".",
"start",
":",
"raise",
"SystemExit",
"(",
"\"Can't parse format of %s. Is this a log file or \"",
"\"system.profile collection?\"",
"%... | 38.263158 | 22.052632 |
def _attrs_to_init_script(
attrs, frozen, slots, post_init, cache_hash, base_attr_map, is_exc
):
"""
Return a script of an initializer for *attrs* and a dict of globals.
The globals are expected by the generated script.
If *frozen* is True, we cannot set the attributes directly so we use
a cac... | [
"def",
"_attrs_to_init_script",
"(",
"attrs",
",",
"frozen",
",",
"slots",
",",
"post_init",
",",
"cache_hash",
",",
"base_attr_map",
",",
"is_exc",
")",
":",
"lines",
"=",
"[",
"]",
"any_slot_ancestors",
"=",
"any",
"(",
"_is_slot_attr",
"(",
"a",
".",
"n... | 37.776978 | 19.133094 |
def CountHuntLogEntries(self, hunt_id, cursor=None):
"""Returns number of hunt log entries of a given hunt."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = ("SELECT COUNT(*) FROM flow_log_entries "
"FORCE INDEX(flow_log_entries_by_hunt) "
"WHERE hunt_id = %s AND flow_id = h... | [
"def",
"CountHuntLogEntries",
"(",
"self",
",",
"hunt_id",
",",
"cursor",
"=",
"None",
")",
":",
"hunt_id_int",
"=",
"db_utils",
".",
"HuntIDToInt",
"(",
"hunt_id",
")",
"query",
"=",
"(",
"\"SELECT COUNT(*) FROM flow_log_entries \"",
"\"FORCE INDEX(flow_log_entries_b... | 43.666667 | 12.222222 |
def check_array(array, *args, **kwargs):
"""Validate inputs
Parameters
----------
accept_dask_array : bool, default True
accept_dask_dataframe : bool, default False
accept_unknown_chunks : bool, default False
For dask Arrays, whether to allow the `.chunks` attribute to contain
a... | [
"def",
"check_array",
"(",
"array",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"accept_dask_array",
"=",
"kwargs",
".",
"pop",
"(",
"\"accept_dask_array\"",
",",
"True",
")",
"preserve_pandas_dataframe",
"=",
"kwargs",
".",
"pop",
"(",
"\"preserve_... | 36.125 | 20.027778 |
def _pigpio_aio_command(self, cmd, p1, p2,):
"""
Runs a pigpio socket command.
sl:= command socket and lock.
cmd:= the command to be executed.
p1:= command parameter 1 (if applicable).
p2:= command parameter 2 (if applicable).
"""
with (yield from self... | [
"def",
"_pigpio_aio_command",
"(",
"self",
",",
"cmd",
",",
"p1",
",",
"p2",
",",
")",
":",
"with",
"(",
"yield",
"from",
"self",
".",
"_lock",
")",
":",
"data",
"=",
"struct",
".",
"pack",
"(",
"'IIII'",
",",
"cmd",
",",
"p1",
",",
"p2",
",",
... | 37.466667 | 10.266667 |
def from_json(cls, raw):
"""Helper to construct a blob from a dict.
Args:
raw (dict): Raw blob representation.
Returns:
NodeBlob: A NodeBlob object or None.
"""
if raw is None:
return None
bcls = None
_type = raw.get('type')
... | [
"def",
"from_json",
"(",
"cls",
",",
"raw",
")",
":",
"if",
"raw",
"is",
"None",
":",
"return",
"None",
"bcls",
"=",
"None",
"_type",
"=",
"raw",
".",
"get",
"(",
"'type'",
")",
"try",
":",
"bcls",
"=",
"cls",
".",
"_blob_type_map",
"[",
"BlobType"... | 26.84 | 20.64 |
def annual_return(returns, period=DAILY, annualization=None):
"""
Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- ... | [
"def",
"annual_return",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"1",
":",
"return",
"np",
".",
"nan",
"ann_factor",
"=",
"annualization_factor",
"(",
"period",
",",
... | 31.65 | 22.95 |
def version_to_write(self, found): # type: (str) -> Version
"""
Take 1st version string found.
:param found: possible version string
:return:
"""
first = False
if self.version is None:
first = True
try:
self.current_version... | [
"def",
"version_to_write",
"(",
"self",
",",
"found",
")",
":",
"# type: (str) -> Version",
"first",
"=",
"False",
"if",
"self",
".",
"version",
"is",
"None",
":",
"first",
"=",
"True",
"try",
":",
"self",
".",
"current_version",
",",
"self",
".",
"version... | 31.521739 | 18.652174 |
def infer_activations(stmts):
"""Return inferred RegulateActivity from Modification + ActiveForm.
This function looks for combinations of Modification and ActiveForm
Statements and infers Activation/Inhibition Statements from them.
For example, if we know that A phosphorylates B, and th... | [
"def",
"infer_activations",
"(",
"stmts",
")",
":",
"linked_stmts",
"=",
"[",
"]",
"af_stmts",
"=",
"_get_statements_by_type",
"(",
"stmts",
",",
"ActiveForm",
")",
"mod_stmts",
"=",
"_get_statements_by_type",
"(",
"stmts",
",",
"Modification",
")",
"for",
"af_s... | 45.519231 | 20.288462 |
def Copy(self):
"""Return a copy without registering in the attribute registry."""
return Attribute(
self.predicate,
self.attribute_type,
self.description,
self.name,
_copy=True) | [
"def",
"Copy",
"(",
"self",
")",
":",
"return",
"Attribute",
"(",
"self",
".",
"predicate",
",",
"self",
".",
"attribute_type",
",",
"self",
".",
"description",
",",
"self",
".",
"name",
",",
"_copy",
"=",
"True",
")"
] | 27.375 | 16.375 |
def render(msgpack_data, saltenv='base', sls='', **kws):
'''
Accepts a message pack string or a file object, renders said data back to
a python dict.
.. note:
This renderer is NOT intended for use in creating sls files by hand,
but exists to allow for data backends to serialize the high... | [
"def",
"render",
"(",
"msgpack_data",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"*",
"*",
"kws",
")",
":",
"if",
"not",
"isinstance",
"(",
"msgpack_data",
",",
"six",
".",
"string_types",
")",
":",
"msgpack_data",
"=",
"msgpack_data",
... | 37.952381 | 24.142857 |
def with_scopes_if_required(credentials, scopes):
"""Creates a copy of the credentials with scopes if scoping is required.
This helper function is useful when you do not know (or care to know) the
specific type of credentials you are using (such as when you use
:func:`google.auth.default`). This functi... | [
"def",
"with_scopes_if_required",
"(",
"credentials",
",",
"scopes",
")",
":",
"if",
"isinstance",
"(",
"credentials",
",",
"Scoped",
")",
"and",
"credentials",
".",
"requires_scopes",
":",
"return",
"credentials",
".",
"with_scopes",
"(",
"scopes",
")",
"else",... | 42.166667 | 25.208333 |
def process_input(self, data, input_prompt, lineno):
"""
Process data block for INPUT token.
"""
decorator, input, rest = data
image_file = None
image_directive = None
is_verbatim = decorator=='@verbatim' or self.is_verbatim
is_doctest = (decorator is no... | [
"def",
"process_input",
"(",
"self",
",",
"data",
",",
"input_prompt",
",",
"lineno",
")",
":",
"decorator",
",",
"input",
",",
"rest",
"=",
"data",
"image_file",
"=",
"None",
"image_directive",
"=",
"None",
"is_verbatim",
"=",
"decorator",
"==",
"'@verbatim... | 40.447368 | 20.377193 |
def remove_event(self, ref):
"""
Removes an event for a ref (reference),
"""
# is this reference one which has been setup?
if ref in self._refs:
self._refs[ref].remove_callback(ref) | [
"def",
"remove_event",
"(",
"self",
",",
"ref",
")",
":",
"# is this reference one which has been setup?",
"if",
"ref",
"in",
"self",
".",
"_refs",
":",
"self",
".",
"_refs",
"[",
"ref",
"]",
".",
"remove_callback",
"(",
"ref",
")"
] | 32.428571 | 7.285714 |
def group(seq: ActualIterable[T]) -> Dict[TR, List[T]]:
"""
>>> from Redy.Collections import Flow, Traversal
>>> x = [1, 1, 2]
>>> Flow(x)[Traversal.group].unbox
"""
ret = defaultdict(list)
for each in seq:
ret[each].append(each)
return ret | [
"def",
"group",
"(",
"seq",
":",
"ActualIterable",
"[",
"T",
"]",
")",
"->",
"Dict",
"[",
"TR",
",",
"List",
"[",
"T",
"]",
"]",
":",
"ret",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"each",
"in",
"seq",
":",
"ret",
"[",
"each",
"]",
".",
... | 27.1 | 11.7 |
def to_bytes(self, dochecksum=True):
'''
Return packed byte representation of the UDP header.
'''
csum = 0
if dochecksum:
csum = self.checksum()
return b''.join((struct.pack(ICMP._PACKFMT, self._type.value, self._code.value, csum), self._icmpdata.to_bytes())) | [
"def",
"to_bytes",
"(",
"self",
",",
"dochecksum",
"=",
"True",
")",
":",
"csum",
"=",
"0",
"if",
"dochecksum",
":",
"csum",
"=",
"self",
".",
"checksum",
"(",
")",
"return",
"b''",
".",
"join",
"(",
"(",
"struct",
".",
"pack",
"(",
"ICMP",
".",
... | 39 | 26.5 |
def rollback(using=None, sid=None):
"""
Possibility of calling transaction.rollback() in new Django versions (in atomic block).
Important: transaction savepoint (sid) is required for Django < 1.8
"""
if sid:
django.db.transaction.savepoint_rollback(sid)
else:
try:
dj... | [
"def",
"rollback",
"(",
"using",
"=",
"None",
",",
"sid",
"=",
"None",
")",
":",
"if",
"sid",
":",
"django",
".",
"db",
".",
"transaction",
".",
"savepoint_rollback",
"(",
"sid",
")",
"else",
":",
"try",
":",
"django",
".",
"db",
".",
"transaction",
... | 39.166667 | 20.166667 |
def http_method(self, method):
"""
Execute the given HTTP method and returns if it's success or not
and the response as a string if not success and as python object after
unjson if it's success.
"""
self.build_url()
try:
response = self.get_http_metho... | [
"def",
"http_method",
"(",
"self",
",",
"method",
")",
":",
"self",
".",
"build_url",
"(",
")",
"try",
":",
"response",
"=",
"self",
".",
"get_http_method",
"(",
"method",
")",
"is_success",
"=",
"response",
".",
"ok",
"try",
":",
"response_message",
"="... | 30.5 | 17.863636 |
def get_longs():
"""
Get a dictionary that maps Backpage city names to their respective longitudes.
Returns:
dictionary that maps city names (Strings) to longitudes (Floats)
"""
longs = {}
fname = pkg_resources.resource_filename(__name__, 'resources/Latitudes-Longitudes.csv')
with open(fname, 'rb') a... | [
"def",
"get_longs",
"(",
")",
":",
"longs",
"=",
"{",
"}",
"fname",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"__name__",
",",
"'resources/Latitudes-Longitudes.csv'",
")",
"with",
"open",
"(",
"fname",
",",
"'rb'",
")",
"as",
"csvfile",
":",
"# Re... | 31.823529 | 19 |
def url_fix(s, charset='utf-8'):
r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix(u'http://de.wikipedia.org/wi... | [
"def",
"url_fix",
"(",
"s",
",",
"charset",
"=",
"'utf-8'",
")",
":",
"# First step is to switch to unicode processing and to convert",
"# backslashes (which are invalid in URLs anyways) to slashes. This is",
"# consistent with what Chrome does.",
"s",
"=",
"to_unicode",
"(",
"s",... | 46.896552 | 22.965517 |
def p_statement(self, program):
"""
statement : decl
| quantum_op ';'
| format ';'
| ignore
| quantum_op error
| format error
"""
if len(program) > 2:
if program[2] != ... | [
"def",
"p_statement",
"(",
"self",
",",
"program",
")",
":",
"if",
"len",
"(",
"program",
")",
">",
"2",
":",
"if",
"program",
"[",
"2",
"]",
"!=",
"';'",
":",
"raise",
"QasmError",
"(",
"\"Missing ';' at end of statement; \"",
"+",
"\"received\"",
",",
... | 34.285714 | 9.428571 |
def highlight(self, message, *values, **colors):
'''
Highlighter works the way that message parameter is a template,
the "values" is a list of arguments going one after another as values there.
And so the "colors" should designate either highlight color or alternate for each.
Ex... | [
"def",
"highlight",
"(",
"self",
",",
"message",
",",
"*",
"values",
",",
"*",
"*",
"colors",
")",
":",
"m_color",
"=",
"colors",
".",
"get",
"(",
"'_main'",
",",
"self",
".",
"_default_color",
")",
"h_color",
"=",
"colors",
".",
"get",
"(",
"'_highl... | 42.631579 | 32.578947 |
def remove(self, digest):
"""Remove an existing file from fsdb.
File with the given digest will be removed from fsdb and
the directory tree will be cleaned (remove empty folders)
Args:
digest -- digest of the file to remove
"""
# remove file
abs... | [
"def",
"remove",
"(",
"self",
",",
"digest",
")",
":",
"# remove file",
"absPath",
"=",
"self",
".",
"get_file_path",
"(",
"digest",
")",
"os",
".",
"remove",
"(",
"absPath",
")",
"# clean directory tree",
"tmpPath",
"=",
"os",
".",
"path",
".",
"dirname",... | 37.5 | 16.409091 |
def _astroid_bootstrapping():
"""astroid bootstrapping the builtins module"""
# this boot strapping is necessary since we need the Const nodes to
# inspect_build builtins, and then we can proxy Const
builder = InspectBuilder()
astroid_builtin = builder.inspect_build(builtins)
# pylint: disable=... | [
"def",
"_astroid_bootstrapping",
"(",
")",
":",
"# this boot strapping is necessary since we need the Const nodes to",
"# inspect_build builtins, and then we can proxy Const",
"builder",
"=",
"InspectBuilder",
"(",
")",
"astroid_builtin",
"=",
"builder",
".",
"inspect_build",
"(",
... | 38.413793 | 15.465517 |
def quad_fejer(order, lower=0, upper=1, growth=False, part=None):
"""
Generate the quadrature abscissas and weights in Fejer quadrature.
Example:
>>> abscissas, weights = quad_fejer(3, 0, 1)
>>> print(numpy.around(abscissas, 4))
[[0.0955 0.3455 0.6545 0.9045]]
>>> print(nump... | [
"def",
"quad_fejer",
"(",
"order",
",",
"lower",
"=",
"0",
",",
"upper",
"=",
"1",
",",
"growth",
"=",
"False",
",",
"part",
"=",
"None",
")",
":",
"order",
"=",
"numpy",
".",
"asarray",
"(",
"order",
",",
"dtype",
"=",
"int",
")",
".",
"flatten"... | 28.934783 | 18.673913 |
def save_df_output(
df_output: pd.DataFrame,
freq_s: int = 3600,
site: str = '',
path_dir_save: Path = Path('.'),)->list:
'''save supy output dataframe to txt files
Parameters
----------
df_output : pd.DataFrame
output dataframe of supy simulation
freq_s : in... | [
"def",
"save_df_output",
"(",
"df_output",
":",
"pd",
".",
"DataFrame",
",",
"freq_s",
":",
"int",
"=",
"3600",
",",
"site",
":",
"str",
"=",
"''",
",",
"path_dir_save",
":",
"Path",
"=",
"Path",
"(",
"'.'",
")",
",",
")",
"->",
"list",
":",
"list_... | 41.683333 | 21.816667 |
def location_lookup(self, req_location):
"""
returns full location given samecode or county and state. Returns False if not valid.
*currently locations are a dictionary, once other geo data is added, they will move to a location class/obj*
"""
location = False
try:
... | [
"def",
"location_lookup",
"(",
"self",
",",
"req_location",
")",
":",
"location",
"=",
"False",
"try",
":",
"location",
"=",
"self",
".",
"samecodes",
"[",
"req_location",
"[",
"'code'",
"]",
"]",
"except",
"Exception",
":",
"pass",
"try",
":",
"location",... | 35.75 | 25.25 |
def pathways(F, A, B, fraction=1.0, maxiter=1000):
r"""Decompose flux network into dominant reaction paths.
Parameters
----------
F : (M, M) scipy.sparse matrix
The flux network (matrix of netflux values)
A : array_like
The set of starting states
B : array_like
The set o... | [
"def",
"pathways",
"(",
"F",
",",
"A",
",",
"B",
",",
"fraction",
"=",
"1.0",
",",
"maxiter",
"=",
"1000",
")",
":",
"if",
"issparse",
"(",
"F",
")",
":",
"return",
"sparse",
".",
"pathways",
".",
"pathways",
"(",
"F",
",",
"A",
",",
"B",
",",
... | 35.78 | 23.12 |
def log_event(self, event, text = None):
"""
Log lines of text associated with a debug event.
@type event: L{Event}
@param event: Event object.
@type text: str
@param text: (Optional) Text to log. If no text is provided the default
is to show a description... | [
"def",
"log_event",
"(",
"self",
",",
"event",
",",
"text",
"=",
"None",
")",
":",
"self",
".",
"__do_log",
"(",
"DebugLog",
".",
"log_event",
"(",
"event",
",",
"text",
")",
")"
] | 33.25 | 16.583333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.