text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def show(only_path=False):
"""Show the current config."""
logger.setLevel(logging.INFO)
infos = ["\n", f'Instance path: "{current_app.instance_path}"']
logger.info("\n ".join(infos))
if not only_path:
log_config(current_app.config) | [
"def",
"show",
"(",
"only_path",
"=",
"False",
")",
":",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"infos",
"=",
"[",
"\"\\n\"",
",",
"f'Instance path: \"{current_app.instance_path}\"'",
"]",
"logger",
".",
"info",
"(",
"\"\\n \"",
".",
"... | 28.222222 | 17.111111 |
def find_numeration(docbody, title):
"""Find numeration pattern
1st try to find numeration in the title
e.g.
References [4] Riotto...
2nd find the numeration alone in the line after the title
e.g.
References
1
Riotto
3rnd find the numeration in the following line
e.g.
... | [
"def",
"find_numeration",
"(",
"docbody",
",",
"title",
")",
":",
"ref_details",
",",
"found_title",
"=",
"find_numeration_in_title",
"(",
"docbody",
",",
"title",
")",
"if",
"not",
"ref_details",
":",
"ref_details",
",",
"found_title",
"=",
"find_numeration_in_bo... | 23.130435 | 23 |
def _find_links(k_vec, sfx, rsfx, k):
"""Find sfx/rsfx recursively."""
k_vec.sort()
if 0 in k_vec:
return k_vec
else:
if sfx[k] not in k_vec:
k_vec.append(sfx[k])
for i in range(len(rsfx[k])):
if rsfx[k][i] not in k_vec:
k_vec.append(rsfx[k... | [
"def",
"_find_links",
"(",
"k_vec",
",",
"sfx",
",",
"rsfx",
",",
"k",
")",
":",
"k_vec",
".",
"sort",
"(",
")",
"if",
"0",
"in",
"k_vec",
":",
"return",
"k_vec",
"else",
":",
"if",
"sfx",
"[",
"k",
"]",
"not",
"in",
"k_vec",
":",
"k_vec",
".",... | 29.75 | 12.375 |
def check_file_for_tabs(filename, verbose=True):
"""identifies if the file contains tabs and returns True if it
does. It also prints the location of the lines and columns. If
verbose is set to False, the location is not printed.
:param verbose: if true prints information about issues
:param filenam... | [
"def",
"check_file_for_tabs",
"(",
"filename",
",",
"verbose",
"=",
"True",
")",
":",
"file_contains_tabs",
"=",
"False",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"read",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",... | 38.259259 | 16.148148 |
def generateLatticeFile(self, beamline, filename=None, format='elegant'):
""" generate simulation files for lattice analysis,
e.g. ".lte" for elegant, ".madx" for madx
input parameters:
:param beamline: keyword for beamline
:param filename: name of lte/mad file,
... | [
"def",
"generateLatticeFile",
"(",
"self",
",",
"beamline",
",",
"filename",
"=",
"None",
",",
"format",
"=",
"'elegant'",
")",
":",
"\"\"\"\n if not self.isBeamline(beamline):\n print(\"%s is a valid defined beamline, do not process.\" % (beamline))\n re... | 41.670886 | 20.43038 |
def step_it_should_fail_with(context):
'''
EXAMPLE:
...
when I run "behave ..."
then it should fail with:
"""
TEXT
"""
'''
assert context.text is not None, "ENSURE: multiline text is provided."
step_command_output_should_contain(context)
... | [
"def",
"step_it_should_fail_with",
"(",
"context",
")",
":",
"assert",
"context",
".",
"text",
"is",
"not",
"None",
",",
"\"ENSURE: multiline text is provided.\"",
"step_command_output_should_contain",
"(",
"context",
")",
"assert_that",
"(",
"context",
".",
"command_re... | 29 | 18.230769 |
def teardown(file): # pylint:disable=redefined-builtin
"""Teardown a polyaxon deployment given a config file."""
config = read_deployment_config(file)
manager = DeployManager(config=config, filepath=file)
exception = None
try:
if click.confirm('Would you like to execute pre-delete hooks?', ... | [
"def",
"teardown",
"(",
"file",
")",
":",
"# pylint:disable=redefined-builtin",
"config",
"=",
"read_deployment_config",
"(",
"file",
")",
"manager",
"=",
"DeployManager",
"(",
"config",
"=",
"config",
",",
"filepath",
"=",
"file",
")",
"exception",
"=",
"None",... | 39.25 | 19.8125 |
def _GetUnsortedNotifications(self,
queue_shard,
notifications_by_session_id=None):
"""Returns all the available notifications for a queue_shard.
Args:
queue_shard: urn of queue shard
notifications_by_session_id: store notifications in... | [
"def",
"_GetUnsortedNotifications",
"(",
"self",
",",
"queue_shard",
",",
"notifications_by_session_id",
"=",
"None",
")",
":",
"if",
"notifications_by_session_id",
"is",
"None",
":",
"notifications_by_session_id",
"=",
"{",
"}",
"end_time",
"=",
"self",
".",
"froze... | 45.083333 | 22.694444 |
def iterSourceCode(paths):
"""
Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is.
"""
for path in paths:
if os.path.isdir(pat... | [
"def",
"iterSourceCode",
"(",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
... | 35.125 | 17.25 |
def get_golden_topics(self, lang):
"""Return the topics mastered ("golden") by a user in a language."""
return [topic['title']
for topic in self.user_data.language_data[lang]['skills']
if topic['learned'] and topic['strength'] == 1.0] | [
"def",
"get_golden_topics",
"(",
"self",
",",
"lang",
")",
":",
"return",
"[",
"topic",
"[",
"'title'",
"]",
"for",
"topic",
"in",
"self",
".",
"user_data",
".",
"language_data",
"[",
"lang",
"]",
"[",
"'skills'",
"]",
"if",
"topic",
"[",
"'learned'",
... | 55.6 | 14.8 |
def _check_pong(self):
"""Checks if a Pong message was received.
:return:
"""
self.pong_timer.cancel()
if self.pong_received:
self.log.debug("_check_pong(): Pong received in time.")
self.pong_received = False
else:
# reconnect
... | [
"def",
"_check_pong",
"(",
"self",
")",
":",
"self",
".",
"pong_timer",
".",
"cancel",
"(",
")",
"if",
"self",
".",
"pong_received",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"_check_pong(): Pong received in time.\"",
")",
"self",
".",
"pong_received",
"... | 32 | 16 |
def ParseFileObject(self, parser_mediator, file_object):
"""Parses a Java WebStart Cache IDX file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dvfvs.FileIO): a file-like object to p... | [
"def",
"ParseFileObject",
"(",
"self",
",",
"parser_mediator",
",",
"file_object",
")",
":",
"file_header_map",
"=",
"self",
".",
"_GetDataTypeMap",
"(",
"'java_idx_file_header'",
")",
"try",
":",
"file_header",
",",
"file_offset",
"=",
"self",
".",
"_ReadStructur... | 40.274336 | 21.778761 |
def setCredentialValues(self, username=None, password=None, public_key=None, private_key=None, new=False):
"""Set the values in disk.0.os.credentials.*."""
credentials_base = "disk.0.os.credentials."
if new:
credentials_base = "disk.0.os.credentials.new."
if username:
... | [
"def",
"setCredentialValues",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"public_key",
"=",
"None",
",",
"private_key",
"=",
"None",
",",
"new",
"=",
"False",
")",
":",
"credentials_base",
"=",
"\"disk.0.os.credentials.\"",
... | 43.066667 | 26 |
def split_elements(value):
"""Split a string with comma or space-separated elements into a list."""
l = [v.strip() for v in value.split(',')]
if len(l) == 1:
l = value.split()
return l | [
"def",
"split_elements",
"(",
"value",
")",
":",
"l",
"=",
"[",
"v",
".",
"strip",
"(",
")",
"for",
"v",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
"if",
"len",
"(",
"l",
")",
"==",
"1",
":",
"l",
"=",
"value",
".",
"split",
"(",
")... | 33.833333 | 13.833333 |
def delete(self):
"""
Deletes the space
"""
return self._client._delete(
self.__class__.base_url(
self.sys['id']
)
) | [
"def",
"delete",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"_delete",
"(",
"self",
".",
"__class__",
".",
"base_url",
"(",
"self",
".",
"sys",
"[",
"'id'",
"]",
")",
")"
] | 18.8 | 15.4 |
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config wa... | [
"def",
"config_control",
"(",
"inherit_napalm_device",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"result",
"=",
"True",
"comment",
"=",
"''",
"changed",
",",
"not_changed_rsn",
"=",
"config_changed",
"(",
"inherit_napalm_de... | 32.564103 | 26.153846 |
def exit_after(s):
"""
Use as decorator to exit process if
function takes longer than s seconds.
Direct call is available via exit_after(TIMEOUT_IN_S)(fce)(args).
Inspired by https://stackoverflow.com/a/31667005
"""
def outer(fn):
def inner(*args, **kwargs):
timer = th... | [
"def",
"exit_after",
"(",
"s",
")",
":",
"def",
"outer",
"(",
"fn",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timer",
"=",
"threading",
".",
"Timer",
"(",
"s",
",",
"thread",
".",
"interrupt_main",
")",
"time... | 27.08 | 20.2 |
def gene_by_protein_id(self, protein_id):
"""
Get the gene ID associated with the given protein ID,
return its Gene object
"""
gene_id = self.gene_id_of_protein_id(protein_id)
return self.gene_by_id(gene_id) | [
"def",
"gene_by_protein_id",
"(",
"self",
",",
"protein_id",
")",
":",
"gene_id",
"=",
"self",
".",
"gene_id_of_protein_id",
"(",
"protein_id",
")",
"return",
"self",
".",
"gene_by_id",
"(",
"gene_id",
")"
] | 35.571429 | 7 |
def _generate_features(self, feature_extractors):
"""Run all FeatureExtractors and record results in a key-value format.
:param feature_extractors: iterable of `FeatureExtractor` objects.
"""
results = [pd.DataFrame()]
n_ext = len(feature_extractors)
for i, extractor in... | [
"def",
"_generate_features",
"(",
"self",
",",
"feature_extractors",
")",
":",
"results",
"=",
"[",
"pd",
".",
"DataFrame",
"(",
")",
"]",
"n_ext",
"=",
"len",
"(",
"feature_extractors",
")",
"for",
"i",
",",
"extractor",
"in",
"enumerate",
"(",
"feature_e... | 38.384615 | 14.884615 |
def duplicate(self):
'''
Returns a copy of the current group, including its lines.
@returns: Group
'''
return self.__class__(amount=self.amount, date=self.date,
method=self.method, ref=self.ref) | [
"def",
"duplicate",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"amount",
"=",
"self",
".",
"amount",
",",
"date",
"=",
"self",
".",
"date",
",",
"method",
"=",
"self",
".",
"method",
",",
"ref",
"=",
"self",
".",
"ref",
")"
] | 36.857143 | 24 |
def _concat_datetime(to_concat, axis=0, typs=None):
"""
provide concatenation of an datetimelike array of arrays each of which is a
single M8[ns], datetimet64[ns, tz] or m8[ns] dtype
Parameters
----------
to_concat : array of arrays
axis : axis to provide concatenation
typs : set of to_... | [
"def",
"_concat_datetime",
"(",
"to_concat",
",",
"axis",
"=",
"0",
",",
"typs",
"=",
"None",
")",
":",
"if",
"typs",
"is",
"None",
":",
"typs",
"=",
"get_dtype_kinds",
"(",
"to_concat",
")",
"# multiple types, need to coerce to object",
"if",
"len",
"(",
"t... | 32.177778 | 19.911111 |
def task_loop(tasks, execute, wait=None, store=TaskStore()):
"""
The inner task loop for a task runner.
execute: A function that runs a task. It should take a task as its
sole argument, and may optionally return a TaskResult.
wait: (optional, None) A function to run whenever there aren't any
... | [
"def",
"task_loop",
"(",
"tasks",
",",
"execute",
",",
"wait",
"=",
"None",
",",
"store",
"=",
"TaskStore",
"(",
")",
")",
":",
"completed",
"=",
"set",
"(",
")",
"failed",
"=",
"set",
"(",
")",
"exceptions",
"=",
"[",
"]",
"def",
"collect",
"(",
... | 32.59375 | 18.625 |
def get(self, q, limit=None):
"""
Performs a search against the predict endpoint
:param q: query to be searched for [STRING]
:return: { score: [0|1] }
"""
uri = '{}/predict?q={}'.format(self.client.remote, q)
self.logger.debug(uri)
body = self.client.get... | [
"def",
"get",
"(",
"self",
",",
"q",
",",
"limit",
"=",
"None",
")",
":",
"uri",
"=",
"'{}/predict?q={}'",
".",
"format",
"(",
"self",
".",
"client",
".",
"remote",
",",
"q",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"uri",
")",
"body",
"=",... | 28.583333 | 14.25 |
def pipeline(self):
"""Returns :class:`Pipeline` object to execute bulk of commands.
It is provided for convenience.
Commands can be pipelined without it.
Example:
>>> pipe = redis.pipeline()
>>> fut1 = pipe.incr('foo') # NO `await` as it will block forever!
>>... | [
"def",
"pipeline",
"(",
"self",
")",
":",
"return",
"Pipeline",
"(",
"self",
".",
"_pool_or_conn",
",",
"self",
".",
"__class__",
",",
"loop",
"=",
"self",
".",
"_pool_or_conn",
".",
"_loop",
")"
] | 32.307692 | 17.884615 |
def get_service(
service_name,
inactive=False,
completed=False
):
""" Get a dictionary describing a service
:param service_name: the service name
:type service_name: str
:param inactive: whether to include inactive services
:type inactive: bool
:param ... | [
"def",
"get_service",
"(",
"service_name",
",",
"inactive",
"=",
"False",
",",
"completed",
"=",
"False",
")",
":",
"services",
"=",
"mesos",
".",
"get_master",
"(",
")",
".",
"frameworks",
"(",
"inactive",
"=",
"inactive",
",",
"completed",
"=",
"complete... | 27.625 | 19.541667 |
def _normalize_key(value):
"""Return a key from an entity, model instance, key, or key string."""
if ndb is not None and isinstance(value, (ndb.Model, ndb.Key)):
return None
if getattr(value, "key", None):
return value.key()
elif isinstance(value, basestring):
return datastore.Key(value)
else:
... | [
"def",
"_normalize_key",
"(",
"value",
")",
":",
"if",
"ndb",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"value",
",",
"(",
"ndb",
".",
"Model",
",",
"ndb",
".",
"Key",
")",
")",
":",
"return",
"None",
"if",
"getattr",
"(",
"value",
",",
"\"key... | 32.4 | 15.8 |
def _parse_interval(value):
'''
Convert an interval string like 1w3d6h into the number of seconds, time
resolution (1 unit of the smallest specified time unit) and the modifier(
'+', '-', or '').
w = week
d = day
h = hour
m = minute
s = second
'''
match = ... | [
"def",
"_parse_interval",
"(",
"value",
")",
":",
"match",
"=",
"_INTERVAL_REGEX",
".",
"match",
"(",
"six",
".",
"text_type",
"(",
"value",
")",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'invalid time interval: \\'{0}\\''",
".",
"f... | 33.892857 | 20.035714 |
def resettable_cached_property(func):
"""Decorator to add cached computed properties to an object.
Similar to Django's `cached_property` decorator, except stores
all the data under a single well-known key so that it can easily
be blown away.
"""
def wrapper(self):
if not hasattr(self, '... | [
"def",
"resettable_cached_property",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_resettable_cached_properties'",
")",
":",
"self",
".",
"_resettable_cached_properties",
"=",
"{",
"}",
"if",
"func... | 43.1875 | 20.625 |
def complete(self):
"""
When *local_workflow_require_branches* of the task was set to *True*, returns whether the
:py:meth:`run` method has been called before. Otherwise, the call is forwarded to the super
class.
"""
if self.task.local_workflow_require_branches:
... | [
"def",
"complete",
"(",
"self",
")",
":",
"if",
"self",
".",
"task",
".",
"local_workflow_require_branches",
":",
"return",
"self",
".",
"_has_run",
"else",
":",
"return",
"super",
"(",
"LocalWorkflowProxy",
",",
"self",
")",
".",
"complete",
"(",
")"
] | 41 | 23.2 |
def BDEVolumeOpen(bde_volume, path_spec, file_object, key_chain):
"""Opens the BDE volume using the path specification.
Args:
bde_volume (pybde.volume): BDE volume.
path_spec (PathSpec): path specification.
file_object (FileIO): file-like object.
key_chain (KeyChain): key chain.
"""
password = ... | [
"def",
"BDEVolumeOpen",
"(",
"bde_volume",
",",
"path_spec",
",",
"file_object",
",",
"key_chain",
")",
":",
"password",
"=",
"key_chain",
".",
"GetCredential",
"(",
"path_spec",
",",
"'password'",
")",
"if",
"password",
":",
"bde_volume",
".",
"set_password",
... | 33.227273 | 18.318182 |
def TR(self,**kwargs): #pragma: no cover
"""
NAME:
TR
PURPOSE:
Calculate the radial period for a power-law rotation curve
INPUT:
scipy.integrate.quadrature keywords
OUTPUT:
T_R(R,vT,vT)*vc/ro + estimate of the error
HISTORY:
... | [
"def",
"TR",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"#pragma: no cover",
"if",
"hasattr",
"(",
"self",
",",
"'_TR'",
")",
":",
"return",
"self",
".",
"_TR",
"(",
"rperi",
",",
"rap",
")",
"=",
"self",
".",
"calcRapRperi",
"(",
"*",
"*",
... | 37.142857 | 16.571429 |
def _combine_attr_fast_update(self, attr, typ):
'''Avoids having to call _update for each intermediate base. Only
works for class attr of type UpdateDict.
'''
values = dict(getattr(self, attr, {}))
for base in self._class_data.bases:
vals = dict(getattr(bas... | [
"def",
"_combine_attr_fast_update",
"(",
"self",
",",
"attr",
",",
"typ",
")",
":",
"values",
"=",
"dict",
"(",
"getattr",
"(",
"self",
",",
"attr",
",",
"{",
"}",
")",
")",
"for",
"base",
"in",
"self",
".",
"_class_data",
".",
"bases",
":",
"vals",
... | 35.615385 | 15.461538 |
def push_notification_devices_destroy_many(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/push_notification_devices#bulk-unregister-push-notification-devices"
api_path = "/api/v2/push_notification_devices/destroy_many.json"
return self.call(api_path, method="POST", data... | [
"def",
"push_notification_devices_destroy_many",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/push_notification_devices/destroy_many.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
... | 83.25 | 43.25 |
def compact_hdf5_file(filename, name=None, index=None, keep_backup=True):
"""Can compress an HDF5 to reduce file size.
The properties on how to compress the new file are taken from a given
trajectory in the file.
Simply calls ``ptrepack`` from the command line.
(Se also https://pytables.github.io/u... | [
"def",
"compact_hdf5_file",
"(",
"filename",
",",
"name",
"=",
"None",
",",
"index",
"=",
"None",
",",
"keep_backup",
"=",
"True",
")",
":",
"if",
"name",
"is",
"None",
"and",
"index",
"is",
"None",
":",
"index",
"=",
"-",
"1",
"tmp_traj",
"=",
"load... | 32.026667 | 22.306667 |
def _recv_byte(self, byte):
"""
Non-printable filtering currently disabled because it did not play
well with extended character sets.
"""
## Filter out non-printing characters
#if (byte >= ' ' and byte <= '~') or byte == '\n':
if self.telnet_echo:
self... | [
"def",
"_recv_byte",
"(",
"self",
",",
"byte",
")",
":",
"## Filter out non-printing characters",
"#if (byte >= ' ' and byte <= '~') or byte == '\\n':",
"if",
"self",
".",
"telnet_echo",
":",
"self",
".",
"_echo_byte",
"(",
"byte",
")",
"self",
".",
"recv_buffer",
"+=... | 36.1 | 9.9 |
def inner_product(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor:
""" Hilbert-Schmidt inner product between qubit vectors
The tensor rank and qubits must match.
"""
if vec0.rank != vec1.rank or vec0.qubit_nb != vec1.qubit_nb:
raise ValueError('Incompatibly vectors. Qubits and rank must ma... | [
"def",
"inner_product",
"(",
"vec0",
":",
"QubitVector",
",",
"vec1",
":",
"QubitVector",
")",
"->",
"bk",
".",
"BKTensor",
":",
"if",
"vec0",
".",
"rank",
"!=",
"vec1",
".",
"rank",
"or",
"vec0",
".",
"qubit_nb",
"!=",
"vec1",
".",
"qubit_nb",
":",
... | 43.4 | 20.8 |
def main(self):
"""
Generates an output string by replacing the keywords in the format
string with the corresponding values from a submission dictionary.
"""
self.manage_submissions()
out_string = self.options['format']
# Pop until we get something which len(titl... | [
"def",
"main",
"(",
"self",
")",
":",
"self",
".",
"manage_submissions",
"(",
")",
"out_string",
"=",
"self",
".",
"options",
"[",
"'format'",
"]",
"# Pop until we get something which len(title) <= max-chars",
"length",
"=",
"float",
"(",
"'inf'",
")",
"while",
... | 41.117647 | 19 |
def metadata_path(self, m_path):
"""Provide pointers to the paths of the metadata file
Args:
m_path: Path to metadata file
"""
if not m_path:
self.metadata_dir = None
self.metadata_file = None
else:
if not op.exists(m_path):
... | [
"def",
"metadata_path",
"(",
"self",
",",
"m_path",
")",
":",
"if",
"not",
"m_path",
":",
"self",
".",
"metadata_dir",
"=",
"None",
"self",
".",
"metadata_file",
"=",
"None",
"else",
":",
"if",
"not",
"op",
".",
"exists",
"(",
"m_path",
")",
":",
"ra... | 28.75 | 16.75 |
def parse_python(classifiers):
"""Parse out the versions of python supported a/c classifiers."""
prefix = 'Programming Language :: Python ::'
python_classifiers = [c.split('::')[2].strip() for c in classifiers if c.startswith(prefix)]
return ', '.join([c for c in python_classifiers if parse_version(c)]) | [
"def",
"parse_python",
"(",
"classifiers",
")",
":",
"prefix",
"=",
"'Programming Language :: Python ::'",
"python_classifiers",
"=",
"[",
"c",
".",
"split",
"(",
"'::'",
")",
"[",
"2",
"]",
".",
"strip",
"(",
")",
"for",
"c",
"in",
"classifiers",
"if",
"c... | 63.2 | 21.4 |
def ask(question, default_answer=False, default_answer_str="no"):
"""
Ask for user input.
This asks a yes/no question with a preset default.
You can bypass the user-input and fetch the default answer, if
you set
Args:
question: The question to ask on stdout.
default_answer: The... | [
"def",
"ask",
"(",
"question",
",",
"default_answer",
"=",
"False",
",",
"default_answer_str",
"=",
"\"no\"",
")",
":",
"response",
"=",
"default_answer",
"def",
"should_ignore_tty",
"(",
")",
":",
"\"\"\"\n Check, if we want to ignore an opened tty result.\n ... | 32.410256 | 22.820513 |
def ask(question, default=None):
"""
@question: str
@default: Any value which can be converted to string.
Asks a user for a input.
If default parameter is passed it will be appended to the end of the message in square brackets.
"""
question = str(question)
if default:
question ... | [
"def",
"ask",
"(",
"question",
",",
"default",
"=",
"None",
")",
":",
"question",
"=",
"str",
"(",
"question",
")",
"if",
"default",
":",
"question",
"+=",
"' ['",
"+",
"str",
"(",
"default",
")",
"+",
"']'",
"question",
"+=",
"': '",
"reply",
"=",
... | 25.058824 | 20.705882 |
def favorites_getList(user_id='', per_page='', page=''):
"""Returns list of Photo objects."""
method = 'flickr.favorites.getList'
data = _doget(method, auth=True, user_id=user_id, per_page=per_page,\
page=page)
photos = []
if isinstance(data.rsp.photos.photo, list):
for pho... | [
"def",
"favorites_getList",
"(",
"user_id",
"=",
"''",
",",
"per_page",
"=",
"''",
",",
"page",
"=",
"''",
")",
":",
"method",
"=",
"'flickr.favorites.getList'",
"data",
"=",
"_doget",
"(",
"method",
",",
"auth",
"=",
"True",
",",
"user_id",
"=",
"user_i... | 38.916667 | 14.25 |
def find_clusters(network, mask=[], t_labels=False):
r"""
Identify connected clusters of pores in the network. This method can
also return a list of throat cluster numbers, which correspond to the
cluster numbers of the pores to which the throat is connected. Either
site and bond percolation can b... | [
"def",
"find_clusters",
"(",
"network",
",",
"mask",
"=",
"[",
"]",
",",
"t_labels",
"=",
"False",
")",
":",
"# Parse the input arguments",
"mask",
"=",
"sp",
".",
"array",
"(",
"mask",
",",
"ndmin",
"=",
"1",
")",
"if",
"mask",
".",
"dtype",
"!=",
"... | 35.653061 | 22.857143 |
def plot_full(candsfile, cands, mode='im'):
""" Plot 'full' features, such as cutout image and spectrum.
"""
loc, prop, d = read_candidates(candsfile, returnstate=True)
npixx, npixy = prop[0][4].shape
nints, nchan, npol = prop[0][5].shape
bin = 10
plt.figure(1)
for i in cands:
... | [
"def",
"plot_full",
"(",
"candsfile",
",",
"cands",
",",
"mode",
"=",
"'im'",
")",
":",
"loc",
",",
"prop",
",",
"d",
"=",
"read_candidates",
"(",
"candsfile",
",",
"returnstate",
"=",
"True",
")",
"npixx",
",",
"npixy",
"=",
"prop",
"[",
"0",
"]",
... | 40.047619 | 23.047619 |
def _update_dirs_on_base(self):
'''Fill up the names of dirs based on the contents of 'base'.'''
if self._dirs['base'] != None:
for d in self._predefined_dir_names:
dstr = d
#if d == "s2":
# dstr = '.'+d
self._dirs[d] = os.pa... | [
"def",
"_update_dirs_on_base",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dirs",
"[",
"'base'",
"]",
"!=",
"None",
":",
"for",
"d",
"in",
"self",
".",
"_predefined_dir_names",
":",
"dstr",
"=",
"d",
"#if d == \"s2\":",
"# dstr = '.'+d",
"self",
".",
"_... | 43.25 | 14.25 |
def renderIndex(self, relpath="", refresh=0, refresh_index=0):
"""Returns HTML index code for this entry.
If 'relpath' is empty, renders complete index.html file.
If 'relpath' is not empty, then index is being included into a top-level log, and
relpath should be passed to all sub-rendere... | [
"def",
"renderIndex",
"(",
"self",
",",
"relpath",
"=",
"\"\"",
",",
"refresh",
"=",
"0",
",",
"refresh_index",
"=",
"0",
")",
":",
"# check if cache can be used",
"refresh_index",
"=",
"max",
"(",
"refresh",
",",
"refresh_index",
")",
"dprintf",
"(",
"2",
... | 53.583333 | 20.12037 |
def get_neighborhood_overlap(self, node1, node2, connection_type=None):
"""Get the intersection of two nodes's neighborhoods.
Neighborhood is defined by parameter connection_type.
:param Vertex node1: First node.
:param Vertex node2: Second node.
:param Optional[str] connection_... | [
"def",
"get_neighborhood_overlap",
"(",
"self",
",",
"node1",
",",
"node2",
",",
"connection_type",
"=",
"None",
")",
":",
"if",
"connection_type",
"is",
"None",
"or",
"connection_type",
"==",
"\"direct\"",
":",
"order",
"=",
"1",
"elif",
"connection_type",
"=... | 43.272727 | 20.727273 |
def toMBI(self, getMemoryDump = False):
"""
Returns a L{win32.MemoryBasicInformation} object using the data
retrieved from the database.
@type getMemoryDump: bool
@param getMemoryDump: (Optional) If C{True} retrieve the memory dump.
Defaults to C{False} since this m... | [
"def",
"toMBI",
"(",
"self",
",",
"getMemoryDump",
"=",
"False",
")",
":",
"mbi",
"=",
"win32",
".",
"MemoryBasicInformation",
"(",
")",
"mbi",
".",
"BaseAddress",
"=",
"self",
".",
"address",
"mbi",
".",
"RegionSize",
"=",
"self",
".",
"size",
"mbi",
... | 39.709677 | 13.129032 |
def print_tokens(output, tokens, style):
"""
Print a list of (Token, text) tuples in the given style to the output.
"""
assert isinstance(output, Output)
assert isinstance(style, Style)
# Reset first.
output.reset_attributes()
output.enable_autowrap()
# Print all (token, text) tupl... | [
"def",
"print_tokens",
"(",
"output",
",",
"tokens",
",",
"style",
")",
":",
"assert",
"isinstance",
"(",
"output",
",",
"Output",
")",
"assert",
"isinstance",
"(",
"style",
",",
"Style",
")",
"# Reset first.",
"output",
".",
"reset_attributes",
"(",
")",
... | 23.888889 | 18.185185 |
def add_filename_pattern(self, dir_name, pattern):
"""
Adds a Unix shell-style wildcard pattern underneath the specified directory
:param dir_name: str: directory that contains the pattern
:param pattern: str: Unix shell-style wildcard pattern
"""
full_pattern = '{}{}{}'.... | [
"def",
"add_filename_pattern",
"(",
"self",
",",
"dir_name",
",",
"pattern",
")",
":",
"full_pattern",
"=",
"'{}{}{}'",
".",
"format",
"(",
"dir_name",
",",
"os",
".",
"sep",
",",
"pattern",
")",
"filename_regex",
"=",
"fnmatch",
".",
"translate",
"(",
"fu... | 51.222222 | 17.666667 |
def messaging(_context, repository, reset_on_start=False):
"""
Directive for setting up the user message resource in the appropriate
repository.
:param str repository: The repository to create the user messages resource
in.
"""
discriminator = ('messaging', repository)
reg = get_curre... | [
"def",
"messaging",
"(",
"_context",
",",
"repository",
",",
"reset_on_start",
"=",
"False",
")",
":",
"discriminator",
"=",
"(",
"'messaging'",
",",
"repository",
")",
"reg",
"=",
"get_current_registry",
"(",
")",
"config",
"=",
"Configurator",
"(",
"reg",
... | 40.666667 | 19.066667 |
def update_account(self, email=None, company_name=None, first_name=None,
last_name=None, address=None, postal_code=None, city=None,
state=None, country=None, phone=None):
"""
::
POST /:login
:param email: Email address
:type email: :... | [
"def",
"update_account",
"(",
"self",
",",
"email",
"=",
"None",
",",
"company_name",
"=",
"None",
",",
"first_name",
"=",
"None",
",",
"last_name",
"=",
"None",
",",
"address",
"=",
"None",
",",
"postal_code",
"=",
"None",
",",
"city",
"=",
"None",
",... | 29.625 | 15.0625 |
def init_ui(self):
"""Setup control widget UI."""
self.control_layout = QHBoxLayout()
self.setLayout(self.control_layout)
self.reset_button = QPushButton()
self.reset_button.setFixedSize(40, 40)
self.reset_button.setIcon(QtGui.QIcon(WIN_PATH))
self.game_timer = QL... | [
"def",
"init_ui",
"(",
"self",
")",
":",
"self",
".",
"control_layout",
"=",
"QHBoxLayout",
"(",
")",
"self",
".",
"setLayout",
"(",
"self",
".",
"control_layout",
")",
"self",
".",
"reset_button",
"=",
"QPushButton",
"(",
")",
"self",
".",
"reset_button",... | 43.941176 | 11.588235 |
def updateBoostStrength(self):
"""
Update boost strength using given strength factor during training
"""
if self.training:
self.boostStrength = self.boostStrength * self.boostStrengthFactor | [
"def",
"updateBoostStrength",
"(",
"self",
")",
":",
"if",
"self",
".",
"training",
":",
"self",
".",
"boostStrength",
"=",
"self",
".",
"boostStrength",
"*",
"self",
".",
"boostStrengthFactor"
] | 34.333333 | 15 |
def is_series(data):
"""
Checks whether the supplied data is of Series type.
"""
dd = None
if 'dask' in sys.modules:
import dask.dataframe as dd
return((pd is not None and isinstance(data, pd.Series)) or
(dd is not None and isinstance(data, dd.Series))) | [
"def",
"is_series",
"(",
"data",
")",
":",
"dd",
"=",
"None",
"if",
"'dask'",
"in",
"sys",
".",
"modules",
":",
"import",
"dask",
".",
"dataframe",
"as",
"dd",
"return",
"(",
"(",
"pd",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"data",
",",
"p... | 31.888889 | 13.222222 |
def frombed(args):
"""
%prog frombed bed_file [--options] > gff_file
Convert bed to gff file. In bed, the accn will convert to key='ID'
Default type will be `match` and default source will be `source`
"""
p = OptionParser(frombed.__doc__)
p.add_option("--type", default="match",
... | [
"def",
"frombed",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"frombed",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--type\"",
",",
"default",
"=",
"\"match\"",
",",
"help",
"=",
"\"GFF feature type [default: %default]\"",
")",
"p",
".",
... | 31 | 18.909091 |
def _GetDirectory(self):
"""Retrieves a directory.
Returns:
TSKPartitionDirectory: a directory or None if not available.
"""
if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY:
return None
return TSKPartitionDirectory(self._file_system, self.path_spec) | [
"def",
"_GetDirectory",
"(",
"self",
")",
":",
"if",
"self",
".",
"entry_type",
"!=",
"definitions",
".",
"FILE_ENTRY_TYPE_DIRECTORY",
":",
"return",
"None",
"return",
"TSKPartitionDirectory",
"(",
"self",
".",
"_file_system",
",",
"self",
".",
"path_spec",
")"
... | 31.777778 | 20.444444 |
def stop_process(self):
"""Request the module process to stop and release it
:return: None
"""
if not self.process:
return
logger.info("I'm stopping module %r (pid=%d)", self.name, self.process.pid)
self.kill()
# Clean inner process reference
... | [
"def",
"stop_process",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"process",
":",
"return",
"logger",
".",
"info",
"(",
"\"I'm stopping module %r (pid=%d)\"",
",",
"self",
".",
"name",
",",
"self",
".",
"process",
".",
"pid",
")",
"self",
".",
"kil... | 27.416667 | 19 |
def can_create_activities(self):
"""Tests if this user can create Activities.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known creating an Activity
will result in a PermissionDenied. This is intended as a hint
to an applic... | [
"def",
"can_create_activities",
"(",
"self",
")",
":",
"url_path",
"=",
"construct_url",
"(",
"'authorization'",
",",
"bank_id",
"=",
"self",
".",
"_catalog_idstr",
")",
"return",
"self",
".",
"_get_request",
"(",
"url_path",
")",
"[",
"'activityHints'",
"]",
... | 50.4 | 19.4 |
def authenticate_credentials(self, token: bytes, request=None):
"""
Authenticate the token with optional request for context.
"""
user = AuthToken.get_user_for_token(token)
if user is None:
raise AuthenticationFailed(_('Invalid auth token.'))
if not user.is_... | [
"def",
"authenticate_credentials",
"(",
"self",
",",
"token",
":",
"bytes",
",",
"request",
"=",
"None",
")",
":",
"user",
"=",
"AuthToken",
".",
"get_user_for_token",
"(",
"token",
")",
"if",
"user",
"is",
"None",
":",
"raise",
"AuthenticationFailed",
"(",
... | 31.846154 | 20.923077 |
def release(self, device_info):
"""This function is called by the segmentation state machine when it
has finished with the device information."""
if _debug: DeviceInfoCache._debug("release %r", device_info)
# this information record might be used by more than one SSM
if device_i... | [
"def",
"release",
"(",
"self",
",",
"device_info",
")",
":",
"if",
"_debug",
":",
"DeviceInfoCache",
".",
"_debug",
"(",
"\"release %r\"",
",",
"device_info",
")",
"# this information record might be used by more than one SSM",
"if",
"device_info",
".",
"_ref_count",
... | 41.545455 | 14.636364 |
def skip_regex(lines, options):
"""
Optionally exclude lines that match '--skip-requirements-regex'
"""
skip_regex = options.skip_requirements_regex if options else None
if skip_regex:
lines = filterfalse(re.compile(skip_regex).search, lines)
return lines | [
"def",
"skip_regex",
"(",
"lines",
",",
"options",
")",
":",
"skip_regex",
"=",
"options",
".",
"skip_requirements_regex",
"if",
"options",
"else",
"None",
"if",
"skip_regex",
":",
"lines",
"=",
"filterfalse",
"(",
"re",
".",
"compile",
"(",
"skip_regex",
")... | 35 | 17 |
def _infer_type(value, element_kind, element_name):
"""
Infer the CIM type name of the value, based upon its Python type.
"""
if value is None:
raise ValueError(
_format("Cannot infer CIM type of {0} {1!A} from its value when "
"the value is None", element_kind, ... | [
"def",
"_infer_type",
"(",
"value",
",",
"element_kind",
",",
"element_name",
")",
":",
"if",
"value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_format",
"(",
"\"Cannot infer CIM type of {0} {1!A} from its value when \"",
"\"the value is None\"",
",",
"element_ki... | 34.25 | 21.375 |
def prepare_sequencemanager(self) -> None:
"""Configure the |SequenceManager| object available in module
|pub| following the definitions of the actual XML `reader` or
`writer` element when available; if not use those of the XML
`series_io` element.
Compare the following results ... | [
"def",
"prepare_sequencemanager",
"(",
"self",
")",
"->",
"None",
":",
"for",
"config",
",",
"convert",
"in",
"(",
"(",
"'filetype'",
",",
"lambda",
"x",
":",
"x",
")",
",",
"(",
"'aggregation'",
",",
"lambda",
"x",
":",
"x",
")",
",",
"(",
"'overwri... | 41.246377 | 15.942029 |
def __get_substitution_paths(g):
"""
get atoms paths from detached atom to attached
:param g: CGRContainer
:return: tuple of atoms numbers
"""
for n, nbrdict in g.adjacency():
for m, l in combinations(nbrdict, 2):
nms = nbrdict[m]['sp_bond']
... | [
"def",
"__get_substitution_paths",
"(",
"g",
")",
":",
"for",
"n",
",",
"nbrdict",
"in",
"g",
".",
"adjacency",
"(",
")",
":",
"for",
"m",
",",
"l",
"in",
"combinations",
"(",
"nbrdict",
",",
"2",
")",
":",
"nms",
"=",
"nbrdict",
"[",
"m",
"]",
"... | 35.6 | 9.2 |
def launch_tor(config, reactor,
tor_binary=None,
progress_updates=None,
connection_creator=None,
timeout=None,
kill_on_stderr=True,
stdout=None, stderr=None):
"""
Deprecated; use launch() instead.
See also controller.... | [
"def",
"launch_tor",
"(",
"config",
",",
"reactor",
",",
"tor_binary",
"=",
"None",
",",
"progress_updates",
"=",
"None",
",",
"connection_creator",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"kill_on_stderr",
"=",
"True",
",",
"stdout",
"=",
"None",
"... | 31 | 12 |
def isomap(geom, n_components=8, eigen_solver='auto',
random_state=None, path_method='auto',
distance_matrix=None, graph_distance_matrix = None,
centered_matrix=None, solver_kwds=None):
"""
Parameters
----------
geom : a Geometry object from megaman.geometry.geometry
... | [
"def",
"isomap",
"(",
"geom",
",",
"n_components",
"=",
"8",
",",
"eigen_solver",
"=",
"'auto'",
",",
"random_state",
"=",
"None",
",",
"path_method",
"=",
"'auto'",
",",
"distance_matrix",
"=",
"None",
",",
"graph_distance_matrix",
"=",
"None",
",",
"center... | 48.180723 | 25.048193 |
def _create_parser() -> ArgumentParser:
"""
Creates argument parser for the CLI.
:return: the argument parser
"""
parser = ArgumentParser(prog=EXECUTABLE_NAME, description=f"{DESCRIPTION} (v{VERSION})")
parser.add_argument(
f"-{VERBOSE_SHORT_PARAMETER}", action="count", default=0,
... | [
"def",
"_create_parser",
"(",
")",
"->",
"ArgumentParser",
":",
"parser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"EXECUTABLE_NAME",
",",
"description",
"=",
"f\"{DESCRIPTION} (v{VERSION})\"",
")",
"parser",
".",
"add_argument",
"(",
"f\"-{VERBOSE_SHORT_PARAMETER}\"",
... | 62.928571 | 37.178571 |
def _first_glimpse_sensor(self, x_t):
"""
Compute first glimpse position using down-sampled image.
"""
downsampled_img = theano.tensor.signal.downsample.max_pool_2d(x_t, (4,4))
downsampled_img = downsampled_img.flatten()
first_l = T.dot(downsampled_img, self.W_f)
... | [
"def",
"_first_glimpse_sensor",
"(",
"self",
",",
"x_t",
")",
":",
"downsampled_img",
"=",
"theano",
".",
"tensor",
".",
"signal",
".",
"downsample",
".",
"max_pool_2d",
"(",
"x_t",
",",
"(",
"4",
",",
"4",
")",
")",
"downsampled_img",
"=",
"downsampled_im... | 45 | 16.294118 |
def multipart_listuploads(self, bucket):
"""List objects in a bucket.
:param bucket: A :class:`invenio_files_rest.models.Bucket` instance.
:returns: The Flask response.
"""
return self.make_response(
data=MultipartObject.query_by_bucket(bucket).limit(1000).all(),
... | [
"def",
"multipart_listuploads",
"(",
"self",
",",
"bucket",
")",
":",
"return",
"self",
".",
"make_response",
"(",
"data",
"=",
"MultipartObject",
".",
"query_by_bucket",
"(",
"bucket",
")",
".",
"limit",
"(",
"1000",
")",
".",
"all",
"(",
")",
",",
"con... | 32.5 | 15.428571 |
def text(self, encoding=None, errors='strict'):
r""" Open this file, read it in, return the content as a string.
This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r'
are automatically translated to '\n'.
Optional arguments:
encoding - The Unicode encoding (or charact... | [
"def",
"text",
"(",
"self",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"# 8-bit",
"f",
"=",
"self",
".",
"open",
"(",
"_textmode",
")",
"try",
":",
"return",
"f",
".",
"read",
"(",
... | 36.75 | 16.388889 |
def popdict(src, keys):
"""
Extract all keys (with values) from `src` dictionary as new dictionary
values are removed from source dictionary.
"""
new = {}
for key in keys:
if key in src:
new[key] = src.pop(key)
return new | [
"def",
"popdict",
"(",
"src",
",",
"keys",
")",
":",
"new",
"=",
"{",
"}",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"in",
"src",
":",
"new",
"[",
"key",
"]",
"=",
"src",
".",
"pop",
"(",
"key",
")",
"return",
"new"
] | 23.636364 | 17.636364 |
def string_to_list(string, sep=",", filter_empty=False):
"""Transforma una string con elementos separados por `sep` en una lista."""
return [value.strip() for value in string.split(sep)
if (not filter_empty or value)] | [
"def",
"string_to_list",
"(",
"string",
",",
"sep",
"=",
"\",\"",
",",
"filter_empty",
"=",
"False",
")",
":",
"return",
"[",
"value",
".",
"strip",
"(",
")",
"for",
"value",
"in",
"string",
".",
"split",
"(",
"sep",
")",
"if",
"(",
"not",
"filter_em... | 58.5 | 8.75 |
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'... | [
"def",
"list_services",
"(",
"kwargs",
"=",
"None",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_services function must be called with -f or --function.'",
")",
... | 24.346154 | 23.192308 |
def render_toolbar(context, config):
"""Render the toolbar for the given config."""
quill_config = getattr(quill_app, config)
t = template.loader.get_template(quill_config['toolbar_template'])
return t.render(context) | [
"def",
"render_toolbar",
"(",
"context",
",",
"config",
")",
":",
"quill_config",
"=",
"getattr",
"(",
"quill_app",
",",
"config",
")",
"t",
"=",
"template",
".",
"loader",
".",
"get_template",
"(",
"quill_config",
"[",
"'toolbar_template'",
"]",
")",
"retur... | 45.8 | 10.2 |
def gaussian(x, y, xsigma, ysigma):
"""
Two-dimensional oriented Gaussian pattern (i.e., 2D version of a
bell curve, like a normal distribution but not necessarily summing
to 1.0).
"""
if xsigma==0.0 or ysigma==0.0:
return x*0.0
with float_error_ignore():
x_w = np.divide(x,x... | [
"def",
"gaussian",
"(",
"x",
",",
"y",
",",
"xsigma",
",",
"ysigma",
")",
":",
"if",
"xsigma",
"==",
"0.0",
"or",
"ysigma",
"==",
"0.0",
":",
"return",
"x",
"*",
"0.0",
"with",
"float_error_ignore",
"(",
")",
":",
"x_w",
"=",
"np",
".",
"divide",
... | 30.692308 | 14.692308 |
def check_api_error(api_response):
print(api_response)
"""Check if returned API response contains an error."""
if type(api_response) == dict and 'code' in api_response and api_response['code'] <> 200:
print("Server response code: %s" % api_response['code'])
print("Server response: %s... | [
"def",
"check_api_error",
"(",
"api_response",
")",
":",
"print",
"(",
"api_response",
")",
"if",
"type",
"(",
"api_response",
")",
"==",
"dict",
"and",
"'code'",
"in",
"api_response",
"and",
"api_response",
"[",
"'code'",
"]",
"<>",
"200",
":",
"print",
"... | 58.875 | 22.25 |
def mass_2d(self, r, rho0, Rs):
"""
mass enclosed projected 2d sphere of radius r
:param r:
:param rho0:
:param a:
:param s:
:return:
"""
sigma0 = self.rho2sigma(rho0, Rs)
return self.mass_2d_lens(r, sigma0, Rs) | [
"def",
"mass_2d",
"(",
"self",
",",
"r",
",",
"rho0",
",",
"Rs",
")",
":",
"sigma0",
"=",
"self",
".",
"rho2sigma",
"(",
"rho0",
",",
"Rs",
")",
"return",
"self",
".",
"mass_2d_lens",
"(",
"r",
",",
"sigma0",
",",
"Rs",
")"
] | 23.416667 | 15.25 |
def _make_expand_x_fn_for_non_batch_interpolation(y_ref, axis):
"""Make func to expand left/right (of axis) dims of tensors shaped like x."""
# This expansion is to help x broadcast with `y`, the output.
# In the non-batch case, the output shape is going to be
# y_ref.shape[:axis] + x.shape + y_ref.shape[axis... | [
"def",
"_make_expand_x_fn_for_non_batch_interpolation",
"(",
"y_ref",
",",
"axis",
")",
":",
"# This expansion is to help x broadcast with `y`, the output.",
"# In the non-batch case, the output shape is going to be",
"# y_ref.shape[:axis] + x.shape + y_ref.shape[axis+1:]",
"# Recall we made... | 35.942857 | 16.714286 |
def find_executable(executable):
'''
Finds executable in PATH
Returns:
string or None
'''
logger = logging.getLogger(__name__)
logger.debug("Checking executable '%s'...", executable)
executable_path = _find_executable(executable)
found = executable_path is not None
if found:... | [
"def",
"find_executable",
"(",
"executable",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"Checking executable '%s'...\"",
",",
"executable",
")",
"executable_path",
"=",
"_find_executable",
"(",
"execu... | 30.3125 | 20.9375 |
def _get_render_prepared_object(cls, context, **option_values):
"""
Returns a fully prepared, request-aware menu object that can be used
for rendering. ``context`` could be a ``django.template.Context``
object passed to ``render_from_tag()`` by a menu tag.
"""
ctx_vals = ... | [
"def",
"_get_render_prepared_object",
"(",
"cls",
",",
"context",
",",
"*",
"*",
"option_values",
")",
":",
"ctx_vals",
"=",
"cls",
".",
"_create_contextualvals_obj_from_context",
"(",
"context",
")",
"opt_vals",
"=",
"cls",
".",
"_create_optionvals_obj_from_values",
... | 43.611111 | 24.277778 |
def sort(self):
"""Sort by detection time.
.. rubric:: Example
>>> family = Family(
... template=Template(name='a'), detections=[
... Detection(template_name='a', detect_time=UTCDateTime(0) + 200,
... no_chans=8, detect_val=4.2, threshold=1.2,
... | [
"def",
"sort",
"(",
"self",
")",
":",
"self",
".",
"detections",
"=",
"sorted",
"(",
"self",
".",
"detections",
",",
"key",
"=",
"lambda",
"d",
":",
"d",
".",
"detect_time",
")",
"return",
"self"
] | 45.692308 | 19.423077 |
def validate_ok_for_update(update):
"""Validate an update document."""
validate_is_mapping("update", update)
# Update can not be {}
if not update:
raise ValueError('update only works with $ operators')
first = next(iter(update))
if not first.startswith('$'):
raise ValueError('upd... | [
"def",
"validate_ok_for_update",
"(",
"update",
")",
":",
"validate_is_mapping",
"(",
"\"update\"",
",",
"update",
")",
"# Update can not be {}",
"if",
"not",
"update",
":",
"raise",
"ValueError",
"(",
"'update only works with $ operators'",
")",
"first",
"=",
"next",... | 38.333333 | 11.444444 |
def register_user_type(self, keyspace, user_type, klass):
"""
Registers a class to use to represent a particular user-defined type.
Query parameters for this user-defined type will be assumed to be
instances of `klass`. Result sets for this user-defined type will
be instances of... | [
"def",
"register_user_type",
"(",
"self",
",",
"keyspace",
",",
"user_type",
",",
"klass",
")",
":",
"if",
"self",
".",
"protocol_version",
"<",
"3",
":",
"log",
".",
"warning",
"(",
"\"User Type serialization is only supported in native protocol version 3+ (%d in use).... | 44.912281 | 27.263158 |
def Tags(self):
"""Return all tags found in the value stream.
Returns:
A `{tagType: ['list', 'of', 'tags']}` dictionary.
"""
return {
IMAGES: self.images.Keys(),
AUDIO: self.audios.Keys(),
HISTOGRAMS: self.histograms.Keys(),
SCALARS: self.scalars.Keys(),
CO... | [
"def",
"Tags",
"(",
"self",
")",
":",
"return",
"{",
"IMAGES",
":",
"self",
".",
"images",
".",
"Keys",
"(",
")",
",",
"AUDIO",
":",
"self",
".",
"audios",
".",
"Keys",
"(",
")",
",",
"HISTOGRAMS",
":",
"self",
".",
"histograms",
".",
"Keys",
"("... | 35.947368 | 15.526316 |
def daytime(date: datetime.date,
daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H),
nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \
-> "Interval":
"""
Returns an :class:`Interval` representing daytime on the date given.
"""
... | [
"def",
"daytime",
"(",
"date",
":",
"datetime",
".",
"date",
",",
"daybreak",
":",
"datetime",
".",
"time",
"=",
"datetime",
".",
"time",
"(",
"NORMAL_DAY_START_H",
")",
",",
"nightfall",
":",
"datetime",
".",
"time",
"=",
"datetime",
".",
"time",
"(",
... | 41 | 18.818182 |
def load_data(self):
"""
Loads data files and stores the output in the data attribute.
"""
data = []
valid_dates = []
mrms_files = np.array(sorted(os.listdir(self.path + self.variable + "/")))
mrms_file_dates = np.array([m_file.split("_")[-2].split("-")[0]
... | [
"def",
"load_data",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"valid_dates",
"=",
"[",
"]",
"mrms_files",
"=",
"np",
".",
"array",
"(",
"sorted",
"(",
"os",
".",
"listdir",
"(",
"self",
".",
"path",
"+",
"self",
".",
"variable",
"+",
"\"/\"",
... | 47.102564 | 17.820513 |
def once(ctx, name):
"""Run kibitzr checks once and exit"""
from kibitzr.app import Application
app = Application()
sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) | [
"def",
"once",
"(",
"ctx",
",",
"name",
")",
":",
"from",
"kibitzr",
".",
"app",
"import",
"Application",
"app",
"=",
"Application",
"(",
")",
"sys",
".",
"exit",
"(",
"app",
".",
"run",
"(",
"once",
"=",
"True",
",",
"log_level",
"=",
"ctx",
".",
... | 40 | 14.8 |
def stop_notifying(cls, user_or_email, instance):
"""Delete the watch created by notify."""
super(InstanceEvent, cls).stop_notifying(user_or_email,
object_id=instance.pk) | [
"def",
"stop_notifying",
"(",
"cls",
",",
"user_or_email",
",",
"instance",
")",
":",
"super",
"(",
"InstanceEvent",
",",
"cls",
")",
".",
"stop_notifying",
"(",
"user_or_email",
",",
"object_id",
"=",
"instance",
".",
"pk",
")"
] | 58 | 15.75 |
def restore_from_checkpoint(sess, input_checkpoint):
"""Return a TensorFlow saver from a checkpoint containing the metagraph."""
saver = tf.train.import_meta_graph('{}.meta'.format(input_checkpoint))
saver.restore(sess, input_checkpoint)
return saver | [
"def",
"restore_from_checkpoint",
"(",
"sess",
",",
"input_checkpoint",
")",
":",
"saver",
"=",
"tf",
".",
"train",
".",
"import_meta_graph",
"(",
"'{}.meta'",
".",
"format",
"(",
"input_checkpoint",
")",
")",
"saver",
".",
"restore",
"(",
"sess",
",",
"inpu... | 52.4 | 14.2 |
def remnant_mass_ulim(eta, ns_g_mass, bh_spin_z, ns_sequence, max_ns_g_mass, shift):
"""
Function that determines the maximum remnant disk mass
for an NS-BH system with given symmetric mass ratio,
NS mass, and BH spin parameter component along the
orbital angular momentum. This is a wrapper to
... | [
"def",
"remnant_mass_ulim",
"(",
"eta",
",",
"ns_g_mass",
",",
"bh_spin_z",
",",
"ns_sequence",
",",
"max_ns_g_mass",
",",
"shift",
")",
":",
"# Sanity checks",
"if",
"not",
"(",
"eta",
">",
"0.",
"and",
"eta",
"<=",
"0.25",
"and",
"abs",
"(",
"bh_spin_z",... | 43.54902 | 20 |
def XYZ_to_galcencyl(X,Y,Z,Xsun=1.,Zsun=0.,_extra_rot=True):
"""
NAME:
XYZ_to_galcencyl
PURPOSE:
transform XYZ coordinates (wrt Sun) to cylindrical Galactocentric coordinates
INPUT:
X - X
Y - Y
Z - Z
Xsun - cylindrical distance to the GC
Z... | [
"def",
"XYZ_to_galcencyl",
"(",
"X",
",",
"Y",
",",
"Z",
",",
"Xsun",
"=",
"1.",
",",
"Zsun",
"=",
"0.",
",",
"_extra_rot",
"=",
"True",
")",
":",
"XYZ",
"=",
"nu",
".",
"atleast_2d",
"(",
"XYZ_to_galcenrect",
"(",
"X",
",",
"Y",
",",
"Z",
",",
... | 20.833333 | 30.777778 |
def parse_input(s):
"""Parse the given input and intelligently transform it into an absolute,
non-naive, timezone-aware datetime object for the UTC timezone.
The input can be specified as a millisecond-precision UTC timestamp (or
delta against Epoch), with or without a terminating 'L'. Alternatively, t... | [
"def",
"parse_input",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"integer_types",
")",
":",
"s",
"=",
"str",
"(",
"s",
")",
"elif",
"not",
"isinstance",
"(",
"s",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueErr... | 33.463415 | 21.829268 |
def exec_commands(commands: str, **parameters: Any) -> None:
"""Execute the given Python commands.
Function |exec_commands| is thought for testing purposes only (see
the main documentation on module |hyd|). Seperate individual commands
by semicolons and replaced whitespaces with underscores:
>>> ... | [
"def",
"exec_commands",
"(",
"commands",
":",
"str",
",",
"*",
"*",
"parameters",
":",
"Any",
")",
"->",
"None",
":",
"cmdlist",
"=",
"commands",
".",
"split",
"(",
"';'",
")",
"print",
"(",
"f'Start to execute the commands {cmdlist} for testing purposes.'",
")"... | 37.916667 | 22.416667 |
def enable_enhanced_monitoring(stream_name, metrics,
region=None, key=None, keyid=None, profile=None):
'''
Enable enhanced monitoring for the specified shard-level metrics on stream stream_name
CLI example::
salt myminion boto_kinesis.enable_enhanced_monitoring my_st... | [
"def",
"enable_enhanced_monitoring",
"(",
"stream_name",
",",
"metrics",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
... | 39.333333 | 29.555556 |
def SetGaugeCallback(self, metric_name, callback, fields=None):
"""See base class."""
self._gauge_metrics[metric_name].SetCallback(callback, fields) | [
"def",
"SetGaugeCallback",
"(",
"self",
",",
"metric_name",
",",
"callback",
",",
"fields",
"=",
"None",
")",
":",
"self",
".",
"_gauge_metrics",
"[",
"metric_name",
"]",
".",
"SetCallback",
"(",
"callback",
",",
"fields",
")"
] | 51.333333 | 16.333333 |
def to_delete(datetimes,
years=0, months=0, weeks=0, days=0,
hours=0, minutes=0, seconds=0,
firstweekday=SATURDAY, now=None):
"""
Return a set of datetimes that should be deleted, out of ``datetimes``.
See ``to_keep`` for a description of arguments.
"""
dat... | [
"def",
"to_delete",
"(",
"datetimes",
",",
"years",
"=",
"0",
",",
"months",
"=",
"0",
",",
"weeks",
"=",
"0",
",",
"days",
"=",
"0",
",",
"hours",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"seconds",
"=",
"0",
",",
"firstweekday",
"=",
"SATURDAY"... | 42 | 15.2 |
def update(self, friendly_name=values.unset, attributes=values.unset,
date_created=values.unset, date_updated=values.unset,
created_by=values.unset):
"""
Update the SessionInstance
:param unicode friendly_name: The human-readable name of this session.
:para... | [
"def",
"update",
"(",
"self",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"attributes",
"=",
"values",
".",
"unset",
",",
"date_created",
"=",
"values",
".",
"unset",
",",
"date_updated",
"=",
"values",
".",
"unset",
",",
"created_by",
"=",
"... | 44.590909 | 19.863636 |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(IPVSCollector, self).get_default_config()
config.update({
'bin': '/usr/sbin/ipvsadm',
'use_sudo': True,
'sudo_cmd': '/usr/b... | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"IPVSCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'bin'",
":",
"'/usr/sbin/ipvsadm'",
",",
"'use_sudo'",
":",
"True",
... | 32.5 | 11 |
def description_of(file, name='stdin'):
"""Return a string describing the probable encoding of a file."""
u = UniversalDetector()
for line in file:
u.feed(line)
u.close()
result = u.result
if result['encoding']:
return '%s: %s with confidence %s' % (name,
... | [
"def",
"description_of",
"(",
"file",
",",
"name",
"=",
"'stdin'",
")",
":",
"u",
"=",
"UniversalDetector",
"(",
")",
"for",
"line",
"in",
"file",
":",
"u",
".",
"feed",
"(",
"line",
")",
"u",
".",
"close",
"(",
")",
"result",
"=",
"u",
".",
"res... | 35.769231 | 16.153846 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.