text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def parse_filespec(fspec, sep=':', gpat='*'):
"""
Parse given filespec `fspec` and return [(filetype, filepath)].
Because anyconfig.load should find correct file's type to load by the file
extension, this function will not try guessing file's type if not file type
is specified explicitly.
:par... | [
"def",
"parse_filespec",
"(",
"fspec",
",",
"sep",
"=",
"':'",
",",
"gpat",
"=",
"'*'",
")",
":",
"if",
"sep",
"in",
"fspec",
":",
"tpl",
"=",
"(",
"ftype",
",",
"fpath",
")",
"=",
"tuple",
"(",
"fspec",
".",
"split",
"(",
"sep",
")",
")",
"els... | 34.375 | 17.8125 |
def _round(self):
"""
This is the environment implementation of
:meth:`BaseAnchor.round`.
Subclasses may override this method.
"""
self.x = normalizers.normalizeRounding(self.x)
self.y = normalizers.normalizeRounding(self.y) | [
"def",
"_round",
"(",
"self",
")",
":",
"self",
".",
"x",
"=",
"normalizers",
".",
"normalizeRounding",
"(",
"self",
".",
"x",
")",
"self",
".",
"y",
"=",
"normalizers",
".",
"normalizeRounding",
"(",
"self",
".",
"y",
")"
] | 30.333333 | 12.333333 |
def stop_capture(self, adapter_number):
"""
Stops a packet capture.
:param adapter_number: adapter number
"""
try:
adapter = self._ethernet_adapters[adapter_number]
except KeyError:
raise DockerError("Adapter {adapter_number} doesn't exist on Doc... | [
"def",
"stop_capture",
"(",
"self",
",",
"adapter_number",
")",
":",
"try",
":",
"adapter",
"=",
"self",
".",
"_ethernet_adapters",
"[",
"adapter_number",
"]",
"except",
"KeyError",
":",
"raise",
"DockerError",
"(",
"\"Adapter {adapter_number} doesn't exist on Docker ... | 43.653846 | 34.5 |
def choose_best_mask(self):
"""This method returns the index of the "best" mask as defined by
having the lowest total penalty score. The penalty rules are defined
by the standard. The mask with the lowest total score should be the
easiest to read by optical scanners.
"""
... | [
"def",
"choose_best_mask",
"(",
"self",
")",
":",
"self",
".",
"scores",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"masks",
")",
")",
":",
"self",
".",
"scores",
".",
"append",
"(",
"[",
"0",
",",
"0",
",",
"0",
... | 36.028986 | 13.376812 |
def add_checkpoint_file(self,filename):
"""
Add filename as a checkpoint file for this DAG node
@param filename: checkpoint filename to add
"""
if filename not in self.__checkpoint_files:
self.__checkpoint_files.append(filename)
if not isinstance(self.job(), CondorDAGManJob):
... | [
"def",
"add_checkpoint_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"not",
"in",
"self",
".",
"__checkpoint_files",
":",
"self",
".",
"__checkpoint_files",
".",
"append",
"(",
"filename",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
... | 40.7 | 7.5 |
def disconnect(self, *args, **kwargs):
"""
WebSocket was disconnected - leave the IRC channel.
"""
quit_message = "%s %s" % (settings.GNOTTY_VERSION_STRING,
settings.GNOTTY_PROJECT_URL)
self.client.connection.quit(quit_message)
super(IRCN... | [
"def",
"disconnect",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"quit_message",
"=",
"\"%s %s\"",
"%",
"(",
"settings",
".",
"GNOTTY_VERSION_STRING",
",",
"settings",
".",
"GNOTTY_PROJECT_URL",
")",
"self",
".",
"client",
".",
"conne... | 44.5 | 12.25 |
def _schedule_next_run(self):
"""
Compute the instant when this job should run next.
"""
if self.unit not in ('seconds', 'minutes', 'hours', 'days', 'weeks'):
raise ScheduleValueError('Invalid unit')
if self.latest is not None:
if not (self.latest >= self... | [
"def",
"_schedule_next_run",
"(",
"self",
")",
":",
"if",
"self",
".",
"unit",
"not",
"in",
"(",
"'seconds'",
",",
"'minutes'",
",",
"'hours'",
",",
"'days'",
",",
"'weeks'",
")",
":",
"raise",
"ScheduleValueError",
"(",
"'Invalid unit'",
")",
"if",
"self"... | 47.565217 | 18.463768 |
def gpg_profile_put_key( blockchain_id, key_id, key_name=None, immutable=True, txid=None, key_url=None, use_key_server=True, key_server=None, proxy=None, wallet_keys=None, gpghome=None ):
"""
Put a local GPG key into a blockchain ID's global account.
If the URL is not given, the key will be replicated to th... | [
"def",
"gpg_profile_put_key",
"(",
"blockchain_id",
",",
"key_id",
",",
"key_name",
"=",
"None",
",",
"immutable",
"=",
"True",
",",
"txid",
"=",
"None",
",",
"key_url",
"=",
"None",
",",
"use_key_server",
"=",
"True",
",",
"key_server",
"=",
"None",
",",
... | 41.222222 | 29.944444 |
def save(self):
""" Easy save(insert or update) for db models """
try:
if self.exists() is False:
self.db.session.add(self)
# self.db.session.merge(self)
self.db.session.commit()
except (Exception, BaseException) as error:
i... | [
"def",
"save",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"exists",
"(",
")",
"is",
"False",
":",
"self",
".",
"db",
".",
"session",
".",
"add",
"(",
"self",
")",
"# self.db.session.merge(self)\r",
"self",
".",
"db",
".",
"session",
".",
... | 35.818182 | 9.454545 |
def doNew(self, WHAT={}, **params):
"""This function will perform the command -new."""
if hasattr(WHAT, '_modified'):
for key in WHAT:
if key not in ['RECORDID','MODID']:
if WHAT.__new2old__.has_key(key):
self._addDBParam(WHAT.__new2old__[key].encode('utf-8'), WHAT[key])
else:
self._ad... | [
"def",
"doNew",
"(",
"self",
",",
"WHAT",
"=",
"{",
"}",
",",
"*",
"*",
"params",
")",
":",
"if",
"hasattr",
"(",
"WHAT",
",",
"'_modified'",
")",
":",
"for",
"key",
"in",
"WHAT",
":",
"if",
"key",
"not",
"in",
"[",
"'RECORDID'",
",",
"'MODID'",
... | 29.461538 | 19.923077 |
def enable_counter(self, base=None, database='counter',
collection='counters'):
"""Register the builtin counter model, return the registered Counter
class and the corresponding ``CounterMixin`` class.
The ``CounterMixin`` automatically increases and decreases the counter
... | [
"def",
"enable_counter",
"(",
"self",
",",
"base",
"=",
"None",
",",
"database",
"=",
"'counter'",
",",
"collection",
"=",
"'counters'",
")",
":",
"Counter",
".",
"_database_",
"=",
"database",
"Counter",
".",
"_collection_",
"=",
"collection",
"bases",
"=",... | 40.584906 | 17.849057 |
def check_shape(meth):
"""
Decorator for larray magic methods, to ensure that the operand has
the same shape as the array.
"""
@wraps(meth)
def wrapped_meth(self, val):
if isinstance(val, (larray, numpy.ndarray)):
if val.shape != self._shape:
raise ValueError(... | [
"def",
"check_shape",
"(",
"meth",
")",
":",
"@",
"wraps",
"(",
"meth",
")",
"def",
"wrapped_meth",
"(",
"self",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"(",
"larray",
",",
"numpy",
".",
"ndarray",
")",
")",
":",
"if",
"val",
"... | 35.666667 | 15.333333 |
def check_docstring_first(src, filename='<unknown>'):
# type: (bytes, str) -> int
"""Returns nonzero if the source has what looks like a docstring that is
not at the beginning of the source.
A string will be considered a docstring if it is a STRING token with a
col offset of 0.
"""
found_do... | [
"def",
"check_docstring_first",
"(",
"src",
",",
"filename",
"=",
"'<unknown>'",
")",
":",
"# type: (bytes, str) -> int",
"found_docstring_line",
"=",
"None",
"found_code_line",
"=",
"None",
"tok_gen",
"=",
"tokenize_tokenize",
"(",
"io",
".",
"BytesIO",
"(",
"src",... | 36.378378 | 17.162162 |
def initiate(self, transport, to = None):
"""Initiate an XMPP connection over the `transport`.
:Parameters:
- `transport`: an XMPP transport instance
- `to`: peer name (defaults to own jid domain part)
"""
if to is None:
to = JID(self.me.domain)
... | [
"def",
"initiate",
"(",
"self",
",",
"transport",
",",
"to",
"=",
"None",
")",
":",
"if",
"to",
"is",
"None",
":",
"to",
"=",
"JID",
"(",
"self",
".",
"me",
".",
"domain",
")",
"return",
"StreamBase",
".",
"initiate",
"(",
"self",
",",
"transport",... | 36.1 | 13.4 |
def tokenize(self, data):
'''
Tokenize sentence.
Args:
[n-gram, n-gram, n-gram, ...]
'''
super().tokenize(data)
token_tuple_zip = self.n_gram.generate_tuple_zip(self.token, self.n)
token_list = []
self.token = ["".join(list(token_tuple)) for ... | [
"def",
"tokenize",
"(",
"self",
",",
"data",
")",
":",
"super",
"(",
")",
".",
"tokenize",
"(",
"data",
")",
"token_tuple_zip",
"=",
"self",
".",
"n_gram",
".",
"generate_tuple_zip",
"(",
"self",
".",
"token",
",",
"self",
".",
"n",
")",
"token_list",
... | 28.333333 | 25.166667 |
def network_get_primary_address(binding):
'''
Deprecated since Juju 2.3; use network_get()
Retrieve the primary network address for a named binding
:param binding: string. The name of a relation of extra-binding
:return: string. The primary IP address for the named binding
:raise: NotImplement... | [
"def",
"network_get_primary_address",
"(",
"binding",
")",
":",
"cmd",
"=",
"[",
"'network-get'",
",",
"'--primary-address'",
",",
"binding",
"]",
"try",
":",
"response",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"subprocess",
"."... | 36.590909 | 21.863636 |
def equal(self, what, epsilon=None):
"""compares given object ``X`` with an expected ``Y`` object.
It primarily assures that the compared objects are absolute equal ``==``.
:param what: the expected value
:param epsilon: a delta to leverage upper-bound floating point permissiveness
... | [
"def",
"equal",
"(",
"self",
",",
"what",
",",
"epsilon",
"=",
"None",
")",
":",
"try",
":",
"comparison",
"=",
"DeepComparison",
"(",
"self",
".",
"obj",
",",
"what",
",",
"epsilon",
")",
".",
"compare",
"(",
")",
"error",
"=",
"False",
"except",
... | 31.166667 | 23.266667 |
def export_handle(self, directory):
"""Get a filehandle for exporting"""
filename = getattr(self, 'filename')
dest_file = "%s/%s" % (directory, filename)
dest_dir = os.path.dirname(dest_file)
if not os.path.isdir(dest_dir):
os.mkdir(dest_dir, 0o700)
return op... | [
"def",
"export_handle",
"(",
"self",
",",
"directory",
")",
":",
"filename",
"=",
"getattr",
"(",
"self",
",",
"'filename'",
")",
"dest_file",
"=",
"\"%s/%s\"",
"%",
"(",
"directory",
",",
"filename",
")",
"dest_dir",
"=",
"os",
".",
"path",
".",
"dirnam... | 36.666667 | 8.222222 |
def encodefuns():
"""Returns a dictionary mapping ICC type signature sig to encoding
function. Each function returns a string comprising the content of
the encoded value. To form the full value, the type sig and the 4
zero bytes should be prefixed (8 bytes).
"""
def desc(ascii):
"""Re... | [
"def",
"encodefuns",
"(",
")",
":",
"def",
"desc",
"(",
"ascii",
")",
":",
"\"\"\"Return textDescription type [ICC 2001] 6.5.17. The ASCII part is\n filled in with the string `ascii`, the Unicode and ScriptCode parts\n are empty.\"\"\"",
"ascii",
"+=",
"'\\x00'",
"n",
... | 33.038462 | 19.807692 |
def _scene(self):
"""
A cached version of the pyembree scene.
"""
return _EmbreeWrap(vertices=self.mesh.vertices,
faces=self.mesh.faces,
scale=self._scale) | [
"def",
"_scene",
"(",
"self",
")",
":",
"return",
"_EmbreeWrap",
"(",
"vertices",
"=",
"self",
".",
"mesh",
".",
"vertices",
",",
"faces",
"=",
"self",
".",
"mesh",
".",
"faces",
",",
"scale",
"=",
"self",
".",
"_scale",
")"
] | 33.571429 | 8.428571 |
def find_peaks(sig):
"""
Find hard peaks and soft peaks in a signal, defined as follows:
- Hard peak: a peak that is either /\ or \/
- Soft peak: a peak that is either /-*\ or \-*/
In this case we define the middle as the peak
Parameters
----------
sig : np array
The 1d signa... | [
"def",
"find_peaks",
"(",
"sig",
")",
":",
"if",
"len",
"(",
"sig",
")",
"==",
"0",
":",
"return",
"np",
".",
"empty",
"(",
"[",
"0",
"]",
")",
",",
"np",
".",
"empty",
"(",
"[",
"0",
"]",
")",
"tmp",
"=",
"sig",
"[",
"1",
":",
"]",
"tmp"... | 25.94 | 20.5 |
def filter_for_filesize(result, size=None):
"""
Will test the filepath result and test if its size is at least self.filesize
:param result: a list of dicts returned by Snakebite ls
:param size: the file size in MB a file should be at least to trigger True
:return: (bool) dependi... | [
"def",
"filter_for_filesize",
"(",
"result",
",",
"size",
"=",
"None",
")",
":",
"if",
"size",
":",
"log",
"=",
"LoggingMixin",
"(",
")",
".",
"log",
"log",
".",
"debug",
"(",
"'Filtering for file size >= %s in files: %s'",
",",
"size",
",",
"map",
"(",
"l... | 41.944444 | 20.166667 |
def create_thing(self, lid):
"""Create a new Thing with a local id (lid).
Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object if successful
or if the Thing already exists
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing... | [
"def",
"create_thing",
"(",
"self",
",",
"lid",
")",
":",
"evt",
"=",
"self",
".",
"create_thing_async",
"(",
"lid",
")",
"self",
".",
"_wait_and_except_if_failed",
"(",
"evt",
")",
"try",
":",
"with",
"self",
".",
"__new_things",
":",
"return",
"self",
... | 49.409091 | 29.909091 |
def wait_for_tasks_to_complete(batch_service_client, job_ids, timeout):
"""Returns when all tasks in the specified job reach the Completed state.
:param batch_service_client: A Batch service client.
:type batch_service_client: `azure.batch.BatchServiceClient`
:param str job_id: The id of the job whose ... | [
"def",
"wait_for_tasks_to_complete",
"(",
"batch_service_client",
",",
"job_ids",
",",
"timeout",
")",
":",
"timeout_expiration",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"+",
"timeout",
"print",
"(",
"\"Monitoring all tasks for 'Completed' state, timeout... | 44.794118 | 22.794118 |
def toArray(self):
"""
Returns a copy of this SparseVector as a 1-dimensional NumPy array.
"""
arr = np.zeros((self.size,), dtype=np.float64)
arr[self.indices] = self.values
return arr | [
"def",
"toArray",
"(",
"self",
")",
":",
"arr",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"size",
",",
")",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"arr",
"[",
"self",
".",
"indices",
"]",
"=",
"self",
".",
"values",
"return",
"arr"... | 32.285714 | 13.428571 |
def deferred_emails():
"""Checks for deferred email, that otherwise fill up the queue."""
status = SERVER_STATUS['OK']
count = Message.objects.deferred().count()
if DEFERRED_WARNING_THRESHOLD <= count < DEFERRED_DANGER_THRESHOLD:
status = SERVER_STATUS['WARNING']
if count >= DEFERRED_DANGER... | [
"def",
"deferred_emails",
"(",
")",
":",
"status",
"=",
"SERVER_STATUS",
"[",
"'OK'",
"]",
"count",
"=",
"Message",
".",
"objects",
".",
"deferred",
"(",
")",
".",
"count",
"(",
")",
"if",
"DEFERRED_WARNING_THRESHOLD",
"<=",
"count",
"<",
"DEFERRED_DANGER_TH... | 34.266667 | 17.6 |
def addcomponent(self, data):
"""
A method to create a component in Bugzilla. Takes a dict, with the
following elements:
product: The product to create the component in
component: The name of the component to create
description: A one sentence summary of the component
... | [
"def",
"addcomponent",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"self",
".",
"_component_data_convert",
"(",
"data",
")",
"return",
"self",
".",
"_proxy",
".",
"Component",
".",
"create",
"(",
"data",
")"
] | 47.45 | 18.15 |
def model_instance_diff(old, new):
"""
Calculates the differences between two model instances. One of the instances may be ``None`` (i.e., a newly
created model or deleted model). This will cause all fields with a value to have changed (from ``None``).
:param old: The old state of the model instance.
... | [
"def",
"model_instance_diff",
"(",
"old",
",",
"new",
")",
":",
"from",
"auditlog",
".",
"registry",
"import",
"auditlog",
"if",
"not",
"(",
"old",
"is",
"None",
"or",
"isinstance",
"(",
"old",
",",
"Model",
")",
")",
":",
"raise",
"TypeError",
"(",
"\... | 38.728814 | 23.779661 |
def unique(seq, key=None, return_as=None):
"""Unique the seq and keep the order.
Instead of the slow way:
`lambda seq: (x for index, x in enumerate(seq) if seq.index(x)==index)`
:param seq: raw sequence.
:param return_as: generator for default, or list / set / str...
>>> from torequests.u... | [
"def",
"unique",
"(",
"seq",
",",
"key",
"=",
"None",
",",
"return_as",
"=",
"None",
")",
":",
"seen",
"=",
"set",
"(",
")",
"add",
"=",
"seen",
".",
"add",
"if",
"key",
":",
"generator",
"=",
"(",
"x",
"for",
"x",
"in",
"seq",
"if",
"key",
"... | 29.0625 | 20.3125 |
def add_scope(self, scope_type, scope_name, scope_start, is_method=False):
"""we identified a scope and add it to positions."""
if self._curr is not None:
self._curr['end'] = scope_start - 1 # close last scope
self._curr = {
'type': scope_type, 'name': scope_name,
... | [
"def",
"add_scope",
"(",
"self",
",",
"scope_type",
",",
"scope_name",
",",
"scope_start",
",",
"is_method",
"=",
"False",
")",
":",
"if",
"self",
".",
"_curr",
"is",
"not",
"None",
":",
"self",
".",
"_curr",
"[",
"'end'",
"]",
"=",
"scope_start",
"-",... | 39.125 | 14.25 |
def extract_header_comment_key_value_tuples_from_file(file_descriptor):
""" Extracts tuples representing comments and localization entries from strings file.
Args:
file_descriptor (file): The file to read the tuples from
Returns:
list : List of tuples representing the headers and localizat... | [
"def",
"extract_header_comment_key_value_tuples_from_file",
"(",
"file_descriptor",
")",
":",
"file_data",
"=",
"file_descriptor",
".",
"read",
"(",
")",
"findall_result",
"=",
"re",
".",
"findall",
"(",
"HEADER_COMMENT_KEY_VALUE_TUPLES_REGEX",
",",
"file_data",
",",
"r... | 37.428571 | 26.857143 |
def dostilt(s, bed_az, bed_dip):
"""
Rotates "s" tensor to stratigraphic coordinates
Parameters
__________
s : [x11,x22,x33,x12,x23,x13] - the six tensor elements
bed_az : bedding dip direction
bed_dip : bedding dip
Return
s_rot : [x11,x22,x33,x12,x23,x13] - after rotation
""... | [
"def",
"dostilt",
"(",
"s",
",",
"bed_az",
",",
"bed_dip",
")",
":",
"tau",
",",
"Vdirs",
"=",
"doseigs",
"(",
"s",
")",
"Vrot",
"=",
"[",
"]",
"for",
"evec",
"in",
"Vdirs",
":",
"d",
",",
"i",
"=",
"dotilt",
"(",
"evec",
"[",
"0",
"]",
",",
... | 23.809524 | 18.761905 |
def get_queries_batch(self, query_get_request, project):
"""GetQueriesBatch.
[Preview API] Gets a list of queries by ids (Maximum 1000)
:param :class:`<QueryBatchGetRequest> <azure.devops.v5_1.work_item_tracking.models.QueryBatchGetRequest>` query_get_request:
:param str project: Project... | [
"def",
"get_queries_batch",
"(",
"self",
",",
"query_get_request",
",",
"project",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
... | 57.647059 | 23.411765 |
def main(args=sys.argv):
"""
Main command-line invocation.
"""
try:
opts, args = getopt.gnu_getopt(args[1:], 'p:o:jdt', [
'jspath=', 'output=', 'private', 'json', 'dependencies',
'test', 'help'])
opts = dict(opts)
except getopt.GetoptError:
usage()
... | [
"def",
"main",
"(",
"args",
"=",
"sys",
".",
"argv",
")",
":",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"gnu_getopt",
"(",
"args",
"[",
"1",
":",
"]",
",",
"'p:o:jdt'",
",",
"[",
"'jspath='",
",",
"'output='",
",",
"'private'",
",",
"... | 30.277778 | 17.555556 |
def main():
"""
NAME
replace_AC_specimens.py
DESCRIPTION
finds anisotropy corrected data and
replaces that specimen with it.
puts in pmag_specimen format file
SYNTAX
replace_AC_specimens.py [command line options]
OPTIONS
-h prints help mes... | [
"def",
"main",
"(",
")",
":",
"dir_path",
"=",
"'.'",
"tspec",
"=",
"\"thellier_specimens.txt\"",
"aspec",
"=",
"\"AC_specimens.txt\"",
"ofile",
"=",
"\"TorAC_specimens.txt\"",
"critfile",
"=",
"\"pmag_criteria.txt\"",
"ACSamplist",
",",
"Samplist",
",",
"sigmin",
"... | 35.32967 | 16.384615 |
def process_line(
line, # type: Text
filename, # type: str
line_number, # type: int
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
wheel_cache=None, # t... | [
"def",
"process_line",
"(",
"line",
",",
"# type: Text",
"filename",
",",
"# type: str",
"line_number",
",",
"# type: int",
"finder",
"=",
"None",
",",
"# type: Optional[PackageFinder]",
"comes_from",
"=",
"None",
",",
"# type: Optional[str]",
"options",
"=",
"None",
... | 40.456 | 16.744 |
def dehtml(text):
'''Remove HTML tag in input text and format the texts
accordingly. '''
# added by BoPeng to handle html output from kernel
#
# Do not understand why, but I cannot define the class outside of the
# function.
try:
# python 2
from HTMLParser import HTMLParser
... | [
"def",
"dehtml",
"(",
"text",
")",
":",
"# added by BoPeng to handle html output from kernel",
"#",
"# Do not understand why, but I cannot define the class outside of the",
"# function.",
"try",
":",
"# python 2",
"from",
"HTMLParser",
"import",
"HTMLParser",
"except",
"ImportErr... | 30.62069 | 16.448276 |
def _load(self, config):
""" Load this config from an existing config
Parameters:
-----------
config : filename, config object, or dict to load
Returns:
--------
params : configuration parameters
"""
if isstring(config):
self.filenam... | [
"def",
"_load",
"(",
"self",
",",
"config",
")",
":",
"if",
"isstring",
"(",
"config",
")",
":",
"self",
".",
"filename",
"=",
"config",
"params",
"=",
"yaml",
".",
"load",
"(",
"open",
"(",
"config",
")",
")",
"elif",
"isinstance",
"(",
"config",
... | 28.692308 | 14 |
def header_length(header):
"""Calculates the ciphertext message header length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:rtype: int
"""
# Because encrypted data key lengths may not be knowable until the ciph... | [
"def",
"header_length",
"(",
"header",
")",
":",
"# Because encrypted data key lengths may not be knowable until the ciphertext",
"# is received from the providers, just serialize the header directly.",
"header_length",
"=",
"len",
"(",
"serialize_header",
"(",
"header",
")",
")",
... | 47.153846 | 21.230769 |
def validate_metadata_token(self, claims, endpoint):
"""
If the token endpoint is used in the grant type, the value of this
parameter MUST be the same as the value of the "grant_type"
parameter passed to the token endpoint defined in the grant type
definition.
"""
... | [
"def",
"validate_metadata_token",
"(",
"self",
",",
"claims",
",",
"endpoint",
")",
":",
"self",
".",
"_grant_types",
".",
"extend",
"(",
"endpoint",
".",
"_grant_types",
".",
"keys",
"(",
")",
")",
"claims",
".",
"setdefault",
"(",
"\"token_endpoint_auth_meth... | 58.846154 | 32.692308 |
def smart_str(s, encoding='utf-8', errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
from django
"""
if not isinstance(s, basestring):
try:
return str(s)
... | [
"def",
"smart_str",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"try",
":",
"return",
"str",
"(",
"s",
")",
"except",
"UnicodeEncodeError",
":",
... | 37.416667 | 19.25 |
def http_proxy(self):
"""Set ivy to use an http proxy.
Expects a string of the form http://<host>:<port>
"""
if os.getenv('HTTP_PROXY'):
return os.getenv('HTTP_PROXY')
if os.getenv('http_proxy'):
return os.getenv('http_proxy')
return self.get_options().http_proxy | [
"def",
"http_proxy",
"(",
"self",
")",
":",
"if",
"os",
".",
"getenv",
"(",
"'HTTP_PROXY'",
")",
":",
"return",
"os",
".",
"getenv",
"(",
"'HTTP_PROXY'",
")",
"if",
"os",
".",
"getenv",
"(",
"'http_proxy'",
")",
":",
"return",
"os",
".",
"getenv",
"(... | 29.1 | 9.8 |
def xml(self, operator='set', indent = ""):
"""Serialize the metadata field to XML"""
xml = indent + "<meta id=\"" + self.key + "\""
if operator != 'set':
xml += " operator=\"" + operator + "\""
if not self.value:
xml += " />"
else:
xml += ">" ... | [
"def",
"xml",
"(",
"self",
",",
"operator",
"=",
"'set'",
",",
"indent",
"=",
"\"\"",
")",
":",
"xml",
"=",
"indent",
"+",
"\"<meta id=\\\"\"",
"+",
"self",
".",
"key",
"+",
"\"\\\"\"",
"if",
"operator",
"!=",
"'set'",
":",
"xml",
"+=",
"\" operator=\\... | 35.4 | 12.5 |
def _to_add_with_category(self, catid):
'''
Used for info2.
:param catid: the uid of category
'''
catinfo = MCategory.get_by_uid(catid)
kwd = {
'uid': self._gen_uid(),
'userid': self.userinfo.user_name if self.userinfo else '',
'gcat0'... | [
"def",
"_to_add_with_category",
"(",
"self",
",",
"catid",
")",
":",
"catinfo",
"=",
"MCategory",
".",
"get_by_uid",
"(",
"catid",
")",
"kwd",
"=",
"{",
"'uid'",
":",
"self",
".",
"_gen_uid",
"(",
")",
",",
"'userid'",
":",
"self",
".",
"userinfo",
"."... | 32.222222 | 19.111111 |
def until(coro, coro_test, assert_coro=None, *args, **kw):
"""
Repeatedly call `coro` coroutine function until `coro_test` returns `True`.
This function is the inverse of `paco.whilst()`.
This function is a coroutine.
Arguments:
coro (coroutinefunction): coroutine function to execute.
... | [
"def",
"until",
"(",
"coro",
",",
"coro_test",
",",
"assert_coro",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"@",
"asyncio",
".",
"coroutine",
"def",
"assert_coro",
"(",
"value",
")",
":",
"return",
"not",
"value",
"return",
"(",
... | 26.604651 | 23.72093 |
def init_app(self, app):
"""
Register this extension with the flask app
:param app: A flask application
"""
# Save this so we can use it later in the extension
if not hasattr(app, 'extensions'): # pragma: no cover
app.extensions = {}
app.extensions[... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"# Save this so we can use it later in the extension",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'extensions'",
")",
":",
"# pragma: no cover",
"app",
".",
"extensions",
"=",
"{",
"}",
"app",
".",
"extensions... | 36 | 16.777778 |
def _new_connection_file(self):
"""
Generate a new connection file
Taken from jupyter_client/console_app.py
Licensed under the BSD license
"""
# Check if jupyter_runtime_dir exists (Spyder addition)
if not osp.isdir(jupyter_runtime_dir()):
tr... | [
"def",
"_new_connection_file",
"(",
"self",
")",
":",
"# Check if jupyter_runtime_dir exists (Spyder addition)\r",
"if",
"not",
"osp",
".",
"isdir",
"(",
"jupyter_runtime_dir",
"(",
")",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"jupyter_runtime_dir",
"(",
... | 35.421053 | 14.157895 |
def get_all_migrations(path, databases=None):
"""
Returns a dictionary of database => [migrations] representing all
migrations contained in ``path``.
"""
# database: [(number, full_path)]
possible_migrations = defaultdict(list)
try:
in_directory = sorted(get_file_list(path))
... | [
"def",
"get_all_migrations",
"(",
"path",
",",
"databases",
"=",
"None",
")",
":",
"# database: [(number, full_path)]",
"possible_migrations",
"=",
"defaultdict",
"(",
"list",
")",
"try",
":",
"in_directory",
"=",
"sorted",
"(",
"get_file_list",
"(",
"path",
")",
... | 33.581395 | 17.069767 |
def vowelinstem(self):
"""vowelinstem() is TRUE <=> k0,...j contains a vowel"""
for i in range(self.k0, self.j + 1):
if not self.cons(i):
return 1
return 0 | [
"def",
"vowelinstem",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"k0",
",",
"self",
".",
"j",
"+",
"1",
")",
":",
"if",
"not",
"self",
".",
"cons",
"(",
"i",
")",
":",
"return",
"1",
"return",
"0"
] | 34.5 | 11.333333 |
def _get_snpeff_transcript(self, transcript_info):
"""Create a transcript based on the snpeff annotation
Args:
transcript_info (dict): A dict with snpeff info
Returns:
transcript (puzzle.models.Transcript): A Transcripts
"""
transcript = ... | [
"def",
"_get_snpeff_transcript",
"(",
"self",
",",
"transcript_info",
")",
":",
"transcript",
"=",
"Transcript",
"(",
"hgnc_symbol",
"=",
"transcript_info",
".",
"get",
"(",
"'Gene_Name'",
")",
",",
"transcript_id",
"=",
"transcript_info",
".",
"get",
"(",
"'Fea... | 41.8 | 19.5 |
def create_new_project():
'''Creates a new XBMC Addon directory based on user input'''
readline.parse_and_bind('tab: complete')
print \
'''
xbmcswift2 - A micro-framework for creating XBMC plugins.
xbmc@jonathanbeluch.com
--
'''
print 'I\'m going to ask you a few questions to get this proje... | [
"def",
"create_new_project",
"(",
")",
":",
"readline",
".",
"parse_and_bind",
"(",
"'tab: complete'",
")",
"print",
"'''\n xbmcswift2 - A micro-framework for creating XBMC plugins.\n xbmc@jonathanbeluch.com\n --\n'''",
"print",
"'I\\'m going to ask you a few questions to get th... | 29.8 | 24.018182 |
def consume_arguments(self, argument_list):
"""
Takes arguments from a list while there are parameters that can accept them
"""
while True:
argument_count = len(argument_list)
for parameter in self.values():
argument_list = parameter.consume_argume... | [
"def",
"consume_arguments",
"(",
"self",
",",
"argument_list",
")",
":",
"while",
"True",
":",
"argument_count",
"=",
"len",
"(",
"argument_list",
")",
"for",
"parameter",
"in",
"self",
".",
"values",
"(",
")",
":",
"argument_list",
"=",
"parameter",
".",
... | 41.9 | 12.7 |
def print_help(self):
"""Prints usage of all registered commands, collapsing aliases
into one record
"""
seen_aliases = set()
print('-'*80)
for cmd in sorted(self.cmds):
if cmd not in self.builtin_cmds:
if cmd not in seen_aliases:
... | [
"def",
"print_help",
"(",
"self",
")",
":",
"seen_aliases",
"=",
"set",
"(",
")",
"print",
"(",
"'-'",
"*",
"80",
")",
"for",
"cmd",
"in",
"sorted",
"(",
"self",
".",
"cmds",
")",
":",
"if",
"cmd",
"not",
"in",
"self",
".",
"builtin_cmds",
":",
"... | 41.833333 | 11.888889 |
def get_external_store(self, project_name, store_name):
""" get the logstore meta info
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type store_name: string
:param store_name: the logstore n... | [
"def",
"get_external_store",
"(",
"self",
",",
"project_name",
",",
"store_name",
")",
":",
"headers",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"resource",
"=",
"\"/externalstores/\"",
"+",
"store_name",
"(",
"resp",
",",
"header",
")",
"=",
"self",
".",
... | 31.08 | 18.64 |
def truncate_table(self, table):
""" Responsys.truncateTable call
Accepts:
InteractObject table
Returns True on success
"""
table = table.get_soap_object(self.client)
return self.call('truncateTable', table) | [
"def",
"truncate_table",
"(",
"self",
",",
"table",
")",
":",
"table",
"=",
"table",
".",
"get_soap_object",
"(",
"self",
".",
"client",
")",
"return",
"self",
".",
"call",
"(",
"'truncateTable'",
",",
"table",
")"
] | 26 | 14.7 |
def get_location(query, format, api_key):
"""Get geographic data of a lab in a coherent way for all labs."""
# Play nice with the API...
sleep(1)
geolocator = OpenCage(api_key=api_key, timeout=10)
# Variables for storing the data
data = {"city": None,
"address_1": None,
... | [
"def",
"get_location",
"(",
"query",
",",
"format",
",",
"api_key",
")",
":",
"# Play nice with the API...",
"sleep",
"(",
"1",
")",
"geolocator",
"=",
"OpenCage",
"(",
"api_key",
"=",
"api_key",
",",
"timeout",
"=",
"10",
")",
"# Variables for storing the data"... | 37.27957 | 14.870968 |
def top10(rest):
"""
Return the top n (default 10) highest entities by Karmic value.
Use negative numbers for the bottom N.
"""
if rest:
topn = int(rest)
else:
topn = 10
selection = Karma.store.list(topn)
res = ' '.join('(%s: %s)' % (', '.join(n), k) for n, k in selection)
return res | [
"def",
"top10",
"(",
"rest",
")",
":",
"if",
"rest",
":",
"topn",
"=",
"int",
"(",
"rest",
")",
"else",
":",
"topn",
"=",
"10",
"selection",
"=",
"Karma",
".",
"store",
".",
"list",
"(",
"topn",
")",
"res",
"=",
"' '",
".",
"join",
"(",
"'(%s: ... | 23.833333 | 19 |
def highlight_code(text, lexer_name='python', **kwargs):
"""
Highlights a block of text using ANSI tags based on language syntax.
Args:
text (str): plain text to highlight
lexer_name (str): name of language
**kwargs: passed to pygments.lexers.get_lexer_by_name
Returns:
... | [
"def",
"highlight_code",
"(",
"text",
",",
"lexer_name",
"=",
"'python'",
",",
"*",
"*",
"kwargs",
")",
":",
"# Resolve extensions to languages",
"lexer_name",
"=",
"{",
"'py'",
":",
"'python'",
",",
"'h'",
":",
"'cpp'",
",",
"'cpp'",
":",
"'cpp'",
",",
"'... | 31.8 | 20.8 |
def set_state(self, state):
"""Set the runtime state of the Controller. Use the internal constants
to ensure proper state values:
- :attr:`Controller.STATE_INITIALIZING`
- :attr:`Controller.STATE_ACTIVE`
- :attr:`Controller.STATE_IDLE`
- :attr:`Controller.STATE_SLEEPING`... | [
"def",
"set_state",
"(",
"self",
",",
"state",
")",
":",
"if",
"state",
"==",
"self",
".",
"_state",
":",
"return",
"elif",
"state",
"not",
"in",
"self",
".",
"_STATES",
".",
"keys",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid state {}'",
".",... | 41.981481 | 21.111111 |
def check_args(state, name, missing_msg=None):
"""Check whether a function argument is specified.
This function can follow ``check_function()`` in an SCT chain and verifies whether an argument is specified.
If you want to go on and check whether the argument was correctly specified, you can can continue ch... | [
"def",
"check_args",
"(",
"state",
",",
"name",
",",
"missing_msg",
"=",
"None",
")",
":",
"if",
"missing_msg",
"is",
"None",
":",
"missing_msg",
"=",
"\"Did you specify the {{part}}?\"",
"if",
"name",
"in",
"[",
"\"*args\"",
",",
"\"**kwargs\"",
"]",
":",
"... | 40.333333 | 29.333333 |
def describe_enum_value(enum_value):
"""Build descriptor for Enum instance.
Args:
enum_value: Enum value to provide descriptor for.
Returns:
Initialized EnumValueDescriptor instance describing the Enum instance.
"""
enum_value_descriptor = EnumValueDescriptor()
enum_value_descripto... | [
"def",
"describe_enum_value",
"(",
"enum_value",
")",
":",
"enum_value_descriptor",
"=",
"EnumValueDescriptor",
"(",
")",
"enum_value_descriptor",
".",
"name",
"=",
"six",
".",
"text_type",
"(",
"enum_value",
".",
"name",
")",
"enum_value_descriptor",
".",
"number",... | 33.307692 | 18.923077 |
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0):
"""
Write the DefaultsInformation structure encoding to the data stream.
Args:
output_buffer (stream): A data stream in which to encode
Attributes structure data, supporting a write method.
... | [
"def",
"write",
"(",
"self",
",",
"output_buffer",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_2_0",
")",
":",
"if",
"kmip_version",
"<",
"enums",
".",
"KMIPVersion",
".",
"KMIP_2_0",
":",
"raise",
"exceptions",
".",
"VersionNotSupported"... | 39.04878 | 21.439024 |
def items(self):
"""Get an iter of VenvDirs and VenvFiles within the directory."""
contents = self.paths
contents = (
BinFile(path.path) if path.is_file else BinDir(path.path)
for path in contents
)
return contents | [
"def",
"items",
"(",
"self",
")",
":",
"contents",
"=",
"self",
".",
"paths",
"contents",
"=",
"(",
"BinFile",
"(",
"path",
".",
"path",
")",
"if",
"path",
".",
"is_file",
"else",
"BinDir",
"(",
"path",
".",
"path",
")",
"for",
"path",
"in",
"conte... | 33.875 | 17.5 |
def settings(self):
'''Generator which returns all of the statements in all of the settings tables'''
for table in self.tables:
if isinstance(table, SettingTable):
for statement in table.statements:
yield statement | [
"def",
"settings",
"(",
"self",
")",
":",
"for",
"table",
"in",
"self",
".",
"tables",
":",
"if",
"isinstance",
"(",
"table",
",",
"SettingTable",
")",
":",
"for",
"statement",
"in",
"table",
".",
"statements",
":",
"yield",
"statement"
] | 45.5 | 16.5 |
def generateIntrospectionXML(objectPath, exportedObjects):
"""
Generates the introspection XML for an object path or partial object path
that matches exported objects.
This allows for browsing the exported objects with tools such as d-feet.
@rtype: C{string}
"""
l = [_dtd_decl]
l.appen... | [
"def",
"generateIntrospectionXML",
"(",
"objectPath",
",",
"exportedObjects",
")",
":",
"l",
"=",
"[",
"_dtd_decl",
"]",
"l",
".",
"append",
"(",
"'<node name=\"%s\">'",
"%",
"(",
"objectPath",
",",
")",
")",
"obj",
"=",
"exportedObjects",
".",
"get",
"(",
... | 29.351351 | 17.891892 |
def delete_scan(self, scan_id):
""" Delete a scan if fully finished. """
if self.get_status(scan_id) == ScanStatus.RUNNING:
return False
self.scans_table.pop(scan_id)
if len(self.scans_table) == 0:
del self.data_manager
self.data_manager = None
... | [
"def",
"delete_scan",
"(",
"self",
",",
"scan_id",
")",
":",
"if",
"self",
".",
"get_status",
"(",
"scan_id",
")",
"==",
"ScanStatus",
".",
"RUNNING",
":",
"return",
"False",
"self",
".",
"scans_table",
".",
"pop",
"(",
"scan_id",
")",
"if",
"len",
"("... | 32.4 | 12 |
async def peek(self, task_id):
"""
Get task without changing its state
:param task_id: Task id
:return: Task instance
"""
args = (task_id,)
res = await self.conn.call(self.__funcs['peek'], args)
return self._create_task(res.body) | [
"async",
"def",
"peek",
"(",
"self",
",",
"task_id",
")",
":",
"args",
"=",
"(",
"task_id",
",",
")",
"res",
"=",
"await",
"self",
".",
"conn",
".",
"call",
"(",
"self",
".",
"__funcs",
"[",
"'peek'",
"]",
",",
"args",
")",
"return",
"self",
".",... | 27 | 13.363636 |
def gridfs_namespace(self, plain_src_ns):
"""Given a plain source namespace, return the corresponding plain
target namespace if this namespace is a gridfs collection.
"""
namespace = self.lookup(plain_src_ns)
if namespace and namespace.gridfs:
return namespace.dest_na... | [
"def",
"gridfs_namespace",
"(",
"self",
",",
"plain_src_ns",
")",
":",
"namespace",
"=",
"self",
".",
"lookup",
"(",
"plain_src_ns",
")",
"if",
"namespace",
"and",
"namespace",
".",
"gridfs",
":",
"return",
"namespace",
".",
"dest_name",
"return",
"None"
] | 41.875 | 7.125 |
def boost_ranks(job, isoform_expression, merged_mhc_calls, transgene_out, univ_options,
rank_boost_options):
"""
This is the final module in the pipeline. It will call the rank boosting R
script.
This module corresponds to node 21 in the tree
"""
job.fileStore.logToMaster('Runn... | [
"def",
"boost_ranks",
"(",
"job",
",",
"isoform_expression",
",",
"merged_mhc_calls",
",",
"transgene_out",
",",
"univ_options",
",",
"rank_boost_options",
")",
":",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Running boost_ranks on %s'",
"%",
"univ_options",
... | 53.216216 | 25.648649 |
def lookup_endpoint(cli):
"""Looks up the application endpoint from dotcloud"""
url = '/applications/{0}/environment'.format(APPNAME)
environ = cli.user.get(url).item
port = environ['DOTCLOUD_SATELLITE_ZMQ_PORT']
host = socket.gethostbyname(environ['DOTCLOUD_SATELLITE_ZMQ_HOST'])
return "tcp://{... | [
"def",
"lookup_endpoint",
"(",
"cli",
")",
":",
"url",
"=",
"'/applications/{0}/environment'",
".",
"format",
"(",
"APPNAME",
")",
"environ",
"=",
"cli",
".",
"user",
".",
"get",
"(",
"url",
")",
".",
"item",
"port",
"=",
"environ",
"[",
"'DOTCLOUD_SATELLI... | 48.571429 | 11.571429 |
def _get_hydrated_path(field):
"""Return HydratedPath object for file-type field."""
# Get only file path if whole file object is given.
if isinstance(field, str) and hasattr(field, 'file_name'):
# field is already actually a HydratedPath object
return field
if isinstance(field, dict) a... | [
"def",
"_get_hydrated_path",
"(",
"field",
")",
":",
"# Get only file path if whole file object is given.",
"if",
"isinstance",
"(",
"field",
",",
"str",
")",
"and",
"hasattr",
"(",
"field",
",",
"'file_name'",
")",
":",
"# field is already actually a HydratedPath object"... | 36.785714 | 19.714286 |
def deconstruct(self):
"""Gets the values to pass to :see:__init__ when
re-creating this object."""
name, path, args, kwargs = super(
HStoreField, self).deconstruct()
if self.uniqueness is not None:
kwargs['uniqueness'] = self.uniqueness
if self.require... | [
"def",
"deconstruct",
"(",
"self",
")",
":",
"name",
",",
"path",
",",
"args",
",",
"kwargs",
"=",
"super",
"(",
"HStoreField",
",",
"self",
")",
".",
"deconstruct",
"(",
")",
"if",
"self",
".",
"uniqueness",
"is",
"not",
"None",
":",
"kwargs",
"[",
... | 29.214286 | 14.571429 |
def next_state(self):
"""This is a method that will be called when the time remaining ends.
The current state can be: roasting, cooling, idle, sleeping, connecting,
or unkown."""
self.active_recipe_item += 1
if self.active_recipe_item >= len(self.recipe):
# we're done... | [
"def",
"next_state",
"(",
"self",
")",
":",
"self",
".",
"active_recipe_item",
"+=",
"1",
"if",
"self",
".",
"active_recipe_item",
">=",
"len",
"(",
"self",
".",
"recipe",
")",
":",
"# we're done!",
"return",
"# show state step on screen",
"print",
"(",
"\"---... | 49.176471 | 18 |
def deny(cls, action, **kwargs):
"""Deny the given action need.
:param action: The action to deny.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
"""
return cls.create(action, exclude=True, **kwargs) | [
"def",
"deny",
"(",
"cls",
",",
"action",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"create",
"(",
"action",
",",
"exclude",
"=",
"True",
",",
"*",
"*",
"kwargs",
")"
] | 36.571429 | 14.714286 |
def generate_private_key(key_type):
"""
Generate a random private key using sensible parameters.
:param str key_type: The type of key to generate. One of: ``rsa``.
"""
if key_type == u'rsa':
return rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_b... | [
"def",
"generate_private_key",
"(",
"key_type",
")",
":",
"if",
"key_type",
"==",
"u'rsa'",
":",
"return",
"rsa",
".",
"generate_private_key",
"(",
"public_exponent",
"=",
"65537",
",",
"key_size",
"=",
"2048",
",",
"backend",
"=",
"default_backend",
"(",
")",... | 35.1 | 15.5 |
def gramm_to_promille(gramm, age, weight, height, sex):
"""Return the blood alcohol content (per mill) for a person with the
given body stats and amount of alcohol (in gramm) in blood
"""
bw = calculate_bw(age, weight, height, sex)
return (gramm * W) / (PB * bw) | [
"def",
"gramm_to_promille",
"(",
"gramm",
",",
"age",
",",
"weight",
",",
"height",
",",
"sex",
")",
":",
"bw",
"=",
"calculate_bw",
"(",
"age",
",",
"weight",
",",
"height",
",",
"sex",
")",
"return",
"(",
"gramm",
"*",
"W",
")",
"/",
"(",
"PB",
... | 45 | 8.5 |
def _form_datetimes(days, msecs):
"""Calculate seconds since EPOCH from days and milliseconds for each of IASI scan."""
all_datetimes = []
for i in range(days.size):
day = int(days[i])
msec = msecs[i]
scanline_datetimes = []
for j in range(int(VALUES_PER_SCAN_LINE / 4)):
... | [
"def",
"_form_datetimes",
"(",
"days",
",",
"msecs",
")",
":",
"all_datetimes",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"days",
".",
"size",
")",
":",
"day",
"=",
"int",
"(",
"days",
"[",
"i",
"]",
")",
"msec",
"=",
"msecs",
"[",
"i",
"]... | 39 | 16.5625 |
def get_default_handler(self, **kw):
"""Return the default logging handler based on the local environment.
:type kw: dict
:param kw: keyword args passed to handler constructor
:rtype: :class:`logging.Handler`
:returns: The default log handler based on the environment
""... | [
"def",
"get_default_handler",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"gke_cluster_name",
"=",
"retrieve_metadata_server",
"(",
"_GKE_CLUSTER_NAME",
")",
"if",
"(",
"_APPENGINE_FLEXIBLE_ENV_VM",
"in",
"os",
".",
"environ",
"or",
"_APPENGINE_INSTANCE_ID",
"in",
... | 35.35 | 17.65 |
def dateint_range(first_dateint, last_dateint):
"""Returns all dateints in the given dateint range.
Arguments
---------
first_dateint : int
An integer object decipting a specific calendaric day; e.g. 20161225.
last_dateint : int
An integer object decipting a specific calendaric day;... | [
"def",
"dateint_range",
"(",
"first_dateint",
",",
"last_dateint",
")",
":",
"first_datetime",
"=",
"dateint_to_datetime",
"(",
"first_dateint",
")",
"last_datetime",
"=",
"dateint_to_datetime",
"(",
"last_dateint",
")",
"delta",
"=",
"last_datetime",
"-",
"first_date... | 34.823529 | 18.941176 |
def sample_from_discretized_mix_logistic(pred, seed=None):
"""Sampling from a discretized mixture of logistics.
Args:
pred: A [batch, height, width, num_mixtures*10] tensor of floats
comprising one unconstrained mixture probability, three means
(one per channel), three standard deviations (one per ... | [
"def",
"sample_from_discretized_mix_logistic",
"(",
"pred",
",",
"seed",
"=",
"None",
")",
":",
"logits",
",",
"locs",
",",
"log_scales",
",",
"coeffs",
"=",
"split_to_discretized_mix_logistic_params",
"(",
"pred",
")",
"# Sample mixture indicator given logits using the g... | 36.234043 | 20.255319 |
def process_all_json_files(build_dir):
"""Return a list of pages to index"""
html_files = []
for root, _, files in os.walk(build_dir):
for filename in fnmatch.filter(files, '*.fjson'):
if filename in ['search.fjson', 'genindex.fjson',
'py-modindex.fjson']:
... | [
"def",
"process_all_json_files",
"(",
"build_dir",
")",
":",
"html_files",
"=",
"[",
"]",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"build_dir",
")",
":",
"for",
"filename",
"in",
"fnmatch",
".",
"filter",
"(",
"files",
",",
... | 35.315789 | 13.894737 |
def parse(cls, fptr, offset, length):
"""Parse component definition box.
Parameters
----------
fptr : file
Open file object.
offset : int
Start position of box in bytes.
length : int
Length of the box in bytes.
Returns
... | [
"def",
"parse",
"(",
"cls",
",",
"fptr",
",",
"offset",
",",
"length",
")",
":",
"num_bytes",
"=",
"offset",
"+",
"length",
"-",
"fptr",
".",
"tell",
"(",
")",
"read_buffer",
"=",
"fptr",
".",
"read",
"(",
"num_bytes",
")",
"# Read the number of componen... | 32.212121 | 16.181818 |
def format(self, subtitles):
"""Turn a string containing the subs xml document into the formatted
subtitle string
@param str|crunchyroll.models.StyledSubtitle sub_xml_text
@return str
"""
logger.debug('Formatting subtitles (id=%s) with %s',
subtitles.id, self... | [
"def",
"format",
"(",
"self",
",",
"subtitles",
")",
":",
"logger",
".",
"debug",
"(",
"'Formatting subtitles (id=%s) with %s'",
",",
"subtitles",
".",
"id",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"return",
"self",
".",
"_format",
"(",
"subtitl... | 38.6 | 15.9 |
def ensure_topic(self):
"""Verify the pub/sub topic exists.
Returns the topic qualified name.
"""
client = self.session.client('pubsub', 'v1', 'projects.topics')
topic = self.get_topic_param()
try:
client.execute_command('get', {'topic': topic})
excep... | [
"def",
"ensure_topic",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"session",
".",
"client",
"(",
"'pubsub'",
",",
"'v1'",
",",
"'projects.topics'",
")",
"topic",
"=",
"self",
".",
"get_topic_param",
"(",
")",
"try",
":",
"client",
".",
"execute_c... | 33.157895 | 18.526316 |
def dcmanonym(
dcmpth,
displayonly=False,
patient='anonymised',
physician='anonymised',
dob='19800101',
verbose=True):
''' Anonymise DICOM file(s)
Arguments:
> dcmpth: it can be passed as a single DICOM file, or
a folder containi... | [
"def",
"dcmanonym",
"(",
"dcmpth",
",",
"displayonly",
"=",
"False",
",",
"patient",
"=",
"'anonymised'",
",",
"physician",
"=",
"'anonymised'",
",",
"dob",
"=",
"'19800101'",
",",
"verbose",
"=",
"True",
")",
":",
"#> check if a single DICOM file",
"if",
"isi... | 35.242647 | 22.036765 |
def healthy(self):
"""Return 200 is healthy, else 500.
Override is_healthy() to change the health check.
"""
try:
if self.is_healthy():
return "OK", 200
else:
return "FAIL", 500
except Exception as e:
self.app... | [
"def",
"healthy",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"is_healthy",
"(",
")",
":",
"return",
"\"OK\"",
",",
"200",
"else",
":",
"return",
"\"FAIL\"",
",",
"500",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"app",
".",
"log... | 23.8 | 16.733333 |
def install_brew(target_path):
""" Install brew to the target path """
if not os.path.exists(target_path):
try:
os.makedirs(target_path)
except OSError:
logger.warn("Unable to create directory %s for brew." % target_path)
logger.warn("Skipping...")
... | [
"def",
"install_brew",
"(",
"target_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"target_path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"target_path",
")",
"except",
"OSError",
":",
"logger",
".",
"warn",
"(",
"\"Unabl... | 39 | 15.5 |
def should_retry_on_error(self, error):
"""rules for retry
:param error:
ProtocolException that returns from Server
"""
if self.is_streaming_request:
# not retry for streaming request
return False
retry_flag = self.headers.get('re', retry.DE... | [
"def",
"should_retry_on_error",
"(",
"self",
",",
"error",
")",
":",
"if",
"self",
".",
"is_streaming_request",
":",
"# not retry for streaming request",
"return",
"False",
"retry_flag",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'re'",
",",
"retry",
".",
... | 31.59375 | 17.375 |
def process_download_path(self):
""" Processes the download path.
It checks if the path exists and the scraper has
write permissions.
"""
if os.path.exists(self.download_path):
if not os.access(self.download_path, os.W_OK):
raise DirectoryAcce... | [
"def",
"process_download_path",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"download_path",
")",
":",
"if",
"not",
"os",
".",
"access",
"(",
"self",
".",
"download_path",
",",
"os",
".",
"W_OK",
")",
":",
"raise"... | 35.785714 | 13.285714 |
def getSegmentKeys(self, segment):
"""
Get the different keys for 1 defined segment
:param segment: Segment to find. Ex : PV1, PID
"""
return list(filter(lambda x: x.startswith(segment), self.getAliasedKeys())) | [
"def",
"getSegmentKeys",
"(",
"self",
",",
"segment",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"startswith",
"(",
"segment",
")",
",",
"self",
".",
"getAliasedKeys",
"(",
")",
")",
")"
] | 42.166667 | 13.833333 |
def _add_scheme():
"""
urllib.parse doesn't support the mongodb scheme, but it's easy
to make it so.
"""
lists = [
urllib.parse.uses_relative,
urllib.parse.uses_netloc,
urllib.parse.uses_query,
]
for l in lists:
l.append('mongodb') | [
"def",
"_add_scheme",
"(",
")",
":",
"lists",
"=",
"[",
"urllib",
".",
"parse",
".",
"uses_relative",
",",
"urllib",
".",
"parse",
".",
"uses_netloc",
",",
"urllib",
".",
"parse",
".",
"uses_query",
",",
"]",
"for",
"l",
"in",
"lists",
":",
"l",
".",... | 23.333333 | 15.5 |
def use(self, plugin, arguments={}):
"""Add plugin to use during compilation.
plugin: Plugin to include.
arguments: Dictionary of arguments to pass to the import.
"""
self.plugins[plugin] = dict(arguments)
return self.plugins | [
"def",
"use",
"(",
"self",
",",
"plugin",
",",
"arguments",
"=",
"{",
"}",
")",
":",
"self",
".",
"plugins",
"[",
"plugin",
"]",
"=",
"dict",
"(",
"arguments",
")",
"return",
"self",
".",
"plugins"
] | 30.375 | 11.75 |
def execute(self):
"""
Invoke the redispy pipeline.execute() method and take all the values
returned in sequential order of commands and map them to the
Future objects we returned when each command was queued inside
the pipeline.
Also invoke all the callback functions que... | [
"def",
"execute",
"(",
"self",
")",
":",
"stack",
"=",
"self",
".",
"_stack",
"callbacks",
"=",
"self",
".",
"_callbacks",
"promises",
"=",
"[",
"]",
"if",
"stack",
":",
"def",
"process",
"(",
")",
":",
"\"\"\"\n take all the commands and pass t... | 35.83871 | 19.064516 |
def old(self):
"""Assess to the state value(s) at beginning of the time step, which
has been processed most recently. When using *HydPy* in the
normal manner. But it can be helpful for demonstration and debugging
purposes.
"""
value = getattr(self.fastaccess_old, self.n... | [
"def",
"old",
"(",
"self",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
".",
"fastaccess_old",
",",
"self",
".",
"name",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'No value/values of sequence %s has/have '",
"'not ... | 39.75 | 15.6875 |
def get_profile_pic_from_id(self, id):
"""
Get full profile pic from an id
The ID must be on your contact book to
successfully get their profile picture.
:param id: ID
:type id: str
"""
profile_pic = self.wapi_functions.getProfilePicFromId(id)
if ... | [
"def",
"get_profile_pic_from_id",
"(",
"self",
",",
"id",
")",
":",
"profile_pic",
"=",
"self",
".",
"wapi_functions",
".",
"getProfilePicFromId",
"(",
"id",
")",
"if",
"profile_pic",
":",
"return",
"b64decode",
"(",
"profile_pic",
")",
"else",
":",
"return",
... | 28.571429 | 12.857143 |
def create_tags(filesystemid,
tags,
keyid=None,
key=None,
profile=None,
region=None,
**kwargs):
'''
Creates or overwrites tags associated with a file system.
Each tag is a key-value pair. If a tag key specified i... | [
"def",
"create_tags",
"(",
"filesystemid",
",",
"tags",
",",
"keyid",
"=",
"None",
",",
"key",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"region",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_conn",
"(",
"key",
"=",
"ke... | 27.909091 | 24.515152 |
def create(self, item, **kwargs):
"""
Creates a new item. You pass in an item containing initial values.
Any attribute names defined in ``prototype`` that are missing from the
item will be added using the default value defined in ``prototype``.
"""
response = self._new_r... | [
"def",
"create",
"(",
"self",
",",
"item",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_new_response",
"(",
")",
"if",
"self",
".",
"_prototype_handler",
".",
"check",
"(",
"item",
",",
"'create'",
",",
"response",
")",
":",
"se... | 43.125 | 13.875 |
def add_text(self, text, position=None, font_size=50, color=None,
font=None, shadow=False, name=None, loc=None):
"""
Adds text to plot object in the top left corner by default
Parameters
----------
text : str
The text to add the the rendering
... | [
"def",
"add_text",
"(",
"self",
",",
"text",
",",
"position",
"=",
"None",
",",
"font_size",
"=",
"50",
",",
"color",
"=",
"None",
",",
"font",
"=",
"None",
",",
"shadow",
"=",
"False",
",",
"name",
"=",
"None",
",",
"loc",
"=",
"None",
")",
":",... | 37.810345 | 19.810345 |
def rouge(hypotheses, references):
"""Calculates average rouge scores for a list of hypotheses and
references"""
# Filter out hyps that are of 0 length
# hyps_and_refs = zip(hypotheses, references)
# hyps_and_refs = [_ for _ in hyps_and_refs if len(_[0]) > 0]
# hypotheses, references = zip(*hyp... | [
"def",
"rouge",
"(",
"hypotheses",
",",
"references",
")",
":",
"# Filter out hyps that are of 0 length",
"# hyps_and_refs = zip(hypotheses, references)",
"# hyps_and_refs = [_ for _ in hyps_and_refs if len(_[0]) > 0]",
"# hypotheses, references = zip(*hyps_and_refs)",
"# Calculate ROUGE-1 F... | 34.153846 | 18.461538 |
def changes(self):
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj | [
"def",
"changes",
"(",
"self",
")",
":",
"obj",
"=",
"AuditLogChanges",
"(",
"self",
",",
"self",
".",
"_changes",
")",
"del",
"self",
".",
"_changes",
"return",
"obj"
] | 37.2 | 13.8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.