text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _close_connection(self, frame_in):
"""Connection Close.
:param specification.Connection.Close frame_in: Amqp frame.
:return:
"""
self._set_connection_state(Stateful.CLOSED)
if frame_in.reply_code != 200:
reply_text = try_utf8_decode(frame_in.reply_text)
... | [
"def",
"_close_connection",
"(",
"self",
",",
"frame_in",
")",
":",
"self",
".",
"_set_connection_state",
"(",
"Stateful",
".",
"CLOSED",
")",
"if",
"frame_in",
".",
"reply_code",
"!=",
"200",
":",
"reply_text",
"=",
"try_utf8_decode",
"(",
"frame_in",
".",
... | 40.2 | 17.866667 |
async def abort(self):
"""Abort current group session."""
state = await self.state()
res = await self.call("X_Abort", MasterSessionID=state.MasterSessionID)
return res | [
"async",
"def",
"abort",
"(",
"self",
")",
":",
"state",
"=",
"await",
"self",
".",
"state",
"(",
")",
"res",
"=",
"await",
"self",
".",
"call",
"(",
"\"X_Abort\"",
",",
"MasterSessionID",
"=",
"state",
".",
"MasterSessionID",
")",
"return",
"res"
] | 39 | 17 |
def from_soup(self,author,soup):
"""
Factory Pattern. Fetches contact data from given soup and builds the object
"""
email = soup.find('span',class_='icon icon-mail').findParent('a').get('href').split(':')[-1] if soup.find('span',class_='icon icon-mail') else ''
facebook = soup.find('span',class_='icon ico... | [
"def",
"from_soup",
"(",
"self",
",",
"author",
",",
"soup",
")",
":",
"email",
"=",
"soup",
".",
"find",
"(",
"'span'",
",",
"class_",
"=",
"'icon icon-mail'",
")",
".",
"findParent",
"(",
"'a'",
")",
".",
"get",
"(",
"'href'",
")",
".",
"split",
... | 81.333333 | 50.777778 |
def metadata_response(self, request, full_url, headers):
"""
Mock response for localhost metadata
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html
"""
parsed_url = urlparse(full_url)
tomorrow = datetime.datetime.utcnow() + datetime.time... | [
"def",
"metadata_response",
"(",
"self",
",",
"request",
",",
"full_url",
",",
"headers",
")",
":",
"parsed_url",
"=",
"urlparse",
"(",
"full_url",
")",
"tomorrow",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta... | 34.076923 | 16.282051 |
def connect(self):
"""Connect the |LinkSequence| instances handled by the actual model
to the |NodeSequence| instances handled by one inlet node and
multiple oulet nodes.
The HydPy-H-Branch model passes multiple output values to different
outlet nodes. This requires additional ... | [
"def",
"connect",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"element",
".",
"inlets",
"total",
"=",
"self",
".",
"sequences",
".",
"inlets",
".",
"total",
"if",
"total",
".",
"shape",
"!=",
"(",
"len",
"(",
"nodes",
")",
",",
")",
":",
"t... | 41.652174 | 19.275362 |
def create_row_to_some_id_col_mapping(id_array):
"""
Parameters
----------
id_array : 1D ndarray.
All elements of the array should be ints representing some id related
to the corresponding row.
Returns
-------
rows_to_ids : 2D scipy sparse array.
Will map each row of... | [
"def",
"create_row_to_some_id_col_mapping",
"(",
"id_array",
")",
":",
"# Get the unique ids, in their original order of appearance",
"original_order_unique_ids",
"=",
"get_original_order_unique_ids",
"(",
"id_array",
")",
"# Create a matrix with the same number of rows as id_array but a s... | 40.461538 | 23.076923 |
def get_ids_by_expression(self, expression, threshold=0.001, func=np.sum):
""" Use a PEG to parse expression and return study IDs."""
lexer = lp.Lexer()
lexer.build()
parser = lp.Parser(
lexer, self.dataset, threshold=threshold, func=func)
parser.build()
retur... | [
"def",
"get_ids_by_expression",
"(",
"self",
",",
"expression",
",",
"threshold",
"=",
"0.001",
",",
"func",
"=",
"np",
".",
"sum",
")",
":",
"lexer",
"=",
"lp",
".",
"Lexer",
"(",
")",
"lexer",
".",
"build",
"(",
")",
"parser",
"=",
"lp",
".",
"Pa... | 44.125 | 16.875 |
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data... | [
"def",
"add_management_certificate",
"(",
"kwargs",
"=",
"None",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The add_management_certificate function must be called with -f ... | 31.093023 | 27.139535 |
def get_sudoers_entry(username=None, sudoers_entries=None):
""" Find the sudoers entry in the sudoers file for the specified user.
args:
username (str): username.
sudoers_entries (list): list of lines from the sudoers file.
returns:`r
str: sudoers entry for the specified user.
... | [
"def",
"get_sudoers_entry",
"(",
"username",
"=",
"None",
",",
"sudoers_entries",
"=",
"None",
")",
":",
"for",
"entry",
"in",
"sudoers_entries",
":",
"if",
"entry",
".",
"startswith",
"(",
"username",
")",
":",
"return",
"entry",
".",
"replace",
"(",
"use... | 33.769231 | 17.230769 |
def revoke_sudo_privileges(request):
"""
Revoke sudo privileges from a request explicitly
"""
request._sudo = False
if COOKIE_NAME in request.session:
del request.session[COOKIE_NAME] | [
"def",
"revoke_sudo_privileges",
"(",
"request",
")",
":",
"request",
".",
"_sudo",
"=",
"False",
"if",
"COOKIE_NAME",
"in",
"request",
".",
"session",
":",
"del",
"request",
".",
"session",
"[",
"COOKIE_NAME",
"]"
] | 29.285714 | 4.714286 |
def verify_otp(request):
"""
Verify a OTP request
"""
ctx = {}
if request.method == "POST":
verification_code = request.POST.get('verification_code')
if verification_code is None:
ctx['error_message'] = "Missing verification code."
else:
otp_ = UserO... | [
"def",
"verify_otp",
"(",
"request",
")",
":",
"ctx",
"=",
"{",
"}",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"verification_code",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'verification_code'",
")",
"if",
"verification_code",
"is",
"Non... | 35.48 | 23 |
def list(self, prefix='', delimiter=None):
"""Limits a list of Bucket's objects based on prefix and delimiter."""
return self.service._list(
bucket=self.name, prefix=prefix, delimiter=delimiter, objects=True
) | [
"def",
"list",
"(",
"self",
",",
"prefix",
"=",
"''",
",",
"delimiter",
"=",
"None",
")",
":",
"return",
"self",
".",
"service",
".",
"_list",
"(",
"bucket",
"=",
"self",
".",
"name",
",",
"prefix",
"=",
"prefix",
",",
"delimiter",
"=",
"delimiter",
... | 48.2 | 15.4 |
def update_data(self):
"""
Returns data for all users including shared data files.
"""
url = ('https://www.openhumans.org/api/direct-sharing/project/'
'members/?access_token={}'.format(self.master_access_token))
results = get_all_results(url)
self.project_d... | [
"def",
"update_data",
"(",
"self",
")",
":",
"url",
"=",
"(",
"'https://www.openhumans.org/api/direct-sharing/project/'",
"'members/?access_token={}'",
".",
"format",
"(",
"self",
".",
"master_access_token",
")",
")",
"results",
"=",
"get_all_results",
"(",
"url",
")"... | 47.263158 | 15.578947 |
def distill_model_event(instance, model, action, user_override=None):
"""
Take created, updated and deleted actions for built-in
app/model mappings, convert to the defined event.name
and let hooks fly.
If that model isn't represented, we just quit silenty.
"""
from rest_hooks.models import ... | [
"def",
"distill_model_event",
"(",
"instance",
",",
"model",
",",
"action",
",",
"user_override",
"=",
"None",
")",
":",
"from",
"rest_hooks",
".",
"models",
"import",
"HOOK_EVENTS",
"event_name",
"=",
"None",
"for",
"maybe_event_name",
",",
"auto",
"in",
"HOO... | 38.038462 | 16.576923 |
def ReadOffer(self, offer_link):
"""Reads an offer.
:param str offer_link:
The link to the offer.
:return:
The read Offer.
:rtype:
dict
"""
path = base.GetPathFromLink(offer_link)
offer_id = base.GetResourceIdOrFullNameFromLi... | [
"def",
"ReadOffer",
"(",
"self",
",",
"offer_link",
")",
":",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"offer_link",
")",
"offer_id",
"=",
"base",
".",
"GetResourceIdOrFullNameFromLink",
"(",
"offer_link",
")",
"return",
"self",
".",
"Read",
"(",
"p... | 25.4 | 18.933333 |
def run(self, app_input, *args, **kwargs):
"""
Creates a new job that executes the function "main" of this app with
the given input *app_input*.
See :meth:`dxpy.bindings.dxapplet.DXExecutable.run` for the available
args.
"""
# Rename app_input to preserve API com... | [
"def",
"run",
"(",
"self",
",",
"app_input",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Rename app_input to preserve API compatibility when calling",
"# DXApp.run(app_input=...).",
"return",
"super",
"(",
"DXApp",
",",
"self",
")",
".",
"run",
"(",
... | 39.545455 | 18.636364 |
def tocimxml(self):
"""
Return the CIM-XML representation of this CIM qualifier type,
as an object of an appropriate subclass of :term:`Element`.
The returned CIM-XML representation is a `QUALIFIER.DECLARATION`
element consistent with :term:`DSP0201`.
Returns:
... | [
"def",
"tocimxml",
"(",
"self",
")",
":",
"if",
"self",
".",
"value",
"is",
"None",
":",
"value_xml",
"=",
"None",
"elif",
"isinstance",
"(",
"self",
".",
"value",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"array_xml",
"=",
"[",
"]",
"for",
... | 40.571429 | 23.52381 |
def send(self, request, blocking=True):
"""Queue request for async network send, return Future()"""
future = Future()
if self.connecting():
return future.failure(Errors.NodeNotReadyError(str(self)))
elif not self.connected():
return future.failure(Errors.KafkaConn... | [
"def",
"send",
"(",
"self",
",",
"request",
",",
"blocking",
"=",
"True",
")",
":",
"future",
"=",
"Future",
"(",
")",
"if",
"self",
".",
"connecting",
"(",
")",
":",
"return",
"future",
".",
"failure",
"(",
"Errors",
".",
"NodeNotReadyError",
"(",
"... | 50.4 | 14.7 |
def cli(ctx, feature_id, name, organism="", sequence=""):
"""Set a feature's name
Output:
A standard apollo feature dictionary ({"features": [{...}]})
"""
return ctx.gi.annotations.set_name(feature_id, name, organism=organism, sequence=sequence) | [
"def",
"cli",
"(",
"ctx",
",",
"feature_id",
",",
"name",
",",
"organism",
"=",
"\"\"",
",",
"sequence",
"=",
"\"\"",
")",
":",
"return",
"ctx",
".",
"gi",
".",
"annotations",
".",
"set_name",
"(",
"feature_id",
",",
"name",
",",
"organism",
"=",
"or... | 32 | 26 |
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
"""
with open(filename, mode='w', encoding=encoding) as text_file:
text... | [
"def",
"dump",
"(",
"self",
",",
"filename",
",",
"encoding",
"=",
"\"utf8\"",
")",
":",
"with",
"open",
"(",
"filename",
",",
"mode",
"=",
"'w'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"text_file",
":",
"text_file",
".",
"write",
"(",
"self",
... | 38.333333 | 10.777778 |
def make_process_header(self, slug, typ, version, source_uri, description, inputs):
"""Generate a process definition header.
:param str slug: process' slug
:param str typ: process' type
:param str version: process' version
:param str source_uri: url to the process definition
... | [
"def",
"make_process_header",
"(",
"self",
",",
"slug",
",",
"typ",
",",
"version",
",",
"source_uri",
",",
"description",
",",
"inputs",
")",
":",
"node",
"=",
"addnodes",
".",
"desc",
"(",
")",
"signode",
"=",
"addnodes",
".",
"desc_signature",
"(",
"s... | 38.155556 | 23.066667 |
def genes_by_name(self, gene_name):
"""
Get all the unqiue genes with the given name (there might be multiple
due to copies in the genome), return a list containing a Gene object
for each distinct ID.
"""
gene_ids = self.gene_ids_of_gene_name(gene_name)
return [se... | [
"def",
"genes_by_name",
"(",
"self",
",",
"gene_name",
")",
":",
"gene_ids",
"=",
"self",
".",
"gene_ids_of_gene_name",
"(",
"gene_name",
")",
"return",
"[",
"self",
".",
"gene_by_id",
"(",
"gene_id",
")",
"for",
"gene_id",
"in",
"gene_ids",
"]"
] | 45 | 16.25 |
def help_center_article_subscriptions(self, article_id, locale=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#list-article-subscriptions"
api_path = "/api/v2/help_center/articles/{article_id}/subscriptions.json"
api_path = api_path.format(article_id=artic... | [
"def",
"help_center_article_subscriptions",
"(",
"self",
",",
"article_id",
",",
"locale",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/articles/{article_id}/subscriptions.json\"",
"api_path",
"=",
"api_path",
".",
"format",
... | 70.375 | 35.875 |
def namespaces(self):
"""Instance depends on the API version:
* 2015-08-01: :class:`NamespacesOperations<azure.mgmt.eventhub.v2015_08_01.operations.NamespacesOperations>`
* 2017-04-01: :class:`NamespacesOperations<azure.mgmt.eventhub.v2017_04_01.operations.NamespacesOperations>`
... | [
"def",
"namespaces",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'namespaces'",
")",
"if",
"api_version",
"==",
"'2015-08-01'",
":",
"from",
".",
"v2015_08_01",
".",
"operations",
"import",
"NamespacesOperations",
"as",
"Ope... | 67.882353 | 39.411765 |
def to_buffer(f):
"""
Decorator converting all strings and iterators/iterables into Buffers.
"""
@functools.wraps(f)
def wrap(*args, **kwargs):
iterator = kwargs.get('iterator', args[0])
if not isinstance(iterator, Buffer):
iterator = Buffer(iterator)
return f(ite... | [
"def",
"to_buffer",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"iterator",
"=",
"kwargs",
".",
"get",
"(",
"'iterator'",
",",
"args",
"[",
"0",
"]",
")"... | 32.090909 | 11.909091 |
def IsWalletTransaction(self, tx):
"""
Verifies if a transaction belongs to the wallet.
Args:
tx (TransactionOutput):an instance of type neo.Core.TX.Transaction.TransactionOutput to verify.
Returns:
bool: True, if transaction belongs to wallet. False, if not.
... | [
"def",
"IsWalletTransaction",
"(",
"self",
",",
"tx",
")",
":",
"for",
"key",
",",
"contract",
"in",
"self",
".",
"_contracts",
".",
"items",
"(",
")",
":",
"for",
"output",
"in",
"tx",
".",
"outputs",
":",
"if",
"output",
".",
"ScriptHash",
".",
"To... | 34.741935 | 22.483871 |
def get_activity_stream(self, before=None):
"""
Get user's activity stream from
``https://www.duolingo.com/stream/<user_id>?before=<date> if before
date is given or else
``https://www.duolingo.com/activity/<user_id>``
:param before: Datetime in format '2015-07-06 05:42:2... | [
"def",
"get_activity_stream",
"(",
"self",
",",
"before",
"=",
"None",
")",
":",
"if",
"before",
":",
"url",
"=",
"\"https://www.duolingo.com/stream/{}?before={}\"",
"url",
"=",
"url",
".",
"format",
"(",
"self",
".",
"user_data",
".",
"id",
",",
"before",
"... | 35.5 | 16.227273 |
def get_independent_nodes(dag):
"""Get a list of all node in the graph with no dependencies."""
nodes = set(dag.keys())
dependent_nodes = set([node for downstream_nodes in dag.values() for node in downstream_nodes])
return set(nodes - dependent_nodes) | [
"def",
"get_independent_nodes",
"(",
"dag",
")",
":",
"nodes",
"=",
"set",
"(",
"dag",
".",
"keys",
"(",
")",
")",
"dependent_nodes",
"=",
"set",
"(",
"[",
"node",
"for",
"downstream_nodes",
"in",
"dag",
".",
"values",
"(",
")",
"for",
"node",
"in",
... | 52.6 | 16.4 |
def set_upper_lower_bands(self,e_lower,e_upper):
"""
Set fake upper/lower bands, useful to set the same energy
range in the spin up/down bands when calculating the DOS
"""
lower_band = e_lower*np.ones((1,self.ebands.shape[1]))
upper_band = e_upper*np.ones((1,self.... | [
"def",
"set_upper_lower_bands",
"(",
"self",
",",
"e_lower",
",",
"e_upper",
")",
":",
"lower_band",
"=",
"e_lower",
"*",
"np",
".",
"ones",
"(",
"(",
"1",
",",
"self",
".",
"ebands",
".",
"shape",
"[",
"1",
"]",
")",
")",
"upper_band",
"=",
"e_upper... | 47.153846 | 17.769231 |
def _apply_tracing(self, handler, attributes):
"""
Helper function to avoid rewriting for middleware and decorator.
Returns a new span from the request with logged attributes and
correct operation name from the func.
"""
operation_name = self._get_operation_name(handler)
... | [
"def",
"_apply_tracing",
"(",
"self",
",",
"handler",
",",
"attributes",
")",
":",
"operation_name",
"=",
"self",
".",
"_get_operation_name",
"(",
"handler",
")",
"headers",
"=",
"handler",
".",
"request",
".",
"headers",
"request",
"=",
"handler",
".",
"req... | 39.769231 | 18.128205 |
def _get_pool_results(*args, **kwargs):
'''
A helper function which returns a dictionary of minion pools along with
their matching result sets.
Useful for developing other "survey style" functions.
Optionally accepts a "survey_sort=up" or "survey_sort=down" kwargs for
specifying sort order.
... | [
"def",
"_get_pool_results",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: the option \"survey.sort=\" would be preferred for namespace",
"# separation but the kwargs parser for the salt-run command seems to",
"# improperly pass the options containing a \".\" in them for lat... | 36.462963 | 25.944444 |
def print_genome_matrix(hits, fastas, id2desc, file_name):
"""
optimize later? slow ...
should combine with calculate_threshold module
"""
out = open(file_name, 'w')
fastas = sorted(fastas)
print('## percent identity between genomes', file=out)
print('# - \t %s' % ('\t'.join(fastas)), fi... | [
"def",
"print_genome_matrix",
"(",
"hits",
",",
"fastas",
",",
"id2desc",
",",
"file_name",
")",
":",
"out",
"=",
"open",
"(",
"file_name",
",",
"'w'",
")",
"fastas",
"=",
"sorted",
"(",
"fastas",
")",
"print",
"(",
"'## percent identity between genomes'",
"... | 38.03125 | 14.96875 |
def comparator(self, x, y):
'''
simple comparator method
'''
indX=0
indY=0
for i in range(len(self.stable_names)):
if self.stable_names[i] == x[0].split('-')[0]:
indX=i
if self.stable_names[i] == y[0].split('-')[0]:
... | [
"def",
"comparator",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"indX",
"=",
"0",
"indY",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"stable_names",
")",
")",
":",
"if",
"self",
".",
"stable_names",
"[",
"i",
"]",
"==",
... | 22.05 | 22.25 |
def new_dotdot(self, vd, parent, seqnum, rock_ridge, log_block_size,
rr_relocated_parent, xa, file_mode):
# type: (headervd.PrimaryOrSupplementaryVD, DirectoryRecord, int, str, int, bool, bool, int) -> None
'''
Create a new 'dotdot' Directory Record.
Parameters:
... | [
"def",
"new_dotdot",
"(",
"self",
",",
"vd",
",",
"parent",
",",
"seqnum",
",",
"rock_ridge",
",",
"log_block_size",
",",
"rr_relocated_parent",
",",
"xa",
",",
"file_mode",
")",
":",
"# type: (headervd.PrimaryOrSupplementaryVD, DirectoryRecord, int, str, int, bool, bool,... | 48.791667 | 28.375 |
def log(logger, level, message):
"""Logs message to stderr if logging isn't initialized."""
if logger.parent.name != 'root':
logger.log(level, message)
else:
print(message, file=sys.stderr) | [
"def",
"log",
"(",
"logger",
",",
"level",
",",
"message",
")",
":",
"if",
"logger",
".",
"parent",
".",
"name",
"!=",
"'root'",
":",
"logger",
".",
"log",
"(",
"level",
",",
"message",
")",
"else",
":",
"print",
"(",
"message",
",",
"file",
"=",
... | 30.285714 | 12.857143 |
def is_multisig_address(addr, blockchain='bitcoin', **blockchain_opts):
"""
Is the given address a multisig address?
"""
if blockchain == 'bitcoin':
return btc_is_multisig_address(addr, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) | [
"def",
"is_multisig_address",
"(",
"addr",
",",
"blockchain",
"=",
"'bitcoin'",
",",
"*",
"*",
"blockchain_opts",
")",
":",
"if",
"blockchain",
"==",
"'bitcoin'",
":",
"return",
"btc_is_multisig_address",
"(",
"addr",
",",
"*",
"*",
"blockchain_opts",
")",
"el... | 37.75 | 16 |
def logout():
""" Log out the active user
"""
flogin.logout_user()
next = flask.request.args.get('next')
return flask.redirect(next or flask.url_for("user")) | [
"def",
"logout",
"(",
")",
":",
"flogin",
".",
"logout_user",
"(",
")",
"next",
"=",
"flask",
".",
"request",
".",
"args",
".",
"get",
"(",
"'next'",
")",
"return",
"flask",
".",
"redirect",
"(",
"next",
"or",
"flask",
".",
"url_for",
"(",
"\"user\""... | 28.666667 | 10 |
def version(context=None):
'''
Attempts to run systemctl --version. Returns None if unable to determine
version.
'''
contextkey = 'salt.utils.systemd.version'
if isinstance(context, dict):
# Can't put this if block on the same line as the above if block,
# because it will break t... | [
"def",
"version",
"(",
"context",
"=",
"None",
")",
":",
"contextkey",
"=",
"'salt.utils.systemd.version'",
"if",
"isinstance",
"(",
"context",
",",
"dict",
")",
":",
"# Can't put this if block on the same line as the above if block,",
"# because it will break the elif below.... | 35.34375 | 20.09375 |
def writerow(self, cells):
"""
Write a row of cells into the default sheet of the spreadsheet.
:param cells: A list of cells (most basic Python types supported).
:return: Nothing.
"""
if self.default_sheet is None:
self.default_sheet = self.new_sheet()
... | [
"def",
"writerow",
"(",
"self",
",",
"cells",
")",
":",
"if",
"self",
".",
"default_sheet",
"is",
"None",
":",
"self",
".",
"default_sheet",
"=",
"self",
".",
"new_sheet",
"(",
")",
"self",
".",
"default_sheet",
".",
"writerow",
"(",
"cells",
")"
] | 38.555556 | 11.888889 |
def unregister_path(self, path):
"""
Unregisters given path.
:param path: Path name.
:type path: unicode
:return: Method success.
:rtype: bool
"""
if not path in self:
raise umbra.exceptions.PathExistsError("{0} | '{1}' path isn't registered!... | [
"def",
"unregister_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"path",
"in",
"self",
":",
"raise",
"umbra",
".",
"exceptions",
".",
"PathExistsError",
"(",
"\"{0} | '{1}' path isn't registered!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",... | 26 | 18.125 |
def unregister(self):
'''Remove this worker from the list of available workers.
This requires the worker to already have been :meth:`register()`.
'''
self.task_master.worker_unregister(self.worker_id)
self.task_master.worker_id = None
self.worker_id = None | [
"def",
"unregister",
"(",
"self",
")",
":",
"self",
".",
"task_master",
".",
"worker_unregister",
"(",
"self",
".",
"worker_id",
")",
"self",
".",
"task_master",
".",
"worker_id",
"=",
"None",
"self",
".",
"worker_id",
"=",
"None"
] | 33.222222 | 23.888889 |
def batch_work(self):
"""
Method to be executed in batch mode for collecting the required fragment (composite)
and then other custom tasks.
:return:
"""
while True:
gen = collect_fragment(self._stop_event, self.config['AGORA'])
for collector, (t, ... | [
"def",
"batch_work",
"(",
"self",
")",
":",
"while",
"True",
":",
"gen",
"=",
"collect_fragment",
"(",
"self",
".",
"_stop_event",
",",
"self",
".",
"config",
"[",
"'AGORA'",
"]",
")",
"for",
"collector",
",",
"(",
"t",
",",
"s",
",",
"p",
",",
"o"... | 36.352941 | 16.117647 |
def helpful_error_list_get(lst, index):
"""
>>> helpful_error_list_get([1, 2, 3], 1)
2
>>> helpful_error_list_get([1, 2, 3], 4)
Traceback (most recent call last):
...
IndexError: Tried to access 4, length is only 3
"""
try:
return lst[index]
except IndexError:
rai... | [
"def",
"helpful_error_list_get",
"(",
"lst",
",",
"index",
")",
":",
"try",
":",
"return",
"lst",
"[",
"index",
"]",
"except",
"IndexError",
":",
"raise",
"IndexError",
"(",
"'Tried to access %r, length is only %r'",
"%",
"(",
"index",
",",
"len",
"(",
"lst",
... | 29.384615 | 15.384615 |
def n_lfom_rows(FLOW,HL_LFOM):
"""This equation states that the open area corresponding to one row can be
set equal to two orifices of diameter=row height. If there are more than
two orifices per row at the top of the LFOM then there are more orifices
than are convenient to drill and more than necessary... | [
"def",
"n_lfom_rows",
"(",
"FLOW",
",",
"HL_LFOM",
")",
":",
"N_estimated",
"=",
"(",
"HL_LFOM",
"*",
"np",
".",
"pi",
"/",
"(",
"2",
"*",
"width_stout",
"(",
"HL_LFOM",
",",
"HL_LFOM",
")",
"*",
"FLOW",
")",
")",
"variablerow",
"=",
"min",
"(",
"1... | 50.692308 | 24.346154 |
def save_module(self, obj):
"""
Save a module as an import
"""
self.modules.add(obj)
self.save_reduce(subimport, (obj.__name__,), obj=obj) | [
"def",
"save_module",
"(",
"self",
",",
"obj",
")",
":",
"self",
".",
"modules",
".",
"add",
"(",
"obj",
")",
"self",
".",
"save_reduce",
"(",
"subimport",
",",
"(",
"obj",
".",
"__name__",
",",
")",
",",
"obj",
"=",
"obj",
")"
] | 25.5 | 9.166667 |
def requester(
url,
main_url=None,
delay=0,
cook=None,
headers=None,
timeout=10,
host=None,
proxies=[None],
user_agents=[None],
failed=None,
processed=None
):
"""Handle the requests and return the response body."""
cook ... | [
"def",
"requester",
"(",
"url",
",",
"main_url",
"=",
"None",
",",
"delay",
"=",
"0",
",",
"cook",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"timeout",
"=",
"10",
",",
"host",
"=",
"None",
",",
"proxies",
"=",
"[",
"None",
"]",
",",
"user_ag... | 28.66129 | 15.887097 |
def loss_maps(curves, conditional_loss_poes):
"""
:param curves: an array of loss curves
:param conditional_loss_poes: a list of conditional loss poes
:returns: a composite array of loss maps with the same shape
"""
loss_maps_dt = numpy.dtype([('poe-%s' % poe, F32)
... | [
"def",
"loss_maps",
"(",
"curves",
",",
"conditional_loss_poes",
")",
":",
"loss_maps_dt",
"=",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"'poe-%s'",
"%",
"poe",
",",
"F32",
")",
"for",
"poe",
"in",
"conditional_loss_poes",
"]",
")",
"loss_maps",
"=",
"numpy",... | 45.214286 | 12.785714 |
def is_mdgel(self):
"""File has MD Gel format."""
# TODO: this likely reads the second page from file
try:
ismdgel = self.pages[0].is_mdgel or self.pages[1].is_mdgel
if ismdgel:
self.is_uniform = False
return ismdgel
except IndexError:
... | [
"def",
"is_mdgel",
"(",
"self",
")",
":",
"# TODO: this likely reads the second page from file",
"try",
":",
"ismdgel",
"=",
"self",
".",
"pages",
"[",
"0",
"]",
".",
"is_mdgel",
"or",
"self",
".",
"pages",
"[",
"1",
"]",
".",
"is_mdgel",
"if",
"ismdgel",
... | 33.5 | 16 |
async def get(self, path, **query):
'''return a get request
Parameters
----------
path : str
same as get_url
query : kargs dict
additional info to pass to get_url
See Also
--------
get_url :
getJson :
Returns
-------
requests.models.Response
the r... | [
"async",
"def",
"get",
"(",
"self",
",",
"path",
",",
"*",
"*",
"query",
")",
":",
"url",
"=",
"self",
".",
"get_url",
"(",
"path",
",",
"*",
"*",
"query",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"tries",
"+",
"1",
")",
":",
"try",
... | 22.058824 | 20.823529 |
def sign_execute_cancellation(cancellation_params, key_pair):
"""
Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange.
Execution of this function is as follows::
sign_execute_cancellation(cancellation_params=signable_params, key_pair=key_pair)
Th... | [
"def",
"sign_execute_cancellation",
"(",
"cancellation_params",
",",
"key_pair",
")",
":",
"signature",
"=",
"sign_transaction",
"(",
"transaction",
"=",
"cancellation_params",
"[",
"'transaction'",
"]",
",",
"private_key_hex",
"=",
"private_key_to_hex",
"(",
"key_pair"... | 45.409091 | 30.681818 |
def vb_list_machines(**kwargs):
'''
Which machines does the hypervisor have
@param kwargs: Passed to vb_xpcom_to_attribute_dict to filter the attributes
@type kwargs: dict
@return: Untreated dicts of the machines known to the hypervisor
@rtype: [{}]
'''
manager = vb_get_manager()
mac... | [
"def",
"vb_list_machines",
"(",
"*",
"*",
"kwargs",
")",
":",
"manager",
"=",
"vb_get_manager",
"(",
")",
"machines",
"=",
"manager",
".",
"getArray",
"(",
"vb_get_box",
"(",
")",
",",
"'machines'",
")",
"return",
"[",
"vb_xpcom_to_attribute_dict",
"(",
"mac... | 34.142857 | 22 |
def cli_print(msg, color='', end=None, file=sys.stdout, logger=_LOG):
"""Print the message to file and also log it.
This function is intended as a 'tee' mechanism to enable the CLI interface as
a first-class citizen, while ensuring that everything the operator sees also
has an analogous logging entry in the te... | [
"def",
"cli_print",
"(",
"msg",
",",
"color",
"=",
"''",
",",
"end",
"=",
"None",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"logger",
"=",
"_LOG",
")",
":",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"'-> {}'",
".",
"format",
"(",
"msg"... | 42.96 | 24.08 |
def register_method(func, name=None, deprecated=False):
"""Register a method of calculating an average spectrogram.
Parameters
----------
func : `callable`
function to execute
name : `str`, optional
name of the method, defaults to ``func.__name__``
deprecated : `bool`, optiona... | [
"def",
"register_method",
"(",
"func",
",",
"name",
"=",
"None",
",",
"deprecated",
"=",
"False",
")",
":",
"# warn about deprecated functions",
"if",
"deprecated",
":",
"func",
"=",
"deprecated_function",
"(",
"func",
",",
"\"the {0!r} PSD methods is deprecated, and ... | 27.857143 | 21.342857 |
def service_absent(name, namespace='default', **kwargs):
'''
Ensures that the named service is absent from the given namespace.
name
The name of the service
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
... | [
"def",
"service_absent",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"... | 27.307692 | 23.820513 |
def filter_nomedia(album, settings=None):
"""Removes all filtered Media and subdirs from an Album"""
nomediapath = os.path.join(album.src_path, ".nomedia")
if os.path.isfile(nomediapath):
if os.path.getsize(nomediapath) == 0:
logger.info("Ignoring album '%s' because of present 0-byte "
... | [
"def",
"filter_nomedia",
"(",
"album",
",",
"settings",
"=",
"None",
")",
":",
"nomediapath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"album",
".",
"src_path",
",",
"\".nomedia\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"nomediapath",
")",... | 42.615385 | 21.794872 |
def formatTimeFromNow(secs=0):
""" Properly Format Time that is `x` seconds in the future
:param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`)
:return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`)
:rtype: str
"""
return datetime.utcfromtimestamp(time.time() ... | [
"def",
"formatTimeFromNow",
"(",
"secs",
"=",
"0",
")",
":",
"return",
"datetime",
".",
"utcfromtimestamp",
"(",
"time",
".",
"time",
"(",
")",
"+",
"int",
"(",
"secs",
")",
")",
".",
"strftime",
"(",
"timeformat",
")"
] | 38.333333 | 24.888889 |
def mod(self, x, axis):
"""Function to modulo 3D View with vector or 2D array (type = numpy.ndarray or 2D Field or 2D View) or 2D View with vector (type = numpy.ndarray)
:param x: array(1D, 2D) or field (2D) or View(2D)
:param axis: specifies axis, eg. axis = (1,2) plane lies in yz-plane, axis=0... | [
"def",
"mod",
"(",
"self",
",",
"x",
",",
"axis",
")",
":",
"return",
"self",
".",
"__array_op",
"(",
"operator",
".",
"mod",
",",
"x",
",",
"axis",
")"
] | 67 | 19.857143 |
def pick_free_port(hostname=REDIRECT_HOST, port=0):
""" Try to bind a port. Default=0 selects a free port. """
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((hostname, port)) # port=0 finds an open port
except OSError as e:
log.warning("Could not bi... | [
"def",
"pick_free_port",
"(",
"hostname",
"=",
"REDIRECT_HOST",
",",
"port",
"=",
"0",
")",
":",
"import",
"socket",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"try",
":",
"s",
".",
"bind",... | 37.5 | 18.25 |
def saveFileTo(self, buf, encoding):
"""Dump an XML document to an I/O buffer. Warning ! This call
xmlOutputBufferClose() on buf which is not available after
this call. """
if buf is None: buf__o = None
else: buf__o = buf._o
ret = libxml2mod.xmlSaveFileTo(buf__o, sel... | [
"def",
"saveFileTo",
"(",
"self",
",",
"buf",
",",
"encoding",
")",
":",
"if",
"buf",
"is",
"None",
":",
"buf__o",
"=",
"None",
"else",
":",
"buf__o",
"=",
"buf",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlSaveFileTo",
"(",
"buf__o",
",",
"self",
... | 43.375 | 11.625 |
def execute(cls, stage, state, data, next_allowed_exec_time=None):
"""Execute the operation, rate limiting allowing."""
try:
context = Context.from_state(state, stage)
now = datetime.utcnow()
if next_allowed_exec_time and now < next_allowed_exec_time:
... | [
"def",
"execute",
"(",
"cls",
",",
"stage",
",",
"state",
",",
"data",
",",
"next_allowed_exec_time",
"=",
"None",
")",
":",
"try",
":",
"context",
"=",
"Context",
".",
"from_state",
"(",
"state",
",",
"stage",
")",
"now",
"=",
"datetime",
".",
"utcnow... | 46.741935 | 16.419355 |
def header(settings):
"""
Writes the Latex header using the settings file.
The header includes all packages and defines all tikz styles.
:param dictionary settings: LaTeX settings for document.
:return: Header of the LaTeX document.
:rtype: string
"""
packages = (r"\documentclass[conve... | [
"def",
"header",
"(",
"settings",
")",
":",
"packages",
"=",
"(",
"r\"\\documentclass[convert={density=300,outext=.png}]{standalone}\"",
",",
"r\"\\usepackage[margin=1in]{geometry}\"",
",",
"r\"\\usepackage[hang,small,bf]{caption}\"",
",",
"r\"\\usepackage{tikz}\"",
",",
"r\"\\usep... | 52.537037 | 28.648148 |
def gradient_helper(optimizer, loss, var_list=None):
'''A helper to get the gradients out at each step.
Args:
optimizer: the optimizer op.
loss: the op that computes your loss value.
Returns: the gradient tensors and the train_step op.
'''
if var_list is None:
var_list = tf.compa... | [
"def",
"gradient_helper",
"(",
"optimizer",
",",
"loss",
",",
"var_list",
"=",
"None",
")",
":",
"if",
"var_list",
"is",
"None",
":",
"var_list",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"trainable_variables",
"(",
")",
"grads_and_vars",
"=",
"optimizer",... | 32.25 | 23 |
def name_indel_mutation(sbjct_seq, indel, sbjct_rf_indel, qry_rf_indel, codon_no, mut, start_offset):
"""
This function serves to name the individual mutations dependently on
the type of the mutation.
"""
# Get the subject and query sequences without gaps
sbjct_nucs = sbjct_rf_indel.replace("-"... | [
"def",
"name_indel_mutation",
"(",
"sbjct_seq",
",",
"indel",
",",
"sbjct_rf_indel",
",",
"qry_rf_indel",
",",
"codon_no",
",",
"mut",
",",
"start_offset",
")",
":",
"# Get the subject and query sequences without gaps",
"sbjct_nucs",
"=",
"sbjct_rf_indel",
".",
"replace... | 34.62963 | 22.814815 |
def disagg_prec(dailyData,
method='equal',
cascade_options=None,
hourly_data_obs=None,
zerodiv="uniform",
shift=0):
"""The disaggregation function for precipitation.
Parameters
----------
dailyData : pd.Series
daily... | [
"def",
"disagg_prec",
"(",
"dailyData",
",",
"method",
"=",
"'equal'",
",",
"cascade_options",
"=",
"None",
",",
"hourly_data_obs",
"=",
"None",
",",
"zerodiv",
"=",
"\"uniform\"",
",",
"shift",
"=",
"0",
")",
":",
"if",
"method",
"not",
"in",
"(",
"'equ... | 34.534884 | 17.325581 |
def select(*cases):
"""
Select the first case that becomes ready.
If a default case (:class:`goless.dcase`) is present,
return that if no other cases are ready.
If there is no default case and no case is ready,
block until one becomes ready.
See Go's ``reflect.Select`` method for an analog
... | [
"def",
"select",
"(",
"*",
"cases",
")",
":",
"if",
"len",
"(",
"cases",
")",
"==",
"0",
":",
"return",
"# If the first argument is a list, it should be the only argument",
"if",
"isinstance",
"(",
"cases",
"[",
"0",
"]",
",",
"list",
")",
":",
"if",
"len",
... | 37.924528 | 18.830189 |
def make_eventlogitem_message(message, condition='contains', negate=False, preserve_case=False):
"""
Create a node for EventLogItem/message
:return: A IndicatorItem represented as an Element node
"""
document = 'EventLogItem'
search = 'EventLogItem/message'
content_type = 'string'
c... | [
"def",
"make_eventlogitem_message",
"(",
"message",
",",
"condition",
"=",
"'contains'",
",",
"negate",
"=",
"False",
",",
"preserve_case",
"=",
"False",
")",
":",
"document",
"=",
"'EventLogItem'",
"search",
"=",
"'EventLogItem/message'",
"content_type",
"=",
"'s... | 40.846154 | 22.230769 |
def sparse_segment(cords):
r"""
Create a segment of a sparse grid.
Convert a ol-index to sparse grid coordinates on ``[0, 1]^N`` hyper-cube.
A sparse grid of order ``D`` coencide with the set of sparse_segments where
``||cords||_1 <= D``.
More specifically, a segment of:
.. math::
... | [
"def",
"sparse_segment",
"(",
"cords",
")",
":",
"cords",
"=",
"np",
".",
"array",
"(",
"cords",
")",
"+",
"1",
"slices",
"=",
"[",
"]",
"for",
"cord",
"in",
"cords",
":",
"slices",
".",
"append",
"(",
"slice",
"(",
"1",
",",
"2",
"**",
"cord",
... | 26.021277 | 22.510638 |
def send_template(self, template, to, reply_to=None, **context):
"""
Send Template message
"""
if self.provider == "SES":
self.mail.send_template(template=template, to=to, reply_to=reply_to, **context)
elif self.provider == "FLASK-MAIL":
ses_mail = ses_mai... | [
"def",
"send_template",
"(",
"self",
",",
"template",
",",
"to",
",",
"reply_to",
"=",
"None",
",",
"*",
"*",
"context",
")",
":",
"if",
"self",
".",
"provider",
"==",
"\"SES\"",
":",
"self",
".",
"mail",
".",
"send_template",
"(",
"template",
"=",
"... | 46.117647 | 17.529412 |
def delete(self, key):
'''Removes the object named by `key`.
Removes the object from the collection corresponding to ``key.path``.
Args:
key: Key naming the object to remove.
'''
try:
del self._collection(key)[key]
if len(self._collection(key)) == 0:
del self._items[str(... | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"del",
"self",
".",
"_collection",
"(",
"key",
")",
"[",
"key",
"]",
"if",
"len",
"(",
"self",
".",
"_collection",
"(",
"key",
")",
")",
"==",
"0",
":",
"del",
"self",
".",
"_items... | 23.4 | 21.666667 |
def as_ihex(self, number_of_data_bytes=32, address_length_bits=32):
"""Format the binary file as Intel HEX records and return them as a
string.
`number_of_data_bytes` is the number of data bytes in each
record.
`address_length_bits` is the number of address bits in each
... | [
"def",
"as_ihex",
"(",
"self",
",",
"number_of_data_bytes",
"=",
"32",
",",
"address_length_bits",
"=",
"32",
")",
":",
"def",
"i32hex",
"(",
"address",
",",
"extended_linear_address",
",",
"data_address",
")",
":",
"if",
"address",
">",
"0xffffffff",
":",
"... | 41.017094 | 20.82906 |
def _compile(cls, lines):
'''Return the filename from the current line.'''
m = cls.RE_EXTEND.match(lines.current)
if m is None:
raise DefineBlockError('''Incorrect block definition at line {}, {}
Should be something like: #extend path/foo.html:'''.format(
lines.pos, l... | [
"def",
"_compile",
"(",
"cls",
",",
"lines",
")",
":",
"m",
"=",
"cls",
".",
"RE_EXTEND",
".",
"match",
"(",
"lines",
".",
"current",
")",
"if",
"m",
"is",
"None",
":",
"raise",
"DefineBlockError",
"(",
"'''Incorrect block definition at line {}, {}\nShould be ... | 44.125 | 16.375 |
def dict(self):
"""
the python object for rendering json.
It is called dict to be
coherent with the other modules but it actually returns a list
:return: the python object for rendering json
:rtype: list
"""
json_list = []
for step in self.steps... | [
"def",
"dict",
"(",
"self",
")",
":",
"json_list",
"=",
"[",
"]",
"for",
"step",
"in",
"self",
".",
"steps",
":",
"json_list",
".",
"append",
"(",
"step",
".",
"dict",
")",
"return",
"json_list"
] | 24.8 | 17.733333 |
def _worker_handler(future, worker, pipe, timeout):
"""Worker lifecycle manager.
Waits for the worker to be perform its task,
collects result, runs the callback and cleans up the process.
"""
result = _get_result(future, pipe, timeout)
if isinstance(result, BaseException):
if isinstan... | [
"def",
"_worker_handler",
"(",
"future",
",",
"worker",
",",
"pipe",
",",
"timeout",
")",
":",
"result",
"=",
"_get_result",
"(",
"future",
",",
"pipe",
",",
"timeout",
")",
"if",
"isinstance",
"(",
"result",
",",
"BaseException",
")",
":",
"if",
"isinst... | 27 | 17.473684 |
def get_response(self, request):
'''Returns the redirect response for this exception.'''
# the redirect key is already placed in the response by HttpResponseJavascriptRedirect
return HttpResponseJavascriptRedirect(self.redirect_to, *self.args, **self.kwargs) | [
"def",
"get_response",
"(",
"self",
",",
"request",
")",
":",
"# the redirect key is already placed in the response by HttpResponseJavascriptRedirect",
"return",
"HttpResponseJavascriptRedirect",
"(",
"self",
".",
"redirect_to",
",",
"*",
"self",
".",
"args",
",",
"*",
"*... | 69.75 | 33.75 |
def Tautoignition(CASRN, AvailableMethods=False, Method=None):
r'''This function handles the retrieval or calculation of a chemical's
autoifnition temperature. Lookup is based on CASRNs. No predictive methods
are currently implemented. Will automatically select a data source to use
if no Method is provi... | [
"def",
"Tautoignition",
"(",
"CASRN",
",",
"AvailableMethods",
"=",
"False",
",",
"Method",
"=",
"None",
")",
":",
"def",
"list_methods",
"(",
")",
":",
"methods",
"=",
"[",
"]",
"if",
"CASRN",
"in",
"IEC_2010",
".",
"index",
"and",
"not",
"np",
".",
... | 35.084507 | 25.056338 |
def span(self, name='child_span'):
"""Create a child span for the current span and append it to the child
spans list.
:type name: str
:param name: (Optional) The name of the child span.
:rtype: :class: `~opencensus.trace.blankspan.BlankSpan`
:returns: A child Span to be... | [
"def",
"span",
"(",
"self",
",",
"name",
"=",
"'child_span'",
")",
":",
"child_span",
"=",
"BlankSpan",
"(",
"name",
",",
"parent_span",
"=",
"self",
")",
"self",
".",
"_child_spans",
".",
"append",
"(",
"child_span",
")",
"return",
"child_span"
] | 36.384615 | 17.076923 |
def _lease_valid(self, lease):
"""
Check if the given lease exist and still has a prefix that owns it.
If the lease exist but its prefix isn't, remove the lease from this
store.
Args:
lease (lago.subnet_lease.Lease): Object representation of the
lease... | [
"def",
"_lease_valid",
"(",
"self",
",",
"lease",
")",
":",
"if",
"not",
"lease",
".",
"exist",
":",
"return",
"None",
"if",
"lease",
".",
"has_env",
":",
"return",
"lease",
".",
"uuid_path",
"else",
":",
"self",
".",
"_release",
"(",
"lease",
")",
"... | 29.636364 | 22.181818 |
def arguments():
"""Pulls in command line arguments."""
DESCRIPTION = """\
"""
parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=Raw)
parser.add_argument("--email", dest="email", action='store', required=False, default=False,
help="An email address ... | [
"def",
"arguments",
"(",
")",
":",
"DESCRIPTION",
"=",
"\"\"\"\\\n \"\"\"",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"DESCRIPTION",
",",
"formatter_class",
"=",
"Raw",
")",
"parser",
".",
"add_argument",
"(",
"\"--email\"",
"... | 40.897436 | 32.974359 |
def COH(self):
"""Coherence.
.. math:: \mathrm{COH}_{ij}(f) = \\frac{S_{ij}(f)}
{\sqrt{S_{ii}(f) S_{jj}(f)}}
References
----------
P. L. Nunez, R. Srinivasan, A. F. Westdorp, R. S. Wijesinghe,
D. M. Tucker, R. B. Silverstei... | [
"def",
"COH",
"(",
"self",
")",
":",
"S",
"=",
"self",
".",
"S",
"(",
")",
"# TODO: can we do that more efficiently?",
"return",
"S",
"/",
"np",
".",
"sqrt",
"(",
"np",
".",
"einsum",
"(",
"'ii..., jj... ->ij...'",
",",
"S",
",",
"S",
".",
"conj",
"(",... | 41.058824 | 23.882353 |
def getdrawings():
"""Get all the drawings."""
infos = Info.query.all()
sketches = [json.loads(info.contents) for info in infos]
return jsonify(drawings=sketches) | [
"def",
"getdrawings",
"(",
")",
":",
"infos",
"=",
"Info",
".",
"query",
".",
"all",
"(",
")",
"sketches",
"=",
"[",
"json",
".",
"loads",
"(",
"info",
".",
"contents",
")",
"for",
"info",
"in",
"infos",
"]",
"return",
"jsonify",
"(",
"drawings",
"... | 34.8 | 11.4 |
def sendEmoji(
self,
emoji=None,
size=EmojiSize.SMALL,
thread_id=None,
thread_type=ThreadType.USER,
):
"""
Deprecated. Use :func:`fbchat.Client.send` instead
"""
return self.send(
Message(text=emoji, emoji_size=size),
th... | [
"def",
"sendEmoji",
"(",
"self",
",",
"emoji",
"=",
"None",
",",
"size",
"=",
"EmojiSize",
".",
"SMALL",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
",",
")",
":",
"return",
"self",
".",
"send",
"(",
"Message",
... | 24.733333 | 15 |
def _parse_kick(client, command, actor, args):
"""Parse a KICK and update channel states, then dispatch events.
Note that two events are dispatched here:
- KICK, because a user was kicked from the channel
- MEMBERS, because the channel's members changed
"""
actor = User(actor)
args,... | [
"def",
"_parse_kick",
"(",
"client",
",",
"command",
",",
"actor",
",",
"args",
")",
":",
"actor",
"=",
"User",
"(",
"actor",
")",
"args",
",",
"_",
",",
"message",
"=",
"args",
".",
"partition",
"(",
"' :'",
")",
"channel",
",",
"target",
"=",
"ar... | 39.941176 | 10.588235 |
def get_html_theme_path():
"""
Get the absolute path of the directory containing the theme files.
"""
return os.path.abspath(os.path.dirname(os.path.dirname(__file__))) | [
"def",
"get_html_theme_path",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")"
] | 36 | 14.8 |
def clean_up(self):
"""Do clean-up before returning buffer"""
self.action_buffer = []
self.sources = {}
self.doc_to_get = {}
self.doc_to_update = [] | [
"def",
"clean_up",
"(",
"self",
")",
":",
"self",
".",
"action_buffer",
"=",
"[",
"]",
"self",
".",
"sources",
"=",
"{",
"}",
"self",
".",
"doc_to_get",
"=",
"{",
"}",
"self",
".",
"doc_to_update",
"=",
"[",
"]"
] | 30.5 | 11 |
def capacity_sp_meyerhof_and_hanna_1978(sp, fd, verbose=0):
"""
Calculates the two-layered foundation capacity according Meyerhof and Hanna (1978)
:param sp: Soil profile object
:param fd: Foundation object
:param wtl: water table level
:param verbose: verbosity
:return: ultimate bearing st... | [
"def",
"capacity_sp_meyerhof_and_hanna_1978",
"(",
"sp",
",",
"fd",
",",
"verbose",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"sp",
",",
"sm",
".",
"SoilProfile",
")",
"sl_0",
"=",
"sp",
".",
"layer",
"(",
"1",
")",
"sl_1",
"=",
"sp",
".",
"la... | 43.55 | 27.773077 |
async def fetch_guild(self, guild_id):
"""|coro|
Retrieves a :class:`.Guild` from an ID.
.. note::
Using this, you will not receive :attr:`.Guild.channels`, :class:`.Guild.members`,
:attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`.
.. no... | [
"async",
"def",
"fetch_guild",
"(",
"self",
",",
"guild_id",
")",
":",
"data",
"=",
"await",
"self",
".",
"http",
".",
"get_guild",
"(",
"guild_id",
")",
"return",
"Guild",
"(",
"data",
"=",
"data",
",",
"state",
"=",
"self",
".",
"_connection",
")"
] | 26.393939 | 23.727273 |
def attribute(func):
"""Wrap a function as an attribute."""
attr = abc.abstractmethod(func)
attr.__iattribute__ = True
attr = _property(attr)
return attr | [
"def",
"attribute",
"(",
"func",
")",
":",
"attr",
"=",
"abc",
".",
"abstractmethod",
"(",
"func",
")",
"attr",
".",
"__iattribute__",
"=",
"True",
"attr",
"=",
"_property",
"(",
"attr",
")",
"return",
"attr"
] | 28 | 12.333333 |
def evidence_from_inversion_terms(chi_squared, regularization_term, log_curvature_regularization_term,
log_regularization_term, noise_normalization):
"""Compute the evidence of an inversion's fit to the datas, where the evidence includes a number of \
terms which quantify the c... | [
"def",
"evidence_from_inversion_terms",
"(",
"chi_squared",
",",
"regularization_term",
",",
"log_curvature_regularization_term",
",",
"log_regularization_term",
",",
"noise_normalization",
")",
":",
"return",
"-",
"0.5",
"*",
"(",
"chi_squared",
"+",
"regularization_term",... | 58.25 | 31.25 |
def p_InterfaceDefList(p):
'''
InterfaceDefList : InterfaceDef
| InterfaceDefList InterfaceDef
'''
if len(p) < 3:
p[0] = InterfaceDefList(None, p[1])
else:
p[0] = InterfaceDefList(p[1], p[2]) | [
"def",
"p_InterfaceDefList",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"<",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"InterfaceDefList",
"(",
"None",
",",
"p",
"[",
"1",
"]",
")",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"InterfaceDefList",
"(",
... | 26.666667 | 17.333333 |
def prompt_update_all(config: 'Config'):
"""Prompt each field of the configuration to the user."""
click.echo()
click.echo('Welcome !')
click.echo('Press enter to keep the defaults or enter a new value to update the configuration.')
click.echo('Press Ctrl+C at any time to quit and save')
click.... | [
"def",
"prompt_update_all",
"(",
"config",
":",
"'Config'",
")",
":",
"click",
".",
"echo",
"(",
")",
"click",
".",
"echo",
"(",
"'Welcome !'",
")",
"click",
".",
"echo",
"(",
"'Press enter to keep the defaults or enter a new value to update the configuration.'",
")",... | 36.931818 | 24.227273 |
def _dispatch(self, cmd, args):
"""Attempt to run the given command with the given arguments
"""
if cmd in self.clis:
extern_cmd, args = args[0], args[1:]
self.clis[cmd]._dispatch(extern_cmd, args)
else:
if cmd in self.cmds:
callback, p... | [
"def",
"_dispatch",
"(",
"self",
",",
"cmd",
",",
"args",
")",
":",
"if",
"cmd",
"in",
"self",
".",
"clis",
":",
"extern_cmd",
",",
"args",
"=",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
":",
"]",
"self",
".",
"clis",
"[",
"cmd",
"]",
"."... | 38.375 | 13.3125 |
def trigger_show_by_trigger_name(self, trigger_name, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/triggers#get-a-trigger"
api_path = "/api/v2/triggers/{trigger_name}"
api_path = api_path.format(trigger_name=trigger_name)
return self.call(api_path, **kwargs) | [
"def",
"trigger_show_by_trigger_name",
"(",
"self",
",",
"trigger_name",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/triggers/{trigger_name}\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"trigger_name",
"=",
"trigger_name",
")",
"return",
... | 60.2 | 20.2 |
def bias_abs(sim=None, obs=None, node=None, skip_nan=False):
"""Calculate the absolute difference between the means of the simulated
and the observed values.
>>> from hydpy import round_
>>> from hydpy import bias_abs
>>> round_(bias_abs(sim=[2.0, 2.0, 2.0], obs=[1.0, 2.0, 3.0]))
0.0
>>> ro... | [
"def",
"bias_abs",
"(",
"sim",
"=",
"None",
",",
"obs",
"=",
"None",
",",
"node",
"=",
"None",
",",
"skip_nan",
"=",
"False",
")",
":",
"sim",
",",
"obs",
"=",
"prepare_arrays",
"(",
"sim",
",",
"obs",
",",
"node",
",",
"skip_nan",
")",
"return",
... | 36.833333 | 20.5 |
def _data(self):
"""A simpler version of data to avoid infinite recursion in some cases.
Don't use this.
"""
if self.is_caching:
return self.cache
with open(self.path, "r") as f:
return json.load(f) | [
"def",
"_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_caching",
":",
"return",
"self",
".",
"cache",
"with",
"open",
"(",
"self",
".",
"path",
",",
"\"r\"",
")",
"as",
"f",
":",
"return",
"json",
".",
"load",
"(",
"f",
")"
] | 28.333333 | 12.777778 |
def transform_with(self, estimator, out_ds, fmt=None):
"""Call the partial_transform method of the estimator on this dataset
Parameters
----------
estimator : object with ``partial_fit`` method
This object will be used to transform this dataset into a new
dataset... | [
"def",
"transform_with",
"(",
"self",
",",
"estimator",
",",
"out_ds",
",",
"fmt",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"out_ds",
",",
"str",
")",
":",
"out_ds",
"=",
"self",
".",
"create_derived",
"(",
"out_ds",
",",
"fmt",
"=",
"fmt",
")... | 39.354839 | 19.096774 |
def derivatives(self, x, y, n_sersic, R_sersic, k_eff, center_x=0, center_y=0):
"""
returns df/dx and df/dy of the function
"""
x_ = x - center_x
y_ = y - center_y
r = np.sqrt(x_**2 + y_**2)
if isinstance(r, int) or isinstance(r, float):
r = max(self._... | [
"def",
"derivatives",
"(",
"self",
",",
"x",
",",
"y",
",",
"n_sersic",
",",
"R_sersic",
",",
"k_eff",
",",
"center_x",
"=",
"0",
",",
"center_y",
"=",
"0",
")",
":",
"x_",
"=",
"x",
"-",
"center_x",
"y_",
"=",
"y",
"-",
"center_y",
"r",
"=",
"... | 35.266667 | 14.733333 |
def list_namespaces():
'''Print out a listing of available namespaces'''
print('{:30s}\t{:40s}'.format('NAME', 'DESCRIPTION'))
print('-' * 78)
for sch in sorted(__NAMESPACE__):
desc = __NAMESPACE__[sch]['description']
desc = (desc[:44] + '..') if len(desc) > 46 else desc
print('{... | [
"def",
"list_namespaces",
"(",
")",
":",
"print",
"(",
"'{:30s}\\t{:40s}'",
".",
"format",
"(",
"'NAME'",
",",
"'DESCRIPTION'",
")",
")",
"print",
"(",
"'-'",
"*",
"78",
")",
"for",
"sch",
"in",
"sorted",
"(",
"__NAMESPACE__",
")",
":",
"desc",
"=",
"_... | 43.25 | 13.75 |
def dissolve(collection, aggfunc=None):
# type: (BaseCollection, Optional[Callable[[list], Any]]) -> GeoFeature
"""Dissolves features contained in a FeatureCollection and applies an aggregation
function to its properties.
"""
new_properties = {}
if aggfunc:
temp_properties = defaultdict... | [
"def",
"dissolve",
"(",
"collection",
",",
"aggfunc",
"=",
"None",
")",
":",
"# type: (BaseCollection, Optional[Callable[[list], Any]]) -> GeoFeature",
"new_properties",
"=",
"{",
"}",
"if",
"aggfunc",
":",
"temp_properties",
"=",
"defaultdict",
"(",
"list",
")",
"# t... | 35.136364 | 19.409091 |
async def query_presence(self, query_presence_request):
"""Return presence status for a list of users."""
response = hangouts_pb2.QueryPresenceResponse()
await self._pb_request('presence/querypresence',
query_presence_request, response)
return response | [
"async",
"def",
"query_presence",
"(",
"self",
",",
"query_presence_request",
")",
":",
"response",
"=",
"hangouts_pb2",
".",
"QueryPresenceResponse",
"(",
")",
"await",
"self",
".",
"_pb_request",
"(",
"'presence/querypresence'",
",",
"query_presence_request",
",",
... | 51.666667 | 14.5 |
def markdown_toclify(input_file, output_file=None, github=False,
back_to_top=False, nolink=False,
no_toc_header=False, spacer=0, placeholder=None,
exclude_h=None, remove_dashes=False):
""" Function to add table of contents to markdown files.
Parame... | [
"def",
"markdown_toclify",
"(",
"input_file",
",",
"output_file",
"=",
"None",
",",
"github",
"=",
"False",
",",
"back_to_top",
"=",
"False",
",",
"nolink",
"=",
"False",
",",
"no_toc_header",
"=",
"False",
",",
"spacer",
"=",
"0",
",",
"placeholder",
"=",... | 36 | 20.808219 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.