text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def check_all(self, all_entries, *args, **kwargs):
"""
Go through lists of entries, find overlaps among each, return the total
"""
all_overlaps = 0
while True:
try:
user_entries = all_entries.next()
except StopIteration:
ret... | [
"def",
"check_all",
"(",
"self",
",",
"all_entries",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"all_overlaps",
"=",
"0",
"while",
"True",
":",
"try",
":",
"user_entries",
"=",
"all_entries",
".",
"next",
"(",
")",
"except",
"StopIteration",
... | 35.714286 | 13.571429 |
async def connect(self):
"""
Connects to the voice channel associated with this Player.
"""
await self.node.join_voice_channel(self.channel.guild.id, self.channel.id) | [
"async",
"def",
"connect",
"(",
"self",
")",
":",
"await",
"self",
".",
"node",
".",
"join_voice_channel",
"(",
"self",
".",
"channel",
".",
"guild",
".",
"id",
",",
"self",
".",
"channel",
".",
"id",
")"
] | 38.8 | 16.8 |
def get_version(version):
"""Dynamically calculate the version based on VERSION tuple."""
if len(version) > 2 and version[2] is not None:
if isinstance(version[2], int):
str_version = "%s.%s.%s" % version[:3]
else:
str_version = "%s.%s_%s" % version[:3]
else:
... | [
"def",
"get_version",
"(",
"version",
")",
":",
"if",
"len",
"(",
"version",
")",
">",
"2",
"and",
"version",
"[",
"2",
"]",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"version",
"[",
"2",
"]",
",",
"int",
")",
":",
"str_version",
"=",
"\... | 33.545455 | 15.090909 |
def add_weights(self, name, nin, nout, mean=0, std=0, sparsity=0, diagonal=0):
'''Helper method to create a new weight matrix.
Parameters
----------
name : str
Name of the parameter to add.
nin : int
Size of "input" for this weight matrix.
nout : ... | [
"def",
"add_weights",
"(",
"self",
",",
"name",
",",
"nin",
",",
"nout",
",",
"mean",
"=",
"0",
",",
"std",
"=",
"0",
",",
"sparsity",
"=",
"0",
",",
"diagonal",
"=",
"0",
")",
":",
"glorot",
"=",
"1",
"/",
"np",
".",
"sqrt",
"(",
"nin",
"+",... | 44.342857 | 19.6 |
def envs(ignore_cache=False):
'''
Return a list of refs that can be used as environments
'''
if not ignore_cache:
env_cache = os.path.join(__opts__['cachedir'], 'svnfs/envs.p')
cache_match = salt.fileserver.check_env_cache(__opts__, env_cache)
if cache_match is not None:
... | [
"def",
"envs",
"(",
"ignore_cache",
"=",
"False",
")",
":",
"if",
"not",
"ignore_cache",
":",
"env_cache",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'svnfs/envs.p'",
")",
"cache_match",
"=",
"salt",
".",
"fileser... | 35.125 | 19.175 |
def params(self):
""" Read self params from configuration. """
parser = JinjaInterpolationNamespace()
parser.read(self.configuration)
return dict(parser['params'] or {}) | [
"def",
"params",
"(",
"self",
")",
":",
"parser",
"=",
"JinjaInterpolationNamespace",
"(",
")",
"parser",
".",
"read",
"(",
"self",
".",
"configuration",
")",
"return",
"dict",
"(",
"parser",
"[",
"'params'",
"]",
"or",
"{",
"}",
")"
] | 39.4 | 6.6 |
def create_sparse_dtm(vocab, doc_labels, docs_terms, sum_uniques_per_doc):
"""
Create a sparse document-term-matrix (DTM) as scipy "coo_matrix" from vocabulary array `vocab`, document
IDs/labels array `doc_labels`, dict of doc_label -> document terms `docs_terms` and the sum of unique terms
per document... | [
"def",
"create_sparse_dtm",
"(",
"vocab",
",",
"doc_labels",
",",
"docs_terms",
",",
"sum_uniques_per_doc",
")",
":",
"vocab_sorter",
"=",
"np",
".",
"argsort",
"(",
"vocab",
")",
"# indices that sort <vocab>",
"nvocab",
"=",
"len",
"(",
"vocab",
")",
"ndocs",
... | 49.434783 | 32.173913 |
def hincr(self, name, key, amount=1):
"""
Increase the value of ``key`` in hash ``name`` by ``amount``. If no key
exists, the value will be initialized as ``amount``
Like **Redis.HINCR**
:param string name: the hash name
:param string key: the key name
... | [
"def",
"hincr",
"(",
"self",
",",
"name",
",",
"key",
",",
"amount",
"=",
"1",
")",
":",
"amount",
"=",
"get_integer",
"(",
"'amount'",
",",
"amount",
")",
"return",
"self",
".",
"execute_command",
"(",
"'hincr'",
",",
"name",
",",
"key",
",",
"amoun... | 34.5 | 18.333333 |
def run(self):
"""
The body of the tread: read lines and put them on the queue.
"""
try:
for line in iter(self._fd.readline, False):
if line is not None:
if self._althandler:
if self._althandler(line):
... | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"for",
"line",
"in",
"iter",
"(",
"self",
".",
"_fd",
".",
"readline",
",",
"False",
")",
":",
"if",
"line",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_althandler",
":",
"if",
"self",
".",
"_... | 39.444444 | 14.444444 |
def access_array(self, id_, lineno, scope=None, default_type=None):
"""
Called whenever an accessed variable is expected to be an array.
ZX BASIC requires arrays to be declared before usage, so they're
checked.
Also checks for class array.
"""
if not self.check_i... | [
"def",
"access_array",
"(",
"self",
",",
"id_",
",",
"lineno",
",",
"scope",
"=",
"None",
",",
"default_type",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"check_is_declared",
"(",
"id_",
",",
"lineno",
",",
"'array'",
",",
"scope",
")",
":",
"r... | 36.333333 | 24.466667 |
def set_size(self, size):
""" choose a preset size for the plot
:param size: 'small' for documents or 'large' for presentations
"""
if size == 'small':
self._set_size_small()
elif size == 'large':
self._set_size_large()
else:
raise Valu... | [
"def",
"set_size",
"(",
"self",
",",
"size",
")",
":",
"if",
"size",
"==",
"'small'",
":",
"self",
".",
"_set_size_small",
"(",
")",
"elif",
"size",
"==",
"'large'",
":",
"self",
".",
"_set_size_large",
"(",
")",
"else",
":",
"raise",
"ValueError",
"("... | 34.8 | 12.8 |
def status(self, order_id):
'''Checks imagery order status. There can be more than one image per
order and this function returns the status of all images
within the order.
Args:
order_id (str): The id of the order placed.
Returns:
List ... | [
"def",
"status",
"(",
"self",
",",
"order_id",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Get status of order '",
"+",
"order_id",
")",
"url",
"=",
"'%(base_url)s/order/%(order_id)s'",
"%",
"{",
"'base_url'",
":",
"self",
".",
"base_url",
",",
"'o... | 37.05 | 23.25 |
def sort(self, key=None, reverse=False):
"""
Same as Molecule.sort(), also remaps nodes in graph.
:param key:
:param reverse:
:return:
"""
old_molecule = self.molecule.copy()
# sort Molecule
self.molecule._sites = sorted(self.molecule._sites, key... | [
"def",
"sort",
"(",
"self",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"old_molecule",
"=",
"self",
".",
"molecule",
".",
"copy",
"(",
")",
"# sort Molecule",
"self",
".",
"molecule",
".",
"_sites",
"=",
"sorted",
"(",
"self",
"... | 35.25 | 18 |
def a_unexpected_prompt(ctx):
"""Provide message when received humphost prompt."""
prompt = ctx.ctrl.match.group(0)
ctx.msg = "Received the jump host prompt: '{}'".format(prompt)
ctx.device.connected = False
ctx.finished = True
raise ConnectionError("Unable to connect to the device.", ctx.ctrl.h... | [
"def",
"a_unexpected_prompt",
"(",
"ctx",
")",
":",
"prompt",
"=",
"ctx",
".",
"ctrl",
".",
"match",
".",
"group",
"(",
"0",
")",
"ctx",
".",
"msg",
"=",
"\"Received the jump host prompt: '{}'\"",
".",
"format",
"(",
"prompt",
")",
"ctx",
".",
"device",
... | 46 | 15.142857 |
def _set_server_ip(self, v, load=False):
"""
Setter method for server_ip, mapped from YANG variable /nas/server_ip (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_server_ip is considered as a private
method. Backends looking to populate this variable should
... | [
"def",
"_set_server_ip",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base... | 110.909091 | 52.636364 |
def check_format(format, subtype=None, endian=None):
"""Check if the combination of format/subtype/endian is valid.
Examples
--------
>>> import soundfile as sf
>>> sf.check_format('WAV', 'PCM_24')
True
>>> sf.check_format('FLAC', 'VORBIS')
False
"""
try:
return bool(_f... | [
"def",
"check_format",
"(",
"format",
",",
"subtype",
"=",
"None",
",",
"endian",
"=",
"None",
")",
":",
"try",
":",
"return",
"bool",
"(",
"_format_int",
"(",
"format",
",",
"subtype",
",",
"endian",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeEr... | 24.8125 | 18.5 |
def set_default_args(self, default_args):
"""Set default args for commands in collection.
Default args are used when the corresponding args aren't passed
on the command line or in a direct call.
"""
for name, args in default_args.items():
command = self[name]
... | [
"def",
"set_default_args",
"(",
"self",
",",
"default_args",
")",
":",
"for",
"name",
",",
"args",
"in",
"default_args",
".",
"items",
"(",
")",
":",
"command",
"=",
"self",
"[",
"name",
"]",
"command",
".",
"default_args",
"=",
"default_args",
".",
"get... | 37.6 | 16.6 |
def generateTarball(self, file_object):
''' Write a tarball of the current component/target to the file object
"file_object", which must already be open for writing at position 0
'''
archive_name = '%s-%s' % (self.getName(), self.getVersion())
def filterArchive(tarinfo):
... | [
"def",
"generateTarball",
"(",
"self",
",",
"file_object",
")",
":",
"archive_name",
"=",
"'%s-%s'",
"%",
"(",
"self",
".",
"getName",
"(",
")",
",",
"self",
".",
"getVersion",
"(",
")",
")",
"def",
"filterArchive",
"(",
"tarinfo",
")",
":",
"if",
"tar... | 48.111111 | 20 |
def get_sample_contacts_formatted_emails(self, sample):
"""Returns a list with the formatted emails from sample contacts
"""
contacts = list(set([sample.getContact()] + sample.getCCContact()))
return map(self.get_contact_formatted_email, contacts) | [
"def",
"get_sample_contacts_formatted_emails",
"(",
"self",
",",
"sample",
")",
":",
"contacts",
"=",
"list",
"(",
"set",
"(",
"[",
"sample",
".",
"getContact",
"(",
")",
"]",
"+",
"sample",
".",
"getCCContact",
"(",
")",
")",
")",
"return",
"map",
"(",
... | 55 | 14.4 |
def mugshot2to3(old):
"""
Upgrader for L{Mugshot} from version 2 to version 3, which re-thumbnails
the mugshot to take into account the new value of L{Mugshot.smallerSize}.
"""
new = old.upgradeVersion(Mugshot.typeName, 2, 3,
person=old.person,
... | [
"def",
"mugshot2to3",
"(",
"old",
")",
":",
"new",
"=",
"old",
".",
"upgradeVersion",
"(",
"Mugshot",
".",
"typeName",
",",
"2",
",",
"3",
",",
"person",
"=",
"old",
".",
"person",
",",
"type",
"=",
"old",
".",
"type",
",",
"body",
"=",
"old",
".... | 43.076923 | 15.076923 |
def push_fbo(self, fbo, offset, csize):
""" Push an FBO on the stack.
This activates the framebuffer and causes subsequent rendering to be
written to the framebuffer rather than the canvas's back buffer. This
will also set the canvas viewport to cover the boundaries of the
... | [
"def",
"push_fbo",
"(",
"self",
",",
"fbo",
",",
"offset",
",",
"csize",
")",
":",
"self",
".",
"_fb_stack",
".",
"append",
"(",
"(",
"fbo",
",",
"offset",
",",
"csize",
")",
")",
"try",
":",
"fbo",
".",
"activate",
"(",
")",
"h",
",",
"w",
"="... | 34.793103 | 18.586207 |
def invalidate_object(self, address, state = 'stale'):
"""Force cache item state change (to 'worse' state only).
:Parameters:
- `state`: the new state requested.
:Types:
- `state`: `str`"""
self._lock.acquire()
try:
item = self.get_item(addres... | [
"def",
"invalidate_object",
"(",
"self",
",",
"address",
",",
"state",
"=",
"'stale'",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"item",
"=",
"self",
".",
"get_item",
"(",
"address",
")",
"if",
"item",
"and",
"item",
".",
... | 33.0625 | 13.4375 |
def save_to_local(self, callback_etat=print):
"""
Saved current in memory base to local file.
It's a backup, not a convenient way to update datas
:param callback_etat: state callback, taking str,int,int as args
"""
callback_etat("Aquisition...", 0, 3)
d = self.d... | [
"def",
"save_to_local",
"(",
"self",
",",
"callback_etat",
"=",
"print",
")",
":",
"callback_etat",
"(",
"\"Aquisition...\"",
",",
"0",
",",
"3",
")",
"d",
"=",
"self",
".",
"dumps",
"(",
")",
"s",
"=",
"json",
".",
"dumps",
"(",
"d",
",",
"indent",
... | 40.157895 | 14.052632 |
def request_session(token, url=None):
"""
Requests a WebSocket session for the Real-Time Messaging API.
Returns a SessionMetadata object containing the information retrieved from
the API call.
"""
if url is None:
api = SlackApi()
else:
api = SlackApi(url)
response = api.rtm.start(token=token)
return Ses... | [
"def",
"request_session",
"(",
"token",
",",
"url",
"=",
"None",
")",
":",
"if",
"url",
"is",
"None",
":",
"api",
"=",
"SlackApi",
"(",
")",
"else",
":",
"api",
"=",
"SlackApi",
"(",
"url",
")",
"response",
"=",
"api",
".",
"rtm",
".",
"start",
"... | 24.357143 | 19.357143 |
def isHandlerPresent(self, event_name):
"""Check if an event has an handler."""
if event_name not in self.handlers:
raise ValueError('{} is not a valid event'.format(event_name))
return self.handlers[event_name] is not None | [
"def",
"isHandlerPresent",
"(",
"self",
",",
"event_name",
")",
":",
"if",
"event_name",
"not",
"in",
"self",
".",
"handlers",
":",
"raise",
"ValueError",
"(",
"'{} is not a valid event'",
".",
"format",
"(",
"event_name",
")",
")",
"return",
"self",
".",
"h... | 51 | 10 |
def library_pg(args, l, config):
"""Report on the operation of a Postgres Library database"""
import tabulate
import terminaltables
from textwrap import fill
from ambry.util.text import getTerminalSize
import sys
if args.connect:
try:
l.database.connection.execute('SELEC... | [
"def",
"library_pg",
"(",
"args",
",",
"l",
",",
"config",
")",
":",
"import",
"tabulate",
"import",
"terminaltables",
"from",
"textwrap",
"import",
"fill",
"from",
"ambry",
".",
"util",
".",
"text",
"import",
"getTerminalSize",
"import",
"sys",
"if",
"args"... | 32.571429 | 23.178571 |
def _count_fields_recursive(dataset, fields):
"""Cuenta la información de campos optativos/recomendados/requeridos
desde 'fields', y cuenta la ocurrencia de los mismos en 'dataset'.
Args:
dataset (dict): diccionario con claves a ser verificadas.
fields (dict): diccionario con los campos a v... | [
"def",
"_count_fields_recursive",
"(",
"dataset",
",",
"fields",
")",
":",
"key_count",
"=",
"{",
"'recomendado'",
":",
"0",
",",
"'optativo'",
":",
"0",
",",
"'requerido'",
":",
"0",
",",
"'total_optativo'",
":",
"0",
",",
"'total_recomendado'",
":",
"0",
... | 38.425926 | 20.703704 |
def view_cookies(self):
"""
View current cookies in the `requests.Session()` object
**Returns:** List of Dicts, one cookie per Dict.
"""
return_list = []
for cookie in self._session.cookies:
return_list.append(vars(cookie))
return return_list | [
"def",
"view_cookies",
"(",
"self",
")",
":",
"return_list",
"=",
"[",
"]",
"for",
"cookie",
"in",
"self",
".",
"_session",
".",
"cookies",
":",
"return_list",
".",
"append",
"(",
"vars",
"(",
"cookie",
")",
")",
"return",
"return_list"
] | 27.454545 | 15.818182 |
def remove_user(name, profile='github'):
'''
Remove a Github user by name.
name
The user for which to obtain information.
profile
The name of the profile configuration to use. Defaults to ``github``.
CLI Example:
.. code-block:: bash
salt myminion github.remove_user ... | [
"def",
"remove_user",
"(",
"name",
",",
"profile",
"=",
"'github'",
")",
":",
"client",
"=",
"_get_client",
"(",
"profile",
")",
"organization",
"=",
"client",
".",
"get_organization",
"(",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
")",
"t... | 23.28125 | 22.90625 |
def all_faces_with_verts(self, v_indices, as_boolean=False):
'''
returns all of the faces that contain at least one of the vertices in v_indices
'''
import numpy as np
included_vertices = np.zeros(self.v.shape[0], dtype=bool)
included_vertices[np.array(v_indices, dtype=np... | [
"def",
"all_faces_with_verts",
"(",
"self",
",",
"v_indices",
",",
"as_boolean",
"=",
"False",
")",
":",
"import",
"numpy",
"as",
"np",
"included_vertices",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"v",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",... | 45.181818 | 22.454545 |
def _get_stack(self, orchestration_client, stack_name):
"""Get the ID for the current deployed overcloud stack if it exists."""
try:
stack = orchestration_client.stacks.get(stack_name)
self.log.info("Stack found, will be doing a stack update")
return stack
ex... | [
"def",
"_get_stack",
"(",
"self",
",",
"orchestration_client",
",",
"stack_name",
")",
":",
"try",
":",
"stack",
"=",
"orchestration_client",
".",
"stacks",
".",
"get",
"(",
"stack_name",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"Stack found, will be doing... | 44.888889 | 21.888889 |
def fire_hooks(ctx, document, elem, element, hooks):
"""Fire hooks on newly created element.
For each newly created element we will try to find defined hooks and execute them.
:Args:
- ctx (:class:`Context`): Context object
- document (:class:`ooxml.doc.Document`): Document object
- elem... | [
"def",
"fire_hooks",
"(",
"ctx",
",",
"document",
",",
"elem",
",",
"element",
",",
"hooks",
")",
":",
"if",
"not",
"hooks",
":",
"return",
"for",
"hook",
"in",
"hooks",
":",
"hook",
"(",
"ctx",
",",
"document",
",",
"elem",
",",
"element",
")"
] | 31.277778 | 22.055556 |
def host(self):
# pylint: disable=too-many-branches
"""Get a passive checks for an host and its services
This function builds the external commands corresponding to the host and services
provided information
:param host_name: host name
:param data: dictionary of the hos... | [
"def",
"host",
"(",
"self",
")",
":",
"# pylint: disable=too-many-branches",
"logger",
".",
"debug",
"(",
"\"Host status...\"",
")",
"if",
"cherrypy",
".",
"request",
".",
"method",
"not",
"in",
"[",
"\"PATCH\"",
",",
"\"POST\"",
"]",
":",
"cherrypy",
".",
"... | 40.804348 | 21.217391 |
def pad(text, bits=32):
"""
Pads the inputted text to ensure it fits the proper block length
for encryption.
:param text | <str>
bits | <int>
:return <str>
"""
return text + (bits - len(text) % bits) * chr(bits - len(text) % bits) | [
"def",
"pad",
"(",
"text",
",",
"bits",
"=",
"32",
")",
":",
"return",
"text",
"+",
"(",
"bits",
"-",
"len",
"(",
"text",
")",
"%",
"bits",
")",
"*",
"chr",
"(",
"bits",
"-",
"len",
"(",
"text",
")",
"%",
"bits",
")"
] | 25.727273 | 19.545455 |
def apply(self, func, *args, **kwargs):
"""Apply the provided function and combine the results together in the
same way as apply from groupby in pandas.
This returns a DataFrame.
"""
self._prep_pandas_groupby()
def key_by_index(data):
"""Key each row by its ... | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_prep_pandas_groupby",
"(",
")",
"def",
"key_by_index",
"(",
"data",
")",
":",
"\"\"\"Key each row by its index.\n \"\"\"",
"# TODO: Is there ... | 39.88 | 13.44 |
def create_ecdsa_public_and_private_from_pem(pem, password=None):
"""
<Purpose>
Create public and private ECDSA keys from a private 'pem'. The public and
private keys are strings in PEM format:
public: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----',
private: '-----BEGIN EC PRIVATE KEY--... | [
"def",
"create_ecdsa_public_and_private_from_pem",
"(",
"pem",
",",
"password",
"=",
"None",
")",
":",
"# Does 'pem' have the correct format?",
"# This check will ensure 'pem' conforms to",
"# 'securesystemslib.formats.ECDSARSA_SCHEMA'.",
"securesystemslib",
".",
"formats",
".",
"P... | 36 | 27.176471 |
def cross_lists(*sets):
"""Return the cross product of the arguments"""
wheels = [iter(_) for _ in sets]
digits = [next(it) for it in wheels]
while True:
yield digits[:]
for i in range(len(digits)-1, -1, -1):
try:
digits[i] = next(wheels[i])
br... | [
"def",
"cross_lists",
"(",
"*",
"sets",
")",
":",
"wheels",
"=",
"[",
"iter",
"(",
"_",
")",
"for",
"_",
"in",
"sets",
"]",
"digits",
"=",
"[",
"next",
"(",
"it",
")",
"for",
"it",
"in",
"wheels",
"]",
"while",
"True",
":",
"yield",
"digits",
"... | 30.733333 | 11.733333 |
def get_global_parameters(config_names=("core", "scheduler", "worker", "retcode")):
"""
Returns a list of global, luigi-internal configuration parameters. Each list item is a 4-tuple
containing the configuration class, the parameter instance, the parameter name, and the full
parameter name in the cli. W... | [
"def",
"get_global_parameters",
"(",
"config_names",
"=",
"(",
"\"core\"",
",",
"\"scheduler\"",
",",
"\"worker\"",
",",
"\"retcode\"",
")",
")",
":",
"params",
"=",
"[",
"]",
"for",
"cls",
"in",
"luigi",
".",
"task",
".",
"Config",
".",
"__subclasses__",
... | 41.416667 | 25.583333 |
def exe_cmd(*cmds):
"""Executes commands in a new shell. Directing stderr to PIPE.
This is fastboot's own exe_cmd because of its peculiar way of writing
non-error info to stderr.
Args:
cmds: A sequence of commands and arguments.
Returns:
The output of the command run.
Raises:... | [
"def",
"exe_cmd",
"(",
"*",
"cmds",
")",
":",
"cmd",
"=",
"' '",
".",
"join",
"(",
"cmds",
")",
"proc",
"=",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"shell",
"=",
"True",
")",
"(",
"out",
",",
"err",
... | 26 | 22.142857 |
def getvalue(x):
"""Return the single value of x or raise TypError if more than one value."""
if isrepeating(x):
raise TypeError(
"Ambiguous call to getvalue for %r which has more than one value."
% x)
for value in getvalues(x):
return value | [
"def",
"getvalue",
"(",
"x",
")",
":",
"if",
"isrepeating",
"(",
"x",
")",
":",
"raise",
"TypeError",
"(",
"\"Ambiguous call to getvalue for %r which has more than one value.\"",
"%",
"x",
")",
"for",
"value",
"in",
"getvalues",
"(",
"x",
")",
":",
"return",
"... | 31.777778 | 21.111111 |
def _get_codename(self, pathname, basename):
"""Return (filename, archivename) for the path.
Given a module name path, return the correct file path and
archive name, compiling if necessary. For example, given
/python/lib/string, return (/python/lib/string.pyc, string).
"""
... | [
"def",
"_get_codename",
"(",
"self",
",",
"pathname",
",",
"basename",
")",
":",
"file_py",
"=",
"pathname",
"+",
"\".py\"",
"file_pyc",
"=",
"pathname",
"+",
"\".pyc\"",
"file_pyo",
"=",
"pathname",
"+",
"\".pyo\"",
"if",
"os",
".",
"path",
".",
"isfile",... | 41.068966 | 14.517241 |
def complete_abstract_value(
exe_context, # type: ExecutionContext
return_type, # type: Union[GraphQLInterfaceType, GraphQLUnionType]
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Dict[str, Any]
... | [
"def",
"complete_abstract_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: Union[GraphQLInterfaceType, GraphQLUnionType]",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, st... | 37.085106 | 24.06383 |
def unicode_from_html(content):
"""Attempts to decode an HTML string into unicode.
If unsuccessful, the original content is returned.
"""
encodings = get_encodings_from_content(content)
for encoding in encodings:
try:
return unicode(content, encoding)
except (UnicodeEr... | [
"def",
"unicode_from_html",
"(",
"content",
")",
":",
"encodings",
"=",
"get_encodings_from_content",
"(",
"content",
")",
"for",
"encoding",
"in",
"encodings",
":",
"try",
":",
"return",
"unicode",
"(",
"content",
",",
"encoding",
")",
"except",
"(",
"Unicode... | 24.2 | 18.666667 |
def declare_example(self, source):
"""Execute the given code, adding it to the runner's namespace."""
with patch_modules():
code = compile(source, "<docs>", "exec")
exec(code, self.namespace) | [
"def",
"declare_example",
"(",
"self",
",",
"source",
")",
":",
"with",
"patch_modules",
"(",
")",
":",
"code",
"=",
"compile",
"(",
"source",
",",
"\"<docs>\"",
",",
"\"exec\"",
")",
"exec",
"(",
"code",
",",
"self",
".",
"namespace",
")"
] | 45.4 | 6.2 |
def _get_library_metadata(self, date_range):
"""
Retrieve the libraries for the given date range, the assumption is that the date ranges do not overlap and
they are CLOSED_CLOSED.
At the moment the date range is mandatory
"""
if date_range is None:
raise Exce... | [
"def",
"_get_library_metadata",
"(",
"self",
",",
"date_range",
")",
":",
"if",
"date_range",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"A date range must be provided\"",
")",
"if",
"not",
"(",
"date_range",
".",
"start",
"and",
"date_range",
".",
"end",
... | 50.852941 | 32.029412 |
def invoke_consumer(self, message):
"""Wrap the actual processor processing bits
:param rejected.data.Message message: The message to process
"""
# Only allow for a single message to be processed at a time
with (yield self.consumer_lock.acquire()):
if self.is_idle:
... | [
"def",
"invoke_consumer",
"(",
"self",
",",
"message",
")",
":",
"# Only allow for a single message to be processed at a time",
"with",
"(",
"yield",
"self",
".",
"consumer_lock",
".",
"acquire",
"(",
")",
")",
":",
"if",
"self",
".",
"is_idle",
":",
"if",
"mess... | 46.614035 | 19.824561 |
def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2
"""Read headers from a Python 2 httplib message object."""
ret = cls(message.items())
# ret now contains only the last header line for each duplicate.
# Importing with all duplicates would be nice, but this would
... | [
"def",
"from_httplib",
"(",
"cls",
",",
"message",
",",
"duplicates",
"=",
"(",
"'set-cookie'",
",",
")",
")",
":",
"# Python 2",
"ret",
"=",
"cls",
"(",
"message",
".",
"items",
"(",
")",
")",
"# ret now contains only the last header line for each duplicate.",
... | 50.714286 | 19.142857 |
def base64_decode(nb):
"""Restore all bytes objects in the notebook from base64-encoded strings.
Note: This is never used
"""
for ws in nb.worksheets:
for cell in ws.cells:
if cell.cell_type == 'code':
for output in cell.outputs:
if 'png' in o... | [
"def",
"base64_decode",
"(",
"nb",
")",
":",
"for",
"ws",
"in",
"nb",
".",
"worksheets",
":",
"for",
"cell",
"in",
"ws",
".",
"cells",
":",
"if",
"cell",
".",
"cell_type",
"==",
"'code'",
":",
"for",
"output",
"in",
"cell",
".",
"outputs",
":",
"if... | 41.611111 | 14.388889 |
def get_title(self):
"""Default title for plot
"""
def fformat(x): # float format
if isinstance(x, (list, tuple)):
return '[{0}]'.format(', '.join(map(fformat, x)))
if isinstance(x, Quantity):
x = x.value
elif isinstance(x, str... | [
"def",
"get_title",
"(",
"self",
")",
":",
"def",
"fformat",
"(",
"x",
")",
":",
"# float format",
"if",
"isinstance",
"(",
"x",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"'[{0}]'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"map"... | 42.892857 | 14.678571 |
def load_chunk(filename, bounds, encoding='utf8', slow=False):
"""
Load a chunk from file using Bounds info.
Pass 'slow=True' for an alternative loading method based on line numbers.
"""
if slow:
return _load_chunk_slow(filename, bounds, encoding)
with open(filename, 'rb') as f:
... | [
"def",
"load_chunk",
"(",
"filename",
",",
"bounds",
",",
"encoding",
"=",
"'utf8'",
",",
"slow",
"=",
"False",
")",
":",
"if",
"slow",
":",
"return",
"_load_chunk_slow",
"(",
"filename",
",",
"bounds",
",",
"encoding",
")",
"with",
"open",
"(",
"filenam... | 35.916667 | 14.75 |
def start(st_reg_number):
"""Checks the number valiaty for the Acre state"""
#st_reg_number = str(st_reg_number)
weights = [4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
digits = st_reg_number[:len(st_reg_number) - 2]
check_digits = st_reg_number[-2:]
divisor = 11
if len(st_reg_number) > 13:
re... | [
"def",
"start",
"(",
"st_reg_number",
")",
":",
"#st_reg_number = str(st_reg_number)",
"weights",
"=",
"[",
"4",
",",
"3",
",",
"2",
",",
"9",
",",
"8",
",",
"7",
",",
"6",
",",
"5",
",",
"4",
",",
"3",
",",
"2",
"]",
"digits",
"=",
"st_reg_number"... | 26.384615 | 19.051282 |
def get_values(text):
"""
Accept a string such as BACKGROUNDCOLOR [r] [g] [b]
and return ['r', 'g', 'b']
"""
res = re.findall(r"\[(.*?)\]", text)
values = []
for r in res:
if "|" in r:
params = r.split("|")
for p in params:
values.append(p)
... | [
"def",
"get_values",
"(",
"text",
")",
":",
"res",
"=",
"re",
".",
"findall",
"(",
"r\"\\[(.*?)\\]\"",
",",
"text",
")",
"values",
"=",
"[",
"]",
"for",
"r",
"in",
"res",
":",
"if",
"\"|\"",
"in",
"r",
":",
"params",
"=",
"r",
".",
"split",
"(",
... | 20.4 | 18.3 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkersRealTimeStatisticsContext for this WorkersRealTimeStatisticsInstance
:rtype: twilio.rest.t... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"WorkersRealTimeStatisticsContext",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_si... | 45.928571 | 27.071429 |
def _create_rates(self, dist='uniform', size=None, eps=1e-4):
'''Create a rate parameter (usually for a recurrent network layer).
Parameters
----------
dist : {'uniform', 'log'}, optional
Distribution of rate values. Defaults to ``'uniform'``.
size : int, optional
... | [
"def",
"_create_rates",
"(",
"self",
",",
"dist",
"=",
"'uniform'",
",",
"size",
"=",
"None",
",",
"eps",
"=",
"1e-4",
")",
":",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"self",
".",
"output_size",
"if",
"dist",
"==",
"'uniform'",
":",
"z",
"=... | 40.111111 | 22.925926 |
def store_records_for_package(self, entry_point, records):
"""
Store the records in a way that permit lookup by package
"""
# If provided records already exist in the module mapping list,
# it likely means that a package declared multiple keys for the
# same package name... | [
"def",
"store_records_for_package",
"(",
"self",
",",
"entry_point",
",",
"records",
")",
":",
"# If provided records already exist in the module mapping list,",
"# it likely means that a package declared multiple keys for the",
"# same package namespace; while normally this does not happen,... | 48.166667 | 20.5 |
def _event_monitor_loop(region_name, vpc_id,
watcher_plugin, health_plugin,
iterations, sleep_time,
route_check_time_interval=30):
"""
Monitor queues to receive updates about new route specs or any detected
failed IPs.
If any of th... | [
"def",
"_event_monitor_loop",
"(",
"region_name",
",",
"vpc_id",
",",
"watcher_plugin",
",",
"health_plugin",
",",
"iterations",
",",
"sleep_time",
",",
"route_check_time_interval",
"=",
"30",
")",
":",
"q_route_spec",
"=",
"watcher_plugin",
".",
"get_route_spec_queue... | 48.038835 | 25.203883 |
def hold_time(self, datetime=None):
"""持仓时间
Keyword Arguments:
datetime {[type]} -- [description] (default: {None})
"""
def weights(x):
if sum(x['amount']) != 0:
return pd.Timestamp(self.datetime
) - pd.to_datet... | [
"def",
"hold_time",
"(",
"self",
",",
"datetime",
"=",
"None",
")",
":",
"def",
"weights",
"(",
"x",
")",
":",
"if",
"sum",
"(",
"x",
"[",
"'amount'",
"]",
")",
"!=",
"0",
":",
"return",
"pd",
".",
"Timestamp",
"(",
"self",
".",
"datetime",
")",
... | 33.2 | 18.24 |
def get_sync_binding_cmds(self, switch_bindings, expected_bindings):
"""Returns the list of commands required to synchronize ACL bindings
1. Delete any unexpected bindings
2. Add any missing bindings
"""
switch_cmds = list()
# Update any necessary switch interface ACLs
... | [
"def",
"get_sync_binding_cmds",
"(",
"self",
",",
"switch_bindings",
",",
"expected_bindings",
")",
":",
"switch_cmds",
"=",
"list",
"(",
")",
"# Update any necessary switch interface ACLs",
"bindings_to_delete",
"=",
"switch_bindings",
"-",
"expected_bindings",
"bindings_t... | 44.809524 | 15.047619 |
def get_buy(self, buy_id, **params):
"""https://developers.coinbase.com/api/v2#show-a-buy"""
return self.api_client.get_buy(self.id, buy_id, **params) | [
"def",
"get_buy",
"(",
"self",
",",
"buy_id",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"api_client",
".",
"get_buy",
"(",
"self",
".",
"id",
",",
"buy_id",
",",
"*",
"*",
"params",
")"
] | 54.666667 | 9.666667 |
def document_examples(p):
"""
Document example programs with purpose (and intent)
"""
p.comment('maths_ml_algorithms.py', 'machine learning algorithms for toolbox in AIKIF')
p.comment('algebra.py', 'toolbox module for based evaluation of maths problems')
p.comment('crypt_utils.py', 'scripts to e... | [
"def",
"document_examples",
"(",
"p",
")",
":",
"p",
".",
"comment",
"(",
"'maths_ml_algorithms.py'",
",",
"'machine learning algorithms for toolbox in AIKIF'",
")",
"p",
".",
"comment",
"(",
"'algebra.py'",
",",
"'toolbox module for based evaluation of maths problems'",
")... | 75.1 | 40.9 |
def install_node_modules(path=None, build_dir=None, source_dir=None, build_cmd='build', force=False):
"""Return a Command for managing an node_modules installation.
Note: The command is skipped if the `--skip-yarn` flag is used.
Parameters
----------
path: str, optional
The base path of... | [
"def",
"install_node_modules",
"(",
"path",
"=",
"None",
",",
"build_dir",
"=",
"None",
",",
"source_dir",
"=",
"None",
",",
"build_cmd",
"=",
"'build'",
",",
"force",
"=",
"False",
")",
":",
"class",
"Yarn",
"(",
"BaseCommand",
")",
":",
"description",
... | 40.767442 | 22.325581 |
def bootstrap(force=False):
'''
Download and install the latest version of the Chocolatey package manager
via the official bootstrap.
Chocolatey requires Windows PowerShell and the .NET v4.0 runtime. Depending
on the host's version of Windows, chocolatey.bootstrap will attempt to
ensure these p... | [
"def",
"bootstrap",
"(",
"force",
"=",
"False",
")",
":",
"# Check if Chocolatey is already present in the path",
"try",
":",
"choc_path",
"=",
"_find_chocolatey",
"(",
"__context__",
",",
"__salt__",
")",
"except",
"CommandExecutionError",
":",
"choc_path",
"=",
"Non... | 43.531915 | 26.765957 |
def distance_similarity(a, b, p, T=CLOSE_DISTANCE_THRESHOLD):
"""Computes the distance similarity between a line segment
and a point
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. P... | [
"def",
"distance_similarity",
"(",
"a",
",",
"b",
",",
"p",
",",
"T",
"=",
"CLOSE_DISTANCE_THRESHOLD",
")",
":",
"d",
"=",
"distance_to_line",
"(",
"a",
",",
"b",
",",
"p",
")",
"r",
"=",
"(",
"-",
"1",
"/",
"float",
"(",
"T",
")",
")",
"*",
"a... | 36 | 21.933333 |
def _compute_distance_fast(self):
"""Calls edit_distance, and asserts that if we already have values for
matches and distance, that they match."""
d, m = edit_distance(self.seq1, self.seq2,
action_function=self.action_function,
test=self.... | [
"def",
"_compute_distance_fast",
"(",
"self",
")",
":",
"d",
",",
"m",
"=",
"edit_distance",
"(",
"self",
".",
"seq1",
",",
"self",
".",
"seq2",
",",
"action_function",
"=",
"self",
".",
"action_function",
",",
"test",
"=",
"self",
".",
"test",
")",
"i... | 40.166667 | 10.416667 |
def click_on_pat(pat: str, mousebutton: int=1, offset: (float, float)=None, tolerance: int=0, restore_pos: bool=False) -> None:
"""
Requires imagemagick, xautomation, xwd.
Click on a pattern at a specified offset (x,y) in percent of the pattern dimension. x is the horizontal distance from the top left corne... | [
"def",
"click_on_pat",
"(",
"pat",
":",
"str",
",",
"mousebutton",
":",
"int",
"=",
"1",
",",
"offset",
":",
"(",
"float",
",",
"float",
")",
"=",
"None",
",",
"tolerance",
":",
"int",
"=",
"0",
",",
"restore_pos",
":",
"bool",
"=",
"False",
")",
... | 69.875 | 42 |
def load_module(full_path):
"""
Load module from full path
Args:
full_path: module full path name
Returns:
python module
References:
https://stackoverflow.com/a/67692/1332656
Examples:
>>> import os
>>>
>>> cur_file = os.path.abspath(__file__).repl... | [
"def",
"load_module",
"(",
"full_path",
")",
":",
"from",
"importlib",
"import",
"util",
"file_name",
"=",
"full_path",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"if",
"file_name",
"[",
"-",
"3... | 31.34375 | 17.96875 |
def with_random_weights(cls, options):
"""
Initialize from a list of options with random weights.
The weights assigned to each object are uniformally random
integers between ``1`` and ``len(options)``
Args:
options (list): The list of options of any type this object... | [
"def",
"with_random_weights",
"(",
"cls",
",",
"options",
")",
":",
"return",
"cls",
"(",
"[",
"(",
"value",
",",
"random",
".",
"randint",
"(",
"1",
",",
"len",
"(",
"options",
")",
")",
")",
"for",
"value",
"in",
"options",
"]",
")"
] | 34.1875 | 19.4375 |
def solution_path(self, min_lambda, max_lambda, lambda_bins, verbose=0):
'''Follows the solution path to find the best lambda value.'''
self.u = np.zeros(self.Dk.shape[0], dtype='double')
lambda_grid = np.exp(np.linspace(np.log(max_lambda), np.log(min_lambda), lambda_bins))
aic_trace = n... | [
"def",
"solution_path",
"(",
"self",
",",
"min_lambda",
",",
"max_lambda",
",",
"lambda_bins",
",",
"verbose",
"=",
"0",
")",
":",
"self",
".",
"u",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"Dk",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
... | 47.84 | 28.666667 |
def cumulative_distribution(self, X):
"""Computes the cumulative distribution function for the copula, :math:`C(u, v)`
Args:
X: `np.ndarray`
Returns:
np.array: cumulative probability
"""
self.check_fit()
U, V = self.split_matrix(X)
if (... | [
"def",
"cumulative_distribution",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"U",
",",
"V",
"=",
"self",
".",
"split_matrix",
"(",
"X",
")",
"if",
"(",
"V",
"==",
"0",
")",
".",
"all",
"(",
")",
"or",
"(",
"U",
"==",
... | 26.888889 | 19.222222 |
def _to_linear(M, N, L, q):
"Converts a qubit in chimera coordinates to its linear index."
(x, y, u, k) = q
return 2 * L * N * x + 2 * L * y + L * u + k | [
"def",
"_to_linear",
"(",
"M",
",",
"N",
",",
"L",
",",
"q",
")",
":",
"(",
"x",
",",
"y",
",",
"u",
",",
"k",
")",
"=",
"q",
"return",
"2",
"*",
"L",
"*",
"N",
"*",
"x",
"+",
"2",
"*",
"L",
"*",
"y",
"+",
"L",
"*",
"u",
"+",
"k"
] | 40.25 | 16.75 |
def fields_metadata(self):
"""
Returns fields metadata as a dataframe.
"""
return (pd.concat([f.metadata() for f in self.fields], axis = 1)
.transpose()
.sort_values(["step_num", "frame", "label", "position"])) | [
"def",
"fields_metadata",
"(",
"self",
")",
":",
"return",
"(",
"pd",
".",
"concat",
"(",
"[",
"f",
".",
"metadata",
"(",
")",
"for",
"f",
"in",
"self",
".",
"fields",
"]",
",",
"axis",
"=",
"1",
")",
".",
"transpose",
"(",
")",
".",
"sort_values... | 35.142857 | 12.857143 |
def normalize(expr):
"""No elimination, but normalize arguments."""
args = [normalize(arg) for arg in expr.args]
return type(expr)(expr.func, *args, start=expr.start, end=expr.end) | [
"def",
"normalize",
"(",
"expr",
")",
":",
"args",
"=",
"[",
"normalize",
"(",
"arg",
")",
"for",
"arg",
"in",
"expr",
".",
"args",
"]",
"return",
"type",
"(",
"expr",
")",
"(",
"expr",
".",
"func",
",",
"*",
"args",
",",
"start",
"=",
"expr",
... | 37.8 | 19.8 |
def resource_created_response(resource):
"""Return HTTP response with status code *201*, signaling a created
*resource*
:param resource: resource created as a result of current request
:type resource: :class:`sandman.model.Model`
:rtype: :class:`flask.Response`
"""
if _get_acceptable_respo... | [
"def",
"resource_created_response",
"(",
"resource",
")",
":",
"if",
"_get_acceptable_response_type",
"(",
")",
"==",
"JSON",
":",
"response",
"=",
"_single_resource_json_response",
"(",
"resource",
")",
"else",
":",
"response",
"=",
"_single_resource_html_response",
... | 35.705882 | 17.117647 |
def insert(self, row, ensure=None, types=None):
"""Add a ``row`` dict by inserting it into the table.
If ``ensure`` is set, any of the keys of the row are not
table columns, they will be created automatically.
During column creation, ``types`` will be checked for a key
matching... | [
"def",
"insert",
"(",
"self",
",",
"row",
",",
"ensure",
"=",
"None",
",",
"types",
"=",
"None",
")",
":",
"row",
"=",
"self",
".",
"_sync_columns",
"(",
"row",
",",
"ensure",
",",
"types",
"=",
"types",
")",
"res",
"=",
"self",
".",
"db",
".",
... | 38.565217 | 20.391304 |
def conditional_jit(function=None, **kwargs): # noqa: D202
"""Use numba's jit decorator if numba is installed.
Notes
-----
If called without arguments then return wrapped function.
@conditional_jit
def my_func():
return
else called with arguments
@co... | [
"def",
"conditional_jit",
"(",
"function",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: D202",
"def",
"wrapper",
"(",
"function",
")",
":",
"try",
":",
"numba",
"=",
"importlib",
".",
"import_module",
"(",
"\"numba\"",
")",
"return",
"numba",
... | 21.064516 | 22.548387 |
def parse(readDataInstance):
"""
Returns a new L{ImageBoundImportDescriptorEntry} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object containing data to create a new L{ImageBoundImportDescriptorEntry}.
@rtype: L{ImageBoundIm... | [
"def",
"parse",
"(",
"readDataInstance",
")",
":",
"boundEntry",
"=",
"ImageBoundImportDescriptorEntry",
"(",
")",
"boundEntry",
".",
"timeDateStamp",
".",
"value",
"=",
"readDataInstance",
".",
"readDword",
"(",
")",
"boundEntry",
".",
"offsetModuleName",
".",
"v... | 50.954545 | 27.318182 |
def _copy_replace(src, dst, replacements):
"""Copies the src file into dst applying the replacements dict"""
with src.open() as infile, dst.open('w') as outfile:
outfile.write(re.sub(
'|'.join(re.escape(k) for k in replacements),
lambda m: str(replacements[m.group(0)]),
... | [
"def",
"_copy_replace",
"(",
"src",
",",
"dst",
",",
"replacements",
")",
":",
"with",
"src",
".",
"open",
"(",
")",
"as",
"infile",
",",
"dst",
".",
"open",
"(",
"'w'",
")",
"as",
"outfile",
":",
"outfile",
".",
"write",
"(",
"re",
".",
"sub",
"... | 42.5 | 12.875 |
def get_child_value(parent, name, allow_missing=0):
""" return the value of the child element with name in the parent Element """
if not parent.HasElement(name):
if allow_missing:
return np.nan
else:
raise Exception('failed to find child element %s... | [
"def",
"get_child_value",
"(",
"parent",
",",
"name",
",",
"allow_missing",
"=",
"0",
")",
":",
"if",
"not",
"parent",
".",
"HasElement",
"(",
"name",
")",
":",
"if",
"allow_missing",
":",
"return",
"np",
".",
"nan",
"else",
":",
"raise",
"Exception",
... | 45.333333 | 16.555556 |
def scale(text="", value=0, min=0 ,max=100, step=1, draw_value=True, title="",
width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, timeout=None):
"""
Select a number with a range widget
:param text: text inside window
:type text: str
:param value: current value
:type value: int
:param min... | [
"def",
"scale",
"(",
"text",
"=",
"\"\"",
",",
"value",
"=",
"0",
",",
"min",
"=",
"0",
",",
"max",
"=",
"100",
",",
"step",
"=",
"1",
",",
"draw_value",
"=",
"True",
",",
"title",
"=",
"\"\"",
",",
"width",
"=",
"DEFAULT_WIDTH",
",",
"height",
... | 30.34375 | 14.84375 |
def calc_v_qa_v1(self):
"""Update the stored water volume based on the equation of continuity.
Note that for too high outflow values, which would result in overdraining
the lake, the outflow is trimmed.
Required derived parameters:
|Seconds|
|NmbSubsteps|
Required flux sequence:
... | [
"def",
"calc_v_qa_v1",
"(",
"self",
")",
":",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"aid",
"=",
"self",
".",
"sequences",
".",
"aides",
".",
"fa... | 28.848485 | 20.984848 |
def _extract_options(orig_script):
"""
Extract any options from the first line of the script.
"""
first = (orig_script + '\n').splitlines()[0]
match = _first_line_re().match(first)
options = match.group(1) or '' if match else ''
return options.strip() | [
"def",
"_extract_options",
"(",
"orig_script",
")",
":",
"first",
"=",
"(",
"orig_script",
"+",
"'\\n'",
")",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
"match",
"=",
"_first_line_re",
"(",
")",
".",
"match",
"(",
"first",
")",
"options",
"=",
"match"... | 37.5 | 8.75 |
def step(g, n1, n2, inbound=False, backward=False, continue_fn=None):
"""
Step along a path through a directed graph unless there is an intersection
Example graph:
Note that edge (1, 2) and (2, 3) are bidirectional, i.e., (2, 1) and
(3, 2) are also edges
1 -- 2 -- 3 -->-- 5 -->-- 7
... | [
"def",
"step",
"(",
"g",
",",
"n1",
",",
"n2",
",",
"inbound",
"=",
"False",
",",
"backward",
"=",
"False",
",",
"continue_fn",
"=",
"None",
")",
":",
"forw",
"=",
"g",
".",
"successors",
"back",
"=",
"g",
".",
"predecessors",
"if",
"backward",
":"... | 25.051948 | 22.220779 |
def get_items(self, project=None, scope_path=None, recursion_level=None, include_links=None, version_descriptor=None):
"""GetItems.
Get a list of Tfvc items
:param str project: Project ID or project name
:param str scope_path: Version control path of a folder to return multiple items.
... | [
"def",
"get_items",
"(",
"self",
",",
"project",
"=",
"None",
",",
"scope_path",
"=",
"None",
",",
"recursion_level",
"=",
"None",
",",
"include_links",
"=",
"None",
",",
"version_descriptor",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"... | 63.666667 | 29.212121 |
def _parse(self, content):
"""
Parse data request to data from python.
@param content: Context of request.
@raise ParseError:
"""
if content:
stream = BytesIO(str(content))
data = json.loads(stream.getvalue())
return dat... | [
"def",
"_parse",
"(",
"self",
",",
"content",
")",
":",
"if",
"content",
":",
"stream",
"=",
"BytesIO",
"(",
"str",
"(",
"content",
")",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"stream",
".",
"getvalue",
"(",
")",
")",
"return",
"data"
] | 22 | 17.857143 |
def query_segdb(cls, flag, *args, **kwargs):
"""Query the initial LIGO segment database for the given flag
Parameters
----------
flag : `str`
The name of the flag for which to query
*args
Either, two `float`-like numbers indicating the
GPS [s... | [
"def",
"query_segdb",
"(",
"cls",
",",
"flag",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"query_segdb is deprecated and will be removed in a \"",
"\"future release\"",
",",
"DeprecationWarning",
")",
"# parse arguments",
"q... | 37 | 20.659574 |
async def dispatch(self, request, view=None, **kwargs):
"""Dispatch request."""
if view is None and request.method not in self.methods:
raise HTTPMethodNotAllowed(request.method, self.methods)
method = getattr(self, view or request.method.lower())
response = await method(req... | [
"async",
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"view",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"view",
"is",
"None",
"and",
"request",
".",
"method",
"not",
"in",
"self",
".",
"methods",
":",
"raise",
"HTTPMethodNotAllowed"... | 48.375 | 19.5 |
def iter_xCharts(self):
"""
Generate each xChart child element in document.
"""
plot_tags = (
qn('c:area3DChart'), qn('c:areaChart'), qn('c:bar3DChart'),
qn('c:barChart'), qn('c:bubbleChart'), qn('c:doughnutChart'),
qn('c:line3DChart'), qn('c:lineChart... | [
"def",
"iter_xCharts",
"(",
"self",
")",
":",
"plot_tags",
"=",
"(",
"qn",
"(",
"'c:area3DChart'",
")",
",",
"qn",
"(",
"'c:areaChart'",
")",
",",
"qn",
"(",
"'c:bar3DChart'",
")",
",",
"qn",
"(",
"'c:barChart'",
")",
",",
"qn",
"(",
"'c:bubbleChart'",
... | 38.411765 | 19.235294 |
def get_tokens(line: str) -> Iterator[str]:
"""
Yields tokens from input string.
:param line: Input string.
:return: Iterator over tokens.
"""
for token in line.rstrip().split():
if len(token) > 0:
yield token | [
"def",
"get_tokens",
"(",
"line",
":",
"str",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"for",
"token",
"in",
"line",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
")",
":",
"if",
"len",
"(",
"token",
")",
">",
"0",
":",
"yield",
"token"
] | 24.5 | 9.5 |
def get_log_file_from_item(history):
"""
Return the log file based on provided history item.
Description is optional.
"""
try:
log_file, description = shlex.split(history)
except ValueError:
log_file = history.strip()
return log_file | [
"def",
"get_log_file_from_item",
"(",
"history",
")",
":",
"try",
":",
"log_file",
",",
"description",
"=",
"shlex",
".",
"split",
"(",
"history",
")",
"except",
"ValueError",
":",
"log_file",
"=",
"history",
".",
"strip",
"(",
")",
"return",
"log_file"
] | 22.333333 | 16.666667 |
def addVars(filename, varNamesStr, outOf=None):
r"""Like `saveVars`, but appends additional variables to file."""
filename, varnames, outOf = __saveVarsHelper(filename, varNamesStr, outOf)
f = None
try:
f = open(filename, "rb")
h = cPickle.load(f)
f.close()
h.update(dict... | [
"def",
"addVars",
"(",
"filename",
",",
"varNamesStr",
",",
"outOf",
"=",
"None",
")",
":",
"filename",
",",
"varnames",
",",
"outOf",
"=",
"__saveVarsHelper",
"(",
"filename",
",",
"varNamesStr",
",",
"outOf",
")",
"f",
"=",
"None",
"try",
":",
"f",
"... | 32.428571 | 19.642857 |
def map_grounding():
"""Map grounding on a list of INDRA Statements."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
stmts_json = body.get('statements')
stmts = stmts_from_json(stmts_json)
stmts_out = ac.map_grou... | [
"def",
"map_grounding",
"(",
")",
":",
"if",
"request",
".",
"method",
"==",
"'OPTIONS'",
":",
"return",
"{",
"}",
"response",
"=",
"request",
".",
"body",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"body",
"=",
"json",
".",
"loads",
... | 35.9 | 7.5 |
def traverse_next(page, nextx, results, tabular_data_headers=[], verbosity=0):
"""
Recursive generator to traverse through the next attribute and \
crawl through the links to be followed.
:param page: The current page being parsed
:param next: The next attribute of the current scraping dict
:pa... | [
"def",
"traverse_next",
"(",
"page",
",",
"nextx",
",",
"results",
",",
"tabular_data_headers",
"=",
"[",
"]",
",",
"verbosity",
"=",
"0",
")",
":",
"for",
"link",
"in",
"page",
".",
"extract_links",
"(",
"selector",
"=",
"nextx",
"[",
"'follow_link'",
"... | 45.205128 | 19.923077 |
def haversine(lat1, lon1, lat2, lon2):
"""
compute the distance in meters between two points in latlon
Parameters
----------
lat1: int or float
the latitude of point 1
lon1: int or float
the longitude of point 1
lat2: int or float
the latitude of point 2
lon2: in... | [
"def",
"haversine",
"(",
"lat1",
",",
"lon1",
",",
"lat2",
",",
"lon2",
")",
":",
"radius",
"=",
"6371000",
"lat1",
",",
"lon1",
",",
"lat2",
",",
"lon2",
"=",
"map",
"(",
"math",
".",
"radians",
",",
"[",
"lat1",
",",
"lon1",
",",
"lat2",
",",
... | 27.038462 | 21.346154 |
def lyricsmode(song):
"""
Returns the lyrics found in lyricsmode.com for the specified mp3 file or an
empty string if not found.
"""
translate = {
URLESCAPE: '',
' ': '_'
}
artist = song.artist.lower()
artist = normalize(artist, translate)
title = song.title.lower()
... | [
"def",
"lyricsmode",
"(",
"song",
")",
":",
"translate",
"=",
"{",
"URLESCAPE",
":",
"''",
",",
"' '",
":",
"'_'",
"}",
"artist",
"=",
"song",
".",
"artist",
".",
"lower",
"(",
")",
"artist",
"=",
"normalize",
"(",
"artist",
",",
"translate",
")",
... | 25.548387 | 16.580645 |
async def fetch_room(self, room_id):
"""Lookup details for a given room id"""
url = "https://production.plum.technology/v2/getRoom"
data = {"rid": room_id}
return await self.__post(url, data) | [
"async",
"def",
"fetch_room",
"(",
"self",
",",
"room_id",
")",
":",
"url",
"=",
"\"https://production.plum.technology/v2/getRoom\"",
"data",
"=",
"{",
"\"rid\"",
":",
"room_id",
"}",
"return",
"await",
"self",
".",
"__post",
"(",
"url",
",",
"data",
")"
] | 43.8 | 7.4 |
def act(self, *args, **kwargs):
"""gather a rules parameters together and run the predicate. If that
returns True, then go on and run the action function
returns:
a tuple indicating the results of applying the predicate and the
action function:
(False, Non... | [
"def",
"act",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"predicate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"bool_result",
"=",
"self",
".",
"action",
"(",
"*",
"args",
",",
"*",
"*",
"... | 46 | 19 |
def _edges_in_tri_except(self, tri, edge):
"""Return the edges in *tri*, excluding *edge*.
"""
edges = [(tri[i], tri[(i+1) % 3]) for i in range(3)]
try:
edges.remove(tuple(edge))
except ValueError:
edges.remove(tuple(edge[::-1]))
return edges | [
"def",
"_edges_in_tri_except",
"(",
"self",
",",
"tri",
",",
"edge",
")",
":",
"edges",
"=",
"[",
"(",
"tri",
"[",
"i",
"]",
",",
"tri",
"[",
"(",
"i",
"+",
"1",
")",
"%",
"3",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
"]",
"try",... | 34 | 10 |
def read_file(self, location):
"""Read in a yaml file and return as a python object"""
try:
return yaml.load(open(location))
except (yaml.parser.ParserError, yaml.scanner.ScannerError) as error:
raise self.BadFileErrorKls("Failed to read yaml", location=location, error_ty... | [
"def",
"read_file",
"(",
"self",
",",
"location",
")",
":",
"try",
":",
"return",
"yaml",
".",
"load",
"(",
"open",
"(",
"location",
")",
")",
"except",
"(",
"yaml",
".",
"parser",
".",
"ParserError",
",",
"yaml",
".",
"scanner",
".",
"ScannerError",
... | 66.833333 | 35.666667 |
def vbar_stack(self, stackers, **kw):
''' Generate multiple ``VBar`` renderers for levels stacked bottom
to top.
Args:
stackers (seq[str]) : a list of data source field names to stack
successively for ``left`` and ``right`` bar coordinates.
Additiona... | [
"def",
"vbar_stack",
"(",
"self",
",",
"stackers",
",",
"*",
"*",
"kw",
")",
":",
"result",
"=",
"[",
"]",
"for",
"kw",
"in",
"_double_stack",
"(",
"stackers",
",",
"\"bottom\"",
",",
"\"top\"",
",",
"*",
"*",
"kw",
")",
":",
"result",
".",
"append... | 38.902439 | 32.073171 |
def _unpack_obs(obs, space, tensorlib=tf):
"""Unpack a flattened Dict or Tuple observation array/tensor.
Arguments:
obs: The flattened observation tensor
space: The original space prior to flattening
tensorlib: The library used to unflatten (reshape) the array/tensor
"""
if (is... | [
"def",
"_unpack_obs",
"(",
"obs",
",",
"space",
",",
"tensorlib",
"=",
"tf",
")",
":",
"if",
"(",
"isinstance",
"(",
"space",
",",
"gym",
".",
"spaces",
".",
"Dict",
")",
"or",
"isinstance",
"(",
"space",
",",
"gym",
".",
"spaces",
".",
"Tuple",
")... | 39.780488 | 17.146341 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.