text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def send_to_splunk(
session=None,
url=None,
data=None,
headers=None,
verify=False,
ssl_options=None,
timeout=10.0):
"""send_to_splunk
Send formatted msgs to Splunk. This will throw exceptions
for any errors. It is decoupled from the publishers to
... | [
"def",
"send_to_splunk",
"(",
"session",
"=",
"None",
",",
"url",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"verify",
"=",
"False",
",",
"ssl_options",
"=",
"None",
",",
"timeout",
"=",
"10.0",
")",
":",
"r",
"=",
"se... | 25.709677 | 16.612903 |
def encipher(self,string):
"""Encipher string using Enigma M3 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Enigma(settings=('A','A','A'),rotors=(1,2,3),reflector='B',
ringstellung=('F','V'... | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ret",
"=",
"''",
"for",
"c",
"in",
"string",
".",
"upper",
"(",
")",
":",
"if",
"c",
".",
"isalpha",
"(",
")",
":",
"r... | 39.5 | 19.8 |
def unpack(self, gpsd_socket_response):
"""Sets new socket data as DataStream attributes in those initialised dictionaries
Arguments:
gpsd_socket_response (json object):
Provides:
self attributes, e.g., self.lat, self.gdop
Raises:
AttributeError: 'str' object ... | [
"def",
"unpack",
"(",
"self",
",",
"gpsd_socket_response",
")",
":",
"try",
":",
"fresh_data",
"=",
"json",
".",
"loads",
"(",
"gpsd_socket_response",
")",
"# 'class' is popped for iterator lead",
"class_name",
"=",
"fresh_data",
".",
"pop",
"(",
"'class'",
")",
... | 52.62963 | 28.740741 |
def _find_already_built_wheel(metadata_directory):
"""Check for a wheel already built during the get_wheel_metadata hook.
"""
if not metadata_directory:
return None
metadata_parent = os.path.dirname(metadata_directory)
if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):
... | [
"def",
"_find_already_built_wheel",
"(",
"metadata_directory",
")",
":",
"if",
"not",
"metadata_directory",
":",
"return",
"None",
"metadata_parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"metadata_directory",
")",
"if",
"not",
"os",
".",
"path",
".",
"... | 34.3 | 18.05 |
def existing_gene(store, panel_obj, hgnc_id):
"""Check if gene is already added to a panel."""
existing_genes = {gene['hgnc_id']: gene for gene in panel_obj['genes']}
return existing_genes.get(hgnc_id) | [
"def",
"existing_gene",
"(",
"store",
",",
"panel_obj",
",",
"hgnc_id",
")",
":",
"existing_genes",
"=",
"{",
"gene",
"[",
"'hgnc_id'",
"]",
":",
"gene",
"for",
"gene",
"in",
"panel_obj",
"[",
"'genes'",
"]",
"}",
"return",
"existing_genes",
".",
"get",
... | 52.5 | 10.5 |
def create_job_queue(self, queue_name, priority, state, compute_env_order):
"""
Create a job queue
:param queue_name: Queue name
:type queue_name: str
:param priority: Queue priority
:type priority: int
:param state: Queue state
:type state: string
... | [
"def",
"create_job_queue",
"(",
"self",
",",
"queue_name",
",",
"priority",
",",
"state",
",",
"compute_env_order",
")",
":",
"for",
"variable",
",",
"var_name",
"in",
"(",
"(",
"queue_name",
",",
"'jobQueueName'",
")",
",",
"(",
"priority",
",",
"'priority'... | 46.568182 | 24.568182 |
async def iter_all(
self,
direction: msg.StreamDirection = msg.StreamDirection.Forward,
from_position: Optional[Union[msg.Position, msg._PositionSentinel]] = None,
batch_size: int = 100,
resolve_links: bool = True,
require_master: bool = False,
correlation_id: Opt... | [
"async",
"def",
"iter_all",
"(",
"self",
",",
"direction",
":",
"msg",
".",
"StreamDirection",
"=",
"msg",
".",
"StreamDirection",
".",
"Forward",
",",
"from_position",
":",
"Optional",
"[",
"Union",
"[",
"msg",
".",
"Position",
",",
"msg",
".",
"_Position... | 37.387097 | 21.967742 |
def connect(self, uuid_value, wait=None):
"""Connect to a specific device by its uuid
Attempt to connect to a device that we have previously scanned using its UUID.
If wait is not None, then it is used in the same was a scan(wait) to override
default wait times with an explicit value.
... | [
"def",
"connect",
"(",
"self",
",",
"uuid_value",
",",
"wait",
"=",
"None",
")",
":",
"if",
"self",
".",
"connected",
":",
"raise",
"HardwareError",
"(",
"\"Cannot connect when we are already connected\"",
")",
"if",
"uuid_value",
"not",
"in",
"self",
".",
"_s... | 40.269231 | 27.346154 |
def encipher(self,string):
"""Encipher string using Foursquare cipher according to initialised key. Punctuation and whitespace
are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.
Example::
ciphertext = Foursquare(key1='zg... | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"if",
"len",
"(",
"string",
")",
"%",
"2",
"==",
"1",
":",
"string",
"=",
"string",
"+",
"'X'",
"ret",
"=",
"''",
"for",
... | 43.166667 | 24.5 |
def auth(self):
"""
Auth is used to call the AUTH API of CricketAPI.
Access token required for every request call to CricketAPI.
Auth functional will post user Cricket API app details to server
and return the access token.
Return:
Access token
... | [
"def",
"auth",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"store_handler",
".",
"has_value",
"(",
"'access_token'",
")",
":",
"params",
"=",
"{",
"}",
"params",
"[",
"\"access_key\"",
"]",
"=",
"self",
".",
"access_key",
"params",
"[",
"\"secret_ke... | 42.482759 | 20.482759 |
def _get_co_from_dump(data):
"""Return the code objects from the dump."""
# Read py2exe header
current = struct.calcsize(b'iiii')
metadata = struct.unpack(b'iiii', data[:current])
# check py2exe magic number
# assert(metadata[0] == 0x78563412)
logging.info("Magic value: %x", metadata[0])
... | [
"def",
"_get_co_from_dump",
"(",
"data",
")",
":",
"# Read py2exe header",
"current",
"=",
"struct",
".",
"calcsize",
"(",
"b'iiii'",
")",
"metadata",
"=",
"struct",
".",
"unpack",
"(",
"b'iiii'",
",",
"data",
"[",
":",
"current",
"]",
")",
"# check py2exe m... | 32.26087 | 15.043478 |
def process(self, metric):
"""
Process a metric by converting metric name to MQTT topic name;
the payload is metric and timestamp.
"""
if not mosquitto:
return
line = str(metric)
topic, value, timestamp = line.split()
if len(self.prefix):
... | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"if",
"not",
"mosquitto",
":",
"return",
"line",
"=",
"str",
"(",
"metric",
")",
"topic",
",",
"value",
",",
"timestamp",
"=",
"line",
".",
"split",
"(",
")",
"if",
"len",
"(",
"self",
".",
... | 32.8 | 19.1 |
def load_lists(keys=[], values=[], name='NT'):
""" Map namedtuples given a pair of key, value lists. """
mapping = dict(zip(keys, values))
return mapper(mapping, _nt_name=name) | [
"def",
"load_lists",
"(",
"keys",
"=",
"[",
"]",
",",
"values",
"=",
"[",
"]",
",",
"name",
"=",
"'NT'",
")",
":",
"mapping",
"=",
"dict",
"(",
"zip",
"(",
"keys",
",",
"values",
")",
")",
"return",
"mapper",
"(",
"mapping",
",",
"_nt_name",
"=",... | 46.25 | 2.5 |
def pretty_table(rows, header=None):
"""
Returns a string with a simple pretty table representing the given rows.
Rows can be:
- Sequences such as lists or tuples
- Mappings such as dicts
- Any object with a __dict__ attribute (most plain python objects) which is
equivalent to passing ... | [
"def",
"pretty_table",
"(",
"rows",
",",
"header",
"=",
"None",
")",
":",
"rows2",
"=",
"[",
"]",
"if",
"header",
":",
"header",
"=",
"ensure_list_if_string",
"(",
"header",
")",
"rows2",
".",
"insert",
"(",
"0",
",",
"header",
")",
"row_type",
"=",
... | 34.708333 | 20.854167 |
def images(self, tag, images, step=None, rows=None, cols=None):
"""Saves (rows, cols) tiled images from onp.ndarray.
If either rows or cols aren't given, they are determined automatically
from the size of the image batch, if neither are given a long column
of images is produced. This truncates the imag... | [
"def",
"images",
"(",
"self",
",",
"tag",
",",
"images",
",",
"step",
"=",
"None",
",",
"rows",
"=",
"None",
",",
"cols",
"=",
"None",
")",
":",
"images",
"=",
"onp",
".",
"array",
"(",
"images",
")",
"if",
"step",
"is",
"None",
":",
"step",
"=... | 33.633333 | 16.6 |
def sinusoidal_bidirectional(target,
num_points=1e2,
surface_tension='pore.surface_tension',
contact_angle='pore.contact_angle',
throat_diameter='throat.diameter',
throat_ampl... | [
"def",
"sinusoidal_bidirectional",
"(",
"target",
",",
"num_points",
"=",
"1e2",
",",
"surface_tension",
"=",
"'pore.surface_tension'",
",",
"contact_angle",
"=",
"'pore.contact_angle'",
",",
"throat_diameter",
"=",
"'throat.diameter'",
",",
"throat_amplitude",
"=",
"'t... | 43.671429 | 20.2 |
def delete_project(self, project_name):
""" delete project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:return: DeleteProjectResponse
:raise: LogException
"""
headers =... | [
"def",
"delete_project",
"(",
"self",
",",
"project_name",
")",
":",
"headers",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"resource",
"=",
"\"/\"",
"(",
"resp",
",",
"header",
")",
"=",
"self",
".",
"_send",
"(",
"\"DELETE\"",
",",
"project_name",
",",
... | 29.411765 | 18.647059 |
def get_most_relevant_words_for_topic(vocab, rel_mat, topic, n=None):
"""
Get words from `vocab` for `topic` ordered by most to least relevance (Sievert and Shirley 2014) using the relevance
matrix `rel_mat` obtained from `get_topic_word_relevance()`.
Optionally only return the `n` most relevant words.
... | [
"def",
"get_most_relevant_words_for_topic",
"(",
"vocab",
",",
"rel_mat",
",",
"topic",
",",
"n",
"=",
"None",
")",
":",
"_check_relevant_words_for_topic_args",
"(",
"vocab",
",",
"rel_mat",
",",
"topic",
")",
"return",
"_words_by_score",
"(",
"vocab",
",",
"rel... | 57.5 | 25.75 |
def search_prod_type_tags(self, ins, type, tags, pipeline):
'''Returns the first coincidence...'''
return StoredProduct(id=100, content='null.fits', tags={}) | [
"def",
"search_prod_type_tags",
"(",
"self",
",",
"ins",
",",
"type",
",",
"tags",
",",
"pipeline",
")",
":",
"return",
"StoredProduct",
"(",
"id",
"=",
"100",
",",
"content",
"=",
"'null.fits'",
",",
"tags",
"=",
"{",
"}",
")"
] | 57 | 17 |
def gevent_spawn(self):
""" Spawn worker threads (using gevent) """
monkey.patch_all(thread=False)
joinall([spawn(self.gevent_worker) for x in range(self.queue_worker_amount)]) | [
"def",
"gevent_spawn",
"(",
"self",
")",
":",
"monkey",
".",
"patch_all",
"(",
"thread",
"=",
"False",
")",
"joinall",
"(",
"[",
"spawn",
"(",
"self",
".",
"gevent_worker",
")",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"queue_worker_amount",
")",
"... | 49.25 | 16 |
def densenet121(num_classes=1000, pretrained='imagenet'):
r"""Densenet-121 model from
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
"""
model = models.densenet121(pretrained=False)
if pretrained is not None:
settings = pretrained_settings['densenet121'][... | [
"def",
"densenet121",
"(",
"num_classes",
"=",
"1000",
",",
"pretrained",
"=",
"'imagenet'",
")",
":",
"model",
"=",
"models",
".",
"densenet121",
"(",
"pretrained",
"=",
"False",
")",
"if",
"pretrained",
"is",
"not",
"None",
":",
"settings",
"=",
"pretrai... | 43.7 | 15.7 |
def get_nfc_chars(self):
"""
Returns the set of IPA symbols that are precomposed (decomposable)
chars. These should not be decomposed during string normalisation,
because they will not be recognised otherwise.
In IPA 2015 there is only one precomposed character: ç, the voiceless
palatal fricative.
"""
... | [
"def",
"get_nfc_chars",
"(",
"self",
")",
":",
"ex",
"=",
"[",
"]",
"for",
"char",
"in",
"self",
".",
"ipa",
".",
"keys",
"(",
")",
":",
"if",
"len",
"(",
"char",
")",
"==",
"1",
":",
"decomp",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFD'",
... | 26.444444 | 21 |
def cyl_to_spher(R,Z, phi):
"""
NAME:
cyl_to_spher
PURPOSE:
convert from cylindrical to spherical coordinates
INPUT:
R, Z, phi- cylindrical coordinates
OUTPUT:
R, theta, phi - spherical coordinates
HISTORY:
2016-05-16 - Written - Aladdin
"""
t... | [
"def",
"cyl_to_spher",
"(",
"R",
",",
"Z",
",",
"phi",
")",
":",
"theta",
"=",
"nu",
".",
"arctan2",
"(",
"R",
",",
"Z",
")",
"r",
"=",
"(",
"R",
"**",
"2",
"+",
"Z",
"**",
"2",
")",
"**",
".5",
"return",
"(",
"r",
",",
"theta",
",",
"phi... | 14.230769 | 24.846154 |
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
... | [
"def",
"version",
"(",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"names",
")",
"==",
"1",
":",
"vers",
"=",
"__proxy__",
"[",
"'dummy.package_status'",
"]",
"(",
"names",
"[",
"0",
"]",
")",
"return",
"vers",
"[",
"names",
... | 29.318182 | 22.318182 |
def duplicate_pvd(self):
# type: () -> None
'''
A method to add a duplicate PVD to the ISO. This is a mostly useless
feature allowed by Ecma-119 to have duplicate PVDs to avoid possible
corruption.
Parameters:
None.
Returns:
Nothing.
''... | [
"def",
"duplicate_pvd",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInvalidInput",
"(",
"'This object is not yet initialized; call either open() or new() to create an ISO'",
")",
"pvd",
... | 34.1 | 29.6 |
def config_loader(app, **kwargs_config):
"""Configuration loader.
Adds support for loading templates from the Flask application's instance
folder (``<instance_folder>/templates``).
"""
# This is the only place customize the Flask application right after
# it has been created, but before all ext... | [
"def",
"config_loader",
"(",
"app",
",",
"*",
"*",
"kwargs_config",
")",
":",
"# This is the only place customize the Flask application right after",
"# it has been created, but before all extensions etc are loaded.",
"local_templates_path",
"=",
"os",
".",
"path",
".",
"join",
... | 36.041667 | 17.666667 |
async def read(self, amt=None):
"""Read at most amt bytes from the stream.
If the amt argument is omitted, read all data.
"""
# botocore to aiohttp mapping
chunk = await self.__wrapped__.read(amt if amt is not None else -1)
self._self_amount_read += len(chunk)
if... | [
"async",
"def",
"read",
"(",
"self",
",",
"amt",
"=",
"None",
")",
":",
"# botocore to aiohttp mapping",
"chunk",
"=",
"await",
"self",
".",
"__wrapped__",
".",
"read",
"(",
"amt",
"if",
"amt",
"is",
"not",
"None",
"else",
"-",
"1",
")",
"self",
".",
... | 41.214286 | 12.857143 |
def create_relationship(self, relationship_form=None):
"""Creates a new ``Relationship``.
arg: relationship_form (osid.relationship.RelationshipForm):
the form for this ``Relationship``
return: (osid.relationship.Relationship) - the new
``Relationship``
... | [
"def",
"create_relationship",
"(",
"self",
",",
"relationship_form",
"=",
"None",
")",
":",
"if",
"relationship_form",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"if",
"not",
"isinstance",
"(",
"relationship_form",
",",
"abc_relationship_objects",
".",
... | 49.341463 | 22.341463 |
def com_google_fonts_check_metadata_match_weight_postscript(font_metadata):
"""METADATA.pb weight matches postScriptName."""
WEIGHTS = {
"Thin": 100,
"ThinItalic": 100,
"ExtraLight": 200,
"ExtraLightItalic": 200,
"Light": 300,
"LightItalic": 300,
"Regular": 400,
"Italic": 400,
"M... | [
"def",
"com_google_fonts_check_metadata_match_weight_postscript",
"(",
"font_metadata",
")",
":",
"WEIGHTS",
"=",
"{",
"\"Thin\"",
":",
"100",
",",
"\"ThinItalic\"",
":",
"100",
",",
"\"ExtraLight\"",
":",
"200",
",",
"\"ExtraLightItalic\"",
":",
"200",
",",
"\"Ligh... | 32.219512 | 19 |
def OnTimeToClose(self, evt):
"""Event handler for the button click."""
print("See ya later!")
sys.stdout.flush()
self.cleanup_consoles(evt)
self.Close()
# Not sure why, but our IPython kernel seems to prevent normal WX
# shutdown, so an explicit exit() call is ne... | [
"def",
"OnTimeToClose",
"(",
"self",
",",
"evt",
")",
":",
"print",
"(",
"\"See ya later!\"",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"self",
".",
"cleanup_consoles",
"(",
"evt",
")",
"self",
".",
"Close",
"(",
")",
"# Not sure why, but our IPyt... | 37.333333 | 14.777778 |
def parse_form_action_url(html, parser=None):
"""Parse <form action="(.+)"> url
:param html: str: raw html text
:param parser: bs4.BeautifulSoup: html parser
:return: url str: for example: /login.php?act=security_check&to=&hash=12346
"""
if parser is None:
parser = bs4.BeautifulSoup(htm... | [
"def",
"parse_form_action_url",
"(",
"html",
",",
"parser",
"=",
"None",
")",
":",
"if",
"parser",
"is",
"None",
":",
"parser",
"=",
"bs4",
".",
"BeautifulSoup",
"(",
"html",
",",
"'html.parser'",
")",
"forms",
"=",
"parser",
".",
"find_all",
"(",
"'form... | 35.470588 | 18.882353 |
def filter(self, source_file, encoding): # noqa A001
"""Parse XML file."""
sources = []
for content, filename, enc in self.get_content(source_file):
self.additional_context = self.get_context(filename)
sources.extend(self._filter(content, source_file, enc))
retu... | [
"def",
"filter",
"(",
"self",
",",
"source_file",
",",
"encoding",
")",
":",
"# noqa A001",
"sources",
"=",
"[",
"]",
"for",
"content",
",",
"filename",
",",
"enc",
"in",
"self",
".",
"get_content",
"(",
"source_file",
")",
":",
"self",
".",
"additional_... | 40.375 | 21.25 |
def linkCustomerToVerifiedUser(sender, **kwargs):
"""
If a Registration is processed in which the associated Customer does not yet
have a User, then check to see if the Customer's email address has been
verified as belonging to a specific User, and if that User has an associated
Customer. If such a... | [
"def",
"linkCustomerToVerifiedUser",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"registration",
"=",
"kwargs",
".",
"get",
"(",
"'registration'",
",",
"None",
")",
"if",
"not",
"registration",
"or",
"(",
"hasattr",
"(",
"registration",
".",
"customer"... | 46.466667 | 27.933333 |
def make_temp_path(path, new_ext=None):
"""
Arguments:
new_ext: the new file extension, including the leading dot.
Defaults to preserving the existing file extension.
"""
root, ext = os.path.splitext(path)
if new_ext is None:
new_ext = ext
temp_path = root + TEMP_EXTENSIO... | [
"def",
"make_temp_path",
"(",
"path",
",",
"new_ext",
"=",
"None",
")",
":",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"if",
"new_ext",
"is",
"None",
":",
"new_ext",
"=",
"ext",
"temp_path",
"=",
"root",
"+",
"T... | 26.153846 | 16.615385 |
def runQueryWithRetry(self, *args, **kw):
"""
Run a database query, like with dbpool.runQuery, but retry the query in
case of a temporary error (like connection lost).
This is needed to be robust against things like database connection
idle timeouts."""
def runQuery(txn... | [
"def",
"runQueryWithRetry",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"def",
"runQuery",
"(",
"txn",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"txn",
".",
"execute",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"retu... | 35.538462 | 19.230769 |
def copy(self, tagname, **kwargs):
"""
Returns a new instance of `TagWrap` using the given *tagname* that has
all the same attributes as this instance. If *kwargs* is given they
will override the attributes of the created instance.
"""
new_kwargs = {
'replace... | [
"def",
"copy",
"(",
"self",
",",
"tagname",
",",
"*",
"*",
"kwargs",
")",
":",
"new_kwargs",
"=",
"{",
"'replacement'",
":",
"self",
".",
"replacement",
",",
"'whitelist'",
":",
"self",
".",
"whitelist",
",",
"'safe_mode'",
":",
"self",
".",
"safe_mode",... | 39.666667 | 11.533333 |
def sort_index(self, ascending=True):
"""Sort the index of the DataFrame.
Currently MultiIndex is not supported since Weld is missing multiple-column sort.
Note this is an expensive operation (brings all data to Weld).
Parameters
----------
ascending : bool, optional
... | [
"def",
"sort_index",
"(",
"self",
",",
"ascending",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"index",
",",
"MultiIndex",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Weld does not yet support sorting on multiple columns'",
")",
"return",
"s... | 29.952381 | 26.047619 |
def get_url(request, application, roles, label=None):
""" Retrieve a link that will work for the current user. """
args = []
if label is not None:
args.append(label)
# don't use secret_token unless we have to
if 'is_admin' in roles:
# Administrators can access anything without secre... | [
"def",
"get_url",
"(",
"request",
",",
"application",
",",
"roles",
",",
"label",
"=",
"None",
")",
":",
"args",
"=",
"[",
"]",
"if",
"label",
"is",
"not",
"None",
":",
"args",
".",
"append",
"(",
"label",
")",
"# don't use secret_token unless we have to",... | 38.514286 | 18.457143 |
def feed(self, data):
"""Consume some data and advances the state as necessary.
:param str data: a blob of data to feed from.
"""
send = self._send_to_parser
draw = self.listener.draw
match_text = self._text_pattern.match
taking_plain_text = self._taking_plain_te... | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"send",
"=",
"self",
".",
"_send_to_parser",
"draw",
"=",
"self",
".",
"listener",
".",
"draw",
"match_text",
"=",
"self",
".",
"_text_pattern",
".",
"match",
"taking_plain_text",
"=",
"self",
".",
"_tak... | 32.48 | 14.56 |
def has_cjk(self):
"""Checks if the word of the chunk contains CJK characters.
This is using unicode codepoint ranges from
https://github.com/nltk/nltk/blob/develop/nltk/tokenize/util.py#L149
Returns:
bool: True if the chunk has any CJK character.
"""
cjk_codepoint_ranges = [
(43... | [
"def",
"has_cjk",
"(",
"self",
")",
":",
"cjk_codepoint_ranges",
"=",
"[",
"(",
"4352",
",",
"4607",
")",
",",
"(",
"11904",
",",
"42191",
")",
",",
"(",
"43072",
",",
"43135",
")",
",",
"(",
"44032",
",",
"55215",
")",
",",
"(",
"63744",
",",
... | 35.058824 | 19.411765 |
def supports_coordinate_type(self, coordinate_type=None):
"""Tests if the given coordinate type is supported.
arg: coordinate_type (osid.type.Type): a coordinate Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syn... | [
"def",
"supports_coordinate_type",
"(",
"self",
",",
"coordinate_type",
"=",
"None",
")",
":",
"# Implemented from template for osid.Metadata.supports_coordinate_type",
"from",
".",
"osid_errors",
"import",
"IllegalState",
",",
"NullArgument",
"if",
"not",
"coordinate_type",
... | 49.388889 | 21.5 |
def send_output(self, value, stdout):
"""Write the output or value of the expression back to user.
>>> 5
5
>>> print('cash rules everything around me')
cash rules everything around me
"""
writer = self.writer
if value is not None:
writer.wri... | [
"def",
"send_output",
"(",
"self",
",",
"value",
",",
"stdout",
")",
":",
"writer",
"=",
"self",
".",
"writer",
"if",
"value",
"is",
"not",
"None",
":",
"writer",
".",
"write",
"(",
"'{!r}\\n'",
".",
"format",
"(",
"value",
")",
".",
"encode",
"(",
... | 24.833333 | 19.777778 |
def find_projects(self, file_identifier=".project"):
""" Search all directory recursively for subdirs
with `file_identifier' in it.
:type file_identifier: str
:param file_identifier: File identier, .project by default.
:rtype: list
:return: The list of subdirs with a `f... | [
"def",
"find_projects",
"(",
"self",
",",
"file_identifier",
"=",
"\".project\"",
")",
":",
"projects",
"=",
"[",
"]",
"for",
"d",
"in",
"self",
".",
"subdirs",
"(",
")",
":",
"project_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"di... | 33.764706 | 17.941176 |
def private_config_content(self, private_config):
"""
Update the private config
:param private_config: content of the private configuration file
"""
try:
private_config_path = os.path.join(self.working_dir, "private-config.cfg")
if private_config is Non... | [
"def",
"private_config_content",
"(",
"self",
",",
"private_config",
")",
":",
"try",
":",
"private_config_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"\"private-config.cfg\"",
")",
"if",
"private_config",
"is",
"None",
":... | 36.92 | 23.24 |
def run(self, grid=None, num_of_paths=2000, seed=0, num_of_workers=CPU_COUNT, profiling=False):
"""
implements simulation
:param list(date) grid: list of Monte Carlo grid dates
:param int num_of_paths: number of Monte Carlo paths
:param hashable seed: seed used for rnds initiali... | [
"def",
"run",
"(",
"self",
",",
"grid",
"=",
"None",
",",
"num_of_paths",
"=",
"2000",
",",
"seed",
"=",
"0",
",",
"num_of_workers",
"=",
"CPU_COUNT",
",",
"profiling",
"=",
"False",
")",
":",
"self",
".",
"grid",
"=",
"sorted",
"(",
"set",
"(",
"g... | 44.534483 | 21.465517 |
def static(self, uri, file_or_directory, *args, **kwargs):
"""Create a blueprint static route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param file_or_directory: Static asset.
"""
static = FutureStatic(uri, file_or_directory, args, kw... | [
"def",
"static",
"(",
"self",
",",
"uri",
",",
"file_or_directory",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"static",
"=",
"FutureStatic",
"(",
"uri",
",",
"file_or_directory",
",",
"args",
",",
"kwargs",
")",
"self",
".",
"statics",
".",
... | 44.25 | 15.5 |
def build_parameters(self):
"""
Build the CLI command line from the parameter values.
:return: list of CLI strings -- not escaped!
:rtype: list[str]
"""
param_bits = []
for name in self.parameters:
param_bits.extend(self.build_parameter_by_name(name) ... | [
"def",
"build_parameters",
"(",
"self",
")",
":",
"param_bits",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".",
"parameters",
":",
"param_bits",
".",
"extend",
"(",
"self",
".",
"build_parameter_by_name",
"(",
"name",
")",
"or",
"[",
"]",
")",
"return",... | 31.090909 | 15.272727 |
def copy(self):
"""
Return a new :class:`~pywbem.CIMParameter` object that is a copy
of this CIM parameter.
This is a middle-deep copy; any mutable types in attributes except the
following are copied, so besides these exceptions, modifications of the
original object will... | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"CIMParameter",
"(",
"self",
".",
"name",
",",
"self",
".",
"type",
",",
"reference_class",
"=",
"self",
".",
"reference_class",
",",
"is_array",
"=",
"self",
".",
"is_array",
",",
"array_size",
"=",
"self"... | 41.142857 | 20.357143 |
def _Rforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | [
"def",
"_Rforce",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"l",
",",
"n",
"=",
"bovy_coords",
".",
"Rz_to_lambdanu",
"(",
"R",
",",
"z",
",",
"ac",
"=",
"self",
".",
"_ac",
",",
"Delta",
"=",
"s... | 32.227273 | 15.954545 |
def delete_key(self, key_name, headers=None,
version_id=None, mfa_token=None, callback=None):
"""
Deletes a key from the bucket. If a version_id is provided,
only that version of the key will be deleted.
:type key_name: string
:param key_name: The key... | [
"def",
"delete_key",
"(",
"self",
",",
"key_name",
",",
"headers",
"=",
"None",
",",
"version_id",
"=",
"None",
",",
"mfa_token",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"provider",
"=",
"self",
".",
"connection",
".",
"provider",
"if",
"v... | 43.846154 | 18.25641 |
def get(self, key, func=None, args=(), kwargs=None, **opts):
"""Manually retrieve a value from the cache, calculating as needed.
Params:
key -> string to store/retrieve value from.
func -> callable to generate value if it does not exist, or has
expired.
... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"func",
"=",
"None",
",",
"args",
"=",
"(",
")",
",",
"kwargs",
"=",
"None",
",",
"*",
"*",
"opts",
")",
":",
"kwargs",
"=",
"kwargs",
"or",
"{",
"}",
"key",
",",
"store",
"=",
"self",
".",
"_expand... | 38.655738 | 24.229508 |
def cnst_AT(self, Y):
r"""Compute :math:`A^T \mathbf{y}`. In this case
:math:`A^T \mathbf{y} = (I \;\; \Gamma_0^T \;\; \Gamma_1^T \;\;
\ldots) \mathbf{y}`.
"""
return self.cnst_A0T(self.block_sep0(Y)) + \
np.sum(self.cnst_A1T(self.block_sep1(Y)), axis=-1) | [
"def",
"cnst_AT",
"(",
"self",
",",
"Y",
")",
":",
"return",
"self",
".",
"cnst_A0T",
"(",
"self",
".",
"block_sep0",
"(",
"Y",
")",
")",
"+",
"np",
".",
"sum",
"(",
"self",
".",
"cnst_A1T",
"(",
"self",
".",
"block_sep1",
"(",
"Y",
")",
")",
"... | 37.625 | 17 |
def add_adjust(self, data, prehashed=False):
"""Add a new leaf, and adjust the tree, without rebuilding the whole thing.
"""
subtrees = self._get_whole_subtrees()
new_node = Node(data, prehashed=prehashed)
self.leaves.append(new_node)
for node in reversed(subtrees):
... | [
"def",
"add_adjust",
"(",
"self",
",",
"data",
",",
"prehashed",
"=",
"False",
")",
":",
"subtrees",
"=",
"self",
".",
"_get_whole_subtrees",
"(",
")",
"new_node",
"=",
"Node",
"(",
"data",
",",
"prehashed",
"=",
"prehashed",
")",
"self",
".",
"leaves",
... | 45.071429 | 7.5 |
def roc_values(fg_vals, bg_vals):
"""
Return fpr (x) and tpr (y) of the ROC curve.
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
Returns
-------
fpr : array
... | [
"def",
"roc_values",
"(",
"fg_vals",
",",
"bg_vals",
")",
":",
"if",
"len",
"(",
"fg_vals",
")",
"==",
"0",
":",
"return",
"0",
"y_true",
",",
"y_score",
"=",
"values_to_labels",
"(",
"fg_vals",
",",
"bg_vals",
")",
"fpr",
",",
"tpr",
",",
"_thresholds... | 20.62963 | 20.925926 |
def load_from_file(swag_path, swag_type='yml', root_path=None):
"""
Load specs from YAML file
"""
if swag_type not in ('yaml', 'yml'):
raise AttributeError("Currently only yaml or yml supported")
# TODO: support JSON
try:
enc = detect_by_bom(swag_path)
with codecs.op... | [
"def",
"load_from_file",
"(",
"swag_path",
",",
"swag_type",
"=",
"'yml'",
",",
"root_path",
"=",
"None",
")",
":",
"if",
"swag_type",
"not",
"in",
"(",
"'yaml'",
",",
"'yml'",
")",
":",
"raise",
"AttributeError",
"(",
"\"Currently only yaml or yml supported\"",... | 40.771429 | 14.942857 |
def _from_dict(cls, _dict):
"""Initialize a UtteranceAnalyses object from a json dictionary."""
args = {}
if 'utterances_tone' in _dict:
args['utterances_tone'] = [
UtteranceAnalysis._from_dict(x)
for x in (_dict.get('utterances_tone'))
]
... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'utterances_tone'",
"in",
"_dict",
":",
"args",
"[",
"'utterances_tone'",
"]",
"=",
"[",
"UtteranceAnalysis",
".",
"_from_dict",
"(",
"x",
")",
"for",
"x",
"in",
"("... | 37.666667 | 16 |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Setting(key)
if key not in Setting._member_map_:
extend_enum(Setting, key, default)
return Setting[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"Setting",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"Setting",
".",
"_member_map_",
":",
"extend_enum",
"(",
"Setti... | 36.285714 | 7.714286 |
def auto_load_app_modules(self, modules):
"""Auto load app modules"""
for app in apps.get_app_configs():
for module in modules:
try:
import_module('{}.{}'.format(app.module.__package__, module))
except ImportError:
pass | [
"def",
"auto_load_app_modules",
"(",
"self",
",",
"modules",
")",
":",
"for",
"app",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
":",
"for",
"module",
"in",
"modules",
":",
"try",
":",
"import_module",
"(",
"'{}.{}'",
".",
"format",
"(",
"app",
".",
... | 39 | 11.375 |
def isheader(self, line):
"""Determine whether a given line is a legal header.
This method should return the header name, suitably canonicalized.
You may override this method in order to use Message parsing on tagged
data in RFC 2822-like formats with special header formats.
"""... | [
"def",
"isheader",
"(",
"self",
",",
"line",
")",
":",
"i",
"=",
"line",
".",
"find",
"(",
"':'",
")",
"if",
"i",
">",
"-",
"1",
":",
"return",
"line",
"[",
":",
"i",
"]",
".",
"lower",
"(",
")",
"return",
"None"
] | 37.454545 | 19.545455 |
def check_class(obj, target_class, allow_none = False):
""" Checks that the obj is a (sub)type of target_class.
Raises a TypeError if this is not the case.
:param obj: object whos type is to be checked
:type obj: any type
:param target_class: target type/class
:type target_... | [
"def",
"check_class",
"(",
"obj",
",",
"target_class",
",",
"allow_none",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"target_class",
")",
":",
"if",
"not",
"(",
"allow_none",
"and",
"obj",
"is",
"None",
")",
":",
"raise",
"Type... | 42.4 | 11.266667 |
def imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p():
"""Gets to 2.92 in just under 4 days on 8 p100s."""
hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_l()
hparams.num_decoder_layers = 14
hparams.batch_size = 8
hparams.layer_prepostprocess_dropout = 0.2
return hparams | [
"def",
"imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p",
"(",
")",
":",
"hparams",
"=",
"imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_l",
"(",
")",
"hparams",
".",
"num_decoder_layers",
"=",
"14",
"hparams",
".",
"batch_size",
"=",
"8",
"hparams",
".",
"layer_... | 42.142857 | 13.714286 |
def grow(self, amount):
"""Spawn new worker threads (not above self.max)."""
if self.max > 0:
budget = max(self.max - len(self._threads), 0)
else:
# self.max <= 0 indicates no maximum
budget = float('inf')
n_new = min(amount, budget)
workers ... | [
"def",
"grow",
"(",
"self",
",",
"amount",
")",
":",
"if",
"self",
".",
"max",
">",
"0",
":",
"budget",
"=",
"max",
"(",
"self",
".",
"max",
"-",
"len",
"(",
"self",
".",
"_threads",
")",
",",
"0",
")",
"else",
":",
"# self.max <= 0 indicates no ma... | 34.071429 | 16.785714 |
def get_sec_project_activity(self):
"""
Generate the "project activity" section of the report.
"""
logger.debug("Calculating Project Activity metrics.")
data_path = os.path.join(self.data_dir, "activity")
if not os.path.exists(data_path):
os.makedirs(data_pa... | [
"def",
"get_sec_project_activity",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Calculating Project Activity metrics.\"",
")",
"data_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_dir",
",",
"\"activity\"",
")",
"if",
"not",
"os"... | 43.16129 | 19.806452 |
def bind_expression_to_resources(expr, resources):
"""
Bind a Blaze expression to resources.
Parameters
----------
expr : bz.Expr
The expression to which we want to bind resources.
resources : dict[bz.Symbol -> any]
Mapping from the loadable terms of ``expr`` to actual data reso... | [
"def",
"bind_expression_to_resources",
"(",
"expr",
",",
"resources",
")",
":",
"# bind the resources into the expression",
"if",
"resources",
"is",
"None",
":",
"resources",
"=",
"{",
"}",
"# _subs stands for substitute. It's not actually private, blaze just",
"# prefixes sym... | 30.076923 | 20 |
def inflate_to_one_hot(tensor, classes):
"""
Converts a tensor with index form to a one hot tensor.
:param tensor: A tensor of shape [batch, h, w, 1]
:param classes: The number of classes that exist. (length of one hot encoding)
:return: A tensor of shape [batch, h, w, classes].
"""
one_hot ... | [
"def",
"inflate_to_one_hot",
"(",
"tensor",
",",
"classes",
")",
":",
"one_hot",
"=",
"tf",
".",
"one_hot",
"(",
"tensor",
",",
"classes",
")",
"shape",
"=",
"one_hot",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"return",
"tf",
".",
"reshape... | 45.5 | 12.1 |
def encode(self, word):
"""Return the MRA personal numeric identifier (PNI) for a word.
Parameters
----------
word : str
The word to transform
Returns
-------
str
The MRA PNI
Examples
--------
>>> pe = MRA()
... | [
"def",
"encode",
"(",
"self",
",",
"word",
")",
":",
"if",
"not",
"word",
":",
"return",
"word",
"word",
"=",
"word",
".",
"upper",
"(",
")",
"word",
"=",
"word",
".",
"replace",
"(",
"'ß',",
" ",
"SS')",
"",
"word",
"=",
"word",
"[",
"0",
"]",... | 22.702703 | 19.027027 |
def main():
"""The main function of the script"""
desc = 'Benchmark the files generated by generate.py'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument(
'--src',
dest='src_dir',
default='generated',
help='The directory containing the sources to benc... | [
"def",
"main",
"(",
")",
":",
"desc",
"=",
"'Benchmark the files generated by generate.py'",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"desc",
")",
"parser",
".",
"add_argument",
"(",
"'--src'",
",",
"dest",
"=",
"'src_dir'",
","... | 27.018868 | 20.584906 |
def GetValueLength(rd, pos):
"""Get value length for a key in rd.
For a key at position pos in the Report Descriptor rd, return the length
of the associated value. This supports both short and long format
values.
Args:
rd: Report Descriptor
pos: The position of the key in rd.
Returns:
(key_s... | [
"def",
"GetValueLength",
"(",
"rd",
",",
"pos",
")",
":",
"rd",
"=",
"bytearray",
"(",
"rd",
")",
"key",
"=",
"rd",
"[",
"pos",
"]",
"if",
"key",
"==",
"LONG_ITEM_ENCODING",
":",
"# If the key is tagged as a long item (0xfe), then the format is",
"# [key (1 byte)]... | 33.157895 | 23.710526 |
def _run_systemdrun_decide(self):
"""
Internal method
decide if it is possible to use --wait option to systemd
for example RHEL7 does not support --wait option
:return: bool
"""
if self.systemd_wait_support is None:
self.systemd_wait_support = "--wait... | [
"def",
"_run_systemdrun_decide",
"(",
"self",
")",
":",
"if",
"self",
".",
"systemd_wait_support",
"is",
"None",
":",
"self",
".",
"systemd_wait_support",
"=",
"\"--wait\"",
"in",
"run_cmd",
"(",
"[",
"\"systemd-run\"",
",",
"\"--help\"",
"]",
",",
"return_outpu... | 35.5 | 14.166667 |
def add_color_stop_rgba(self, offset, red, green, blue, alpha=1):
"""Adds a translucent color stop to a gradient pattern.
The offset specifies the location along the gradient's control vector.
For example,
a linear gradient's control vector is from (x0,y0) to (x1,y1)
while a rad... | [
"def",
"add_color_stop_rgba",
"(",
"self",
",",
"offset",
",",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
"=",
"1",
")",
":",
"cairo",
".",
"cairo_pattern_add_color_stop_rgba",
"(",
"self",
".",
"_pointer",
",",
"offset",
",",
"red",
",",
"green",
"... | 40.891892 | 19.378378 |
def _TempRootPath():
"""Returns a default root path for storing temporary files."""
# `FLAGS.test_tmpdir` is defined only in test environment, so we can't expect
# for it to be always defined.
test_tmpdir = (
compatibility.Environ("TEST_TMPDIR", default=None) or
FLAGS.get_flag_value("test_tmpdir", d... | [
"def",
"_TempRootPath",
"(",
")",
":",
"# `FLAGS.test_tmpdir` is defined only in test environment, so we can't expect",
"# for it to be always defined.",
"test_tmpdir",
"=",
"(",
"compatibility",
".",
"Environ",
"(",
"\"TEST_TMPDIR\"",
",",
"default",
"=",
"None",
")",
"or",
... | 38 | 22.5 |
def create_swag_from_ctx(ctx):
"""Creates SWAG client from the current context."""
swag_opts = {}
if ctx.type == 'file':
swag_opts = {
'swag.type': 'file',
'swag.data_dir': ctx.data_dir,
'swag.data_file': ctx.data_file
}
elif ctx.type == 's3':
... | [
"def",
"create_swag_from_ctx",
"(",
"ctx",
")",
":",
"swag_opts",
"=",
"{",
"}",
"if",
"ctx",
".",
"type",
"==",
"'file'",
":",
"swag_opts",
"=",
"{",
"'swag.type'",
":",
"'file'",
",",
"'swag.data_dir'",
":",
"ctx",
".",
"data_dir",
",",
"'swag.data_file'... | 31.272727 | 12.954545 |
def parse_bowtie_stats(self, stats_file):
"""
Parses Bowtie2 stats file, returns series with values.
:param str stats_file: Bowtie2 output file with alignment statistics.
"""
import pandas as pd
stats = pd.Series(index=["readCount", "unpaired", "unaligned", "unique", "mu... | [
"def",
"parse_bowtie_stats",
"(",
"self",
",",
"stats_file",
")",
":",
"import",
"pandas",
"as",
"pd",
"stats",
"=",
"pd",
".",
"Series",
"(",
"index",
"=",
"[",
"\"readCount\"",
",",
"\"unpaired\"",
",",
"\"unaligned\"",
",",
"\"unique\"",
",",
"\"multiple\... | 57.909091 | 32.636364 |
def has_dynamic_getattr(self, context=None):
"""Check if the class has a custom __getattr__ or __getattribute__.
If any such method is found and it is not from
builtins, nor from an extension module, then the function
will return True.
:returns: True if the class has a custom
... | [
"def",
"has_dynamic_getattr",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"def",
"_valid_getattr",
"(",
"node",
")",
":",
"root",
"=",
"node",
".",
"root",
"(",
")",
"return",
"root",
".",
"name",
"!=",
"BUILTINS",
"and",
"getattr",
"(",
"root"... | 37.923077 | 21.076923 |
def download_pojo(self, path="", get_genmodel_jar=False, genmodel_name=""):
"""
Download the POJO for this model to the directory specified by path.
If path is an empty string, then dump the output to screen.
:param path: An absolute path to the directory where POJO should be saved.
... | [
"def",
"download_pojo",
"(",
"self",
",",
"path",
"=",
"\"\"",
",",
"get_genmodel_jar",
"=",
"False",
",",
"genmodel_name",
"=",
"\"\"",
")",
":",
"assert_is_type",
"(",
"path",
",",
"str",
")",
"assert_is_type",
"(",
"get_genmodel_jar",
",",
"bool",
")",
... | 49.4 | 26.066667 |
def get_dev_vlans(devid, auth, url):
"""Function takes input of devID to issue RESTUL call to HP IMC
:param devid: requires devId as the only input parameter
:return: dictionary of existing vlans on the devices. Device must be supported in HP IMC platform VLAN manager module
"""
# checks to see if ... | [
"def",
"get_dev_vlans",
"(",
"devid",
",",
"auth",
",",
"url",
")",
":",
"# checks to see if the imc credentials are already available",
"get_dev_vlans_url",
"=",
"\"/imcrs/vlan?devId=\"",
"+",
"str",
"(",
"devid",
")",
"+",
"\"&start=0&size=5000&total=false\"",
"f_url",
... | 45 | 20.619048 |
async def _handle_metrics(self, request: Request) -> Response:
"""Handler for metrics."""
if self._update_handler:
await self._update_handler(self.registry.get_metrics())
response = Response(body=self.registry.generate_metrics())
response.content_type = CONTENT_TYPE_LATEST
... | [
"async",
"def",
"_handle_metrics",
"(",
"self",
",",
"request",
":",
"Request",
")",
"->",
"Response",
":",
"if",
"self",
".",
"_update_handler",
":",
"await",
"self",
".",
"_update_handler",
"(",
"self",
".",
"registry",
".",
"get_metrics",
"(",
")",
")",... | 47.857143 | 15.857143 |
def match_many(self, models, results, relation):
"""
Match the eargerly loaded resuls to their single parents.
:param models: The parents
:type models: list
:param results: The results collection
:type results: Collection
:param relation: The relation
:... | [
"def",
"match_many",
"(",
"self",
",",
"models",
",",
"results",
",",
"relation",
")",
":",
"return",
"self",
".",
"_match_one_or_many",
"(",
"models",
",",
"results",
",",
"relation",
",",
"'many'",
")"
] | 26.9375 | 18.4375 |
def has_command(self, command):
"""Returns True if any of the plugins have the given command."""
for pbt in self._plugins.values():
if pbt.command == command:
return True
return False | [
"def",
"has_command",
"(",
"self",
",",
"command",
")",
":",
"for",
"pbt",
"in",
"self",
".",
"_plugins",
".",
"values",
"(",
")",
":",
"if",
"pbt",
".",
"command",
"==",
"command",
":",
"return",
"True",
"return",
"False"
] | 38.333333 | 7.666667 |
def get_tunnel_info_output_tunnel_has_conflicts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_tunnel_info = ET.Element("get_tunnel_info")
config = get_tunnel_info
output = ET.SubElement(get_tunnel_info, "output")
tunnel = ET.SubElem... | [
"def",
"get_tunnel_info_output_tunnel_has_conflicts",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_tunnel_info",
"=",
"ET",
".",
"Element",
"(",
"\"get_tunnel_info\"",
")",
"config",
"=",
"ge... | 40.333333 | 13.583333 |
def nextPlot(self):
"""Moves the displayed plot to the next one"""
if self.stacker.currentIndex() < self.stacker.count():
self.stacker.setCurrentIndex(self.stacker.currentIndex()+1) | [
"def",
"nextPlot",
"(",
"self",
")",
":",
"if",
"self",
".",
"stacker",
".",
"currentIndex",
"(",
")",
"<",
"self",
".",
"stacker",
".",
"count",
"(",
")",
":",
"self",
".",
"stacker",
".",
"setCurrentIndex",
"(",
"self",
".",
"stacker",
".",
"curren... | 51.5 | 18.5 |
def check_sas_base_dir(root=None):
''' Check for the SAS_BASE_DIR environment variable
Will set the SAS_BASE_DIR in your local environment
or prompt you to define one if is undefined
Parameters:
root (str):
Optional override of the SAS_BASE_DIR envvar
'''
sasbasedir = root... | [
"def",
"check_sas_base_dir",
"(",
"root",
"=",
"None",
")",
":",
"sasbasedir",
"=",
"root",
"or",
"os",
".",
"getenv",
"(",
"\"SAS_BASE_DIR\"",
")",
"if",
"not",
"sasbasedir",
":",
"sasbasedir",
"=",
"input",
"(",
"'Enter a path for SAS_BASE_DIR: '",
")",
"os"... | 30.933333 | 20.666667 |
def _update_structure_lines(self):
'''ATOM and HETATM lines may be altered by function calls. When this happens, this function should be called to keep self.structure_lines up to date.'''
structure_lines = []
atom_chain_order = []
chain_atoms = {}
for line in self.lines:
... | [
"def",
"_update_structure_lines",
"(",
"self",
")",
":",
"structure_lines",
"=",
"[",
"]",
"atom_chain_order",
"=",
"[",
"]",
"chain_atoms",
"=",
"{",
"}",
"for",
"line",
"in",
"self",
".",
"lines",
":",
"linetype",
"=",
"line",
"[",
"0",
":",
"6",
"]"... | 49.357143 | 22.142857 |
def build(self, recursive=True):
"""
Building an assembly buffers the :meth:`components` and :meth:`constraints`.
Running ``build()`` is optional, it's automatically run when requesting
:meth:`components` or :meth:`constraints`.
Mostly it's used to test that there aren't any c... | [
"def",
"build",
"(",
"self",
",",
"recursive",
"=",
"True",
")",
":",
"# initialize values",
"self",
".",
"_components",
"=",
"{",
"}",
"self",
".",
"_constraints",
"=",
"[",
"]",
"def",
"genwrap",
"(",
"obj",
",",
"name",
",",
"iter_type",
"=",
"None"... | 36.6 | 20.844444 |
def removeCodedValue(self, name):
"""removes a codedValue by name"""
for i in self._codedValues:
if i['name'] == name:
self._codedValues.remove(i)
return True
return False | [
"def",
"removeCodedValue",
"(",
"self",
",",
"name",
")",
":",
"for",
"i",
"in",
"self",
".",
"_codedValues",
":",
"if",
"i",
"[",
"'name'",
"]",
"==",
"name",
":",
"self",
".",
"_codedValues",
".",
"remove",
"(",
"i",
")",
"return",
"True",
"return"... | 33.285714 | 7.857143 |
def client_info(self, client):
"""
Get client info. Uses GET to /clients/<client> interface.
:Args:
* *client*: (str) Client's ID
:Returns: (dict) Client dictionary
"""
client = self._client_id(client)
response = self._get(url.clients_id.format(id=c... | [
"def",
"client_info",
"(",
"self",
",",
"client",
")",
":",
"client",
"=",
"self",
".",
"_client_id",
"(",
"client",
")",
"response",
"=",
"self",
".",
"_get",
"(",
"url",
".",
"clients_id",
".",
"format",
"(",
"id",
"=",
"client",
")",
")",
"self",
... | 31.230769 | 13.538462 |
def get_sensor_data(**kwargs):
'''
Get sensor readings
Iterates sensor reading objects
:param kwargs:
- api_host=127.0.0.1
- api_user=admin
- api_pass=example
- api_port=623
- api_kg=None
CLI Example:
.. code-block:: bash
salt-call ipmi.get_se... | [
"def",
"get_sensor_data",
"(",
"*",
"*",
"kwargs",
")",
":",
"import",
"ast",
"with",
"_IpmiCommand",
"(",
"*",
"*",
"kwargs",
")",
"as",
"s",
":",
"data",
"=",
"{",
"}",
"for",
"reading",
"in",
"s",
".",
"get_sensor_data",
"(",
")",
":",
"if",
"re... | 22.444444 | 22 |
def get_patch_op(self, keypath, value, op='replace'):
"""
Return an object that describes a change of configuration on the given staging.
Setting will be applied on all available HTTP methods.
"""
if isinstance(value, bool):
value = str(value).lower()
return {... | [
"def",
"get_patch_op",
"(",
"self",
",",
"keypath",
",",
"value",
",",
"op",
"=",
"'replace'",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
".",
"lower",
"(",
")",
"return",
"{",
"'op'",... | 46.625 | 15.625 |
def next(self):
"""Return the next match; raises Exception if no next match available"""
# Check the state and find the next match as a side-effect if necessary.
if not self.has_next():
raise StopIteration("No next match")
# Don't retain that memory any longer than necessary.... | [
"def",
"next",
"(",
"self",
")",
":",
"# Check the state and find the next match as a side-effect if necessary.",
"if",
"not",
"self",
".",
"has_next",
"(",
")",
":",
"raise",
"StopIteration",
"(",
"\"No next match\"",
")",
"# Don't retain that memory any longer than necessar... | 45.1 | 14.9 |
async def profile(self, ctx, platform, name):
'''Fetch a profile.'''
player = await self.client.get_player(platform, name)
solos = await player.get_solos()
await ctx.send("# of kills in solos for {}: {}".format(name,solos.kills.value)) | [
"async",
"def",
"profile",
"(",
"self",
",",
"ctx",
",",
"platform",
",",
"name",
")",
":",
"player",
"=",
"await",
"self",
".",
"client",
".",
"get_player",
"(",
"platform",
",",
"name",
")",
"solos",
"=",
"await",
"player",
".",
"get_solos",
"(",
"... | 37.571429 | 23.285714 |
def __obj2choices(self, values):
"""
- json list of key, value pairs:
Example: [["A", "Option 1 Label"], ["B", "Option 2 Label"]]
- space separated string with a list of options:
Example: "Option1 Opt2 Opt3"
will be converted to a key, value pair of the follow... | [
"def",
"__obj2choices",
"(",
"self",
",",
"values",
")",
":",
"choices",
"=",
"values",
"# choices from string",
"if",
"type",
"(",
"values",
")",
"==",
"type",
"(",
"''",
")",
":",
"obj",
"=",
"None",
"# try json string",
"try",
":",
"obj",
"=",
"json",... | 35.083333 | 11.833333 |
def estimate_gaussian(X):
"""
Returns the mean and the variance of a data set of X points assuming that
the points come from a gaussian distribution X.
"""
mean = np.mean(X,0)
variance = np.var(X,0)
return Gaussian(mean,variance) | [
"def",
"estimate_gaussian",
"(",
"X",
")",
":",
"mean",
"=",
"np",
".",
"mean",
"(",
"X",
",",
"0",
")",
"variance",
"=",
"np",
".",
"var",
"(",
"X",
",",
"0",
")",
"return",
"Gaussian",
"(",
"mean",
",",
"variance",
")"
] | 31.375 | 12.625 |
def filter(self, predicates):
"""Summary
Args:
grouping_column_name (TYPE): Description
Returns:
TYPE: Description
"""
tys = []
for col_name, raw_column in self.raw_columns.items():
dtype = str(raw_column.dtype)
if dtype =... | [
"def",
"filter",
"(",
"self",
",",
"predicates",
")",
":",
"tys",
"=",
"[",
"]",
"for",
"col_name",
",",
"raw_column",
"in",
"self",
".",
"raw_columns",
".",
"items",
"(",
")",
":",
"dtype",
"=",
"str",
"(",
"raw_column",
".",
"dtype",
")",
"if",
"... | 27.166667 | 16.972222 |
def add_fast(self, filepath, hashfn=None, force=False):
"""
Bespoke function to add filepaths but set shortcircuit to True, which
means only the first calculable hash will be stored. In this way only
one "fast" hashing function need be called for each filepath.
"""
if has... | [
"def",
"add_fast",
"(",
"self",
",",
"filepath",
",",
"hashfn",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"hashfn",
"is",
"None",
":",
"hashfn",
"=",
"fast_hashes",
"self",
".",
"add",
"(",
"filepath",
",",
"hashfn",
",",
"force",
",",... | 46.444444 | 17.777778 |
async def heater_control(self, device_id, fan_status=None,
power_status=None):
"""Set heater temps."""
heater = self.heaters.get(device_id)
if heater is None:
_LOGGER.error("No such device")
return
if fan_status is None:
fa... | [
"async",
"def",
"heater_control",
"(",
"self",
",",
"device_id",
",",
"fan_status",
"=",
"None",
",",
"power_status",
"=",
"None",
")",
":",
"heater",
"=",
"self",
".",
"heaters",
".",
"get",
"(",
"device_id",
")",
"if",
"heater",
"is",
"None",
":",
"_... | 41 | 7.863636 |
def _get_metadata(network_id, user_id):
"""
Get all the metadata in a network, across all scenarios
returns a dictionary of dict objects, keyed on dataset ID
"""
log.info("Getting Metadata")
dataset_qry = db.DBSession.query(
Dataset
).outerjoin(DatasetOwner, and_(Data... | [
"def",
"_get_metadata",
"(",
"network_id",
",",
"user_id",
")",
":",
"log",
".",
"info",
"(",
"\"Getting Metadata\"",
")",
"dataset_qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Dataset",
")",
".",
"outerjoin",
"(",
"DatasetOwner",
",",
"and_",
"(... | 39.542857 | 22.342857 |
def user(session, uid, ladder_ids=None):
"""Get all possible user info by name."""
data = get_user(session, uid)
resp = dict(data)
if not ladder_ids:
return resp
resp['ladders'] = {}
for ladder_id in ladder_ids:
if isinstance(ladder_id, str):
ladder_id = lookup_ladder... | [
"def",
"user",
"(",
"session",
",",
"uid",
",",
"ladder_ids",
"=",
"None",
")",
":",
"data",
"=",
"get_user",
"(",
"session",
",",
"uid",
")",
"resp",
"=",
"dict",
"(",
"data",
")",
"if",
"not",
"ladder_ids",
":",
"return",
"resp",
"resp",
"[",
"'l... | 32.705882 | 14.411765 |
def execute(self, uri, namespace, action, timeout=2, **kwargs):
"""Executes a given action with optional arguments.
The execution of an action of an UPnP/TR64 device needs more than just the name of an action. It needs the
control URI which is called to place the action and also the namespace a... | [
"def",
"execute",
"(",
"self",
",",
"uri",
",",
"namespace",
",",
"action",
",",
"timeout",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"uri",
":",
"raise",
"ValueError",
"(",
"\"No action URI has been defined.\"",
")",
"if",
"not",
"namesp... | 42.03125 | 30.515625 |
def likelihood3(args):
"""
%prog likelihood3 140_20.json 140_70.json
Plot the likelihood surface and marginal distributions for two settings.
"""
from matplotlib import gridspec
p = OptionParser(likelihood3.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="10x10",
... | [
"def",
"likelihood3",
"(",
"args",
")",
":",
"from",
"matplotlib",
"import",
"gridspec",
"p",
"=",
"OptionParser",
"(",
"likelihood3",
".",
"__doc__",
")",
"opts",
",",
"args",
",",
"iopts",
"=",
"p",
".",
"set_image_options",
"(",
"args",
",",
"figsize",
... | 31.828571 | 15.6 |
def GC_partial(portion):
"""Manually compute GC content percentage in a DNA string, taking
ambiguous values into account (according to standard IUPAC notation).
"""
sequence_count = collections.Counter(portion)
gc = ((sum([sequence_count[i] for i in 'gGcCsS']) +
sum([sequence_count[i] for... | [
"def",
"GC_partial",
"(",
"portion",
")",
":",
"sequence_count",
"=",
"collections",
".",
"Counter",
"(",
"portion",
")",
"gc",
"=",
"(",
"(",
"sum",
"(",
"[",
"sequence_count",
"[",
"i",
"]",
"for",
"i",
"in",
"'gGcCsS'",
"]",
")",
"+",
"sum",
"(",
... | 45.454545 | 18.909091 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.