text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def build_mxnet(app):
"""Build mxnet .so lib"""
if not os.path.exists(os.path.join(app.builder.srcdir, '..', 'config.mk')):
_run_cmd("cd %s/.. && cp make/config.mk config.mk && make -j$(nproc) USE_MKLDNN=0 USE_CPP_PACKAGE=1 " %
app.builder.srcdir)
else:
_run_cmd("cd %s/.. && ... | [
"def",
"build_mxnet",
"(",
"app",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"app",
".",
"builder",
".",
"srcdir",
",",
"'..'",
",",
"'config.mk'",
")",
")",
":",
"_run_cmd",
"(",
"\"cd %s/.. ... | 49.875 | 26.25 |
def get_job_statuses(github_token, api_url, build_id,
polling_interval, job_number):
"""Wait for all the travis jobs to complete.
Once the other jobs are complete, return a list of booleans,
indicating whether or not the job was successful. Ignore jobs
marked "allow_failure".
"... | [
"def",
"get_job_statuses",
"(",
"github_token",
",",
"api_url",
",",
"build_id",
",",
"polling_interval",
",",
"job_number",
")",
":",
"auth",
"=",
"get_json",
"(",
"'{api_url}/auth/github'",
".",
"format",
"(",
"api_url",
"=",
"api_url",
")",
",",
"data",
"="... | 44.034483 | 18.827586 |
def _pp(dict_data):
"""Pretty print."""
for key, val in dict_data.items():
# pylint: disable=superfluous-parens
print('{0:<11}: {1}'.format(key, val)) | [
"def",
"_pp",
"(",
"dict_data",
")",
":",
"for",
"key",
",",
"val",
"in",
"dict_data",
".",
"items",
"(",
")",
":",
"# pylint: disable=superfluous-parens",
"print",
"(",
"'{0:<11}: {1}'",
".",
"format",
"(",
"key",
",",
"val",
")",
")"
] | 34 | 6.6 |
def serialize(self):
"""Get the unicode string representing the whole collection."""
import datetime
items = []
time_begin = datetime.datetime.now()
for href in self.list():
items.append(self.get(href).item)
time_end = datetime.datetime.now()
self.logg... | [
"def",
"serialize",
"(",
"self",
")",
":",
"import",
"datetime",
"items",
"=",
"[",
"]",
"time_begin",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"for",
"href",
"in",
"self",
".",
"list",
"(",
")",
":",
"items",
".",
"append",
"(",
"se... | 44.173913 | 13.782609 |
def delete_dbinstance(self, id, skip_final_snapshot=False,
final_snapshot_id=''):
"""
Delete an existing DBInstance.
:type id: str
:param id: Unique identifier for the new instance.
:type skip_final_snapshot: bool
:param skip_final_snapshot: Th... | [
"def",
"delete_dbinstance",
"(",
"self",
",",
"id",
",",
"skip_final_snapshot",
"=",
"False",
",",
"final_snapshot_id",
"=",
"''",
")",
":",
"params",
"=",
"{",
"'DBInstanceIdentifier'",
":",
"id",
"}",
"if",
"skip_final_snapshot",
":",
"params",
"[",
"'SkipFi... | 43.310345 | 20.62069 |
def get_cluster(self, label):
"""Returns a connection to a mongo-clusters.
Args:
label (string): the label of a cluster.
Returns:
A connection to the cluster labeld with label.
Raises:
AttributeError: there is no cluster with the given label in the
... | [
"def",
"get_cluster",
"(",
"self",
",",
"label",
")",
":",
"for",
"cluster",
"in",
"self",
".",
"_clusters",
":",
"if",
"label",
"==",
"cluster",
"[",
"'label'",
"]",
":",
"return",
"self",
".",
"_get_connection",
"(",
"cluster",
")",
"raise",
"Attribute... | 31.294118 | 19 |
def _determine_redirect(self, url, verb, timeout=15, headers={}):
"""
Internal redirect function, focuses on HTTP and worries less about
application-y stuff.
@param url: the url to check
@param verb: the verb, e.g. head, or get.
@param timeout: the time, in seconds, that ... | [
"def",
"_determine_redirect",
"(",
"self",
",",
"url",
",",
"verb",
",",
"timeout",
"=",
"15",
",",
"headers",
"=",
"{",
"}",
")",
":",
"requests_verb",
"=",
"getattr",
"(",
"self",
".",
"session",
",",
"verb",
")",
"r",
"=",
"requests_verb",
"(",
"u... | 37.121212 | 18.454545 |
def create_thumbnail(img, width, height):
"""
创建缩略图
缩略图的意思就是缩小
:param img: 图片对象
:param width: 宽
:param height: 高
:return:
"""
size = (width, height)
img.thumbnail(size)
return img | [
"def",
"create_thumbnail",
"(",
"img",
",",
"width",
",",
"height",
")",
":",
"size",
"=",
"(",
"width",
",",
"height",
")",
"img",
".",
"thumbnail",
"(",
"size",
")",
"return",
"img"
] | 17.666667 | 17 |
def set_writer_position(self, name, timestamp):
"""Insert a timestamp to keep track of the current writer position"""
execute = self.cursor.execute
execute('DELETE FROM gauged_writer_history WHERE id = %s', (name,))
execute('INSERT INTO gauged_writer_history (id, timestamp) '
... | [
"def",
"set_writer_position",
"(",
"self",
",",
"name",
",",
"timestamp",
")",
":",
"execute",
"=",
"self",
".",
"cursor",
".",
"execute",
"execute",
"(",
"'DELETE FROM gauged_writer_history WHERE id = %s'",
",",
"(",
"name",
",",
")",
")",
"execute",
"(",
"'I... | 59.666667 | 14.5 |
def _metadata_endpoint(self, context):
"""
Endpoint for retrieving the backend metadata
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response with metadata
"""
satosa_logging(logger, l... | [
"def",
"_metadata_endpoint",
"(",
"self",
",",
"context",
")",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Sending metadata response\"",
",",
"context",
".",
"state",
")",
"metadata_string",
"=",
"create_metadata_string",
"(",
"None... | 42.5 | 18.5 |
def split(self, cutting_points, shift_times=False, overlap=0.0):
"""
Split the label-list into x parts and return them as new label-lists.
x is defined by the number of cutting-points(``x == len(cutting_points) + 1``)
The result is a list of label-lists corresponding to each part.
... | [
"def",
"split",
"(",
"self",
",",
"cutting_points",
",",
"shift_times",
"=",
"False",
",",
"overlap",
"=",
"0.0",
")",
":",
"if",
"len",
"(",
"cutting_points",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'At least one cutting-point is needed!'",
")",
"... | 33.472222 | 20.712963 |
def create_guest_screen_info(self, display, status, primary, change_origin, origin_x, origin_y, width, height, bits_per_pixel):
"""Make a IGuestScreenInfo object with the provided parameters.
in display of type int
The number of the guest display.
in status of type :class:`GuestMon... | [
"def",
"create_guest_screen_info",
"(",
"self",
",",
"display",
",",
"status",
",",
"primary",
",",
"change_origin",
",",
"origin_x",
",",
"origin_y",
",",
"width",
",",
"height",
",",
"bits_per_pixel",
")",
":",
"if",
"not",
"isinstance",
"(",
"display",
",... | 44.672414 | 23.293103 |
def sample_outcomes(probs, n):
"""
For a discrete probability distribution ``probs`` with outcomes 0, 1, ..., k-1 draw ``n``
random samples.
:param list probs: A list of probabilities.
:param Number n: The number of random samples to draw.
:return: An array of samples drawn from distribution pr... | [
"def",
"sample_outcomes",
"(",
"probs",
",",
"n",
")",
":",
"dist",
"=",
"np",
".",
"cumsum",
"(",
"probs",
")",
"rs",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"n",
")",
"return",
"np",
".",
"array",
"(",
"[",
"(",
"np",
".",
"where",
"(",
... | 37.692308 | 20.153846 |
def deepnn(x):
"""deepnn builds the graph for a deep net for classifying digits.
Args:
x: an input tensor with the dimensions (N_examples, 784), where 784 is
the number of pixels in a standard MNIST image.
Returns:
A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10)... | [
"def",
"deepnn",
"(",
"x",
")",
":",
"# Reshape to use within a convolutional neural net.",
"# Last dimension is for \"features\" - there is only one here, since images",
"# are grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.",
"with",
"tf",
".",
"name_scope",
"(",
"\"resha... | 39.032787 | 20.737705 |
def prep_db_parallel(samples, parallel_fn):
"""Prepares gemini databases in parallel, handling jointly called populations.
"""
batch_groups, singles, out_retrieve, extras = _group_by_batches(samples, _has_variant_calls)
to_process = []
has_batches = False
for (name, caller), info in batch_groups... | [
"def",
"prep_db_parallel",
"(",
"samples",
",",
"parallel_fn",
")",
":",
"batch_groups",
",",
"singles",
",",
"out_retrieve",
",",
"extras",
"=",
"_group_by_batches",
"(",
"samples",
",",
"_has_variant_calls",
")",
"to_process",
"=",
"[",
"]",
"has_batches",
"="... | 41.241379 | 16.034483 |
def set_attrs(self, **attrs):
"""Set model attributes, e.g. input resistance of a cell."""
self.attrs.update(attrs)
self._backend.set_attrs(**attrs) | [
"def",
"set_attrs",
"(",
"self",
",",
"*",
"*",
"attrs",
")",
":",
"self",
".",
"attrs",
".",
"update",
"(",
"attrs",
")",
"self",
".",
"_backend",
".",
"set_attrs",
"(",
"*",
"*",
"attrs",
")"
] | 42.25 | 4.75 |
def delete_cell(self, key):
"""Deletes key cell"""
try:
self.code_array.pop(key)
except KeyError:
pass
self.grid.code_array.result_cache.clear() | [
"def",
"delete_cell",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"self",
".",
"code_array",
".",
"pop",
"(",
"key",
")",
"except",
"KeyError",
":",
"pass",
"self",
".",
"grid",
".",
"code_array",
".",
"result_cache",
".",
"clear",
"(",
")"
] | 19.5 | 21.3 |
def _setup(self, delete=True):
"""Create a function instance and execute setup.
Args:
delete (bool): Delete buffered variables.
"""
if delete:
self.clear()
with nn.context_scope(self.ctx):
outputs = self.func(
*(self.inputs_f ... | [
"def",
"_setup",
"(",
"self",
",",
"delete",
"=",
"True",
")",
":",
"if",
"delete",
":",
"self",
".",
"clear",
"(",
")",
"with",
"nn",
".",
"context_scope",
"(",
"self",
".",
"ctx",
")",
":",
"outputs",
"=",
"self",
".",
"func",
"(",
"*",
"(",
... | 32.111111 | 13.722222 |
def ensure_path_exists(path, *args):
'''Like os.makedirs but keeps quiet if path already exists'''
if os.path.exists(path):
return
os.makedirs(path, *args) | [
"def",
"ensure_path_exists",
"(",
"path",
",",
"*",
"args",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"os",
".",
"makedirs",
"(",
"path",
",",
"*",
"args",
")"
] | 28.5 | 19.833333 |
def setup(self):
"""Additional setup steps."""
LOGGER.info('Tinman v%s starting up with Tornado v%s',
__version__, tornado_version)
# Setup debugging and paths
self.enable_debug()
self.set_base_path(os.getcwd())
self.insert_paths()
# Setup chi... | [
"def",
"setup",
"(",
"self",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Tinman v%s starting up with Tornado v%s'",
",",
"__version__",
",",
"tornado_version",
")",
"# Setup debugging and paths",
"self",
".",
"enable_debug",
"(",
")",
"self",
".",
"set_base_path",
"(",
... | 40.1 | 12.85 |
def get_signed_query_params_v2(credentials, expiration, string_to_sign):
"""Gets query parameters for creating a signed URL.
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: The credentials used to create a private key
for signing text.
:type expi... | [
"def",
"get_signed_query_params_v2",
"(",
"credentials",
",",
"expiration",
",",
"string_to_sign",
")",
":",
"ensure_signed_credentials",
"(",
"credentials",
")",
"signature_bytes",
"=",
"credentials",
".",
"sign_bytes",
"(",
"string_to_sign",
")",
"signature",
"=",
"... | 36.758621 | 20.137931 |
def expand_state_definition(source, loc, tokens):
"""
Parse action to convert statemachine to corresponding Python classes and methods
"""
indent = " " * (pp.col(loc, source) - 1)
statedef = []
# build list of states
states = set()
fromTo = {}
for tn in tokens.transitions:
s... | [
"def",
"expand_state_definition",
"(",
"source",
",",
"loc",
",",
"tokens",
")",
":",
"indent",
"=",
"\" \"",
"*",
"(",
"pp",
".",
"col",
"(",
"loc",
",",
"source",
")",
"-",
"1",
")",
"statedef",
"=",
"[",
"]",
"# build list of states",
"states",
"=",... | 31.275862 | 19.896552 |
def name(username):
"""Display / set / update the user name."""
if not username:
click.secho(dtool_config.utils.get_username(CONFIG_PATH))
else:
username_str = " ".join(username)
click.secho(dtool_config.utils.set_username(CONFIG_PATH, username_str)) | [
"def",
"name",
"(",
"username",
")",
":",
"if",
"not",
"username",
":",
"click",
".",
"secho",
"(",
"dtool_config",
".",
"utils",
".",
"get_username",
"(",
"CONFIG_PATH",
")",
")",
"else",
":",
"username_str",
"=",
"\" \"",
".",
"join",
"(",
"username",
... | 40 | 19.571429 |
def get_acl(self, key_name='', headers=None, version_id=None):
"""returns a bucket's acl. We include a version_id argument
to support a polymorphic interface for callers, however,
version_id is not relevant for Google Cloud Storage buckets
and is therefore ignored here."""
... | [
"def",
"get_acl",
"(",
"self",
",",
"key_name",
"=",
"''",
",",
"headers",
"=",
"None",
",",
"version_id",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_acl_helper",
"(",
"key_name",
",",
"headers",
",",
"STANDARD_ACL",
")"
] | 63.333333 | 18 |
def connect(self):
"""Return "dummy" connection."""
log.critical('NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!')
log.critical('ONLY FOR DEBUGGING AND TESTING!!!')
# The code below uses HARD-CODED secret key - and should be used ONLY
# for GnuPG integration tests (e.g. when no r... | [
"def",
"connect",
"(",
"self",
")",
":",
"log",
".",
"critical",
"(",
"'NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!'",
")",
"log",
".",
"critical",
"(",
"'ONLY FOR DEBUGGING AND TESTING!!!'",
")",
"# The code below uses HARD-CODED secret key - and should be used ONLY",
"# fo... | 52 | 22 |
def save(self, data, *args, **kwargs):
"""
inserts data (dict or list of dicts)
expected kwargs:
collection_name: by default uses MONGODB_DEFAULT_COLLECTION
w: by default set to 0 to disable write acknowledgement
assumes that data has been verified / validated
... | [
"def",
"save",
"(",
"self",
",",
"data",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"collection_name",
"=",
"kwargs",
".",
"get",
"(",
"'collection_name'",
",",
"MONGODB_DEFAULT_COLLECTION",
")",
"w",
"=",
"kwargs",
".",
"get",
"(... | 39.869565 | 15.521739 |
def _exit_now_changed(self, name, old, new):
"""stop eventloop when exit_now fires"""
if new:
loop = ioloop.IOLoop.instance()
loop.add_timeout(time.time()+0.1, loop.stop) | [
"def",
"_exit_now_changed",
"(",
"self",
",",
"name",
",",
"old",
",",
"new",
")",
":",
"if",
"new",
":",
"loop",
"=",
"ioloop",
".",
"IOLoop",
".",
"instance",
"(",
")",
"loop",
".",
"add_timeout",
"(",
"time",
".",
"time",
"(",
")",
"+",
"0.1",
... | 41.2 | 9.6 |
def sync_ik_robot(self, joint_positions, simulate=False, sync_last=True):
"""
Force the internal robot model to match the provided joint angles.
Args:
joint_positions (list): a list or flat numpy array of joint positions.
simulate (bool): If True, actually use physics si... | [
"def",
"sync_ik_robot",
"(",
"self",
",",
"joint_positions",
",",
"simulate",
"=",
"False",
",",
"sync_last",
"=",
"True",
")",
":",
"num_joints",
"=",
"len",
"(",
"joint_positions",
")",
"if",
"not",
"sync_last",
":",
"num_joints",
"-=",
"1",
"for",
"i",
... | 41.965517 | 17.344828 |
def install_all_labels(stdout=None):
"""
Discover all subclasses of StructuredNode in your application and execute install_labels on each.
Note: code most be loaded (imported) in order for a class to be discovered.
:param stdout: output stream
:return: None
"""
if not stdout:
stdou... | [
"def",
"install_all_labels",
"(",
"stdout",
"=",
"None",
")",
":",
"if",
"not",
"stdout",
":",
"stdout",
"=",
"sys",
".",
"stdout",
"def",
"subsub",
"(",
"kls",
")",
":",
"# recursively return all subclasses",
"return",
"kls",
".",
"__subclasses__",
"(",
")"... | 30.074074 | 26.148148 |
def write_file(environ, term='bash', out_dir=None, tree_dir=None):
''' Write a tree environment file
Loops over the tree environ and writes them out to a bash, tsch, or
modules file
Parameters:
environ (dict):
The tree dictionary environment
term (str):
The type... | [
"def",
"write_file",
"(",
"environ",
",",
"term",
"=",
"'bash'",
",",
"out_dir",
"=",
"None",
",",
"tree_dir",
"=",
"None",
")",
":",
"# get the proper name, header and file extension",
"name",
"=",
"environ",
"[",
"'default'",
"]",
"[",
"'name'",
"]",
"header... | 34.229167 | 18.520833 |
def Nu_cylinder_Whitaker(Re, Pr, mu=None, muw=None):
r'''Calculates Nusselt number for crossflow across a single tube as shown
in [1]_ at a specified `Re` and `Pr`, both evaluated at the free stream
temperature. Recommends a viscosity exponent correction of 0.25, which is
applied only if provided. Also ... | [
"def",
"Nu_cylinder_Whitaker",
"(",
"Re",
",",
"Pr",
",",
"mu",
"=",
"None",
",",
"muw",
"=",
"None",
")",
":",
"Nu",
"=",
"(",
"0.4",
"*",
"Re",
"**",
"0.5",
"+",
"0.06",
"*",
"Re",
"**",
"(",
"2",
"/",
"3.",
")",
")",
"*",
"Pr",
"**",
"0.... | 36.211538 | 26.25 |
def transp(I,J,c,d,M):
"""transp -- model for solving the transportation problem
Parameters:
I - set of customers
J - set of facilities
c[i,j] - unit transportation cost on arc (i,j)
d[i] - demand at node i
M[j] - capacity
Returns a model, ready to be solved.
"""
... | [
"def",
"transp",
"(",
"I",
",",
"J",
",",
"c",
",",
"d",
",",
"M",
")",
":",
"model",
"=",
"Model",
"(",
"\"transportation\"",
")",
"# Create variables",
"x",
"=",
"{",
"}",
"for",
"i",
"in",
"I",
":",
"for",
"j",
"in",
"J",
":",
"x",
"[",
"i... | 25.628571 | 24.942857 |
def calc_system(self, x, Y, Y_agg=None, L=None, population=None):
""" Calculates the missing part of the extension plus accounts
This method allows to specify an aggregated Y_agg for the
account calculation (see Y_agg below). However, the full Y needs
to be specified for the calculation... | [
"def",
"calc_system",
"(",
"self",
",",
"x",
",",
"Y",
",",
"Y_agg",
"=",
"None",
",",
"L",
"=",
"None",
",",
"population",
"=",
"None",
")",
":",
"if",
"Y_agg",
"is",
"None",
":",
"try",
":",
"Y_agg",
"=",
"Y",
".",
"sum",
"(",
"level",
"=",
... | 42.016575 | 19.104972 |
def get_tweet(self, id):
"""
Get an existing tweet.
:param id: ID of the tweet in question
:return: Tweet object. None if not found
"""
try:
return Tweet(self._client.get_status(id=id)._json)
except TweepError as e:
if e.api_code == TWITTE... | [
"def",
"get_tweet",
"(",
"self",
",",
"id",
")",
":",
"try",
":",
"return",
"Tweet",
"(",
"self",
".",
"_client",
".",
"get_status",
"(",
"id",
"=",
"id",
")",
".",
"_json",
")",
"except",
"TweepError",
"as",
"e",
":",
"if",
"e",
".",
"api_code",
... | 29.076923 | 14.923077 |
def parseFASTACommandLineOptions(args):
"""
Examine parsed command-line options and return a Reads instance.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@return: A C{Reads} subclass instance, depending on the type of FASTA file
given.
"""
... | [
"def",
"parseFASTACommandLineOptions",
"(",
"args",
")",
":",
"# Set default FASTA type.",
"if",
"not",
"(",
"args",
".",
"fasta",
"or",
"args",
".",
"fastq",
"or",
"args",
".",
"fasta_ss",
")",
":",
"args",
".",
"fasta",
"=",
"True",
"readClass",
"=",
"re... | 34.791667 | 18.791667 |
def longest_overlap(ovls):
"""
From a list of overlays if any overlap keep the longest.
"""
# Ovls know how to compare to each other.
ovls = sorted(ovls)
# I know this could be better but ovls wont be more than 50 or so.
for i, s in enumerate(ovls):
passing = True
for l in... | [
"def",
"longest_overlap",
"(",
"ovls",
")",
":",
"# Ovls know how to compare to each other.",
"ovls",
"=",
"sorted",
"(",
"ovls",
")",
"# I know this could be better but ovls wont be more than 50 or so.",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"ovls",
")",
":",
... | 27.1 | 20.1 |
def _simple_dispatch(self, name, params):
"""
Dispatch method
"""
try:
# Internal method
func = self.funcs[name]
except KeyError:
# Other method
pass
else:
# Internal method found
if isinstance(params... | [
"def",
"_simple_dispatch",
"(",
"self",
",",
"name",
",",
"params",
")",
":",
"try",
":",
"# Internal method",
"func",
"=",
"self",
".",
"funcs",
"[",
"name",
"]",
"except",
"KeyError",
":",
"# Other method",
"pass",
"else",
":",
"# Internal method found",
"... | 28.4 | 14.4 |
def prev_img_ws(self, ws, loop=True):
"""Go to the previous image in the focused channel in the workspace.
"""
channel = self.get_active_channel_ws(ws)
if channel is None:
return
channel.prev_image()
return True | [
"def",
"prev_img_ws",
"(",
"self",
",",
"ws",
",",
"loop",
"=",
"True",
")",
":",
"channel",
"=",
"self",
".",
"get_active_channel_ws",
"(",
"ws",
")",
"if",
"channel",
"is",
"None",
":",
"return",
"channel",
".",
"prev_image",
"(",
")",
"return",
"Tru... | 33 | 9.875 |
def kalman_filter(kalman_state, old_indices, coordinates, q, r):
'''Return the kalman filter for the features in the new frame
kalman_state - state from last frame
old_indices - the index per feature in the last frame or -1 for new
coordinates - Coordinates of the features in the new frame.
q - ... | [
"def",
"kalman_filter",
"(",
"kalman_state",
",",
"old_indices",
",",
"coordinates",
",",
"q",
",",
"r",
")",
":",
"assert",
"isinstance",
"(",
"kalman_state",
",",
"KalmanState",
")",
"old_indices",
"=",
"np",
".",
"array",
"(",
"old_indices",
")",
"if",
... | 41.421053 | 22.669173 |
def _move_content_to(self, other_tc):
"""
Append the content of this cell to *other_tc*, leaving this cell with
a single empty ``<w:p>`` element.
"""
if other_tc is self:
return
if self._is_empty:
return
other_tc._remove_trailing_empty_p()
... | [
"def",
"_move_content_to",
"(",
"self",
",",
"other_tc",
")",
":",
"if",
"other_tc",
"is",
"self",
":",
"return",
"if",
"self",
".",
"_is_empty",
":",
"return",
"other_tc",
".",
"_remove_trailing_empty_p",
"(",
")",
"# appending moves each element from self to other... | 37.666667 | 12.066667 |
def get_serializer_class(self, view, method_func):
"""
Try to get the serializer class from view method.
If view method don't have request serializer, fallback to serializer_class on view class
"""
if hasattr(method_func, 'request_serializer'):
return getattr(method_f... | [
"def",
"get_serializer_class",
"(",
"self",
",",
"view",
",",
"method_func",
")",
":",
"if",
"hasattr",
"(",
"method_func",
",",
"'request_serializer'",
")",
":",
"return",
"getattr",
"(",
"method_func",
",",
"'request_serializer'",
")",
"if",
"hasattr",
"(",
... | 37.533333 | 20.2 |
def iri_to_uri(value, normalize=False):
"""
Encodes a unicode IRI into an ASCII byte string URI
:param value:
A unicode string of an IRI
:param normalize:
A bool that controls URI normalization
:return:
A byte string of the ASCII-encoded URI
"""
if not isinstance(... | [
"def",
"iri_to_uri",
"(",
"value",
",",
"normalize",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str_cls",
")",
":",
"raise",
"TypeError",
"(",
"unwrap",
"(",
"'''\n value must be a unicode string, not %s\n '''",
",",... | 33.061728 | 20.024691 |
def from_schema(cls, schema, *args, **kwargs):
"""
Construct a resolver from a JSON schema object.
:argument schema schema: the referring schema
:rtype: :class:`RefResolver`
"""
return cls(schema.get(u"id", u""), schema, *args, **kwargs) | [
"def",
"from_schema",
"(",
"cls",
",",
"schema",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
"(",
"schema",
".",
"get",
"(",
"u\"id\"",
",",
"u\"\"",
")",
",",
"schema",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 27.9 | 18.5 |
def get_backend_class():
"""Return reference to the configured backed class."""
# this will (intentionally) blow up if the setting does not exist
assert hasattr(settings, 'INBOUND_EMAIL_PARSER')
assert getattr(settings, 'INBOUND_EMAIL_PARSER') is not None
package, klass = settings.INBOUND_EMAIL_PAR... | [
"def",
"get_backend_class",
"(",
")",
":",
"# this will (intentionally) blow up if the setting does not exist",
"assert",
"hasattr",
"(",
"settings",
",",
"'INBOUND_EMAIL_PARSER'",
")",
"assert",
"getattr",
"(",
"settings",
",",
"'INBOUND_EMAIL_PARSER'",
")",
"is",
"not",
... | 44.444444 | 17.555556 |
def load(cls, path):
"""
Load a SOM from a JSON file saved with this package.
Parameters
----------
path : str
The path to the JSON file.
Returns
-------
s : cls
A som of the specified class.
"""
data = json.load(... | [
"def",
"load",
"(",
"cls",
",",
"path",
")",
":",
"data",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"path",
")",
")",
"weights",
"=",
"data",
"[",
"'weights'",
"]",
"weights",
"=",
"np",
".",
"asarray",
"(",
"weights",
",",
"dtype",
"=",
"np",
... | 25.757576 | 18.484848 |
def persist_experiment(experiment):
"""
Persist this experiment in the benchbuild database.
Args:
experiment: The experiment we want to persist.
"""
from benchbuild.utils.schema import Experiment, Session
session = Session()
cfg_exp = experiment.id
LOG.debug("Using experiment ... | [
"def",
"persist_experiment",
"(",
"experiment",
")",
":",
"from",
"benchbuild",
".",
"utils",
".",
"schema",
"import",
"Experiment",
",",
"Session",
"session",
"=",
"Session",
"(",
")",
"cfg_exp",
"=",
"experiment",
".",
"id",
"LOG",
".",
"debug",
"(",
"\"... | 25.571429 | 19.628571 |
def read_nb(filename, solution) -> nbformat.NotebookNode:
"""
Takes in a filename of a notebook and returns a notebook object containing
only the cell outputs to export.
"""
with open(filename, 'r') as f:
nb = nbformat.read(f, as_version=4)
email = find_student_email(nb)
preamble = ... | [
"def",
"read_nb",
"(",
"filename",
",",
"solution",
")",
"->",
"nbformat",
".",
"NotebookNode",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"nb",
"=",
"nbformat",
".",
"read",
"(",
"f",
",",
"as_version",
"=",
"4",
")",
"... | 32.894737 | 16.894737 |
def is_dataframe(data):
"""
Checks whether the supplied data is of DataFrame type.
"""
dd = None
if 'dask' in sys.modules and 'pandas' in sys.modules:
import dask.dataframe as dd
return((pd is not None and isinstance(data, pd.DataFrame)) or
(dd is not None and isinstance(data, ... | [
"def",
"is_dataframe",
"(",
"data",
")",
":",
"dd",
"=",
"None",
"if",
"'dask'",
"in",
"sys",
".",
"modules",
"and",
"'pandas'",
"in",
"sys",
".",
"modules",
":",
"import",
"dask",
".",
"dataframe",
"as",
"dd",
"return",
"(",
"(",
"pd",
"is",
"not",
... | 36.333333 | 14.555556 |
def proportional_weights(self, fraction_stdev=1.0, wmax=100.0,
leave_zero=True):
"""setup weights inversely proportional to the observation value
Parameters
----------
fraction_stdev : float
the fraction portion of the observation
va... | [
"def",
"proportional_weights",
"(",
"self",
",",
"fraction_stdev",
"=",
"1.0",
",",
"wmax",
"=",
"100.0",
",",
"leave_zero",
"=",
"True",
")",
":",
"new_weights",
"=",
"[",
"]",
"for",
"oval",
",",
"ow",
"in",
"zip",
"(",
"self",
".",
"observation_data",... | 35.25 | 14.607143 |
def encode(self, response):
"""Encode a response to a L{WebResponse}.
@raises EncodingError: When I can't figure out how to encode this
message.
"""
encode_as = response.whichEncoding()
if encode_as == ENCODE_KVFORM:
wr = self.responseFactory(body=respons... | [
"def",
"encode",
"(",
"self",
",",
"response",
")",
":",
"encode_as",
"=",
"response",
".",
"whichEncoding",
"(",
")",
"if",
"encode_as",
"==",
"ENCODE_KVFORM",
":",
"wr",
"=",
"self",
".",
"responseFactory",
"(",
"body",
"=",
"response",
".",
"encodeToKVF... | 42.565217 | 14.913043 |
def collection_callback(result=None):
"""
:type result: opendnp3.CommandPointResult
"""
print("Header: {0} | Index: {1} | State: {2} | Status: {3}".format(
result.headerIndex,
result.index,
opendnp3.CommandPointStateToString(result.state),
opendnp3.CommandStatusToString... | [
"def",
"collection_callback",
"(",
"result",
"=",
"None",
")",
":",
"print",
"(",
"\"Header: {0} | Index: {1} | State: {2} | Status: {3}\"",
".",
"format",
"(",
"result",
".",
"headerIndex",
",",
"result",
".",
"index",
",",
"opendnp3",
".",
"CommandPointStateToStri... | 33.3 | 13.7 |
def get_currentDim(self):
'''
returns the current dimensions of the object
'''
selfDim = self._dimensions.copy()
if not isinstance(selfDim,dimStr):
if selfDim.has_key('_ndims') : nself = selfDim.pop('_ndims')
else :
self.warning(1,... | [
"def",
"get_currentDim",
"(",
"self",
")",
":",
"selfDim",
"=",
"self",
".",
"_dimensions",
".",
"copy",
"(",
")",
"if",
"not",
"isinstance",
"(",
"selfDim",
",",
"dimStr",
")",
":",
"if",
"selfDim",
".",
"has_key",
"(",
"'_ndims'",
")",
":",
"nself",
... | 43.076923 | 19.230769 |
def edit_preferences(self, resource):
"""Edit preferences in /usr/cdrouter-data/etc/config.yml.
:param resource: :class:`system.Preferences <system.Preferences>` object
:return: :class:`system.Preferences <system.Preferences>` object
:rtype: system.Preferences
"""
schema... | [
"def",
"edit_preferences",
"(",
"self",
",",
"resource",
")",
":",
"schema",
"=",
"PreferencesSchema",
"(",
")",
"json",
"=",
"self",
".",
"service",
".",
"encode",
"(",
"schema",
",",
"resource",
")",
"schema",
"=",
"PreferencesSchema",
"(",
")",
"resp",
... | 41.615385 | 16.846154 |
def toggle_grid(self, evt=None, show=None):
"toggle grid display"
if show is None:
show = not self.conf.show_grid
self.conf.enable_grid(show) | [
"def",
"toggle_grid",
"(",
"self",
",",
"evt",
"=",
"None",
",",
"show",
"=",
"None",
")",
":",
"if",
"show",
"is",
"None",
":",
"show",
"=",
"not",
"self",
".",
"conf",
".",
"show_grid",
"self",
".",
"conf",
".",
"enable_grid",
"(",
"show",
")"
] | 34.6 | 7.4 |
def get_HDX_code_from_location_partial(location, locations=None, configuration=None):
# type: (str, Optional[List[Dict]], Optional[Configuration]) -> Tuple[Optional[str], bool]
"""Get HDX code for location
Args:
location (str): Location for which to get HDX code
location... | [
"def",
"get_HDX_code_from_location_partial",
"(",
"location",
",",
"locations",
"=",
"None",
",",
"configuration",
"=",
"None",
")",
":",
"# type: (str, Optional[List[Dict]], Optional[Configuration]) -> Tuple[Optional[str], bool]",
"hdx_code",
"=",
"Locations",
".",
"get_HDX_co... | 44.769231 | 28.961538 |
def answerUnsupported(self, message, preferred_association_type=None,
preferred_session_type=None):
"""Respond to this request indicating that the association
type or association session type is not supported."""
if self.message.isOpenID1():
raise ProtocolEr... | [
"def",
"answerUnsupported",
"(",
"self",
",",
"message",
",",
"preferred_association_type",
"=",
"None",
",",
"preferred_session_type",
"=",
"None",
")",
":",
"if",
"self",
".",
"message",
".",
"isOpenID1",
"(",
")",
":",
"raise",
"ProtocolError",
"(",
"self",... | 40.2 | 17.85 |
def str2date(self, datestr):
"""Parse date from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your date string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
... | [
"def",
"str2date",
"(",
"self",
",",
"datestr",
")",
":",
"if",
"datestr",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Parser must be a string or character stream, not NoneType\"",
")",
"# try default date template",
"try",
":",
"return",
"datetime",
".",
"strpt... | 31.536585 | 18.585366 |
def pipeline(line, cell=None):
"""Implements the pipeline cell magic for ipython notebooks.
The supported syntax is:
%%pipeline <command> [<args>]
<cell>
or:
%pipeline <command> [<args>]
Use %pipeline --help for a list of commands, or %pipeline <command> --help for
help on a specific command.... | [
"def",
"pipeline",
"(",
"line",
",",
"cell",
"=",
"None",
")",
":",
"return",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"handle_magic_line",
"(",
"line",
",",
"cell",
",",
"_pipeline_parser",
")"
] | 24.875 | 25.0625 |
def end_of_history(self, e): # (M->)
u'''Move to the end of the input history, i.e., the line currently
being entered.'''
self._history.end_of_history(self.l_buffer)
self.finalize() | [
"def",
"end_of_history",
"(",
"self",
",",
"e",
")",
":",
"# (M->)\r",
"self",
".",
"_history",
".",
"end_of_history",
"(",
"self",
".",
"l_buffer",
")",
"self",
".",
"finalize",
"(",
")"
] | 42.8 | 16 |
def decode(var, encoding):
"""
If not already unicode, decode it.
"""
if PY2:
if isinstance(var, unicode):
ret = var
elif isinstance(var, str):
if encoding:
ret = var.decode(encoding)
else:
ret = unicode(var)
els... | [
"def",
"decode",
"(",
"var",
",",
"encoding",
")",
":",
"if",
"PY2",
":",
"if",
"isinstance",
"(",
"var",
",",
"unicode",
")",
":",
"ret",
"=",
"var",
"elif",
"isinstance",
"(",
"var",
",",
"str",
")",
":",
"if",
"encoding",
":",
"ret",
"=",
"var... | 22.647059 | 13.705882 |
def lookup_matching(self, urls):
"""Get matching hosts for the given URLs.
:param urls: an iterable containing URLs
:returns: instances of AddressListItem representing listed
hosts matching the ones used by the given URLs
:raises InvalidURLError: if there are any invalid URLs in... | [
"def",
"lookup_matching",
"(",
"self",
",",
"urls",
")",
":",
"hosts",
"=",
"(",
"urlparse",
"(",
"u",
")",
".",
"hostname",
"for",
"u",
"in",
"urls",
")",
"for",
"val",
"in",
"hosts",
":",
"item",
"=",
"self",
".",
"lookup",
"(",
"val",
")",
"if... | 36.785714 | 13.928571 |
def _add_asset_content(self,
asset_id,
asset_data=None,
asset_url=None,
asset_content_type=None,
asset_label=None):
"""stub"""
rm = self.my_osid_object_form._get_provide... | [
"def",
"_add_asset_content",
"(",
"self",
",",
"asset_id",
",",
"asset_data",
"=",
"None",
",",
"asset_url",
"=",
"None",
",",
"asset_content_type",
"=",
"None",
",",
"asset_label",
"=",
"None",
")",
":",
"rm",
"=",
"self",
".",
"my_osid_object_form",
".",
... | 39.8 | 18.111111 |
def generate_base(model, model_dict, config, manifest, source_config,
provider, adapter=None):
"""Generate the common aspects of the config dict."""
if provider is None:
raise dbt.exceptions.InternalException(
"Invalid provider given to context: {}".format(provider))
t... | [
"def",
"generate_base",
"(",
"model",
",",
"model_dict",
",",
"config",
",",
"manifest",
",",
"source_config",
",",
"provider",
",",
"adapter",
"=",
"None",
")",
":",
"if",
"provider",
"is",
"None",
":",
"raise",
"dbt",
".",
"exceptions",
".",
"InternalExc... | 32.55 | 16.433333 |
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
"""Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows ... | [
"def",
"ExtractEvents",
"(",
"self",
",",
"parser_mediator",
",",
"registry_key",
",",
"*",
"*",
"kwargs",
")",
":",
"values_dict",
"=",
"{",
"}",
"if",
"registry_key",
".",
"number_of_values",
"==",
"0",
":",
"values_dict",
"[",
"'Value'",
"]",
"=",
"'No ... | 38.811321 | 21.037736 |
def send(messages=None, conf=None, parse_mode=None, disable_web_page_preview=False, files=None, images=None,
captions=None, locations=None, timeout=30):
"""Send data over Telegram. All arguments are optional.
Always use this function with explicit keyword arguments. So
`send(messages=["Hello!"])` ... | [
"def",
"send",
"(",
"messages",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"parse_mode",
"=",
"None",
",",
"disable_web_page_preview",
"=",
"False",
",",
"files",
"=",
"None",
",",
"images",
"=",
"None",
",",
"captions",
"=",
"None",
",",
"locations",
... | 42.902174 | 26.619565 |
def DEFINE_alias(name, original_name, flag_values=FLAGS, module_name=None): # pylint: disable=g-bad-name
"""Defines an alias flag for an existing one.
Args:
name: A string, name of the alias flag.
original_name: A string, name of the original flag.
flag_values: FlagValues object with which the flag wi... | [
"def",
"DEFINE_alias",
"(",
"name",
",",
"original_name",
",",
"flag_values",
"=",
"FLAGS",
",",
"module_name",
"=",
"None",
")",
":",
"# pylint: disable=g-bad-name",
"if",
"original_name",
"not",
"in",
"flag_values",
":",
"raise",
"UnrecognizedFlagError",
"(",
"o... | 33.95122 | 21.804878 |
def results_to_csv(query_name, **kwargs):
""" Generate CSV from result data
"""
query = get_result_set(query_name, **kwargs)
result = query.result
columns = list(result[0].keys())
data = [tuple(row.values()) for row in result]
frame = tablib.Dataset()
frame.headers = columns
for row ... | [
"def",
"results_to_csv",
"(",
"query_name",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"get_result_set",
"(",
"query_name",
",",
"*",
"*",
"kwargs",
")",
"result",
"=",
"query",
".",
"result",
"columns",
"=",
"list",
"(",
"result",
"[",
"0",
"]",... | 29.923077 | 10.230769 |
def get_argparser():
"""
Get the command line argument parser.
"""
parser = argparse.ArgumentParser("twarc")
parser.add_argument('command', choices=commands)
parser.add_argument('query', nargs='?', default=None)
parser.add_argument("--log", dest="log",
default="twarc... | [
"def",
"get_argparser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"\"twarc\"",
")",
"parser",
".",
"add_argument",
"(",
"'command'",
",",
"choices",
"=",
"commands",
")",
"parser",
".",
"add_argument",
"(",
"'query'",
",",
"nargs"... | 56.016393 | 21.42623 |
def _detect_xerial_stream(payload):
"""Detects if the data given might have been encoded with the blocking mode
of the xerial snappy library.
This mode writes a magic header of the format:
+--------+--------------+------------+---------+--------+
| Marker | Magic String | Nu... | [
"def",
"_detect_xerial_stream",
"(",
"payload",
")",
":",
"if",
"len",
"(",
"payload",
")",
">",
"16",
":",
"header",
"=",
"struct",
".",
"unpack",
"(",
"'!'",
"+",
"_XERIAL_V1_FORMAT",
",",
"bytes",
"(",
"payload",
")",
"[",
":",
"16",
"]",
")",
"re... | 46.5 | 24.5 |
def ecg_process(ecg, rsp=None, sampling_rate=1000, filter_type="FIR", filter_band="bandpass", filter_frequency=[3, 45], segmenter="hamilton", quality_model="default", hrv_features=["time", "frequency"], age=None, sex=None, position=None):
"""
Automated processing of ECG and RSP signals.
Parameters
----... | [
"def",
"ecg_process",
"(",
"ecg",
",",
"rsp",
"=",
"None",
",",
"sampling_rate",
"=",
"1000",
",",
"filter_type",
"=",
"\"FIR\"",
",",
"filter_band",
"=",
"\"bandpass\"",
",",
"filter_frequency",
"=",
"[",
"3",
",",
"45",
"]",
",",
"segmenter",
"=",
"\"h... | 84.910569 | 74.471545 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# get mean and std using the superclass
mean, stddevs = super... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# get mean and std using the superclass",
"mean",
",",
"stddevs",
"=",
"super",
"(",
")",
".",
"get_mean_and_stddevs",
"(",
"sites",
... | 35.6 | 15.733333 |
def set_quickchart_resource(self, resource):
# type: (Union[hdx.data.resource.Resource,Dict,str,int]) -> bool
"""Set the resource that will be used for displaying QuickCharts in dataset preview
Args:
resource (Union[hdx.data.resource.Resource,Dict,str,int]): Either resource id or na... | [
"def",
"set_quickchart_resource",
"(",
"self",
",",
"resource",
")",
":",
"# type: (Union[hdx.data.resource.Resource,Dict,str,int]) -> bool",
"if",
"isinstance",
"(",
"resource",
",",
"int",
")",
"and",
"not",
"isinstance",
"(",
"resource",
",",
"bool",
")",
":",
"r... | 45.121212 | 22.939394 |
def password_attributes_character_restriction_numeric(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
password_attributes = ET.SubElement(config, "password-attributes", xmlns="urn:brocade.com:mgmt:brocade-aaa")
character_restriction = ET.SubElement(passw... | [
"def",
"password_attributes_character_restriction_numeric",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"password_attributes",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"password-attributes... | 50.181818 | 23.181818 |
def grab_zipped_url(zipped_url, ensure=True, appname='utool',
download_dir=None, force_commonprefix=True, cleanup=False,
redownload=False, spoof=False):
r"""
downloads and unzips the url
Args:
zipped_url (str): url which must be either a .zip of a .tar.gz fil... | [
"def",
"grab_zipped_url",
"(",
"zipped_url",
",",
"ensure",
"=",
"True",
",",
"appname",
"=",
"'utool'",
",",
"download_dir",
"=",
"None",
",",
"force_commonprefix",
"=",
"True",
",",
"cleanup",
"=",
"False",
",",
"redownload",
"=",
"False",
",",
"spoof",
... | 38.268657 | 16.19403 |
def _last_index(x, default_dim):
"""Returns the last dimension's index or default_dim if x has no shape."""
if x.get_shape().ndims is not None:
return len(x.get_shape()) - 1
else:
return default_dim | [
"def",
"_last_index",
"(",
"x",
",",
"default_dim",
")",
":",
"if",
"x",
".",
"get_shape",
"(",
")",
".",
"ndims",
"is",
"not",
"None",
":",
"return",
"len",
"(",
"x",
".",
"get_shape",
"(",
")",
")",
"-",
"1",
"else",
":",
"return",
"default_dim"
... | 34.5 | 11.5 |
def get_comment_replies(self, *args, **kwargs):
"""Return a get_content generator for inboxed comment replies.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
"""
return self.get_content(self.config['comment_... | [
"def",
"get_comment_replies",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get_content",
"(",
"self",
".",
"config",
"[",
"'comment_replies'",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 41.222222 | 18.888889 |
def assign_category(salts):
"""
Identifies IL type based on name/str
Parameters
----------
salts: pandas DataFrame
dataframe containing column with cation name
Returns
----------
salts: pandas DataFrame
returns the same dataframe with categories
"""
if "name-cat... | [
"def",
"assign_category",
"(",
"salts",
")",
":",
"if",
"\"name-cation\"",
"in",
"salts",
".",
"columns",
":",
"label",
"=",
"\"name-cation\"",
"elif",
"\"Molecular Relative\"",
"in",
"salts",
".",
"columns",
":",
"label",
"=",
"\"Molecular Relative\"",
"else",
... | 33.466667 | 12.4 |
def is_coincident(self, other, keys = None):
"""
Return True if any segment in any list in self intersects
any segment in any list in other. If the optional keys
argument is not None, then it should be an iterable of keys
and only segment lists for those keys will be considered in
the test (instead of rais... | [
"def",
"is_coincident",
"(",
"self",
",",
"other",
",",
"keys",
"=",
"None",
")",
":",
"if",
"keys",
"is",
"not",
"None",
":",
"keys",
"=",
"set",
"(",
"keys",
")",
"self",
"=",
"tuple",
"(",
"self",
"[",
"key",
"]",
"for",
"key",
"in",
"set",
... | 37.576923 | 16.269231 |
def classes(self, values):
"""Classes setter."""
if isinstance(values, dict):
if self.__data is not None and len(self.__data) != len(values):
raise ValueError(
'number of samples do not match the previously assigned data')
elif set(self.keys) !... | [
"def",
"classes",
"(",
"self",
",",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"dict",
")",
":",
"if",
"self",
".",
"__data",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"__data",
")",
"!=",
"len",
"(",
"values",
")",
":... | 46.5 | 20.083333 |
def normalizeBPointType(value):
"""
Normalizes bPoint type.
* **value** must be an string.
* **value** must be one of the following:
+--------+
| corner |
+--------+
| curve |
+--------+
* Returned value will be an unencoded ``unicode`` string.
"""
allowedTy... | [
"def",
"normalizeBPointType",
"(",
"value",
")",
":",
"allowedTypes",
"=",
"[",
"'corner'",
",",
"'curve'",
"]",
"if",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"bPoint type must be a string, not %s.\"",
"%",
"t... | 28.130435 | 17 |
def _get_example_from_basic_type(type):
"""Get example from the given type.
Args:
type: the type you want an example of.
Returns:
An array with two example values of the given type.
"""
if type == 'integer':
return [42, 24]
elif type ... | [
"def",
"_get_example_from_basic_type",
"(",
"type",
")",
":",
"if",
"type",
"==",
"'integer'",
":",
"return",
"[",
"42",
",",
"24",
"]",
"elif",
"type",
"==",
"'number'",
":",
"return",
"[",
"5.5",
",",
"5.5",
"]",
"elif",
"type",
"==",
"'string'",
":"... | 31.095238 | 14.142857 |
def validNormalizeAttributeValue(self, doc, name, value):
"""Does the validation related extra step of the normalization
of attribute values: If the declared value is not CDATA,
then the XML processor must further process the normalized
attribute value by discarding any leading an... | [
"def",
"validNormalizeAttributeValue",
"(",
"self",
",",
"doc",
",",
"name",
",",
"value",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlValidNormalizeAtt... | 57.454545 | 18.363636 |
def DEFINE_boolean(flag_name, default_value, docstring): # pylint: disable=invalid-name
"""Defines a flag of type 'boolean'.
Args:
flag_name: The name of the flag as a string.
default_value: The default value the flag should take as a boolean.
docstring: A helpful message explaining the... | [
"def",
"DEFINE_boolean",
"(",
"flag_name",
",",
"default_value",
",",
"docstring",
")",
":",
"# pylint: disable=invalid-name",
"# Register a custom function for 'bool' so --flag=True works.",
"def",
"str2bool",
"(",
"bool_str",
")",
":",
"\"\"\"Return a boolean value from a give ... | 35.111111 | 18.555556 |
def write_longlong(self, n):
"""
Write an integer as an unsigned 64-bit value.
"""
if (n < 0) or (n >= (2**64)):
raise ValueError('Octet out of range 0..2**64-1')
self._flushbits()
self.out.write(pack('>Q', n)) | [
"def",
"write_longlong",
"(",
"self",
",",
"n",
")",
":",
"if",
"(",
"n",
"<",
"0",
")",
"or",
"(",
"n",
">=",
"(",
"2",
"**",
"64",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Octet out of range 0..2**64-1'",
")",
"self",
".",
"_flushbits",
"(",
... | 29.222222 | 11.888889 |
def include_end(self):
""" Performs and end of include.
"""
self.lex = self.filestack[-1][2]
self.input_data = self.filestack[-1][3]
self.filestack.pop()
if not self.filestack: # End of input?
return
self.filestack[-1][1] += 1 # Increment line coun... | [
"def",
"include_end",
"(",
"self",
")",
":",
"self",
".",
"lex",
"=",
"self",
".",
"filestack",
"[",
"-",
"1",
"]",
"[",
"2",
"]",
"self",
".",
"input_data",
"=",
"self",
".",
"filestack",
"[",
"-",
"1",
"]",
"[",
"3",
"]",
"self",
".",
"filest... | 28.947368 | 16.684211 |
def register_event(self, event_type, pattern, handler):
""" When ``event_type`` is observed for ``pattern``, triggers ``handler``.
For "CHANGE" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and
the base screen state.
"""
if event_type not in self._supported_eve... | [
"def",
"register_event",
"(",
"self",
",",
"event_type",
",",
"pattern",
",",
"handler",
")",
":",
"if",
"event_type",
"not",
"in",
"self",
".",
"_supported_events",
":",
"raise",
"ValueError",
"(",
"\"Unsupported event type {}\"",
".",
"format",
"(",
"event_typ... | 48.208333 | 26.5 |
def select_atoms(indices):
'''Select atoms by their indices.
You can select the first 3 atoms as follows::
select_atoms([0, 1, 2])
Return the current selection dictionary.
'''
rep = current_representation()
rep.select({'atoms': Selection(indices, current_system().n_atoms)})
ret... | [
"def",
"select_atoms",
"(",
"indices",
")",
":",
"rep",
"=",
"current_representation",
"(",
")",
"rep",
".",
"select",
"(",
"{",
"'atoms'",
":",
"Selection",
"(",
"indices",
",",
"current_system",
"(",
")",
".",
"n_atoms",
")",
"}",
")",
"return",
"rep",... | 25.461538 | 21.307692 |
def combinetargets(targets, targetpath, mol_type='nt'):
"""
Creates a set of all unique sequences in a list of supplied FASTA files. Properly formats headers and sequences
to be compatible with local pipelines. Splits hybrid entries. Removes illegal characters.
:param targets: fasta gene targets to comb... | [
"def",
"combinetargets",
"(",
"targets",
",",
"targetpath",
",",
"mol_type",
"=",
"'nt'",
")",
":",
"make_path",
"(",
"targetpath",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"targetpath",
",",
"'combinedtargets.fasta'",
")",
",",
"'w'"... | 56.475 | 22.95 |
def batch_get_archive(self, archive_names, default_versions=None):
'''
Batch version of :py:meth:`~DataAPI.get_archive`
Parameters
----------
archive_names: list
Iterable of archive names to retrieve
default_versions: str, object, or dict
Defa... | [
"def",
"batch_get_archive",
"(",
"self",
",",
"archive_names",
",",
"default_versions",
"=",
"None",
")",
":",
"# toss prefixes and normalize names",
"archive_names",
"=",
"map",
"(",
"lambda",
"arch",
":",
"self",
".",
"_normalize_archive_name",
"(",
"arch",
")",
... | 30.691176 | 25.220588 |
def rename(self, channel_name, new_name):
""" https://api.slack.com/methods/channels.rename
"""
channel_id = self.get_channel_id(channel_name)
self.params.update({
'channel': channel_id,
'name': new_name,
})
return FromUrl('https://slack.c... | [
"def",
"rename",
"(",
"self",
",",
"channel_name",
",",
"new_name",
")",
":",
"channel_id",
"=",
"self",
".",
"get_channel_id",
"(",
"channel_name",
")",
"self",
".",
"params",
".",
"update",
"(",
"{",
"'channel'",
":",
"channel_id",
",",
"'name'",
":",
... | 41.888889 | 14.333333 |
def hypercube(number_of_samples, variables):
"""
This implements Latin Hypercube Sampling.
See https://mathieu.fenniak.net/latin-hypercube-sampling/ for intuitive explanation of what it is
:param number_of_samples: number of segments/samples
:param variables: initial parameters and conditions (lis... | [
"def",
"hypercube",
"(",
"number_of_samples",
",",
"variables",
")",
":",
"number_of_dimensions",
"=",
"len",
"(",
"variables",
")",
"# Split range 0-1 into `nSeg` segments of equal size",
"segment_ranges",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"number_of_sam... | 39.865385 | 23.557692 |
def oauth_token_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/oauth_tokens#create-token"
api_path = "/api/v2/oauth/tokens.json"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"oauth_token_create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/oauth/tokens.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
"data",
",",
"*",
... | 61.25 | 21.25 |
def repeat(coro, times=1, step=1, limit=1, loop=None):
"""
Executes the coroutine function ``x`` number of times,
and accumulates results in order as you would use with ``map``.
Execution concurrency is configurable using ``limit`` param.
This function is a coroutine.
Arguments:
coro... | [
"def",
"repeat",
"(",
"coro",
",",
"times",
"=",
"1",
",",
"step",
"=",
"1",
",",
"limit",
"=",
"1",
",",
"loop",
"=",
"None",
")",
":",
"assert_corofunction",
"(",
"coro",
"=",
"coro",
")",
"# Iterate and attach coroutine for defer scheduling",
"times",
"... | 29.615385 | 23.461538 |
def mtf_transformer_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.no_data_parallelism = True
hparams.use_fixed_batch_size = True
hparams.add_hparam("mtf_mode", True)
hparams.batch_size = 64
hparams.max_length = 256
hparams.add_hparam("d_model", 512)
hparams.add... | [
"def",
"mtf_transformer_base",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"no_data_parallelism",
"=",
"True",
"hparams",
".",
"use_fixed_batch_size",
"=",
"True",
"hparams",
".",
"add_hparam",
"(",
"\"mtf_mode\... | 41.731183 | 18.107527 |
def copy(self):
"""Correctly copies the `Record`
# Returns
`Record`
> A completely decoupled copy of the original
"""
c = copy.copy(self)
c._fieldDict = c._fieldDict.copy()
return c | [
"def",
"copy",
"(",
"self",
")",
":",
"c",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"c",
".",
"_fieldDict",
"=",
"c",
".",
"_fieldDict",
".",
"copy",
"(",
")",
"return",
"c"
] | 19.75 | 20.333333 |
def _is_collect_cx_state_runnable(self, proc_location):
"""
Determine if collect_connection_state is set and can effectively run.
If self._collect_cx_state is True and a custom proc_location is provided, the system cannot
run `ss` or `netstat` over a custom proc_location
:param ... | [
"def",
"_is_collect_cx_state_runnable",
"(",
"self",
",",
"proc_location",
")",
":",
"if",
"self",
".",
"_collect_cx_state",
"is",
"False",
":",
"return",
"False",
"if",
"proc_location",
"!=",
"\"/proc\"",
":",
"self",
".",
"warning",
"(",
"\"Cannot collect connec... | 39.125 | 23.125 |
def get_request(self, request_id, status=False):
"""
Retrieves a single request by ID.
:param request_id: The unique ID of the request.
:type request_id: ``str``
:param status: Retreive the full status of the request.
:type status: ``bool``
... | [
"def",
"get_request",
"(",
"self",
",",
"request_id",
",",
"status",
"=",
"False",
")",
":",
"if",
"status",
":",
"response",
"=",
"self",
".",
"_perform_request",
"(",
"'/requests/'",
"+",
"request_id",
"+",
"'/status'",
")",
"else",
":",
"response",
"=",... | 29.315789 | 16.684211 |
def _serialize_to_one(self, key, val, rlink):
""" Make a to_one JSON API compliant
:spec:
jsonapi.org/format/#document-resource-object-relationships
:param key:
the string name of the relationship field
:param val:
dict containing `rid` & `rtype` keys... | [
"def",
"_serialize_to_one",
"(",
"self",
",",
"key",
",",
"val",
",",
"rlink",
")",
":",
"data",
"=",
"None",
"if",
"val",
"and",
"val",
"[",
"'rid'",
"]",
":",
"data",
"=",
"{",
"'id'",
":",
"val",
"[",
"'rid'",
"]",
",",
"'type'",
":",
"val",
... | 27.884615 | 19.384615 |
def get_starter_kit_meta(name):
"""
Extract metadata link for starter kit from platform configs. Starter kit available on add component - starter kit menu.
Beware, config could be changed by deploy scripts during deploy.
:param name: Name of starter kit
:return: Link to metadata
"""
kits = y... | [
"def",
"get_starter_kit_meta",
"(",
"name",
")",
":",
"kits",
"=",
"yaml",
".",
"safe_load",
"(",
"requests",
".",
"get",
"(",
"url",
"=",
"starter_kits_url",
")",
".",
"content",
")",
"[",
"'kits'",
"]",
"kits_meta_url",
"=",
"[",
"x",
"[",
"'metaUrl'",... | 48.692308 | 27.461538 |
def count(self, sub, start=0, end=-1):
"""Return the number of non-overlapping occurrences of substring sub in string[start:end].
Optional arguments start and end are interpreted as in slice notation.
:param str sub: Substring to search.
:param int start: Beginning position.
:p... | [
"def",
"count",
"(",
"self",
",",
"sub",
",",
"start",
"=",
"0",
",",
"end",
"=",
"-",
"1",
")",
":",
"return",
"self",
".",
"value_no_colors",
".",
"count",
"(",
"sub",
",",
"start",
",",
"end",
")"
] | 42.9 | 16.4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.