text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def viewport(self) -> Tuple[int, int, int, int]:
'''
tuple: The viewport of the window.
'''
return self.wnd.viewport | [
"def",
"viewport",
"(",
"self",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
",",
"int",
"]",
":",
"return",
"self",
".",
"wnd",
".",
"viewport"
] | 24.666667 | 20 |
def encoding(encoding=True):
"""DEPRECATED: use pynvim.decode()."""
if isinstance(encoding, str):
encoding = True
def dec(f):
f._nvim_decode = encoding
return f
return dec | [
"def",
"encoding",
"(",
"encoding",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"encoding",
",",
"str",
")",
":",
"encoding",
"=",
"True",
"def",
"dec",
"(",
"f",
")",
":",
"f",
".",
"_nvim_decode",
"=",
"encoding",
"return",
"f",
"return",
"dec"... | 22.666667 | 17.555556 |
def droit_d_accise(depense, droit_cn, consommation_cn, taux_plein_tva):
"""
Calcule le montant de droit d'accise sur un volume de dépense payé pour le poste adéquat.
"""
return depense * ((1 + taux_plein_tva) * droit_cn) / (consommation_cn - (1 + taux_plein_tva) * droit_cn) | [
"def",
"droit_d_accise",
"(",
"depense",
",",
"droit_cn",
",",
"consommation_cn",
",",
"taux_plein_tva",
")",
":",
"return",
"depense",
"*",
"(",
"(",
"1",
"+",
"taux_plein_tva",
")",
"*",
"droit_cn",
")",
"/",
"(",
"consommation_cn",
"-",
"(",
"1",
"+",
... | 57.2 | 30.4 |
def _adjust_sell_amount(self, stock_code, amount):
"""
根据实际持仓值计算雪球卖出股数
因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。
导致如下情况的产生,计算出的指令为买入 1049 股,取近似值买入 1000 股。
而卖出的指令计算出为卖出 1051 股,取近似值卖出 1100 股,超过 1000 股的买入量,
导致卖出失败
:param stock_code: 证券代码
:type stock_code: str
... | [
"def",
"_adjust_sell_amount",
"(",
"self",
",",
"stock_code",
",",
"amount",
")",
":",
"stock_code",
"=",
"stock_code",
"[",
"-",
"6",
":",
"]",
"user",
"=",
"self",
".",
"_users",
"[",
"0",
"]",
"position",
"=",
"user",
".",
"position",
"try",
":",
... | 33.375 | 14.3125 |
def _make_ta_service_dict(self):
"""
Build our service and limits dict. This is laid out identical to
``self.all_services``, but keys limits by their ``ta_service_name``
and ``ta_limit_name`` properties.
:return: dict of TA service names to TA limit names to AwsLimit objects.
... | [
"def",
"_make_ta_service_dict",
"(",
"self",
")",
":",
"res",
"=",
"{",
"}",
"for",
"svc_name",
"in",
"self",
".",
"all_services",
":",
"svc_obj",
"=",
"self",
".",
"all_services",
"[",
"svc_name",
"]",
"for",
"lim_name",
",",
"lim",
"in",
"svc_obj",
"."... | 42.0625 | 17.4375 |
def _GetLineNumbers(code_object):
"""Generator for getting the line numbers of a code object.
Args:
code_object: the code object.
Yields:
The next line number in the code object.
"""
# Get the line number deltas, which are the odd number entries, from the
# lnotab. See
# https://svn.python.org/p... | [
"def",
"_GetLineNumbers",
"(",
"code_object",
")",
":",
"# Get the line number deltas, which are the odd number entries, from the",
"# lnotab. See",
"# https://svn.python.org/projects/python/branches/pep-0384/Objects/lnotab_notes.txt",
"# In Python 3, this is just a byte array. In Python 2 it is a... | 34.818182 | 21.090909 |
def new_datetime(d):
"""
Generate a safe datetime from a datetime.date or datetime.datetime object.
"""
kw = [d.year, d.month, d.day]
if isinstance(d, real_datetime):
kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])
return datetime(*kw) | [
"def",
"new_datetime",
"(",
"d",
")",
":",
"kw",
"=",
"[",
"d",
".",
"year",
",",
"d",
".",
"month",
",",
"d",
".",
"day",
"]",
"if",
"isinstance",
"(",
"d",
",",
"real_datetime",
")",
":",
"kw",
".",
"extend",
"(",
"[",
"d",
".",
"hour",
","... | 34.625 | 14.625 |
def find(self, path, match, flags):
""" find every matching child path under path """
try:
match = re.compile(match, flags)
except sre_constants.error as ex:
print("Bad regexp: %s" % (ex))
return
offset = len(path)
for cpath in Tree(self, path... | [
"def",
"find",
"(",
"self",
",",
"path",
",",
"match",
",",
"flags",
")",
":",
"try",
":",
"match",
"=",
"re",
".",
"compile",
"(",
"match",
",",
"flags",
")",
"except",
"sre_constants",
".",
"error",
"as",
"ex",
":",
"print",
"(",
"\"Bad regexp: %s\... | 32.5 | 11.416667 |
def _check_valid_data(self, data):
"""Checks that the given data is a float array with one channel.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to check.
Raises
------
ValueError
If the data is invalid.
"""
... | [
"def",
"_check_valid_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"dtype",
".",
"type",
"is",
"not",
"np",
".",
"float32",
"and",
"data",
".",
"dtype",
".",
"type",
"is",
"not",
"np",
".",
"float64",
":",
"raise",
"ValueError",
"(",
... | 31.714286 | 18.809524 |
def distance(x,y):
"""[summary]
HELPER-FUNCTION
calculates the (eulidean) distance between vector x and y.
Arguments:
x {[tuple]} -- [vector]
y {[tuple]} -- [vector]
"""
assert len(x) == len(y), "The vector must have same length"
result = ()
sum = 0
for i in range(le... | [
"def",
"distance",
"(",
"x",
",",
"y",
")",
":",
"assert",
"len",
"(",
"x",
")",
"==",
"len",
"(",
"y",
")",
",",
"\"The vector must have same length\"",
"result",
"=",
"(",
")",
"sum",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"x",
"... | 25 | 16.941176 |
def parse_chromosome_string(job, chromosome_string):
"""
Parse a chromosome string into a list.
:param chromosome_string: Input chromosome string
:return: list of chromosomes to handle
:rtype: list
"""
if chromosome_string is None:
return []
else:
assert isinstance(chrom... | [
"def",
"parse_chromosome_string",
"(",
"job",
",",
"chromosome_string",
")",
":",
"if",
"chromosome_string",
"is",
"None",
":",
"return",
"[",
"]",
"else",
":",
"assert",
"isinstance",
"(",
"chromosome_string",
",",
"str",
")",
"chroms",
"=",
"[",
"c",
".",
... | 44.323529 | 19.441176 |
def fof(self, linkinglength, out=None, method='splay'):
""" Friend-of-Friend clustering with linking length.
Returns: the label
"""
if out is None:
out = numpy.empty(self.size, dtype='intp')
return _core.KDNode.fof(self, linkinglength, out, method) | [
"def",
"fof",
"(",
"self",
",",
"linkinglength",
",",
"out",
"=",
"None",
",",
"method",
"=",
"'splay'",
")",
":",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"numpy",
".",
"empty",
"(",
"self",
".",
"size",
",",
"dtype",
"=",
"'intp'",
")",
"ret... | 37.25 | 15.125 |
def flush_synced(self, index=None, params=None):
"""
Perform a normal flush, then add a generated unique marker (sync_id) to all shards.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-synced-flush.html>`_
:arg index: A comma-separated list of index names; use `... | [
"def",
"flush_synced",
"(",
"self",
",",
"index",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"\"POST\"",
",",
"_make_path",
"(",
"index",
",",
"\"_flush\"",
",",
"\"synced\"",
")",
... | 55.263158 | 26.421053 |
def _pfp__snapshot(self, recurse=True):
"""Save off the current value of the field
"""
super(Struct, self)._pfp__snapshot(recurse=recurse)
if recurse:
for child in self._pfp__children:
child._pfp__snapshot(recurse=recurse) | [
"def",
"_pfp__snapshot",
"(",
"self",
",",
"recurse",
"=",
"True",
")",
":",
"super",
"(",
"Struct",
",",
"self",
")",
".",
"_pfp__snapshot",
"(",
"recurse",
"=",
"recurse",
")",
"if",
"recurse",
":",
"for",
"child",
"in",
"self",
".",
"_pfp__children",
... | 34.5 | 12.375 |
def _get_descendent_cat_idstrs(self, cat_id, hierarchy_session=None):
"""Recursively returns a list of all descendent catalog ids, inclusive"""
def get_descendent_ids(h_session):
idstr_list = [str(cat_id)]
if h_session is None:
pkg_name = cat_id.get_identifier_nam... | [
"def",
"_get_descendent_cat_idstrs",
"(",
"self",
",",
"cat_id",
",",
"hierarchy_session",
"=",
"None",
")",
":",
"def",
"get_descendent_ids",
"(",
"h_session",
")",
":",
"idstr_list",
"=",
"[",
"str",
"(",
"cat_id",
")",
"]",
"if",
"h_session",
"is",
"None"... | 48.506494 | 22.571429 |
def send_batch(messages, api_key=None, secure=None, test=None, **request_args):
'''Send a batch of messages.
:param messages: Messages to send.
:type message: A list of `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https ... | [
"def",
"send_batch",
"(",
"messages",
",",
"api_key",
"=",
"None",
",",
"secure",
"=",
"None",
",",
"test",
"=",
"None",
",",
"*",
"*",
"request_args",
")",
":",
"return",
"_default_pyst_batch_sender",
".",
"send",
"(",
"messages",
"=",
"messages",
",",
... | 48.1875 | 21.4375 |
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens to have nice filenames.
From Django's "django/template/defaultfilters.py".
>>> slugify("El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y frío, añoraba a su q... | [
"def",
"slugify",
"(",
"value",
")",
":",
"try",
":",
"unicode_type",
"=",
"unicode",
"except",
"NameError",
":",
"unicode_type",
"=",
"str",
"if",
"not",
"isinstance",
"(",
"value",
",",
"unicode_type",
")",
":",
"value",
"=",
"unicode_type",
"(",
"value"... | 56.85 | 38.25 |
def config_cmd():
"""Configuration handling.
Other Parameters:
conf.config
"""
if not (conf.common.config or conf.config.create or
conf.config.create_local or conf.config.update or
conf.config.edit):
config_pp(conf.sections_())
loam.tools.config_cmd_handler(c... | [
"def",
"config_cmd",
"(",
")",
":",
"if",
"not",
"(",
"conf",
".",
"common",
".",
"config",
"or",
"conf",
".",
"config",
".",
"create",
"or",
"conf",
".",
"config",
".",
"create_local",
"or",
"conf",
".",
"config",
".",
"update",
"or",
"conf",
".",
... | 28.545455 | 14.090909 |
def playlist(netease, name, id):
"""Download a playlist's songs by id."""
if name:
netease.download_playlist_by_search(name)
if id:
netease.download_playlist_by_id(id, 'playlist'+str(id)) | [
"def",
"playlist",
"(",
"netease",
",",
"name",
",",
"id",
")",
":",
"if",
"name",
":",
"netease",
".",
"download_playlist_by_search",
"(",
"name",
")",
"if",
"id",
":",
"netease",
".",
"download_playlist_by_id",
"(",
"id",
",",
"'playlist'",
"+",
"str",
... | 30 | 19.714286 |
def get_date_data(self, date_string, date_formats=None):
"""
Parse string representing date and/or time in recognizable localized formats.
Supports parsing multiple languages and timezones.
:param date_string:
A string representing date and/or time in a recognizably valid fo... | [
"def",
"get_date_data",
"(",
"self",
",",
"date_string",
",",
"date_formats",
"=",
"None",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"date_string",
",",
"six",
".",
"text_type",
")",
"or",
"isinstance",
"(",
"date_string",
",",
"six",
".",
"string_typ... | 45.846154 | 30 |
def delete(self, **args):
'''
Delete a gist by gistname/gistID
'''
if 'name' in args:
self.gist_name = args['name']
self.gist_id = self.getMyID(self.gist_name)
elif 'id' in args:
self.gist_id = args['id']
else:
raise Exception('Provide GistName to delete')
url = 'gists'
if self.gist_id:
... | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"if",
"'name'",
"in",
"args",
":",
"self",
".",
"gist_name",
"=",
"args",
"[",
"'name'",
"]",
"self",
".",
"gist_id",
"=",
"self",
".",
"getMyID",
"(",
"self",
".",
"gist_name",
")",
... | 20.576923 | 20.730769 |
def list_inputs(self):
"""Return a string listing all the Step's input names and their types.
The types are returned in a copy/pastable format, so if the type is
`string`, `'string'` (with single quotes) is returned.
Returns:
str containing all input names and types.
... | [
"def",
"list_inputs",
"(",
"self",
")",
":",
"doc",
"=",
"[",
"]",
"for",
"inp",
",",
"typ",
"in",
"self",
".",
"input_types",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"typ",
",",
"six",
".",
"string_types",
")",
":",
"typ",
"=",
"\"... | 36.6 | 16.933333 |
def get_group_policy(self, group_name, policy_name):
"""
Retrieves the specified policy document for the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type policy_name: string
:param policy_name: The p... | [
"def",
"get_group_policy",
"(",
"self",
",",
"group_name",
",",
"policy_name",
")",
":",
"params",
"=",
"{",
"'GroupName'",
":",
"group_name",
",",
"'PolicyName'",
":",
"policy_name",
"}",
"return",
"self",
".",
"get_response",
"(",
"'GetGroupPolicy'",
",",
"p... | 36.571429 | 18.857143 |
def folder_shared_message(self, request, user, folder):
"""
Send messages.success message after successful share.
"""
messages.success(request, _("Folder {} is now shared with {}".format(folder, user))) | [
"def",
"folder_shared_message",
"(",
"self",
",",
"request",
",",
"user",
",",
"folder",
")",
":",
"messages",
".",
"success",
"(",
"request",
",",
"_",
"(",
"\"Folder {} is now shared with {}\"",
".",
"format",
"(",
"folder",
",",
"user",
")",
")",
")"
] | 46 | 17.6 |
def from_file( cls, filename ):
"""
Create a VASPMeta object by reading a `vaspmeta.yaml` file
Args:
filename (Str): filename to read in.
Returns:
(vasppy.VASPMeta): the VASPMeta object
"""
with open( filename, 'r' ) as stream:
data =... | [
"def",
"from_file",
"(",
"cls",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"stream",
":",
"data",
"=",
"yaml",
".",
"load",
"(",
"stream",
",",
"Loader",
"=",
"yaml",
".",
"SafeLoader",
")",
"notes",
"=",
"da... | 34.666667 | 11.703704 |
def partial(cls, id, token, *, adapter):
"""Creates a partial :class:`Webhook`.
A partial webhook is just a webhook object with an ID and a token.
Parameters
-----------
id: :class:`int`
The ID of the webhook.
token: :class:`str`
The authenticati... | [
"def",
"partial",
"(",
"cls",
",",
"id",
",",
"token",
",",
"*",
",",
"adapter",
")",
":",
"if",
"not",
"isinstance",
"(",
"adapter",
",",
"WebhookAdapter",
")",
":",
"raise",
"TypeError",
"(",
"'adapter must be a subclass of WebhookAdapter'",
")",
"data",
"... | 31.653846 | 20.692308 |
def _get_running_apps(self, instance, requests_config):
"""
Determine what mode was specified
"""
tags = instance.get('tags', [])
if tags is None:
tags = []
master_address = self._get_master_address(instance)
# Get the cluster name from the instance co... | [
"def",
"_get_running_apps",
"(",
"self",
",",
"instance",
",",
"requests_config",
")",
":",
"tags",
"=",
"instance",
".",
"get",
"(",
"'tags'",
",",
"[",
"]",
")",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"master_address",
"=",
"self",
... | 45 | 22.368421 |
def cleanup_on_delete(self, sender, document, **kwargs):
'''
Clean up slug redirections on object deletion
'''
if not self.follow or sender is not self.owner_document:
return
slug = getattr(document, self.db_field)
namespace = self.owner_document.__name__
... | [
"def",
"cleanup_on_delete",
"(",
"self",
",",
"sender",
",",
"document",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"follow",
"or",
"sender",
"is",
"not",
"self",
".",
"owner_document",
":",
"return",
"slug",
"=",
"getattr",
"(",
"doc... | 42.111111 | 19.888889 |
def set_visual_style(self, full_screen_style=False):
"""
Sets the Application visual style.
:param full_screen_style: Use fullscreen stylesheet file.
:type full_screen_style: bool
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Setting Applicat... | [
"def",
"set_visual_style",
"(",
"self",
",",
"full_screen_style",
"=",
"False",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Setting Application visual style.\"",
")",
"platform_styles",
"=",
"{",
"\"Windows\"",
":",
"(",
"(",
"\"Windows\"",
",",
"\"Microsoft\"",
"... | 55.915254 | 29.779661 |
def from_response(response, body):
"""
Return an instance of a ClientException or subclass
based on an httplib2 response.
Usage::
resp, body = http.request(...)
if resp.status_code != 200:
raise exception_from_response(resp, body)
"""
if isinstance(response, dict):
... | [
"def",
"from_response",
"(",
"response",
",",
"body",
")",
":",
"if",
"isinstance",
"(",
"response",
",",
"dict",
")",
":",
"status",
"=",
"response",
".",
"get",
"(",
"\"status_code\"",
")",
"else",
":",
"status",
"=",
"response",
".",
"status_code",
"c... | 30.926829 | 14.829268 |
def leland94(V, s, r, a, t, C=None, d=None, PosEq=False):
"""Leland94 Capital Structure model, Corporate Bond valuation model
Parameters:
-----------
V : float
Asset Value of the unlevered firm
s : float
Volatility s of the asset value V of the unlevered firm
r : float
... | [
"def",
"leland94",
"(",
"V",
",",
"s",
",",
"r",
",",
"a",
",",
"t",
",",
"C",
"=",
"None",
",",
"d",
"=",
"None",
",",
"PosEq",
"=",
"False",
")",
":",
"# subfunction for",
"def",
"netcashpayout_by_dividend",
"(",
"r",
",",
"d",
",",
"s",
")",
... | 28.125 | 21.013393 |
def keybd_event(bVk: int, bScan: int, dwFlags: int, dwExtraInfo: int) -> None:
"""keybd_event from Win32."""
ctypes.windll.user32.keybd_event(bVk, bScan, dwFlags, dwExtraInfo) | [
"def",
"keybd_event",
"(",
"bVk",
":",
"int",
",",
"bScan",
":",
"int",
",",
"dwFlags",
":",
"int",
",",
"dwExtraInfo",
":",
"int",
")",
"->",
"None",
":",
"ctypes",
".",
"windll",
".",
"user32",
".",
"keybd_event",
"(",
"bVk",
",",
"bScan",
",",
"... | 60.333333 | 22.666667 |
def fit_mcmc(self,nwalkers=300,nburn=200,niter=100,
p0=None,initial_burn=None,
ninitial=100, loglike_kwargs=None,
**kwargs):
"""Fits stellar model using MCMC.
:param nwalkers: (optional)
Number of walkers to pass to :class:`emcee.EnsembleSa... | [
"def",
"fit_mcmc",
"(",
"self",
",",
"nwalkers",
"=",
"300",
",",
"nburn",
"=",
"200",
",",
"niter",
"=",
"100",
",",
"p0",
"=",
"None",
",",
"initial_burn",
"=",
"None",
",",
"ninitial",
"=",
"100",
",",
"loglike_kwargs",
"=",
"None",
",",
"*",
"*... | 39.646465 | 20.737374 |
def check_multi_dimensional_coords(self, ds):
'''
Checks that no multidimensional coordinate shares a name with its
dimensions.
Chapter 5 paragraph 4
We recommend that the name of a [multidimensional coordinate] should
not match the name of any of its dimensions.
... | [
"def",
"check_multi_dimensional_coords",
"(",
"self",
",",
"ds",
")",
":",
"ret_val",
"=",
"[",
"]",
"# This can only apply to auxiliary coordinate variables",
"for",
"coord",
"in",
"self",
".",
"_find_aux_coord_vars",
"(",
"ds",
")",
":",
"variable",
"=",
"ds",
"... | 35.206897 | 24.103448 |
def _do_http(opts, profile='default'):
'''
Make the http request and return the data
'''
ret = {}
url = __salt__['config.get']('modjk:{0}:url'.format(profile), '')
user = __salt__['config.get']('modjk:{0}:user'.format(profile), '')
passwd = __salt__['config.get']('modjk:{0}:pass'.format(pr... | [
"def",
"_do_http",
"(",
"opts",
",",
"profile",
"=",
"'default'",
")",
":",
"ret",
"=",
"{",
"}",
"url",
"=",
"__salt__",
"[",
"'config.get'",
"]",
"(",
"'modjk:{0}:url'",
".",
"format",
"(",
"profile",
")",
",",
"''",
")",
"user",
"=",
"__salt__",
"... | 31.833333 | 25.766667 |
def find_all(query: Query=None) -> List['ApiKey']:
"""
List all API keys.
"""
return [ApiKey.from_db(key) for key in db.get_keys(query)] | [
"def",
"find_all",
"(",
"query",
":",
"Query",
"=",
"None",
")",
"->",
"List",
"[",
"'ApiKey'",
"]",
":",
"return",
"[",
"ApiKey",
".",
"from_db",
"(",
"key",
")",
"for",
"key",
"in",
"db",
".",
"get_keys",
"(",
"query",
")",
"]"
] | 32.8 | 10 |
def changes_since(self, domain, date_or_datetime):
"""
Gets the changes for a domain since the specified date/datetime.
The date can be one of:
- a Python datetime object
- a Python date object
- a string in the format 'YYYY-MM-YY HH:MM:SS'
- a str... | [
"def",
"changes_since",
"(",
"self",
",",
"domain",
",",
"date_or_datetime",
")",
":",
"domain_id",
"=",
"utils",
".",
"get_id",
"(",
"domain",
")",
"dt",
"=",
"utils",
".",
"iso_time_string",
"(",
"date_or_datetime",
",",
"show_tzinfo",
"=",
"True",
")",
... | 42.724138 | 13 |
def get_volume(self):
"""Get the current volume."""
self.request(EP_GET_VOLUME)
return 0 if self.last_response is None else self.last_response.get('payload').get('volume') | [
"def",
"get_volume",
"(",
"self",
")",
":",
"self",
".",
"request",
"(",
"EP_GET_VOLUME",
")",
"return",
"0",
"if",
"self",
".",
"last_response",
"is",
"None",
"else",
"self",
".",
"last_response",
".",
"get",
"(",
"'payload'",
")",
".",
"get",
"(",
"'... | 48 | 20.75 |
def delay(self):
'''How long to wait before the next check'''
if self._last_checked:
return self._interval - (time.time() - self._last_checked)
return self._interval | [
"def",
"delay",
"(",
"self",
")",
":",
"if",
"self",
".",
"_last_checked",
":",
"return",
"self",
".",
"_interval",
"-",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_last_checked",
")",
"return",
"self",
".",
"_interval"
] | 39.4 | 17.4 |
def pre_order(root):
# type: (Nonterminal) -> Generator
"""
Perform pre-order traversing. Expects tree like structure.
Traverse in DFS fashion.
:param root: Root tree of the parsed tree.
:return: Sequence of nodes to traverse.
"""
def traverse_rule(item, ... | [
"def",
"pre_order",
"(",
"root",
")",
":",
"# type: (Nonterminal) -> Generator",
"def",
"traverse_rule",
"(",
"item",
",",
"callback",
")",
":",
"yield",
"item",
"for",
"el",
"in",
"item",
".",
"to_symbols",
":",
"yield",
"callback",
"(",
"el",
")",
"def",
... | 31.818182 | 17.181818 |
def command(self, dbname, spec, slave_ok=False,
read_preference=ReadPreference.PRIMARY,
codec_options=DEFAULT_CODEC_OPTIONS, check=True,
allowable_errors=None, check_keys=False,
read_concern=None,
write_concern=None,
parse_w... | [
"def",
"command",
"(",
"self",
",",
"dbname",
",",
"spec",
",",
"slave_ok",
"=",
"False",
",",
"read_preference",
"=",
"ReadPreference",
".",
"PRIMARY",
",",
"codec_options",
"=",
"DEFAULT_CODEC_OPTIONS",
",",
"check",
"=",
"True",
",",
"allowable_errors",
"="... | 49.686047 | 18.313953 |
def get_plugin_info(plugin):
"""
Fetch information about the given package on PyPI and return it as a dict.
If the package cannot be found on PyPI, :exc:`NameError` will be raised.
"""
url = 'https://pypi.python.org/pypi/{}/json'.format(plugin)
try:
resp = request.urlopen(url)
excep... | [
"def",
"get_plugin_info",
"(",
"plugin",
")",
":",
"url",
"=",
"'https://pypi.python.org/pypi/{}/json'",
".",
"format",
"(",
"plugin",
")",
"try",
":",
"resp",
"=",
"request",
".",
"urlopen",
"(",
"url",
")",
"except",
"HTTPError",
"as",
"e",
":",
"if",
"e... | 31.758621 | 22.862069 |
def parse_consumer_offsets(cls, json_file):
"""Parse current offsets from json-file."""
with open(json_file, 'r') as consumer_offsets_json:
try:
parsed_offsets = {}
parsed_offsets_data = json.load(consumer_offsets_json)
# Create new dict with p... | [
"def",
"parse_consumer_offsets",
"(",
"cls",
",",
"json_file",
")",
":",
"with",
"open",
"(",
"json_file",
",",
"'r'",
")",
"as",
"consumer_offsets_json",
":",
"try",
":",
"parsed_offsets",
"=",
"{",
"}",
"parsed_offsets_data",
"=",
"json",
".",
"load",
"(",... | 50.190476 | 19.761905 |
def weights(self, matrix_id=0):
"""
Return the frame for the respective weight matrix.
:param: matrix_id: an integer, ranging from 0 to number of layers, that specifies the weight matrix to return.
:returns: an H2OFrame which represents the weight matrix identified by matrix_id
... | [
"def",
"weights",
"(",
"self",
",",
"matrix_id",
"=",
"0",
")",
":",
"return",
"{",
"model",
".",
"model_id",
":",
"model",
".",
"weights",
"(",
"matrix_id",
")",
"for",
"model",
"in",
"self",
".",
"models",
"}"
] | 49.875 | 29.375 |
def dframe(self, dimensions=None, multi_index=False):
"""Convert dimension values to DataFrame.
Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.
Args:
dimensions: Dimensions to return as columns
mul... | [
"def",
"dframe",
"(",
"self",
",",
"dimensions",
"=",
"None",
",",
"multi_index",
"=",
"False",
")",
":",
"import",
"pandas",
"as",
"pd",
"if",
"dimensions",
"is",
"None",
":",
"dimensions",
"=",
"[",
"d",
".",
"name",
"for",
"d",
"in",
"self",
".",
... | 39.166667 | 22.75 |
def require(self, name):
"""Return the value of the requested parameter or raise an error."""
value = self.get(name)
if value is None:
raise TypeError(
"{0} requires the parameter '{1}'.".format(
self.__class__, name
)
)... | [
"def",
"require",
"(",
"self",
",",
"name",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"name",
")",
"if",
"value",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"{0} requires the parameter '{1}'.\"",
".",
"format",
"(",
"self",
".",
"__class__",
... | 33.2 | 14.2 |
async def start(self):
"""Start the websocket server.
When this method returns, the websocket server will be running and
the port property of this class will have its assigned port number.
This method should be called only once in the lifetime of the server
and must be paired w... | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server_task",
"is",
"not",
"None",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"AsyncValidatingWSServer.start() called twice, ignoring\"",
")",
"return",
"started_signal",
"=",
"self",
".... | 35.545455 | 25.681818 |
def get_or_create(self, **kwargs):
"""
Looks up an object with the given kwargs, creating one if necessary.
Returns a tuple of (object, created), where created is a boolean
specifying whether an object was created.
"""
model = self.get(**kwargs)
is_c... | [
"def",
"get_or_create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"model",
"=",
"self",
".",
"get",
"(",
"*",
"*",
"kwargs",
")",
"is_created",
"=",
"False",
"if",
"model",
"is",
"None",
":",
"is_created",
"=",
"True",
"model",
"=",
"self",
"... | 28.578947 | 19.105263 |
def detect_log_config(arguments):
"""
Detect access log config (path and format) of nginx. Offer user to select if multiple access logs are detected.
:return: path and format of detected / selected access log
"""
config = arguments['--config']
if config is None:
config = detect_config_pa... | [
"def",
"detect_log_config",
"(",
"arguments",
")",
":",
"config",
"=",
"arguments",
"[",
"'--config'",
"]",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"detect_config_path",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config",
")... | 45.363636 | 20.575758 |
def _show(self):
""" Return a list of unsorted bridge details. """
p = _runshell([brctlexe, 'show', self.name],
"Could not show %s." % self.name)
return p.stdout.read().split()[7:] | [
"def",
"_show",
"(",
"self",
")",
":",
"p",
"=",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'show'",
",",
"self",
".",
"name",
"]",
",",
"\"Could not show %s.\"",
"%",
"self",
".",
"name",
")",
"return",
"p",
".",
"stdout",
".",
"read",
"(",
")",
"."... | 42.6 | 8.6 |
def _get_choices(self, gandi):
""" Internal method to get choices list """
image_list = []
for item in gandi.image.list():
label = item['label']
if item['visibility'] == 'deprecated':
label = '*%s' % label
image_list.append(label)
disk_... | [
"def",
"_get_choices",
"(",
"self",
",",
"gandi",
")",
":",
"image_list",
"=",
"[",
"]",
"for",
"item",
"in",
"gandi",
".",
"image",
".",
"list",
"(",
")",
":",
"label",
"=",
"item",
"[",
"'label'",
"]",
"if",
"item",
"[",
"'visibility'",
"]",
"=="... | 42.7 | 10 |
def user(self) -> str:
"""Generate a random user.
:return: Path to user.
:Example:
/home/oretha
"""
user = self.random.choice(USERNAMES)
user = user.capitalize() if 'win' in self.platform else user.lower()
return str(self._pathlib_home / user) | [
"def",
"user",
"(",
"self",
")",
"->",
"str",
":",
"user",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"USERNAMES",
")",
"user",
"=",
"user",
".",
"capitalize",
"(",
")",
"if",
"'win'",
"in",
"self",
".",
"platform",
"else",
"user",
".",
"lower... | 27.545455 | 17.454545 |
def read_namespaced_replication_controller_scale(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replication_controller_scale # noqa: E501
read scale of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | [
"def",
"read_namespaced_replication_controller_scale",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")"... | 54.913043 | 29.086957 |
def move(self, path, dest):
"""
Use snakebite.rename, if available.
:param path: source file(s)
:type path: either a string or sequence of strings
:param dest: destination file (single input) or directory (multiple)
:type dest: string
:return: list of renamed ite... | [
"def",
"move",
"(",
"self",
",",
"path",
",",
"dest",
")",
":",
"parts",
"=",
"dest",
".",
"rstrip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"parts",
")",
">",
"1",
":",
"dir_path",
"=",
"'/'",
".",
"join",
"(",
"par... | 37.5 | 12.125 |
def log(self, n=None, template=None):
"""
Run the repository log command
Returns:
str: output of log command (``bzr log -l <n>``)
"""
cmd = ['bzr', 'log']
if n:
cmd.append('-l%d' % n)
return self.sh(cmd, shell=False) | [
"def",
"log",
"(",
"self",
",",
"n",
"=",
"None",
",",
"template",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'bzr'",
",",
"'log'",
"]",
"if",
"n",
":",
"cmd",
".",
"append",
"(",
"'-l%d'",
"%",
"n",
")",
"return",
"self",
".",
"sh",
"(",
"cmd"... | 26.090909 | 12.090909 |
def _drop_indices(self):
"""Drops the database indices relating to n-grams."""
self._logger.info('Dropping database indices')
self._conn.execute(constants.DROP_TEXTNGRAM_INDEX_SQL)
self._logger.info('Finished dropping database indices') | [
"def",
"_drop_indices",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Dropping database indices'",
")",
"self",
".",
"_conn",
".",
"execute",
"(",
"constants",
".",
"DROP_TEXTNGRAM_INDEX_SQL",
")",
"self",
".",
"_logger",
".",
"info",
"(... | 52.8 | 15 |
def segment_to_line(document, coords):
"polyline with 2 vertices using <line> tag"
return setattribs(
document.createElement('line'),
x1 = coords[0],
y1 = coords[1],
x2 = coords[2],
y2 = coords[3],
) | [
"def",
"segment_to_line",
"(",
"document",
",",
"coords",
")",
":",
"return",
"setattribs",
"(",
"document",
".",
"createElement",
"(",
"'line'",
")",
",",
"x1",
"=",
"coords",
"[",
"0",
"]",
",",
"y1",
"=",
"coords",
"[",
"1",
"]",
",",
"x2",
"=",
... | 22.666667 | 18.222222 |
async def main_loop(loop, password, user, ip): # pylint: disable=invalid-name
"""Main loop."""
async with aiohttp.ClientSession(loop=loop) as session:
VAR['sma'] = pysma.SMA(session, ip, password=password, group=user)
await VAR['sma'].new_session()
if VAR['sma'].sma_sid is None:
... | [
"async",
"def",
"main_loop",
"(",
"loop",
",",
"password",
",",
"user",
",",
"ip",
")",
":",
"# pylint: disable=invalid-name",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
"loop",
"=",
"loop",
")",
"as",
"session",
":",
"VAR",
"[",
"'sma'",
"]",
... | 32.347826 | 16.26087 |
def build_reverse_dictionary(word_to_id):
"""Given a dictionary that maps word to integer id.
Returns a reverse dictionary that maps a id to word.
Parameters
----------
word_to_id : dictionary
that maps word to ID.
Returns
--------
dictionary
A dictionary that maps IDs ... | [
"def",
"build_reverse_dictionary",
"(",
"word_to_id",
")",
":",
"reverse_dictionary",
"=",
"dict",
"(",
"zip",
"(",
"word_to_id",
".",
"values",
"(",
")",
",",
"word_to_id",
".",
"keys",
"(",
")",
")",
")",
"return",
"reverse_dictionary"
] | 25.117647 | 20.294118 |
def cp_objectinfo_worker(task):
'''This is a parallel worker for `parallel_update_cp_objectinfo`.
Parameters
----------
task : tuple
- task[0] = checkplot pickle file
- task[1] = kwargs
Returns
-------
str
The name of the checkplot file that was updated. None if t... | [
"def",
"cp_objectinfo_worker",
"(",
"task",
")",
":",
"cpf",
",",
"cpkwargs",
"=",
"task",
"try",
":",
"newcpf",
"=",
"update_checkplot_objectinfo",
"(",
"cpf",
",",
"*",
"*",
"cpkwargs",
")",
"return",
"newcpf",
"except",
"Exception",
"as",
"e",
":",
"LOG... | 19.827586 | 27.758621 |
def _rest_request_to_json(self, address, object_path, service_name, requests_config, tags, *args, **kwargs):
"""
Query the given URL and return the JSON response
"""
response = self._rest_request(address, object_path, service_name, requests_config, tags, *args, **kwargs)
try:
... | [
"def",
"_rest_request_to_json",
"(",
"self",
",",
"address",
",",
"object_path",
",",
"service_name",
",",
"requests_config",
",",
"tags",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_rest_request",
"(",
"address",
"... | 35.368421 | 23.473684 |
def redirectLoggerStreamHandlers(oldStream, newStream):
"""Redirect the stream of a stream handler to a different stream
"""
for handler in list(logger.handlers): #Remove old handlers
if handler.stream == oldStream:
handler.close()
logger.removeHandler(handler)
for handle... | [
"def",
"redirectLoggerStreamHandlers",
"(",
"oldStream",
",",
"newStream",
")",
":",
"for",
"handler",
"in",
"list",
"(",
"logger",
".",
"handlers",
")",
":",
"#Remove old handlers",
"if",
"handler",
".",
"stream",
"==",
"oldStream",
":",
"handler",
".",
"clos... | 43.363636 | 10.727273 |
def earthsun_distance(moment):
r'''Calculates the distance between the earth and the sun as a function
of date and time. Uses the Reda and Andreas (2004) model described in [1]_,
originally incorporated into the excellent
`pvlib library <https://github.com/pvlib/pvlib-python>`_
Parameters
... | [
"def",
"earthsun_distance",
"(",
"moment",
")",
":",
"from",
"fluids",
".",
"optional",
"import",
"spa",
"delta_t",
"=",
"spa",
".",
"calculate_deltat",
"(",
"moment",
".",
"year",
",",
"moment",
".",
"month",
")",
"import",
"calendar",
"unixtime",
"=",
"c... | 34.982143 | 26.303571 |
def set_indent(TokenClass, implicit=False):
"""Set the previously saved indentation level."""
def callback(lexer, match, context):
text = match.group()
if context.indent < context.next_indent:
context.indent_stack.append(context.indent)
context.indent = context.next_inden... | [
"def",
"set_indent",
"(",
"TokenClass",
",",
"implicit",
"=",
"False",
")",
":",
"def",
"callback",
"(",
"lexer",
",",
"match",
",",
"context",
")",
":",
"text",
"=",
"match",
".",
"group",
"(",
")",
"if",
"context",
".",
"indent",
"<",
"context",
".... | 40 | 8.25 |
def recorded(self):
"""Return if the stream is a recording."""
if self.tune and self.tune.get('@src'):
return True if self.tune.get('@src').startswith('mbr') else False
else:
raise PyMediaroomError("No information in <node> about @src") | [
"def",
"recorded",
"(",
"self",
")",
":",
"if",
"self",
".",
"tune",
"and",
"self",
".",
"tune",
".",
"get",
"(",
"'@src'",
")",
":",
"return",
"True",
"if",
"self",
".",
"tune",
".",
"get",
"(",
"'@src'",
")",
".",
"startswith",
"(",
"'mbr'",
")... | 46.5 | 20.833333 |
def _definition_equivalent_to_call(definition, call):
"""Check if a definition signature is equivalent to a call."""
if definition.kwargs:
same_kw_variadics = definition.kwargs in call.starred_kws
else:
same_kw_variadics = not call.starred_kws
if definition.varargs:
same_args_var... | [
"def",
"_definition_equivalent_to_call",
"(",
"definition",
",",
"call",
")",
":",
"if",
"definition",
".",
"kwargs",
":",
"same_kw_variadics",
"=",
"definition",
".",
"kwargs",
"in",
"call",
".",
"starred_kws",
"else",
":",
"same_kw_variadics",
"=",
"not",
"cal... | 35.942857 | 17.6 |
def boundplot(results, dims, it=None, idx=None, prior_transform=None,
periodic=None, ndraws=5000, color='gray', plot_kwargs=None,
labels=None, label_kwargs=None, max_n_ticks=5,
use_math_text=False, show_live=False, live_color='darkviolet',
live_kwargs=None, span=N... | [
"def",
"boundplot",
"(",
"results",
",",
"dims",
",",
"it",
"=",
"None",
",",
"idx",
"=",
"None",
",",
"prior_transform",
"=",
"None",
",",
"periodic",
"=",
"None",
",",
"ndraws",
"=",
"5000",
",",
"color",
"=",
"'gray'",
",",
"plot_kwargs",
"=",
"No... | 40.880259 | 21.029126 |
def name(self, *args):
'''
get/set the descriptive name text of this object.
'''
if len(args):
self.__name = args[0]
else:
return self.__name | [
"def",
"name",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
":",
"self",
".",
"__name",
"=",
"args",
"[",
"0",
"]",
"else",
":",
"return",
"self",
".",
"__name"
] | 24.75 | 19.5 |
def set_value_for_keypath(obj, path, new_value, preserve_child = False):
"""Set attribute value new_value at key path of start object obj.
"""
parts = path.split('.')
last_part = len(parts) - 1
dst = obj
for i, part in enumerate(parts):
match = re.match(list_index_re, part)
if ma... | [
"def",
"set_value_for_keypath",
"(",
"obj",
",",
"path",
",",
"new_value",
",",
"preserve_child",
"=",
"False",
")",
":",
"parts",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"last_part",
"=",
"len",
"(",
"parts",
")",
"-",
"1",
"dst",
"=",
"obj",
"f... | 37.483871 | 11.483871 |
def _get_digraph_char(self, cli):
" Return `False`, or the Digraph symbol to be used. "
if cli.quoted_insert:
return '^'
if cli.vi_state.waiting_for_digraph:
if cli.vi_state.digraph_symbol1:
return cli.vi_state.digraph_symbol1
return '?'
... | [
"def",
"_get_digraph_char",
"(",
"self",
",",
"cli",
")",
":",
"if",
"cli",
".",
"quoted_insert",
":",
"return",
"'^'",
"if",
"cli",
".",
"vi_state",
".",
"waiting_for_digraph",
":",
"if",
"cli",
".",
"vi_state",
".",
"digraph_symbol1",
":",
"return",
"cli... | 36.222222 | 12.666667 |
def set_banner(self, banner_type, value=None, default=False,
disable=False):
"""Configures system banners
Args:
banner_type(str): banner to be changed (likely login or motd)
value(str): value to set for the banner
default (bool): Controls the use o... | [
"def",
"set_banner",
"(",
"self",
",",
"banner_type",
",",
"value",
"=",
"None",
",",
"default",
"=",
"False",
",",
"disable",
"=",
"False",
")",
":",
"command_string",
"=",
"\"banner %s\"",
"%",
"banner_type",
"if",
"default",
"is",
"True",
"or",
"disable... | 40.708333 | 19.583333 |
def set_top_bar_color(self, index):
"""Set the color of the upper frame to the background color of the reftrack status
:param index: the index
:type index: :class:`QtGui.QModelIndex`
:returns: None
:rtype: None
:raises: None
"""
dr = QtCore.Qt.ForegroundR... | [
"def",
"set_top_bar_color",
"(",
"self",
",",
"index",
")",
":",
"dr",
"=",
"QtCore",
".",
"Qt",
".",
"ForegroundRole",
"c",
"=",
"index",
".",
"model",
"(",
")",
".",
"index",
"(",
"index",
".",
"row",
"(",
")",
",",
"8",
",",
"index",
".",
"par... | 39.571429 | 17.642857 |
def expand_on(self, col1, col2, rename1 = None, rename2 = None, drop = [], drop_collections = False):
"""
Returns a reshaped version of extractor's data, where unique combinations of values from col1 and col2
are given individual rows.
Example function call from ``tidymbox``:
.... | [
"def",
"expand_on",
"(",
"self",
",",
"col1",
",",
"col2",
",",
"rename1",
"=",
"None",
",",
"rename2",
"=",
"None",
",",
"drop",
"=",
"[",
"]",
",",
"drop_collections",
"=",
"False",
")",
":",
"# Assumption 1: Expanded columns are either atomic are built in col... | 43.467033 | 25.313187 |
def shared_blockchain_instance(self):
""" This method will initialize ``SharedInstance.instance`` and return it.
The purpose of this method is to have offer single default
instance that can be reused by multiple classes.
"""
if not self._sharedInstance.instance:
... | [
"def",
"shared_blockchain_instance",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_sharedInstance",
".",
"instance",
":",
"klass",
"=",
"self",
".",
"get_instance_class",
"(",
")",
"self",
".",
"_sharedInstance",
".",
"instance",
"=",
"klass",
"(",
"*",... | 52.666667 | 11.888889 |
def _invoke(task, args):
'''Invoke a task with the appropriate args; return the remaining args.'''
kwargs = task.defaults.copy()
if task.kwargs:
temp_kwargs, args = getopt.getopt(args, '', task.kwargs)
temp_kwargs = _opts_to_dict(*temp_kwargs)
kwargs.update(temp_kwargs)
if task.args:
for arg in task.args:
... | [
"def",
"_invoke",
"(",
"task",
",",
"args",
")",
":",
"kwargs",
"=",
"task",
".",
"defaults",
".",
"copy",
"(",
")",
"if",
"task",
".",
"kwargs",
":",
"temp_kwargs",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"args",
",",
"''",
",",
"task",
... | 25 | 22.047619 |
def get(self, file_id: str) -> [typing.BinaryIO, str, datetime.datetime]:
"""Return the file identified by a file_id string, its file name and upload date."""
raise NotImplementedError("Downloading files for downloading files in FileStore has not been implemented yet.") | [
"def",
"get",
"(",
"self",
",",
"file_id",
":",
"str",
")",
"->",
"[",
"typing",
".",
"BinaryIO",
",",
"str",
",",
"datetime",
".",
"datetime",
"]",
":",
"raise",
"NotImplementedError",
"(",
"\"Downloading files for downloading files in FileStore has not been implem... | 94.666667 | 37.333333 |
def visitor(arg_type):
"""Decorator that creates a visitor method."""
def decorator(fn):
declaring_class = _declaring_class(fn)
_methods[(declaring_class, arg_type)] = fn
# Replace all decorated methods with _visitor_impl
return _visitor_impl
return decorator | [
"def",
"visitor",
"(",
"arg_type",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"declaring_class",
"=",
"_declaring_class",
"(",
"fn",
")",
"_methods",
"[",
"(",
"declaring_class",
",",
"arg_type",
")",
"]",
"=",
"fn",
"# Replace all decorated methods wi... | 26.909091 | 20.181818 |
def run(self, ket: State = None) -> State:
"""Compiles and runs a program. The optional program argument
supplies the initial state and memory. Else qubits and classical
bits start from zero states.
"""
if ket is None:
qubits = self.qubits
ket = zero_state... | [
"def",
"run",
"(",
"self",
",",
"ket",
":",
"State",
"=",
"None",
")",
"->",
"State",
":",
"if",
"ket",
"is",
"None",
":",
"qubits",
"=",
"self",
".",
"qubits",
"ket",
"=",
"zero_state",
"(",
"qubits",
")",
"ket",
"=",
"self",
".",
"_initilize",
... | 30.210526 | 13.789474 |
def _AtNonLeaf(self, attr_value, path):
"""Makes dictionaries expandable when dealing with plists."""
if isinstance(attr_value, dict):
for value in self.Expand(attr_value, path[1:]):
yield value
else:
for v in objectfilter.ValueExpander._AtNonLeaf(self, attr_value, path):
yield v | [
"def",
"_AtNonLeaf",
"(",
"self",
",",
"attr_value",
",",
"path",
")",
":",
"if",
"isinstance",
"(",
"attr_value",
",",
"dict",
")",
":",
"for",
"value",
"in",
"self",
".",
"Expand",
"(",
"attr_value",
",",
"path",
"[",
"1",
":",
"]",
")",
":",
"yi... | 39.125 | 16.5 |
def _check_cmdline(data):
'''
In some cases where there are an insane number of processes being created
on a system a PID can get recycled or assigned to a non-Salt process.
On Linux this fn checks to make sure the PID we are checking on is actually
a Salt process.
For non-Linux systems we punt... | [
"def",
"_check_cmdline",
"(",
"data",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"platform",
".",
"is_linux",
"(",
")",
":",
"return",
"True",
"pid",
"=",
"data",
".",
"get",
"(",
"'pid'",
")",
"if",
"not",
"pid",
":",
"return",
"False",
"if... | 32 | 20.48 |
def easeInOutCirc(n):
"""A circular tween function that accelerates, reaches the midpoint, and then decelerates.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(... | [
"def",
"easeInOutCirc",
"(",
"n",
")",
":",
"_checkRange",
"(",
"n",
")",
"n",
"=",
"n",
"*",
"2",
"if",
"n",
"<",
"1",
":",
"return",
"-",
"0.5",
"*",
"(",
"math",
".",
"sqrt",
"(",
"1",
"-",
"n",
"**",
"2",
")",
"-",
"1",
")",
"else",
"... | 30.3125 | 25 |
def check_entitlement(doi):
"""Check whether IP and credentials enable access to content for a doi.
This function uses the entitlement endpoint of the Elsevier API to check
whether an article is available to a given institution. Note that this
feature of the API is itself not available for all institut... | [
"def",
"check_entitlement",
"(",
"doi",
")",
":",
"if",
"doi",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'doi:'",
")",
":",
"doi",
"=",
"doi",
"[",
"4",
":",
"]",
"url",
"=",
"'%s/%s'",
"%",
"(",
"elsevier_entitlement_url",
",",
"doi",
")",
... | 44.055556 | 17.944444 |
def winsorize(row, min_percentile, max_percentile):
"""
This implementation is based on scipy.stats.mstats.winsorize
"""
a = row.copy()
nan_count = isnan(row).sum()
nonnan_count = a.size - nan_count
# NOTE: argsort() sorts nans to the end of the array.
idx = a.argsort()
# Set value... | [
"def",
"winsorize",
"(",
"row",
",",
"min_percentile",
",",
"max_percentile",
")",
":",
"a",
"=",
"row",
".",
"copy",
"(",
")",
"nan_count",
"=",
"isnan",
"(",
"row",
")",
".",
"sum",
"(",
")",
"nonnan_count",
"=",
"a",
".",
"size",
"-",
"nan_count",... | 35.678571 | 20.964286 |
def read_frame(self):
"""
Read an AMQP frame.
"""
frame_type, channel, size = unpack('>BHI', self._read(7))
payload = self._read(size)
ch = ord(self._read(1))
if ch == 206: # '\xce'
return frame_type, channel, payload
else:
raise E... | [
"def",
"read_frame",
"(",
"self",
")",
":",
"frame_type",
",",
"channel",
",",
"size",
"=",
"unpack",
"(",
"'>BHI'",
",",
"self",
".",
"_read",
"(",
"7",
")",
")",
"payload",
"=",
"self",
".",
"_read",
"(",
"size",
")",
"ch",
"=",
"ord",
"(",
"se... | 31.416667 | 16.916667 |
def data_to_binary(self):
"""
:return: bytes
"""
return bytes([
COMMAND_CODE,
self._wday,
self._hour,
self._min
]) | [
"def",
"data_to_binary",
"(",
"self",
")",
":",
"return",
"bytes",
"(",
"[",
"COMMAND_CODE",
",",
"self",
".",
"_wday",
",",
"self",
".",
"_hour",
",",
"self",
".",
"_min",
"]",
")"
] | 19.3 | 14.9 |
def sanitize_cloud(cloud: str) -> str:
"""
Fix rare cloud layer issues
"""
if len(cloud) < 4:
return cloud
if not cloud[3].isdigit() and cloud[3] != '/':
if cloud[3] == 'O':
cloud = cloud[:3] + '0' + cloud[4:] # Bad "O": FEWO03 -> FEW003
else: # Move modifiers t... | [
"def",
"sanitize_cloud",
"(",
"cloud",
":",
"str",
")",
"->",
"str",
":",
"if",
"len",
"(",
"cloud",
")",
"<",
"4",
":",
"return",
"cloud",
"if",
"not",
"cloud",
"[",
"3",
"]",
".",
"isdigit",
"(",
")",
"and",
"cloud",
"[",
"3",
"]",
"!=",
"'/'... | 33.666667 | 13.5 |
def lis_to_bio_map(folder):
"""
Senators have a lis_id that is used in some places. That's dumb. Build a
dict from lis_id to bioguide_id which every member of congress has.
"""
logger.info("Opening legislator csv for lis_dct creation")
lis_dic = {}
leg_path = "{0}/legislators.csv".format(fol... | [
"def",
"lis_to_bio_map",
"(",
"folder",
")",
":",
"logger",
".",
"info",
"(",
"\"Opening legislator csv for lis_dct creation\"",
")",
"lis_dic",
"=",
"{",
"}",
"leg_path",
"=",
"\"{0}/legislators.csv\"",
".",
"format",
"(",
"folder",
")",
"logger",
".",
"info",
... | 35.666667 | 13.533333 |
def intersect_3(self, second, third):
"""
Intersection routine for three inputs. Built out of the intersect,
coalesce and play routines
"""
self.intersection(second)
self.intersection(third)
self.coalesce()
return len(self) | [
"def",
"intersect_3",
"(",
"self",
",",
"second",
",",
"third",
")",
":",
"self",
".",
"intersection",
"(",
"second",
")",
"self",
".",
"intersection",
"(",
"third",
")",
"self",
".",
"coalesce",
"(",
")",
"return",
"len",
"(",
"self",
")"
] | 27.555556 | 12 |
def _evaluate_objective_multiple(objective_function, arg_batch,
batch_evaluate_objective):
"""Evaluates the objective function on a batch of points.
If `batch_evaluate_objective` is True, returns
`objective function(arg_batch)` else it maps the `objective_function`
across the `... | [
"def",
"_evaluate_objective_multiple",
"(",
"objective_function",
",",
"arg_batch",
",",
"batch_evaluate_objective",
")",
":",
"n_points",
"=",
"tf",
".",
"shape",
"(",
"input",
"=",
"arg_batch",
")",
"[",
"0",
"]",
"if",
"batch_evaluate_objective",
":",
"return",... | 49.147059 | 24.088235 |
def json2lte(self, filename):
""" convert json to lte
return tuple of json, lte file content
"""
data_json = open(filename, 'r').read().strip()
latins = lattice.Lattice(data_json)
self.lattice_instance = latins
self.all_beamlines = latins.getAllBl()
... | [
"def",
"json2lte",
"(",
"self",
",",
"filename",
")",
":",
"data_json",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"latins",
"=",
"lattice",
".",
"Lattice",
"(",
"data_json",
")",
"self",
".",
"lat... | 38.421053 | 17.684211 |
def update_items(portal_type=None, uid=None, endpoint=None, **kw):
""" update items
1. If the uid is given, the user wants to update the object with the data
given in request body
2. If no uid is given, the user wants to update a bunch of objects.
-> each record contains either an UID, path o... | [
"def",
"update_items",
"(",
"portal_type",
"=",
"None",
",",
"uid",
"=",
"None",
",",
"endpoint",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"# disable CSRF",
"req",
".",
"disable_csrf_protection",
"(",
")",
"# the data to update",
"records",
"=",
"req",
... | 30.230769 | 20.666667 |
def decode_and_evaluate(self,
checkpoint: Optional[int] = None,
output_name: str = os.devnull) -> Dict[str, float]:
"""
Decodes data set and evaluates given a checkpoint.
:param checkpoint: Checkpoint to load parameters from.
:para... | [
"def",
"decode_and_evaluate",
"(",
"self",
",",
"checkpoint",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"output_name",
":",
"str",
"=",
"os",
".",
"devnull",
")",
"->",
"Dict",
"[",
"str",
",",
"float",
"]",
":",
"models",
",",
"vocab_target"... | 66.140625 | 32.515625 |
def delete_association(self, target, api_type=None, api_sub_type=None, unique_id=None):
"""
Deletes a association from a Indicator/Group/Victim
Args:
target:
api_type:
api_sub_type:
unique_id:
Returns:
"""
api_type = api_... | [
"def",
"delete_association",
"(",
"self",
",",
"target",
",",
"api_type",
"=",
"None",
",",
"api_sub_type",
"=",
"None",
",",
"unique_id",
"=",
"None",
")",
":",
"api_type",
"=",
"api_type",
"or",
"target",
".",
"api_type",
"api_sub_type",
"=",
"api_sub_type... | 27.516129 | 19.516129 |
def nfa_determinization(nfa: dict) -> dict:
""" Returns a DFA that reads the same language of the input NFA.
Let A be an NFA, then there exists a DFA :math:`A_d` such
that :math:`L(A_d) = L(A)`. Intuitively, :math:`A_d`
collapses all possible runs of A on a given input word into
one run over a larg... | [
"def",
"nfa_determinization",
"(",
"nfa",
":",
"dict",
")",
"->",
"dict",
":",
"def",
"state_name",
"(",
"s",
")",
":",
"return",
"str",
"(",
"set",
"(",
"sorted",
"(",
"s",
")",
")",
")",
"dfa",
"=",
"{",
"'alphabet'",
":",
"nfa",
"[",
"'alphabet'... | 35.666667 | 18.590909 |
def VersionPath():
"""Returns a path to version.ini."""
# Try to get a version.ini. It should be in the resources if the code
# was packed with "pip sdist". It will be 2 levels up from grr_response_core
# if the code was installed via "pip install -e".
version_ini = (
package.ResourcePath("grr-response... | [
"def",
"VersionPath",
"(",
")",
":",
"# Try to get a version.ini. It should be in the resources if the code",
"# was packed with \"pip sdist\". It will be 2 levels up from grr_response_core",
"# if the code was installed via \"pip install -e\".",
"version_ini",
"=",
"(",
"package",
".",
"R... | 38 | 25 |
def build_vec(self):
"""build call validity vector for each device"""
for item in all_calls:
self.__dict__[item] = []
for dev in self.devices:
for item in all_calls:
if self.system.__dict__[dev].n == 0:
val = False
else... | [
"def",
"build_vec",
"(",
"self",
")",
":",
"for",
"item",
"in",
"all_calls",
":",
"self",
".",
"__dict__",
"[",
"item",
"]",
"=",
"[",
"]",
"for",
"dev",
"in",
"self",
".",
"devices",
":",
"for",
"item",
"in",
"all_calls",
":",
"if",
"self",
".",
... | 36.083333 | 14.083333 |
def add_interval(self, precision=0):
""" Adds an interval to :prop:intervals
-> #str formatted time
"""
precision = precision or self.precision
interval = round((self._stop - self._start), precision)
self.intervals.append(interval)
self._intervals_len += 1
... | [
"def",
"add_interval",
"(",
"self",
",",
"precision",
"=",
"0",
")",
":",
"precision",
"=",
"precision",
"or",
"self",
".",
"precision",
"interval",
"=",
"round",
"(",
"(",
"self",
".",
"_stop",
"-",
"self",
".",
"_start",
")",
",",
"precision",
")",
... | 39.1 | 5.1 |
def synchronized(wrapped):
""" Synchronization decorator. """
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
self = args[0]
with self._lock:
return wrapped(*args, **kwargs)
return wrapper | [
"def",
"synchronized",
"(",
"wrapped",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"wrapped",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"with",
"self",
".",
"_lock",
":",
"r... | 23.3 | 17.1 |
def _prime_group_perm_caches(self):
"""
Prime the group cache and put them on the ``self.group``.
In addition add a cache filled flag on ``self.group``.
"""
perm_cache = self._get_group_cached_perms()
self.group._authority_perm_cache = perm_cache
self.group._autho... | [
"def",
"_prime_group_perm_caches",
"(",
"self",
")",
":",
"perm_cache",
"=",
"self",
".",
"_get_group_cached_perms",
"(",
")",
"self",
".",
"group",
".",
"_authority_perm_cache",
"=",
"perm_cache",
"self",
".",
"group",
".",
"_authority_perm_cache_filled",
"=",
"T... | 42.75 | 11.25 |
def strlimit (s, length=72):
"""If the length of the string exceeds the given limit, it will be cut
off and three dots will be appended.
@param s: the string to limit
@type s: string
@param length: maximum length
@type length: non-negative integer
@return: limited string, at most length+3 c... | [
"def",
"strlimit",
"(",
"s",
",",
"length",
"=",
"72",
")",
":",
"assert",
"length",
">=",
"0",
",",
"\"length limit must be a non-negative integer\"",
"if",
"not",
"s",
"or",
"len",
"(",
"s",
")",
"<=",
"length",
":",
"return",
"s",
"if",
"length",
"=="... | 32.375 | 13.9375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.