text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def handle_sigterm():
"""Handle SIGTERM like a normal SIGINT (KeyboardInterrupt).
By default Docker sends a SIGTERM for stopping containers, giving them
time to terminate before getting killed. If a process does not catch this
signal and does nothing, it just gets killed.
Handling SIGTERM like SIG... | [
"def",
"handle_sigterm",
"(",
")",
":",
"original_sigterm_handler",
"=",
"signal",
".",
"getsignal",
"(",
"signal",
".",
"SIGTERM",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"signal",
".",
"default_int_handler",
")",
"try",
":",
"yiel... | 39.111111 | 0.001387 |
def parse_unix(self, lines):
'''Parse listings from a Unix ls command format.'''
# This method uses some Filezilla parsing algorithms
for line in lines:
original_line = line
fields = line.split(' ')
after_perm_index = 0
# Search for the permissio... | [
"def",
"parse_unix",
"(",
"self",
",",
"lines",
")",
":",
"# This method uses some Filezilla parsing algorithms",
"for",
"line",
"in",
"lines",
":",
"original_line",
"=",
"line",
"fields",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"after_perm_index",
"=",
"0",... | 34.983871 | 0.001345 |
def open(
bucket_id,
key_id,
mode,
buffer_size=DEFAULT_BUFFER_SIZE,
min_part_size=DEFAULT_MIN_PART_SIZE,
session=None,
resource_kwargs=None,
multipart_upload_kwargs=None,
):
"""Open an S3 object for reading or writing.
Parameters
-----... | [
"def",
"open",
"(",
"bucket_id",
",",
"key_id",
",",
"mode",
",",
"buffer_size",
"=",
"DEFAULT_BUFFER_SIZE",
",",
"min_part_size",
"=",
"DEFAULT_MIN_PART_SIZE",
",",
"session",
"=",
"None",
",",
"resource_kwargs",
"=",
"None",
",",
"multipart_upload_kwargs",
"=",
... | 30.888889 | 0.001992 |
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Opt... | [
"def",
"update_subnet",
"(",
"subnet",
",",
"name",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"update_subnet",
"(",
"subnet",
",",
"name",
")"
] | 25.705882 | 0.002208 |
def plot_pnlmoney(self):
"""
画出pnl盈亏额散点图
"""
plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_money)
plt.gcf().autofmt_xdate()
return plt | [
"def",
"plot_pnlmoney",
"(",
"self",
")",
":",
"plt",
".",
"scatter",
"(",
"x",
"=",
"self",
".",
"pnl",
".",
"sell_date",
".",
"apply",
"(",
"str",
")",
",",
"y",
"=",
"self",
".",
"pnl",
".",
"pnl_money",
")",
"plt",
".",
"gcf",
"(",
")",
"."... | 27.142857 | 0.010204 |
def add_custom_options(parser):
"""Adds custom options to a parser.
:param parser: the parser to which to add options.
:type parser: argparse.ArgumentParser
"""
parser.add_argument("--report-title", type=str, metavar="TITLE",
default="Genetic Data Clean Up",
... | [
"def",
"add_custom_options",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"\"--report-title\"",
",",
"type",
"=",
"str",
",",
"metavar",
"=",
"\"TITLE\"",
",",
"default",
"=",
"\"Genetic Data Clean Up\"",
",",
"help",
"=",
"\"The report title. [def... | 48.791667 | 0.000838 |
def set_constants(self, *constants, verbose=True):
"""Set the constants associated with the data.
Parameters
----------
constants : str
Expressions for the new set of constants.
verbose : boolean (optional)
Toggle talkback. Default is True
See Al... | [
"def",
"set_constants",
"(",
"self",
",",
"*",
"constants",
",",
"verbose",
"=",
"True",
")",
":",
"# create",
"new",
"=",
"[",
"]",
"current",
"=",
"{",
"c",
".",
"expression",
":",
"c",
"for",
"c",
"in",
"self",
".",
"_constants",
"}",
"for",
"ex... | 29.909091 | 0.001963 |
def do_walk(data_path):
"""
Walk through data_files and list all in dict format
"""
data_files = {}
def cond(File, prefix):
"""
Return True for useful files
Return False for non-useful files
"""
file_path = path.join(prefix, 'data_files', File)
return ... | [
"def",
"do_walk",
"(",
"data_path",
")",
":",
"data_files",
"=",
"{",
"}",
"def",
"cond",
"(",
"File",
",",
"prefix",
")",
":",
"\"\"\"\n Return True for useful files\n Return False for non-useful files\n \"\"\"",
"file_path",
"=",
"path",
".",
"joi... | 32.384615 | 0.002307 |
def cleanup(test_data, udfs, tmp_data, tmp_db):
"""Cleanup Ibis test data and UDFs"""
con = make_ibis_client(ENV)
if udfs:
# this comes before test_data bc the latter clobbers this too
con.hdfs.rmdir(os.path.join(ENV.test_data_dir, 'udf'))
if test_data:
con.drop_database(ENV.te... | [
"def",
"cleanup",
"(",
"test_data",
",",
"udfs",
",",
"tmp_data",
",",
"tmp_db",
")",
":",
"con",
"=",
"make_ibis_client",
"(",
"ENV",
")",
"if",
"udfs",
":",
"# this comes before test_data bc the latter clobbers this too",
"con",
".",
"hdfs",
".",
"rmdir",
"(",... | 28.764706 | 0.00198 |
def method_delegate(**methods):
"""
Construct a renderer that delegates based on the request's HTTP method.
"""
methods = {k.upper(): v for k, v in iteritems(methods)}
if PY3:
methods = {k.encode("utf-8"): v for k, v in iteritems(methods)}
def render(request):
renderer = meth... | [
"def",
"method_delegate",
"(",
"*",
"*",
"methods",
")",
":",
"methods",
"=",
"{",
"k",
".",
"upper",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"methods",
")",
"}",
"if",
"PY3",
":",
"methods",
"=",
"{",
"k",
".",
"encod... | 26.176471 | 0.002169 |
def clone_from(repo_url, repo_dir):
"""Clone a remote git repo into a local directory."""
repo_url = _fix_repo_url(repo_url)
LOG.info("Cloning %s into %s." % (repo_url, repo_dir))
cmd = GIT_CLONE_CMD.format(repo_url, repo_dir)
resp = envoy.run(cmd)
if resp.status_code != 0:
LOG.error("Cl... | [
"def",
"clone_from",
"(",
"repo_url",
",",
"repo_dir",
")",
":",
"repo_url",
"=",
"_fix_repo_url",
"(",
"repo_url",
")",
"LOG",
".",
"info",
"(",
"\"Cloning %s into %s.\"",
"%",
"(",
"repo_url",
",",
"repo_dir",
")",
")",
"cmd",
"=",
"GIT_CLONE_CMD",
".",
... | 41.8 | 0.002342 |
def rundata(self, strjson):
"""POST JSON data object to server"""
d = json.loads(strjson)
return self.api.data.post(d) | [
"def",
"rundata",
"(",
"self",
",",
"strjson",
")",
":",
"d",
"=",
"json",
".",
"loads",
"(",
"strjson",
")",
"return",
"self",
".",
"api",
".",
"data",
".",
"post",
"(",
"d",
")"
] | 27.8 | 0.013986 |
def current_target(self):
"""Return current target."""
actions = self.state[self.state['current_step']]['actions']
for action, value in reversed(actions):
if action == 'target':
return value | [
"def",
"current_target",
"(",
"self",
")",
":",
"actions",
"=",
"self",
".",
"state",
"[",
"self",
".",
"state",
"[",
"'current_step'",
"]",
"]",
"[",
"'actions'",
"]",
"for",
"action",
",",
"value",
"in",
"reversed",
"(",
"actions",
")",
":",
"if",
... | 39.5 | 0.008264 |
def add_option(self, block, name, *values):
""" Adds an option to the AST, either as a non-block option or for an
existing block.
`block`
Block name. Set to ``None`` for non-block option.
`name`
Option name.
`*values`
... | [
"def",
"add_option",
"(",
"self",
",",
"block",
",",
"name",
",",
"*",
"values",
")",
":",
"if",
"not",
"self",
".",
"RE_NAME",
".",
"match",
"(",
"name",
")",
":",
"raise",
"ValueError",
"(",
"u\"Invalid option name '{0}'\"",
".",
"format",
"(",
"common... | 32.538462 | 0.002295 |
def model(x_train, y_train, x_test, y_test):
"""
Model providing function:
Create Keras model with double curly brackets dropped-in as needed.
Return value has to be a valid python dictionary with two customary keys:
- loss: Specify a numeric evaluation metric to be minimized
- status: ... | [
"def",
"model",
"(",
"x_train",
",",
"y_train",
",",
"x_test",
",",
"y_test",
")",
":",
"model",
"=",
"Sequential",
"(",
")",
"model",
".",
"add",
"(",
"Dense",
"(",
"512",
",",
"input_shape",
"=",
"(",
"784",
",",
")",
")",
")",
"model",
".",
"a... | 38.952381 | 0.001789 |
def add_seperator(self):
"""
Add separator between labels in menu that called on right mouse click.
"""
m_item = Gtk.SeparatorMenuItem()
self.menu.append(m_item)
self.menu.show_all() | [
"def",
"add_seperator",
"(",
"self",
")",
":",
"m_item",
"=",
"Gtk",
".",
"SeparatorMenuItem",
"(",
")",
"self",
".",
"menu",
".",
"append",
"(",
"m_item",
")",
"self",
".",
"menu",
".",
"show_all",
"(",
")"
] | 32 | 0.008696 |
def mad(arr, relative=True):
""" Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
med = np.nanme... | [
"def",
"mad",
"(",
"arr",
",",
"relative",
"=",
"True",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"med",
"=",
"np",
".",
"nanmedian",
"(",
"arr",
",",
"axis",
"=",
"1"... | 37 | 0.002028 |
def arcball_constrain_to_axis(point, axis):
"""Return sphere point perpendicular to axis."""
v = np.array(point, dtype=np.float64, copy=True)
a = np.array(axis, dtype=np.float64, copy=True)
v -= a * np.dot(a, v) # on plane
n = vector_norm(v)
if n > _EPS:
if v[2] < 0.0:
np.ne... | [
"def",
"arcball_constrain_to_axis",
"(",
"point",
",",
"axis",
")",
":",
"v",
"=",
"np",
".",
"array",
"(",
"point",
",",
"dtype",
"=",
"np",
".",
"float64",
",",
"copy",
"=",
"True",
")",
"a",
"=",
"np",
".",
"array",
"(",
"axis",
",",
"dtype",
... | 32.5 | 0.002137 |
def map_status_to_catalog(status):
"""Convierte el resultado de action.status_show() en metadata a nivel de
catálogo."""
catalog = dict()
catalog_mapping = {
"site_title": "title",
"site_description": "description"
}
for status_key, catalog_key in iteritems(catalog_mapping):
... | [
"def",
"map_status_to_catalog",
"(",
"status",
")",
":",
"catalog",
"=",
"dict",
"(",
")",
"catalog_mapping",
"=",
"{",
"\"site_title\"",
":",
"\"title\"",
",",
"\"site_description\"",
":",
"\"description\"",
"}",
"for",
"status_key",
",",
"catalog_key",
"in",
"... | 33.714286 | 0.000686 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CompositionSettingsContext for this CompositionSettingsInstance
:rtype: twilio.rest.video.v1.comp... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"CompositionSettingsContext",
"(",
"self",
".",
"_version",
",",
")",
"return",
"self",
".",
"_context"
] | 45.454545 | 0.011765 |
def papermill(
notebook_path,
output_path,
parameters,
parameters_raw,
parameters_file,
parameters_yaml,
parameters_base64,
inject_input_path,
inject_output_path,
inject_paths,
engine,
prepare_only,
kernel,
cwd,
progress_bar,
log_output,
log_level,
... | [
"def",
"papermill",
"(",
"notebook_path",
",",
"output_path",
",",
"parameters",
",",
"parameters_raw",
",",
"parameters_file",
",",
"parameters_yaml",
",",
"parameters_base64",
",",
"inject_input_path",
",",
"inject_output_path",
",",
"inject_paths",
",",
"engine",
"... | 28.142857 | 0.000545 |
def extract_code_from_args(args):
"""
Extracts the access code from the arguments dictionary (given back
from github)
"""
if args is None:
raise_error("Couldn't extract GitHub authentication code "
"from response")
# TODO: Is there a case where the length of the erro... | [
"def",
"extract_code_from_args",
"(",
"args",
")",
":",
"if",
"args",
"is",
"None",
":",
"raise_error",
"(",
"\"Couldn't extract GitHub authentication code \"",
"\"from response\"",
")",
"# TODO: Is there a case where the length of the error will be < 0?",
"error",
"=",
"args",... | 33.793103 | 0.000992 |
def got_score(self, score):
"""Update the best score if the new score is higher, returning the change."""
if score > self._score:
delta = score - self._score
self._score = score
self._score_changed = True
self.save()
return delta
return... | [
"def",
"got_score",
"(",
"self",
",",
"score",
")",
":",
"if",
"score",
">",
"self",
".",
"_score",
":",
"delta",
"=",
"score",
"-",
"self",
".",
"_score",
"self",
".",
"_score",
"=",
"score",
"self",
".",
"_score_changed",
"=",
"True",
"self",
".",
... | 34.888889 | 0.009317 |
def create(filename, spec):
"""Create a new segy file.
Create a new segy file with the geometry and properties given by `spec`.
This enables creating SEGY files from your data. The created file supports
all segyio modes, but has an emphasis on writing. The spec must be
complete, otherwise an except... | [
"def",
"create",
"(",
"filename",
",",
"spec",
")",
":",
"from",
".",
"import",
"_segyio",
"if",
"not",
"structured",
"(",
"spec",
")",
":",
"tracecount",
"=",
"spec",
".",
"tracecount",
"else",
":",
"tracecount",
"=",
"len",
"(",
"spec",
".",
"ilines"... | 29.368421 | 0.008194 |
def _op(self, operation, other, *allowed):
"""A basic operation operating on a single value."""
f = self._field
if self._combining: # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz).
return reduce(self._combining,
(q._op(operation, other, *allowed) for q in f)) # pylint:disable=pr... | [
"def",
"_op",
"(",
"self",
",",
"operation",
",",
"other",
",",
"*",
"allowed",
")",
":",
"f",
"=",
"self",
".",
"_field",
"if",
"self",
".",
"_combining",
":",
"# We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz).",
"return",
"reduce",
"(",
"self... | 42 | 0.038356 |
def read_analogies_file(eval_file='questions-words.txt', word2id=None):
"""Reads through an analogy question file, return its id format.
Parameters
----------
eval_file : str
The file name.
word2id : dictionary
a dictionary that maps word to ID.
Returns
--------
numpy.a... | [
"def",
"read_analogies_file",
"(",
"eval_file",
"=",
"'questions-words.txt'",
",",
"word2id",
"=",
"None",
")",
":",
"if",
"word2id",
"is",
"None",
":",
"word2id",
"=",
"{",
"}",
"questions",
"=",
"[",
"]",
"questions_skipped",
"=",
"0",
"with",
"open",
"(... | 32.476923 | 0.001839 |
def plot(X, marker='.', kind='plot', title=None, fig='current', ax=None,
**kwargs):
'''General plotting function that aims to cover most common cases.
X : numpy array of 1d, 2d, or 3d points, with one point per row.
marker : passed to the underlying plotting function
kind : one of {plot, scatter} that ... | [
"def",
"plot",
"(",
"X",
",",
"marker",
"=",
"'.'",
",",
"kind",
"=",
"'plot'",
",",
"title",
"=",
"None",
",",
"fig",
"=",
"'current'",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"X",
"=",
"np",
".",
"asanyarray",
"(",
"X",
"... | 38.243902 | 0.022388 |
def search(self, query, search_term, search_field, catalog):
"""Performs a search against the catalog and returns the brains
"""
logger.info("Reference Widget Catalog: {}".format(catalog.id))
if not search_term:
return catalog(query)
index = self.get_index(search_fie... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"search_term",
",",
"search_field",
",",
"catalog",
")",
":",
"logger",
".",
"info",
"(",
"\"Reference Widget Catalog: {}\"",
".",
"format",
"(",
"catalog",
".",
"id",
")",
")",
"if",
"not",
"search_term",
"... | 37.242424 | 0.001586 |
def DeleteMessageHandlerRequests(self, requests):
"""Deletes a list of message handler requests from the database."""
for r in requests:
flow_dict = self.message_handler_requests.get(r.handler_name, {})
if r.request_id in flow_dict:
del flow_dict[r.request_id]
flow_dict = self.message... | [
"def",
"DeleteMessageHandlerRequests",
"(",
"self",
",",
"requests",
")",
":",
"for",
"r",
"in",
"requests",
":",
"flow_dict",
"=",
"self",
".",
"message_handler_requests",
".",
"get",
"(",
"r",
".",
"handler_name",
",",
"{",
"}",
")",
"if",
"r",
".",
"r... | 42.2 | 0.011601 |
def verify_manifest_main_checksum(self, manifest):
"""
Verify the checksum over the manifest main section.
:return: True if the signature over main section verifies
"""
# NOTE: JAR spec does not state whether there can be >1 digest used,
# and should the validator requi... | [
"def",
"verify_manifest_main_checksum",
"(",
"self",
",",
"manifest",
")",
":",
"# NOTE: JAR spec does not state whether there can be >1 digest used,",
"# and should the validator require any or all digests to match.",
"# We allow mismatching digests and require just one to be correct.",
"# We... | 41.590909 | 0.002137 |
def get_relation_count_query(self, query, parent):
"""
Add the constraints for a relationship count query.
:type query: eloquent.orm.Builder
:type parent: eloquent.orm.Builder
:rtype: eloquent.orm.Builder
"""
query = super(MorphToMany, self).get_relation_count_q... | [
"def",
"get_relation_count_query",
"(",
"self",
",",
"query",
",",
"parent",
")",
":",
"query",
"=",
"super",
"(",
"MorphToMany",
",",
"self",
")",
".",
"get_relation_count_query",
"(",
"query",
",",
"parent",
")",
"return",
"query",
".",
"where",
"(",
"'%... | 34.833333 | 0.009324 |
def parse_dbus_address(address):
"""Parse a D-BUS address string into a list of addresses."""
if address == 'session':
address = os.environ.get('DBUS_SESSION_BUS_ADDRESS')
if not address:
raise ValueError('$DBUS_SESSION_BUS_ADDRESS not set')
elif address == 'system':
addr... | [
"def",
"parse_dbus_address",
"(",
"address",
")",
":",
"if",
"address",
"==",
"'session'",
":",
"address",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'DBUS_SESSION_BUS_ADDRESS'",
")",
"if",
"not",
"address",
":",
"raise",
"ValueError",
"(",
"'$DBUS_SESSION_B... | 41.83871 | 0.000754 |
def _getUE4BuildInterrogator(self):
"""
Uses UE4BuildInterrogator to interrogate UnrealBuildTool about third-party library details
"""
ubtLambda = lambda target, platform, config, args: self._runUnrealBuildTool(target, platform, config, args, True)
interrogator = UE4BuildInterrogator(self.getEngineRoot(), sel... | [
"def",
"_getUE4BuildInterrogator",
"(",
"self",
")",
":",
"ubtLambda",
"=",
"lambda",
"target",
",",
"platform",
",",
"config",
",",
"args",
":",
"self",
".",
"_runUnrealBuildTool",
"(",
"target",
",",
"platform",
",",
"config",
",",
"args",
",",
"True",
"... | 58 | 0.029126 |
def model_from_string(self, model_str, verbose=True):
"""Load Booster from a string.
Parameters
----------
model_str : string
Model will be loaded from this string.
verbose : bool, optional (default=True)
Whether to print messages while loading model.
... | [
"def",
"model_from_string",
"(",
"self",
",",
"model_str",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"self",
".",
"handle",
"is",
"not",
"None",
":",
"_safe_call",
"(",
"_LIB",
".",
"LGBM_BoosterFree",
"(",
"self",
".",
"handle",
")",
")",
"self",
"... | 36.212121 | 0.002445 |
def _write_bed_header(self):
"""Writes the BED first 3 bytes."""
# Writing the first three bytes
final_byte = 1 if self._bed_format == "SNP-major" else 0
self._bed.write(bytearray((108, 27, final_byte))) | [
"def",
"_write_bed_header",
"(",
"self",
")",
":",
"# Writing the first three bytes",
"final_byte",
"=",
"1",
"if",
"self",
".",
"_bed_format",
"==",
"\"SNP-major\"",
"else",
"0",
"self",
".",
"_bed",
".",
"write",
"(",
"bytearray",
"(",
"(",
"108",
",",
"27... | 46.2 | 0.008511 |
def escape( x, lb=False ):
"""
Ensure a string does not contain HTML-reserved characters (including
double quotes)
Optionally also insert a linebreak if the string is too long
"""
# Insert a linebreak? Roughly around the middle of the string,
if lb:
l = len(x)
if l >= 10:
... | [
"def",
"escape",
"(",
"x",
",",
"lb",
"=",
"False",
")",
":",
"# Insert a linebreak? Roughly around the middle of the string,",
"if",
"lb",
":",
"l",
"=",
"len",
"(",
"x",
")",
"if",
"l",
">=",
"10",
":",
"l",
">>=",
"1",
"# middle of the string",
"s1",
"=... | 40.85 | 0.014354 |
def convert(self, normalization=None, csphase=None, lmax=None):
"""
Return an SHMagCoeffs class instance with a different normalization
convention.
Usage
-----
clm = x.convert([normalization, csphase, lmax])
Returns
-------
clm : SHMagCoeffs clas... | [
"def",
"convert",
"(",
"self",
",",
"normalization",
"=",
"None",
",",
"csphase",
"=",
"None",
",",
"lmax",
"=",
"None",
")",
":",
"if",
"normalization",
"is",
"None",
":",
"normalization",
"=",
"self",
".",
"normalization",
"if",
"csphase",
"is",
"None"... | 43.633803 | 0.000631 |
def profile_list(list_names=False, remote_addr=None,
cert=None, key=None, verify_cert=True):
''' Lists all profiles from the LXD.
list_names :
Return a list of names instead of full blown dicts.
remote_addr :
An URL to a remote Server, you also have to giv... | [
"def",
"profile_list",
"(",
"list_names",
"=",
"False",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
")",
":",
"client",
"=",
"pylxd_client_get",
"(",
"remote_addr",
",",
"cert",
","... | 26.625 | 0.000755 |
def execute(self, cmd, cwd):
"""
Execute commands and output this
:param cmd: -- list of cmd command and arguments
:type cmd: list
:param cwd: -- workdir for executions
:type cwd: str,unicode
:return: -- string with full output
:rtype: str
"""
... | [
"def",
"execute",
"(",
"self",
",",
"cmd",
",",
"cwd",
")",
":",
"self",
".",
"output",
"=",
"\"\"",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
".",
"update",
"(",
"self",
".",
"env",
")",
"if",
"six",
".",
"PY2",
":",
"#... | 33.571429 | 0.001654 |
def all(self, cache=False):
"""
can use cache to return objects
"""
if cache:
return [get_object(self.modelb, obj_id, cache=True, use_local=True) for obj_id in self.keys(True)]
else:
return self | [
"def",
"all",
"(",
"self",
",",
"cache",
"=",
"False",
")",
":",
"if",
"cache",
":",
"return",
"[",
"get_object",
"(",
"self",
".",
"modelb",
",",
"obj_id",
",",
"cache",
"=",
"True",
",",
"use_local",
"=",
"True",
")",
"for",
"obj_id",
"in",
"self... | 31.375 | 0.011628 |
def newDocRawNode(self, doc, name, content):
"""Creation of a new node element within a document. @ns and
@content are optional (None). """
if doc is None: doc__o = None
else: doc__o = doc._o
ret = libxml2mod.xmlNewDocRawNode(doc__o, self._o, name, content)
if ret is N... | [
"def",
"newDocRawNode",
"(",
"self",
",",
"doc",
",",
"name",
",",
"content",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlNewDocRawNode",
"(",
"doc_... | 46.111111 | 0.014184 |
def leapfrog(func,yo,t,args=(),rtol=1.49012e-12,atol=1.49012e-12):
"""
NAME:
leapfrog
PURPOSE:
leapfrog integrate an ode
INPUT:
func - force function of (y,*args)
yo - initial condition [q,p]
t - set of times at which one wants the result
rtol, atol
OUTPUT:
... | [
"def",
"leapfrog",
"(",
"func",
",",
"yo",
",",
"t",
",",
"args",
"=",
"(",
")",
",",
"rtol",
"=",
"1.49012e-12",
",",
"atol",
"=",
"1.49012e-12",
")",
":",
"#Initialize",
"qo",
"=",
"yo",
"[",
"0",
":",
"len",
"(",
"yo",
")",
"//",
"2",
"]",
... | 30.844444 | 0.037709 |
def total_energy(self):
"""
The total energy.
"""
return sum(sum(self._recip)) + sum(sum(self._real)) + sum(self._point) + self._charged_cell_energy | [
"def",
"total_energy",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"sum",
"(",
"self",
".",
"_recip",
")",
")",
"+",
"sum",
"(",
"sum",
"(",
"self",
".",
"_real",
")",
")",
"+",
"sum",
"(",
"self",
".",
"_point",
")",
"+",
"self",
".",
"_charg... | 35.2 | 0.016667 |
def set_rest_notification(self, url, hit_type_id):
"""Set a REST endpoint to recieve notifications about the HIT
The newer AWS MTurk API does not support this feature, which means we
cannot use boto3 here. Instead, we make the call manually after
assembling a properly signed request.
... | [
"def",
"set_rest_notification",
"(",
"self",
",",
"url",
",",
"hit_type_id",
")",
":",
"ISO8601",
"=",
"\"%Y-%m-%dT%H:%M:%SZ\"",
"notification_version",
"=",
"\"2006-05-05\"",
"API_version",
"=",
"\"2014-08-15\"",
"data",
"=",
"{",
"\"AWSAccessKeyId\"",
":",
"self",
... | 48.756757 | 0.002174 |
def returnSplineList(dependentVar, independentVar, subsetPercentage=0.4,
cycles=10, minKnotPoints=10, initialKnots=200,
splineOrder=2, terminalExpansion=0.1
):
""" #TODO: docstring
Note: Expects sorted arrays.
:param dependentVar: #TODO: docst... | [
"def",
"returnSplineList",
"(",
"dependentVar",
",",
"independentVar",
",",
"subsetPercentage",
"=",
"0.4",
",",
"cycles",
"=",
"10",
",",
"minKnotPoints",
"=",
"10",
",",
"initialKnots",
"=",
"200",
",",
"splineOrder",
"=",
"2",
",",
"terminalExpansion",
"=",... | 40.732394 | 0.001688 |
def _query(self, cmd, *datas):
"""Helper function to allow method queries."""
cmd = Command(query=cmd)
return cmd.query(self._transport, self._protocol, *datas) | [
"def",
"_query",
"(",
"self",
",",
"cmd",
",",
"*",
"datas",
")",
":",
"cmd",
"=",
"Command",
"(",
"query",
"=",
"cmd",
")",
"return",
"cmd",
".",
"query",
"(",
"self",
".",
"_transport",
",",
"self",
".",
"_protocol",
",",
"*",
"datas",
")"
] | 45.25 | 0.01087 |
def _compile_rules(self):
"""Compile the rules into the internal lexer state."""
for state, table in self.RULES.items():
patterns = list()
actions = list()
nextstates = list()
for i, row in enumerate(table):
if len(row) == 2:
... | [
"def",
"_compile_rules",
"(",
"self",
")",
":",
"for",
"state",
",",
"table",
"in",
"self",
".",
"RULES",
".",
"items",
"(",
")",
":",
"patterns",
"=",
"list",
"(",
")",
"actions",
"=",
"list",
"(",
")",
"nextstates",
"=",
"list",
"(",
")",
"for",
... | 43.15 | 0.002268 |
def get_system_encoding():
"""
The encoding of the default system locale but falls back to the given
fallback encoding if the encoding is unsupported by python or could
not be determined. See tickets #10335 and #5846
"""
try:
encoding = locale.getdefaultlocale()[1] or 'ascii'
co... | [
"def",
"get_system_encoding",
"(",
")",
":",
"try",
":",
"encoding",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"[",
"1",
"]",
"or",
"'ascii'",
"codecs",
".",
"lookup",
"(",
"encoding",
")",
"except",
"Exception",
":",
"encoding",
"=",
"'ascii'",
... | 33.25 | 0.002439 |
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
shear parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another... | [
"def",
"transform",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"# convert to radians and unpack",
"shear",
"=",
"[",
"math",
".",
"pi",
"/",
"180",
"*",
"s",
"for",
"s",
"in",
"self",
".",
"shear",
"]",
"shear_x",
",",
"sh... | 35.023256 | 0.001292 |
def fix_calculation_version_inconsistencies(portal):
"""Creates the first version of all Calculations that hasn't been yet edited
See: https://github.com/senaite/senaite.core/pull/1260
"""
logger.info("Fix Calculation version inconsistencies ...")
brains = api.search({"portal_type": "Calculation"}, ... | [
"def",
"fix_calculation_version_inconsistencies",
"(",
"portal",
")",
":",
"logger",
".",
"info",
"(",
"\"Fix Calculation version inconsistencies ...\"",
")",
"brains",
"=",
"api",
".",
"search",
"(",
"{",
"\"portal_type\"",
":",
"\"Calculation\"",
"}",
",",
"\"bika_s... | 50 | 0.002181 |
def _check_token_cache_type(self, cache_value):
'''
Checks the cache_value for appropriate type correctness.
Pass strict=True for strict validation to ensure the latest types are
being written.
Returns true is correct type, False otherwise.
'''
def check_string_... | [
"def",
"_check_token_cache_type",
"(",
"self",
",",
"cache_value",
")",
":",
"def",
"check_string_value",
"(",
"name",
")",
":",
"return",
"(",
"isinstance",
"(",
"cache_value",
"[",
"name",
"]",
",",
"str",
")",
"or",
"isinstance",
"(",
"cache_value",
"[",
... | 31.517241 | 0.002123 |
def set_menu(self, menu):
'''add a menu from the parent'''
self.menu = menu
wx_menu = menu.wx_menu()
self.frame.SetMenuBar(wx_menu)
self.frame.Bind(wx.EVT_MENU, self.on_menu) | [
"def",
"set_menu",
"(",
"self",
",",
"menu",
")",
":",
"self",
".",
"menu",
"=",
"menu",
"wx_menu",
"=",
"menu",
".",
"wx_menu",
"(",
")",
"self",
".",
"frame",
".",
"SetMenuBar",
"(",
"wx_menu",
")",
"self",
".",
"frame",
".",
"Bind",
"(",
"wx",
... | 34.833333 | 0.009346 |
def user(self):
"""
| Comment: The id of the user who has this subscription
"""
if self.api and self.user_id:
return self.api._get_user(self.user_id) | [
"def",
"user",
"(",
"self",
")",
":",
"if",
"self",
".",
"api",
"and",
"self",
".",
"user_id",
":",
"return",
"self",
".",
"api",
".",
"_get_user",
"(",
"self",
".",
"user_id",
")"
] | 31.5 | 0.010309 |
def _publish_instruction_as_executed(self, insn):
"""
Notify listeners that an instruction has been executed.
"""
self._icount += 1
self._publish('did_execute_instruction', self._last_pc, self.PC, insn) | [
"def",
"_publish_instruction_as_executed",
"(",
"self",
",",
"insn",
")",
":",
"self",
".",
"_icount",
"+=",
"1",
"self",
".",
"_publish",
"(",
"'did_execute_instruction'",
",",
"self",
".",
"_last_pc",
",",
"self",
".",
"PC",
",",
"insn",
")"
] | 39.5 | 0.008264 |
def remove_role(self, databaseName, roleName, collectionName=None):
"""Remove one role
Args:
databaseName (str): Database Name
roleName (RoleSpecs): role
Keyword Args:
collectionName (str): Collection
"""
role = {"database... | [
"def",
"remove_role",
"(",
"self",
",",
"databaseName",
",",
"roleName",
",",
"collectionName",
"=",
"None",
")",
":",
"role",
"=",
"{",
"\"databaseName\"",
":",
"databaseName",
",",
"\"roleName\"",
":",
"roleName",
"}",
"if",
"collectionName",
":",
"role",
... | 29.277778 | 0.014706 |
def get_redacted_args(entrypoint, *args, **kwargs):
""" Utility function for use with entrypoints that are marked with
``sensitive_arguments`` -- e.g. :class:`nameko.rpc.Rpc` and
:class:`nameko.events.EventHandler`.
:Parameters:
entrypoint : :class:`~nameko.extensions.Entrypoint`
Th... | [
"def",
"get_redacted_args",
"(",
"entrypoint",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"sensitive_arguments",
"=",
"entrypoint",
".",
"sensitive_arguments",
"if",
"isinstance",
"(",
"sensitive_arguments",
",",
"six",
".",
"string_types",
")",
":",
... | 34.916667 | 0.00029 |
def readline(self, size=-1):
"The size is ignored since a complete line must be read."
line = self.fin.readline()
if not line:
return ''
return self.process_line(line.rstrip('\n')) | [
"def",
"readline",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"line",
"=",
"self",
".",
"fin",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"return",
"''",
"return",
"self",
".",
"process_line",
"(",
"line",
".",
"rstrip",
"(",
"'... | 36.5 | 0.008929 |
def gen_listfiles(ext, data_path=current_path, start_date=None, end_date=None):
"""**Generate list of files in data directory**
Using a specified data path and extension generate list of files in data
directory. If start_date and end_date aren't specified, all files in the
data directory are selected.
... | [
"def",
"gen_listfiles",
"(",
"ext",
",",
"data_path",
"=",
"current_path",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
")",
":",
"# make list of all files in data directory with certain extension ext",
"listfiles",
"=",
"[",
"fn",
"for",
"fn",
"in"... | 39.583333 | 0.000685 |
def list_paths(self):
"""Utility method to list all the paths in the jar."""
paths = []
for cookie in iter(self):
if cookie.path not in paths:
paths.append(cookie.path)
return paths | [
"def",
"list_paths",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"if",
"cookie",
".",
"path",
"not",
"in",
"paths",
":",
"paths",
".",
"append",
"(",
"cookie",
".",
"path",
")",
"return",
"... | 33.571429 | 0.008299 |
def elliot_function( signal, derivative=False ):
""" A fast approximation of sigmoid """
s = 1 # steepness
abs_signal = (1 + np.abs(signal * s))
if derivative:
return 0.5 * s / abs_signal**2
else:
# Return the activation signal
return 0.5*(signal * s) / abs_signal + 0.5 | [
"def",
"elliot_function",
"(",
"signal",
",",
"derivative",
"=",
"False",
")",
":",
"s",
"=",
"1",
"# steepness",
"abs_signal",
"=",
"(",
"1",
"+",
"np",
".",
"abs",
"(",
"signal",
"*",
"s",
")",
")",
"if",
"derivative",
":",
"return",
"0.5",
"*",
... | 31 | 0.015674 |
def new_context(environment, template_name, blocks, vars=None,
shared=None, globals=None, locals=None):
"""Internal helper to for context creation."""
if vars is None:
vars = {}
if shared:
parent = vars
else:
parent = dict(globals or (), **vars)
if locals:
... | [
"def",
"new_context",
"(",
"environment",
",",
"template_name",
",",
"blocks",
",",
"vars",
"=",
"None",
",",
"shared",
"=",
"None",
",",
"globals",
"=",
"None",
",",
"locals",
"=",
"None",
")",
":",
"if",
"vars",
"is",
"None",
":",
"vars",
"=",
"{",... | 37.052632 | 0.001385 |
def display_start(self):
"""Start status display if option selected."""
if self.opt['Verbose'] and self.opt['StatusHeader']:
print(self.hdrstr)
print("-" * self.nsep) | [
"def",
"display_start",
"(",
"self",
")",
":",
"if",
"self",
".",
"opt",
"[",
"'Verbose'",
"]",
"and",
"self",
".",
"opt",
"[",
"'StatusHeader'",
"]",
":",
"print",
"(",
"self",
".",
"hdrstr",
")",
"print",
"(",
"\"-\"",
"*",
"self",
".",
"nsep",
"... | 33.666667 | 0.009662 |
def parser_available(fpath):
""" test if parser plugin available for fpath
Examples
--------
>>> load_builtin_plugins('parsers')
[]
>>> test_file = StringIO('{"a":[1,2,3.4]}')
>>> test_file.name = 'test.json'
>>> parser_available(test_file)
True
>>> test_file.name = 'test.other... | [
"def",
"parser_available",
"(",
"fpath",
")",
":",
"if",
"isinstance",
"(",
"fpath",
",",
"basestring",
")",
":",
"fname",
"=",
"fpath",
"elif",
"hasattr",
"(",
"fpath",
",",
"'open'",
")",
"and",
"hasattr",
"(",
"fpath",
",",
"'name'",
")",
":",
"fnam... | 25.352941 | 0.001117 |
def get_extension(self, index):
"""
Get a specific extension of the certificate by index.
Extensions on a certificate are kept in order. The index
parameter selects which extension will be returned.
:param int index: The index of the extension to retrieve.
:return: The ... | [
"def",
"get_extension",
"(",
"self",
",",
"index",
")",
":",
"ext",
"=",
"X509Extension",
".",
"__new__",
"(",
"X509Extension",
")",
"ext",
".",
"_extension",
"=",
"_lib",
".",
"X509_get_ext",
"(",
"self",
".",
"_x509",
",",
"index",
")",
"if",
"ext",
... | 38.772727 | 0.002288 |
def overlaps(self,in_genomic_range,padding=0):
"""do the ranges overlap?
:param in_genomic_range: range to compare to
:param padding: add to the ends this many (default 0)
:type in_genomic_range: GenomicRange
:type padding: int
:return: True if they overlap
:rtype: bool
"""
if pad... | [
"def",
"overlaps",
"(",
"self",
",",
"in_genomic_range",
",",
"padding",
"=",
"0",
")",
":",
"if",
"padding",
">",
"0",
":",
"in_genomic_range",
"=",
"GenomicRange",
"(",
"in_genomic_range",
".",
"chr",
",",
"max",
"(",
"[",
"1",
",",
"in_genomic_range",
... | 36.763158 | 0.016039 |
def get_argument_parser():
"""Returns an argument parser object for the script."""
desc = 'Filter FASTA file by chromosome names.'
parser = cli.get_argument_parser(desc=desc)
parser.add_argument(
'-f', '--fasta-file', default='-', type=str, help=textwrap.dedent("""\
Path of the... | [
"def",
"get_argument_parser",
"(",
")",
":",
"desc",
"=",
"'Filter FASTA file by chromosome names.'",
"parser",
"=",
"cli",
".",
"get_argument_parser",
"(",
"desc",
"=",
"desc",
")",
"parser",
".",
"add_argument",
"(",
"'-f'",
",",
"'--fasta-file'",
",",
"default"... | 36.777778 | 0.001472 |
def convert_units_to_base_units(units):
"""Convert a set of units into a set of "base" units.
Returns a 2-tuple of `factor, new_units`.
"""
total_factor = 1
new_units = []
for unit in units:
if unit not in BASE_UNIT_CONVERSIONS:
continue
factor, new_unit = BASE_UNIT... | [
"def",
"convert_units_to_base_units",
"(",
"units",
")",
":",
"total_factor",
"=",
"1",
"new_units",
"=",
"[",
"]",
"for",
"unit",
"in",
"units",
":",
"if",
"unit",
"not",
"in",
"BASE_UNIT_CONVERSIONS",
":",
"continue",
"factor",
",",
"new_unit",
"=",
"BASE_... | 26.588235 | 0.002137 |
def write(self, data):
"""Write the chunk data"""
if len(data) > self.data_size:
raise ValueError
self.__fileobj.seek(self.data_offset)
self.__fileobj.write(data) | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
">",
"self",
".",
"data_size",
":",
"raise",
"ValueError",
"self",
".",
"__fileobj",
".",
"seek",
"(",
"self",
".",
"data_offset",
")",
"self",
".",
"__fileobj",
".",
... | 25.125 | 0.009615 |
def make_strain_from_inj_object(self, inj, delta_t, detector_name,
f_lower=None, distance_scale=1):
"""Make a h(t) strain time-series from an injection object.
Parameters
-----------
inj : injection object
The injection object to turn into... | [
"def",
"make_strain_from_inj_object",
"(",
"self",
",",
"inj",
",",
"delta_t",
",",
"detector_name",
",",
"f_lower",
"=",
"None",
",",
"distance_scale",
"=",
"1",
")",
":",
"detector",
"=",
"Detector",
"(",
"detector_name",
")",
"if",
"f_lower",
"is",
"None"... | 34.545455 | 0.002047 |
def _do_poll_problems(self):
"""Poll the server for the status of a set of problems.
Note:
This method is always run inside of a daemon thread.
"""
try:
# grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME)
frame_futures = {}
def... | [
"def",
"_do_poll_problems",
"(",
"self",
")",
":",
"try",
":",
"# grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME)",
"frame_futures",
"=",
"{",
"}",
"def",
"task_done",
"(",
")",
":",
"self",
".",
"_poll_queue",
".",
"task_done",
"(",
")",
"def",
"add"... | 36.02 | 0.001891 |
def path(self):
"""Return path
:returns: path
:rtype: str
:raises: None
"""
p = os.path.normpath(self._path)
if p.endswith(':'):
p = p + os.path.sep
return p | [
"def",
"path",
"(",
"self",
")",
":",
"p",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"self",
".",
"_path",
")",
"if",
"p",
".",
"endswith",
"(",
"':'",
")",
":",
"p",
"=",
"p",
"+",
"os",
".",
"path",
".",
"sep",
"return",
"p"
] | 20.363636 | 0.008547 |
def _update_color_hsv(self, event=None):
"""Update display after a change in the HSV spinboxes."""
if event is None or event.widget.old_value != event.widget.get():
h = self.hue.get()
s = self.saturation.get()
v = self.value.get()
sel_color = hsv_to_rgb(h,... | [
"def",
"_update_color_hsv",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"if",
"event",
"is",
"None",
"or",
"event",
".",
"widget",
".",
"old_value",
"!=",
"event",
".",
"widget",
".",
"get",
"(",
")",
":",
"h",
"=",
"self",
".",
"hue",
".",
... | 41.526316 | 0.002478 |
def add_keyrepeat_callback(self, key, fn):
"""
Allows for custom callback functions for the viewer. Called on key repeat.
Parameter 'any' will ensure that the callback is called on any key repeat,
and block default mujoco viewer callbacks from executing, except for
the ESC callb... | [
"def",
"add_keyrepeat_callback",
"(",
"self",
",",
"key",
",",
"fn",
")",
":",
"self",
".",
"viewer",
".",
"keyrepeat",
"[",
"key",
"]",
".",
"append",
"(",
"fn",
")"
] | 49.375 | 0.012438 |
def read_midc(filename, variable_map=VARIABLE_MAP, raw_data=False):
"""Read in National Renewable Energy Laboratory Measurement and
Instrumentation Data Center [1]_ weather data.
Parameters
----------
filename: string
Filename or url of data to read.
variable_map: dictionary
Dic... | [
"def",
"read_midc",
"(",
"filename",
",",
"variable_map",
"=",
"VARIABLE_MAP",
",",
"raw_data",
"=",
"False",
")",
":",
"data",
"=",
"pd",
".",
"read_csv",
"(",
"filename",
")",
"if",
"raw_data",
":",
"data",
"=",
"format_index_raw",
"(",
"data",
")",
"e... | 35.734694 | 0.000556 |
def grant_qualification(self, qualification_request_id, integer_value=1):
"""TODO: Document."""
params = {'QualificationRequestId' : qualification_request_id,
'IntegerValue' : integer_value}
return self._process_request('GrantQualification', params) | [
"def",
"grant_qualification",
"(",
"self",
",",
"qualification_request_id",
",",
"integer_value",
"=",
"1",
")",
":",
"params",
"=",
"{",
"'QualificationRequestId'",
":",
"qualification_request_id",
",",
"'IntegerValue'",
":",
"integer_value",
"}",
"return",
"self",
... | 57.4 | 0.013746 |
def SynchronizedClassMethod(*locks_attr_names, **kwargs):
# pylint: disable=C1801
"""
A synchronizer decorator for class methods. An AttributeError can be raised
at runtime if the given lock attribute doesn't exist or if it is None.
If a parameter ``sorted`` is found in ``kwargs`` and its value is ... | [
"def",
"SynchronizedClassMethod",
"(",
"*",
"locks_attr_names",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C1801",
"# Filter the names (remove empty ones)",
"locks_attr_names",
"=",
"[",
"lock_name",
"for",
"lock_name",
"in",
"locks_attr_names",
"if",
"lock_nam... | 32.493506 | 0.000776 |
def Analyze(self, hashes):
"""Looks up hashes in nsrlsvr.
Args:
hashes (list[str]): hash values to look up.
Returns:
list[HashAnalysis]: analysis results, or an empty list on error.
"""
logger.debug(
'Opening connection to {0:s}:{1:d}'.format(self._host, self._port))
nsrl_... | [
"def",
"Analyze",
"(",
"self",
",",
"hashes",
")",
":",
"logger",
".",
"debug",
"(",
"'Opening connection to {0:s}:{1:d}'",
".",
"format",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_port",
")",
")",
"nsrl_socket",
"=",
"self",
".",
"_GetSocket",
"(",
... | 24.34375 | 0.008642 |
def expQt(self, t):
'''
Parameters
----------
t : float
Time to propagate
Returns
--------
expQt : numpy.array
Matrix exponential of exo(Qt)
'''
eLambdaT = np.diag(self._exp_lt(t)) # vector length = a
Qs = self.... | [
"def",
"expQt",
"(",
"self",
",",
"t",
")",
":",
"eLambdaT",
"=",
"np",
".",
"diag",
"(",
"self",
".",
"_exp_lt",
"(",
"t",
")",
")",
"# vector length = a",
"Qs",
"=",
"self",
".",
"v",
".",
"dot",
"(",
"eLambdaT",
".",
"dot",
"(",
"self",
".",
... | 23.588235 | 0.01199 |
def smart_text(s, encoding="utf-8", strings_only=False, errors="strict"):
"""Return a unicode object representing 's'.
Treats bytes using the 'encoding' codec.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, six.text_type):
return s
... | [
"def",
"smart_text",
"(",
"s",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"\"strict\"",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"text_type",
")",
":",
"return",
"s",
"if",
"strings_only",
... | 37 | 0.000941 |
def get_dpi(raise_error=True):
"""Get screen DPI from the OS
Parameters
----------
raise_error : bool
If True, raise an error if DPI could not be determined.
Returns
-------
dpi : float
Dots per inch of the primary screen.
"""
try:
user32.SetProcessDPIAware(... | [
"def",
"get_dpi",
"(",
"raise_error",
"=",
"True",
")",
":",
"try",
":",
"user32",
".",
"SetProcessDPIAware",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"# not present on XP",
"dc",
"=",
"user32",
".",
"GetDC",
"(",
"0",
")",
"h_size",
"=",
"gdi32"... | 27.791667 | 0.001449 |
def _table_limit(table, n, offset=0):
"""
Select the first n rows at beginning of table (may not be deterministic
depending on implementation and presence of a sorting).
Parameters
----------
n : int
Number of rows to include
offset : int, default 0
Number of rows to skip first
... | [
"def",
"_table_limit",
"(",
"table",
",",
"n",
",",
"offset",
"=",
"0",
")",
":",
"op",
"=",
"ops",
".",
"Limit",
"(",
"table",
",",
"n",
",",
"offset",
"=",
"offset",
")",
"return",
"op",
".",
"to_expr",
"(",
")"
] | 23.722222 | 0.002252 |
def readNullModelFile(nfile):
""""
reading file with null model info
nfile File containing null model info
"""
params0_file = nfile+'.p0'
nll0_file = nfile+'.nll0'
assert os.path.exists(params0_file), '%s is missing.'%params0_file
assert os.path.exists(nll0_file), '%s is missing.'%nl... | [
"def",
"readNullModelFile",
"(",
"nfile",
")",
":",
"params0_file",
"=",
"nfile",
"+",
"'.p0'",
"nll0_file",
"=",
"nfile",
"+",
"'.nll0'",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"params0_file",
")",
",",
"'%s is missing.'",
"%",
"params0_file",
"as... | 29.190476 | 0.025276 |
def xmoe_tr_2d():
"""Mixture of experts (16 experts).
623M Params, einsum=1.09e13
Returns:
a hparams
"""
hparams = xmoe_tr_dense_2k()
hparams.mesh_shape = "b0:2;b1:4"
hparams.outer_batch_size = 4
hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0"
hparams.encoder_layers = ["... | [
"def",
"xmoe_tr_2d",
"(",
")",
":",
"hparams",
"=",
"xmoe_tr_dense_2k",
"(",
")",
"hparams",
".",
"mesh_shape",
"=",
"\"b0:2;b1:4\"",
"hparams",
".",
"outer_batch_size",
"=",
"4",
"hparams",
".",
"layout",
"=",
"\"outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0\... | 27.666667 | 0.023301 |
def format_message(self, message):
""" Formats a message with :class:Look """
look = Look(message)
return look.pretty(display=False) | [
"def",
"format_message",
"(",
"self",
",",
"message",
")",
":",
"look",
"=",
"Look",
"(",
"message",
")",
"return",
"look",
".",
"pretty",
"(",
"display",
"=",
"False",
")"
] | 38.25 | 0.012821 |
def add_node(self, node):
"""Link the agent to a random member of the previous generation."""
nodes = [n for n in self.nodes() if not isinstance(n, Source)]
num_agents = len(nodes)
curr_generation = int((num_agents - 1) / float(self.generation_size))
node.generation = curr_genera... | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"nodes",
"=",
"[",
"n",
"for",
"n",
"in",
"self",
".",
"nodes",
"(",
")",
"if",
"not",
"isinstance",
"(",
"n",
",",
"Source",
")",
"]",
"num_agents",
"=",
"len",
"(",
"nodes",
")",
"curr_gene... | 38.424242 | 0.001538 |
def place(vertices_resources, nets, machine, constraints, breadth_first=True):
"""Places vertices in breadth-first order along a hilbert-curve path
through the chips in the machine.
This is a thin wrapper around the :py:func:`sequential
<rig.place_and_route.place.sequential.place>` placement algorithm ... | [
"def",
"place",
"(",
"vertices_resources",
",",
"nets",
",",
"machine",
",",
"constraints",
",",
"breadth_first",
"=",
"True",
")",
":",
"return",
"sequential_place",
"(",
"vertices_resources",
",",
"nets",
",",
"machine",
",",
"constraints",
",",
"(",
"None",... | 48.090909 | 0.000927 |
def aspirate(self, volume=None, location=None, rate=1.0):
"""
Aspirate a volume of liquid (in microliters/uL) using this pipette
from the specified location
Notes
-----
If only a volume is passed, the pipette will aspirate
from it's current position. If only a lo... | [
"def",
"aspirate",
"(",
"self",
",",
"volume",
"=",
"None",
",",
"location",
"=",
"None",
",",
"rate",
"=",
"1.0",
")",
":",
"if",
"not",
"self",
".",
"tip_attached",
":",
"log",
".",
"warning",
"(",
"\"Cannot aspirate without a tip attached.\"",
")",
"# N... | 40.3125 | 0.000504 |
def _parse_section_three(self, part, mimetypes):
""" Parse & validate a part according to section #3
The logic applied follows section 3 guidelines from top
to bottom.
"""
link = 'tools.ietf.org/html/rfc2388#section-3'
if part.disposition != 'form-data' or not part.nam... | [
"def",
"_parse_section_three",
"(",
"self",
",",
"part",
",",
"mimetypes",
")",
":",
"link",
"=",
"'tools.ietf.org/html/rfc2388#section-3'",
"if",
"part",
".",
"disposition",
"!=",
"'form-data'",
"or",
"not",
"part",
".",
"name",
":",
"self",
".",
"fail",
"(",... | 46.5 | 0.002342 |
def getTempFile(suffix="", rootDir=None):
"""Returns a string representing a temporary file, that must be manually deleted
"""
if rootDir is None:
handle, tmpFile = tempfile.mkstemp(suffix)
os.close(handle)
return tmpFile
else:
tmpFile = os.path.join(rootDir, "tmp_" + get... | [
"def",
"getTempFile",
"(",
"suffix",
"=",
"\"\"",
",",
"rootDir",
"=",
"None",
")",
":",
"if",
"rootDir",
"is",
"None",
":",
"handle",
",",
"tmpFile",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
")",
"os",
".",
"close",
"(",
"handle",
")",
"retur... | 39.666667 | 0.010267 |
def addLogicalInterfaceToDeviceType(self, typeId, logicalInterfaceId):
"""
Adds a logical interface to a device type.
Parameters:
- typeId (string) - the device type
- logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface
... | [
"def",
"addLogicalInterfaceToDeviceType",
"(",
"self",
",",
"typeId",
",",
"logicalInterfaceId",
")",
":",
"req",
"=",
"ApiClient",
".",
"allDeviceTypeLogicalInterfacesUrl",
"%",
"(",
"self",
".",
"host",
",",
"\"/draft\"",
",",
"typeId",
")",
"body",
"=",
"{",
... | 54.666667 | 0.008562 |
def list_targets():
"""! @brief Generate dictionary with info about all supported targets.
Output version history:
- 1.0, initial version
- 1.1, added part_families
- 1.2, added source
"""
targets = []
obj = {
'pyocd_version' : __versi... | [
"def",
"list_targets",
"(",
")",
":",
"targets",
"=",
"[",
"]",
"obj",
"=",
"{",
"'pyocd_version'",
":",
"__version__",
",",
"'version'",
":",
"{",
"'major'",
":",
"1",
",",
"'minor'",
":",
"2",
"}",
",",
"'status'",
":",
"0",
",",
"'targets'",
":",
... | 34.304348 | 0.014171 |
def Glob(self, pathname, ondisk=True, source=True, strings=False, exclude=None, cwd=None):
"""
Globs
This is mainly a shim layer
"""
if cwd is None:
cwd = self.getcwd()
return cwd.glob(pathname, ondisk, source, strings, exclude) | [
"def",
"Glob",
"(",
"self",
",",
"pathname",
",",
"ondisk",
"=",
"True",
",",
"source",
"=",
"True",
",",
"strings",
"=",
"False",
",",
"exclude",
"=",
"None",
",",
"cwd",
"=",
"None",
")",
":",
"if",
"cwd",
"is",
"None",
":",
"cwd",
"=",
"self",... | 31.222222 | 0.010381 |
def get_channelstate_for(
chain_state: ChainState,
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
partner_address: Address,
) -> Optional[NettingChannelState]:
""" Return the NettingChannelState if it exists, None otherwise. """
token_network = get_token_netwo... | [
"def",
"get_channelstate_for",
"(",
"chain_state",
":",
"ChainState",
",",
"payment_network_id",
":",
"PaymentNetworkID",
",",
"token_address",
":",
"TokenAddress",
",",
"partner_address",
":",
"Address",
",",
")",
"->",
"Optional",
"[",
"NettingChannelState",
"]",
... | 32.357143 | 0.002144 |
def filter_convolve_stack(data, filters, filter_rot=False, method='scipy'):
r"""Filter convolve
This method convolves the a stack of input images with the wavelet filters
Parameters
----------
data : np.ndarray
Input data, 3D array
filters : np.ndarray
Wavelet filters, 3D array... | [
"def",
"filter_convolve_stack",
"(",
"data",
",",
"filters",
",",
"filter_rot",
"=",
"False",
",",
"method",
"=",
"'scipy'",
")",
":",
"# Return the convolved data cube.",
"return",
"np",
".",
"array",
"(",
"[",
"filter_convolve",
"(",
"x",
",",
"filters",
","... | 28.333333 | 0.000812 |
def _dashboard_diff(_new_dashboard, _old_dashboard):
'''Return a dictionary of changes between dashboards.'''
diff = {}
# Dashboard diff
new_dashboard = copy.deepcopy(_new_dashboard)
old_dashboard = copy.deepcopy(_old_dashboard)
dashboard_diff = DictDiffer(new_dashboard, old_dashboard)
diff... | [
"def",
"_dashboard_diff",
"(",
"_new_dashboard",
",",
"_old_dashboard",
")",
":",
"diff",
"=",
"{",
"}",
"# Dashboard diff",
"new_dashboard",
"=",
"copy",
".",
"deepcopy",
"(",
"_new_dashboard",
")",
"old_dashboard",
"=",
"copy",
".",
"deepcopy",
"(",
"_old_dash... | 39.043478 | 0.000362 |
def _parse_storage_embedded_health(self, data):
"""Gets the storage data from get_embedded_health
Parse the get_host_health_data() for essential properties
:param data: the output returned by get_host_health_data()
:returns: disk size in GB.
"""
local_gb = 0
st... | [
"def",
"_parse_storage_embedded_health",
"(",
"self",
",",
"data",
")",
":",
"local_gb",
"=",
"0",
"storage",
"=",
"self",
".",
"get_value_as_list",
"(",
"data",
"[",
"'GET_EMBEDDED_HEALTH_DATA'",
"]",
",",
"'STORAGE'",
")",
"if",
"storage",
"is",
"None",
":",... | 41.86 | 0.000934 |
def ip_in_ip_mask(ip, mask_ip, mask):
'''
Checks whether an ip is contained in an ip subnet where the subnet is stated as an ip in the dotted format, and a hex mask
'''
ip = ip2hex(ip)
if ip is None: raise Exception("bad ip format")
if (mask_ip & mask) == (ip & mask):
return True
ret... | [
"def",
"ip_in_ip_mask",
"(",
"ip",
",",
"mask_ip",
",",
"mask",
")",
":",
"ip",
"=",
"ip2hex",
"(",
"ip",
")",
"if",
"ip",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"bad ip format\"",
")",
"if",
"(",
"mask_ip",
"&",
"mask",
")",
"==",
"(",
"i... | 35.666667 | 0.009119 |
def Prod(a, axis, keep_dims):
"""
Prod reduction op.
"""
return np.prod(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),
keepdims=keep_dims), | [
"def",
"Prod",
"(",
"a",
",",
"axis",
",",
"keep_dims",
")",
":",
"return",
"np",
".",
"prod",
"(",
"a",
",",
"axis",
"=",
"axis",
"if",
"not",
"isinstance",
"(",
"axis",
",",
"np",
".",
"ndarray",
")",
"else",
"tuple",
"(",
"axis",
")",
",",
"... | 31.5 | 0.010309 |
def generate_proxy(
prefix, base_url='', verify_ssl=True, middleware=None,
append_middleware=None, cert=None, timeout=None):
"""Generate a ProxyClass based view that uses the passed base_url."""
middleware = list(middleware or HttpProxy.proxy_middleware)
middleware += list(append_middleware ... | [
"def",
"generate_proxy",
"(",
"prefix",
",",
"base_url",
"=",
"''",
",",
"verify_ssl",
"=",
"True",
",",
"middleware",
"=",
"None",
",",
"append_middleware",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"middleware",
"=",... | 37.666667 | 0.001727 |
def echo_verbose_results(data, no_color):
"""Print list of tests and result of each test."""
click.echo()
click.echo(
'\n'.join(
'{}: {}'.format(key, val) for key, val in data['info'].items()
)
)
click.echo()
for test in data['tests']:
if test['outcome'] == 'p... | [
"def",
"echo_verbose_results",
"(",
"data",
",",
"no_color",
")",
":",
"click",
".",
"echo",
"(",
")",
"click",
".",
"echo",
"(",
"'\\n'",
".",
"join",
"(",
"'{}: {}'",
".",
"format",
"(",
"key",
",",
"val",
")",
"for",
"key",
",",
"val",
"in",
"da... | 26.565217 | 0.00158 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.