text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def present(name,
type,
url,
access=None,
user=None,
password=None,
database=None,
basic_auth=None,
basic_auth_user=None,
basic_auth_password=None,
tls_auth=None,
json_data=None,
... | [
"def",
"present",
"(",
"name",
",",
"type",
",",
"url",
",",
"access",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"database",
"=",
"None",
",",
"basic_auth",
"=",
"None",
",",
"basic_auth_user",
"=",
"None",
",",
"basic... | 28.935484 | 22.370968 |
def strain_out_of_plane(self, **kwargs):
'''
Returns the out-of-plane strain assuming no lattice relaxation, which
is negative for tensile strain and positive for compressive strain.
This is the strain measured by X-ray diffraction (XRD) symmetric
omega-2theta scans.
'''
... | [
"def",
"strain_out_of_plane",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_strain_out_of_plane",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_strain_out_of_plane",
"else",
":",
"return",
"(",
"-",
"2",
"*",
"self",
".",
"uns... | 44.846154 | 19.923077 |
def get(self, size, create=True):
"""
Returns a Thumbnail instance.
First check whether thumbnail is already cached. If it doesn't:
1. Try to fetch the thumbnail
2. Create thumbnail if it's not present
3. Cache the thumbnail for future use
"""
if self._thu... | [
"def",
"get",
"(",
"self",
",",
"size",
",",
"create",
"=",
"True",
")",
":",
"if",
"self",
".",
"_thumbnails",
"is",
"None",
":",
"self",
".",
"_refresh_cache",
"(",
")",
"thumbnail",
"=",
"self",
".",
"_thumbnails",
".",
"get",
"(",
"size",
")",
... | 31.26087 | 16.217391 |
def build_edges(self):
"""
Build edges based on node `edges` property.
Filters out any `Edge` not defined in the DAG.
"""
self.edges = [
edge if isinstance(edge, Edge) else Edge(*edge)
for node in self.nodes.values()
for edge in getattr(node,... | [
"def",
"build_edges",
"(",
"self",
")",
":",
"self",
".",
"edges",
"=",
"[",
"edge",
"if",
"isinstance",
"(",
"edge",
",",
"Edge",
")",
"else",
"Edge",
"(",
"*",
"edge",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
".",
"values",
"(",
")",
"fo... | 29.5 | 17.642857 |
def sort_key_process(request, sort_key='sort'):
"""
process sort-parameter value (for example, "-name")
return:
current_param - field for sorting ("name)
current_reversed - revers flag (True)
"""
current = request.GET.get(sort_key)
current_reversed = False
cur... | [
"def",
"sort_key_process",
"(",
"request",
",",
"sort_key",
"=",
"'sort'",
")",
":",
"current",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"sort_key",
")",
"current_reversed",
"=",
"False",
"current_param",
"=",
"None",
"if",
"current",
":",
"mo",
"=",
... | 33.352941 | 14.411765 |
def get_or_create_folder(self, folder_names):
"""
Gets or creates a Folder based the list of folder names in hierarchical
order (like breadcrumbs).
get_or_create_folder(['root', 'subfolder', 'subsub folder'])
creates the folders with correct parent relations and returns the
... | [
"def",
"get_or_create_folder",
"(",
"self",
",",
"folder_names",
")",
":",
"if",
"not",
"len",
"(",
"folder_names",
")",
":",
"return",
"None",
"current_parent",
"=",
"None",
"for",
"folder_name",
"in",
"folder_names",
":",
"current_parent",
",",
"created",
"=... | 42 | 20.7 |
def _deconstruct_url(self, url: str) -> List[str]:
"""
Split a regular URL into parts
:param url: A normalized URL
:return: Parts of the URL
:raises kua.routes.RouteError: \
If the depth of the URL exceeds\
the max depth of the deepest\
registered pattern... | [
"def",
"_deconstruct_url",
"(",
"self",
",",
"url",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"parts",
"=",
"url",
".",
"split",
"(",
"'/'",
",",
"self",
".",
"_max_depth",
"+",
"1",
")",
"if",
"depth_of",
"(",
"parts",
")",
">",
"self... | 26.052632 | 13.631579 |
def write_padding(self, s):
"""
Write string that are not part of the original file.
"""
lines = s.splitlines(True)
for line in lines:
self.stream.write(line)
if line[-1] in '\r\n':
self._newline()
else:
# this ... | [
"def",
"write_padding",
"(",
"self",
",",
"s",
")",
":",
"lines",
"=",
"s",
".",
"splitlines",
"(",
"True",
")",
"for",
"line",
"in",
"lines",
":",
"self",
".",
"stream",
".",
"write",
"(",
"line",
")",
"if",
"line",
"[",
"-",
"1",
"]",
"in",
"... | 28.615385 | 11.076923 |
def replace_broker(self, source_id, dest_id):
"""Move all partitions in source broker to destination broker.
:param source_id: source broker-id
:param dest_id: destination broker-id
:raises: InvalidBrokerIdError, when either of given broker-ids is invalid.
"""
try:
... | [
"def",
"replace_broker",
"(",
"self",
",",
"source_id",
",",
"dest_id",
")",
":",
"try",
":",
"source",
"=",
"self",
".",
"brokers",
"[",
"source_id",
"]",
"dest",
"=",
"self",
".",
"brokers",
"[",
"dest_id",
"]",
"# Move all partitions from source to destinat... | 46.173913 | 15.434783 |
def cluster(self, n, embed_dim=None, algo=spectral.SPECTRAL, method=methods.KMEANS):
"""
Cluster the embedded coordinates using spectral clustering
Parameters
----------
n: int
The number of clusters to return
embed_dim: ... | [
"def",
"cluster",
"(",
"self",
",",
"n",
",",
"embed_dim",
"=",
"None",
",",
"algo",
"=",
"spectral",
".",
"SPECTRAL",
",",
"method",
"=",
"methods",
".",
"KMEANS",
")",
":",
"if",
"n",
"==",
"1",
":",
"return",
"Partition",
"(",
"[",
"1",
"]",
"... | 40.282609 | 20.456522 |
def init_app(self, app, client_id=None):
"""Initialize the Micropub extension if it was not given app
in the constructor.
Args:
app (flask.Flask): the flask application to extend.
client_id (string, optional): the IndieAuth client id, will be
displayed when the u... | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"client_id",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"client_id",
":",
"if",
"client_id",
":",
"self",
".",
"client_id",
"=",
"client_id",
"else",
":",
"self",
".",
"client_id",
"=",
"app",
".... | 38.133333 | 15.266667 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'credential_id') and self.credential_id is not None:
_dict['credential_id'] = self.credential_id
if hasattr(self, 'status') and self.status is not None:
_dict['... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'credential_id'",
")",
"and",
"self",
".",
"credential_id",
"is",
"not",
"None",
":",
"_dict",
"[",
"'credential_id'",
"]",
"=",
"self",
".",
"credent... | 44.5 | 17.375 |
def nsl(h, use_threads=True):
"""Compute the unstandardized number of segregating sites by length (nSl)
for each variant, comparing the reference and alternate alleles,
after Ferrer-Admetlla et al. (2014).
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplo... | [
"def",
"nsl",
"(",
"h",
",",
"use_threads",
"=",
"True",
")",
":",
"# check inputs",
"h",
"=",
"asarray_ndim",
"(",
"h",
",",
"2",
")",
"check_integer_dtype",
"(",
"h",
")",
"h",
"=",
"memoryview_safe",
"(",
"h",
")",
"# # check there are no invariant sites"... | 26.847059 | 23.482353 |
def getMorphParameters(fromTGFN, toTGFN, tierName,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on the contents of ... | [
"def",
"getMorphParameters",
"(",
"fromTGFN",
",",
"toTGFN",
",",
"tierName",
",",
"filterFunc",
"=",
"None",
",",
"useBlanks",
"=",
"False",
")",
":",
"if",
"filterFunc",
"is",
"None",
":",
"filterFunc",
"=",
"lambda",
"entry",
":",
"True",
"# Everything is... | 37.871795 | 24.384615 |
def assignrepr(self, prefix):
"""Return a |repr| string with a prefixed assignment."""
caller = 'Timegrids('
blanks = ' ' * (len(prefix) + len(caller))
prefix = f'{prefix}{caller}'
lines = [f'{self.init.assignrepr(prefix)},']
if self.sim != self.init:
lines.ap... | [
"def",
"assignrepr",
"(",
"self",
",",
"prefix",
")",
":",
"caller",
"=",
"'Timegrids('",
"blanks",
"=",
"' '",
"*",
"(",
"len",
"(",
"prefix",
")",
"+",
"len",
"(",
"caller",
")",
")",
"prefix",
"=",
"f'{prefix}{caller}'",
"lines",
"=",
"[",
"f'{self.... | 42.3 | 8.3 |
def create_lazy_user(self):
""" Create a lazy user. Returns a 2-tuple of the underlying User
object (which may be of a custom class), and the username.
"""
user_class = self.model.get_user_class()
username = self.generate_username(user_class)
user = user_class.objects.cre... | [
"def",
"create_lazy_user",
"(",
"self",
")",
":",
"user_class",
"=",
"self",
".",
"model",
".",
"get_user_class",
"(",
")",
"username",
"=",
"self",
".",
"generate_username",
"(",
"user_class",
")",
"user",
"=",
"user_class",
".",
"objects",
".",
"create_use... | 43.888889 | 11.111111 |
def _parse_args(argv):
"""
Show supported config format types or usage.
:param argv: Argument list to parse or None (sys.argv will be set).
:return: argparse.Namespace object or None (exit before return)
"""
parser = make_parser()
args = parser.parse_args(argv)
LOGGER.setLevel(to_log_le... | [
"def",
"_parse_args",
"(",
"argv",
")",
":",
"parser",
"=",
"make_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"argv",
")",
"LOGGER",
".",
"setLevel",
"(",
"to_log_level",
"(",
"args",
".",
"loglevel",
")",
")",
"if",
"args",
".",
... | 28.551724 | 19.586207 |
def unrank(n, sequence=string.ascii_lowercase):
"""Unrank n from sequence in colexicographical order.
>>> [''.join(unrank(i)) for i in range(8)]
['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
>>> unrank(299009)
['a', 'm', 'p', 's']
"""
return list(map(sequence.__getitem__, indexes(n))) | [
"def",
"unrank",
"(",
"n",
",",
"sequence",
"=",
"string",
".",
"ascii_lowercase",
")",
":",
"return",
"list",
"(",
"map",
"(",
"sequence",
".",
"__getitem__",
",",
"indexes",
"(",
"n",
")",
")",
")"
] | 30.5 | 14.9 |
def debug (logname, msg, *args, **kwargs):
"""Log a debug message.
return: None
"""
log = logging.getLogger(logname)
if log.isEnabledFor(logging.DEBUG):
_log(log.debug, msg, args, **kwargs) | [
"def",
"debug",
"(",
"logname",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"logname",
")",
"if",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"_log",
"(",
... | 26.375 | 9.375 |
def find_closed_date_by_commit(self, issue):
"""
Fill "actual_date" parameter of specified issue by closed date of
the commit, if it was closed by commit.
:param dict issue: issue to edit
"""
if not issue.get('events'):
return
# if it's PR -> then fi... | [
"def",
"find_closed_date_by_commit",
"(",
"self",
",",
"issue",
")",
":",
"if",
"not",
"issue",
".",
"get",
"(",
"'events'",
")",
":",
"return",
"# if it's PR -> then find \"merged event\", in case",
"# of usual issue -> find closed date",
"compare_string",
"=",
"\"merged... | 40.37037 | 15.185185 |
def init_passbands(refresh=False):
"""
This function should be called only once, at import time. It
traverses the passbands directory and builds a lookup table of
passband names qualified as 'pbset:pbname' and corresponding files
and atmosphere content within.
"""
global _initialized
if... | [
"def",
"init_passbands",
"(",
"refresh",
"=",
"False",
")",
":",
"global",
"_initialized",
"if",
"not",
"_initialized",
"or",
"refresh",
":",
"# load information from online passbands first so that any that are",
"# available locally will override",
"online_passbands",
"=",
"... | 39.142857 | 17.885714 |
def show_minimum_needs(self):
"""Show the minimum needs dialog."""
# import here only so that it is AFTER i18n set up
from safe.gui.tools.minimum_needs.needs_calculator_dialog import (
NeedsCalculatorDialog
)
dialog = NeedsCalculatorDialog(self.iface.mainWindow())
... | [
"def",
"show_minimum_needs",
"(",
"self",
")",
":",
"# import here only so that it is AFTER i18n set up",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"minimum_needs",
".",
"needs_calculator_dialog",
"import",
"(",
"NeedsCalculatorDialog",
")",
"dialog",
"=",
"NeedsCa... | 36.888889 | 20.222222 |
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {... | [
"def",
"remove_apppool",
"(",
"name",
")",
":",
"# Remove IIS AppPool",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"current_apppools",
"=",
"__salt__",
"[",
"'w... | 28.111111 | 21.444444 |
def _call(self, x, out):
"""Return ``self(x)``."""
if self.domain.is_real:
# Real domain, multiply separately
out.real = self.scalar.real * x
out.imag = self.scalar.imag * x
else:
# Complex domain
out.lincomb(self.scalar, x) | [
"def",
"_call",
"(",
"self",
",",
"x",
",",
"out",
")",
":",
"if",
"self",
".",
"domain",
".",
"is_real",
":",
"# Real domain, multiply separately",
"out",
".",
"real",
"=",
"self",
".",
"scalar",
".",
"real",
"*",
"x",
"out",
".",
"imag",
"=",
"self... | 33.333333 | 8.555556 |
def get_conditional_uni(cls, left_parent, right_parent):
"""Identify pair univariate value from parents.
Args:
left_parent(Edge): left parent
right_parent(Edge): right parent
Returns:
tuple[np.ndarray, np.ndarray]: left and right parents univariate.
... | [
"def",
"get_conditional_uni",
"(",
"cls",
",",
"left_parent",
",",
"right_parent",
")",
":",
"left",
",",
"right",
",",
"_",
"=",
"cls",
".",
"_identify_eds_ing",
"(",
"left_parent",
",",
"right_parent",
")",
"left_u",
"=",
"left_parent",
".",
"U",
"[",
"0... | 36.375 | 24.875 |
def intervals_union(S):
"""Union of intervals
:param S: list of pairs (low, high) defining intervals [low, high)
:returns: ordered list of disjoint intervals with the same union as S
:complexity: O(n log n)
"""
E = [(low, -1) for (low, high) in S]
E += [(high, +1) for (low, high) in S]
... | [
"def",
"intervals_union",
"(",
"S",
")",
":",
"E",
"=",
"[",
"(",
"low",
",",
"-",
"1",
")",
"for",
"(",
"low",
",",
"high",
")",
"in",
"S",
"]",
"E",
"+=",
"[",
"(",
"high",
",",
"+",
"1",
")",
"for",
"(",
"low",
",",
"high",
")",
"in",
... | 27.318182 | 16.409091 |
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
"""
Updates references to the old logical id of a resource to the new (generated) logical id.
Example:
{"Ref": "MyLayer"} => {"Ref": "MyLayerABC123"}
:param dict input_dict: Dictionary representing ... | [
"def",
"resolve_resource_id_refs",
"(",
"self",
",",
"input_dict",
",",
"supported_resource_id_refs",
")",
":",
"if",
"not",
"self",
".",
"can_handle",
"(",
"input_dict",
")",
":",
"return",
"input_dict",
"ref_value",
"=",
"input_dict",
"[",
"self",
".",
"intrin... | 35.571429 | 27.071429 |
def get_mount_targets(filesystemid=None,
mounttargetid=None,
keyid=None,
key=None,
profile=None,
region=None,
**kwargs):
'''
Get all the EFS mount point properties for a specific f... | [
"def",
"get_mount_targets",
"(",
"filesystemid",
"=",
"None",
",",
"mounttargetid",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"key",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"region",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
... | 33.466667 | 24.044444 |
def project(self,projection_matrix,inplace=True,log=None,
enforce_bounds="reset"):
""" project the ensemble using the null-space Monte Carlo method
Parameters
----------
projection_matrix : pyemu.Matrix
projection operator - must already respect log transform... | [
"def",
"project",
"(",
"self",
",",
"projection_matrix",
",",
"inplace",
"=",
"True",
",",
"log",
"=",
"None",
",",
"enforce_bounds",
"=",
"\"reset\"",
")",
":",
"if",
"self",
".",
"istransformed",
":",
"self",
".",
"_back_transform",
"(",
")",
"istransfor... | 36.123288 | 22.082192 |
def create(opts):
"""Create a new environment
Usage:
datacats create [-bin] [--interactive] [-s NAME] [--address=IP] [--syslog]
[--ckan=CKAN_VERSION] [--no-datapusher] [--site-url SITE_URL]
[--no-init-db] ENVIRONMENT_DIR [PORT]
Options:
--address=IP Address to li... | [
"def",
"create",
"(",
"opts",
")",
":",
"if",
"opts",
"[",
"'--address'",
"]",
"and",
"is_boot2docker",
"(",
")",
":",
"raise",
"DatacatsError",
"(",
"'Cannot specify address on boot2docker.'",
")",
"return",
"create_environment",
"(",
"environment_dir",
"=",
"opt... | 44.536585 | 19.804878 |
def _enable_session_activity(self, app):
"""Enable session activity."""
user_logged_in.connect(login_listener, app)
user_logged_out.connect(logout_listener, app)
from .views.settings import blueprint
from .views.security import security, revoke_session
blueprint.route('/s... | [
"def",
"_enable_session_activity",
"(",
"self",
",",
"app",
")",
":",
"user_logged_in",
".",
"connect",
"(",
"login_listener",
",",
"app",
")",
"user_logged_out",
".",
"connect",
"(",
"logout_listener",
",",
"app",
")",
"from",
".",
"views",
".",
"settings",
... | 53.625 | 13.875 |
def setSeries(self, startId, length, color):
"""
Command 0x07
sets all lights in the series starting from "startId" to "endId" to "color"
Data:
[0x07][startId][length][r][g][b]
"""
buff = bytearray()
buff.append(LightProtocolCommand.SetSeries)
buff.extend(struct.pack('<H', startId))
buff.extend(st... | [
"def",
"setSeries",
"(",
"self",
",",
"startId",
",",
"length",
",",
"color",
")",
":",
"buff",
"=",
"bytearray",
"(",
")",
"buff",
".",
"append",
"(",
"LightProtocolCommand",
".",
"SetSeries",
")",
"buff",
".",
"extend",
"(",
"struct",
".",
"pack",
"(... | 23.5 | 18 |
def create_zone(args):
"""Create zone.
Argument:
args: arguments object
"""
action = True
password = get_password(args)
token = connect.get_token(args.username, password, args.server)
domain = args.domain
template = args.domain.replace('.', '_')
master = None
dnsaddr... | [
"def",
"create_zone",
"(",
"args",
")",
":",
"action",
"=",
"True",
"password",
"=",
"get_password",
"(",
"args",
")",
"token",
"=",
"connect",
".",
"get_token",
"(",
"args",
".",
"username",
",",
"password",
",",
"args",
".",
"server",
")",
"domain",
... | 23.216216 | 22.297297 |
def load_spec(filename):
"""
Load a protobuf model specification from file
Parameters
----------
filename: str
Location on disk (a valid filepath) from which the file is loaded
as a protobuf spec.
Returns
-------
model_spec: Model_pb
Protobuf representation of t... | [
"def",
"load_spec",
"(",
"filename",
")",
":",
"from",
".",
".",
"proto",
"import",
"Model_pb2",
"spec",
"=",
"Model_pb2",
".",
"Model",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"contents",
"=",
"f",
".",
"read",
... | 20.5625 | 22.0625 |
def delete(self, model, commit=True):
"""
Delete
Puts model for deletion into unit of work and optionall commits
transaction
:param model: object, model to delete
:param commit: bool, commit?
:return: object, deleted model
... | [
"def",
"delete",
"(",
"self",
",",
"model",
",",
"commit",
"=",
"True",
")",
":",
"self",
".",
"is_instance",
"(",
"model",
")",
"db",
".",
"session",
".",
"delete",
"(",
"model",
")",
"if",
"commit",
":",
"db",
".",
"session",
".",
"commit",
"(",
... | 28 | 16.375 |
def get_feats(self, doc):
'''
Parameters
----------
doc, Spacy Docs
Returns
-------
Counter (unigram, bigram) -> count
'''
ngram_counter = Counter()
for sent in doc.sents:
unigrams = self._get_unigram_feats(sent)
bigrams = self._get_bigram_feats(unigrams)
ngram_counter += Counter(chain(uni... | [
"def",
"get_feats",
"(",
"self",
",",
"doc",
")",
":",
"ngram_counter",
"=",
"Counter",
"(",
")",
"for",
"sent",
"in",
"doc",
".",
"sents",
":",
"unigrams",
"=",
"self",
".",
"_get_unigram_feats",
"(",
"sent",
")",
"bigrams",
"=",
"self",
".",
"_get_bi... | 21.5 | 21.125 |
def clip(attrs, inputs, proto_obj):
"""Clips (limits) the values in an array."""
new_attrs = translation_utils._fix_attribute_names(attrs, {'min' : 'a_min',
'max' : 'a_max'})
if 'a_max' not in new_attrs:
new_attrs = translation_utils._ad... | [
"def",
"clip",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"new_attrs",
"=",
"translation_utils",
".",
"_fix_attribute_names",
"(",
"attrs",
",",
"{",
"'min'",
":",
"'a_min'",
",",
"'max'",
":",
"'a_max'",
"}",
")",
"if",
"'a_max'",
"not",
"... | 58.111111 | 22.777778 |
def getVMstats(self):
"""Return stats for Virtual Memory Subsystem.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp = open(vmstatFile, 'r')
data = fp.read()
fp.close()
except:
raise IOError('Failed... | [
"def",
"getVMstats",
"(",
"self",
")",
":",
"info_dict",
"=",
"{",
"}",
"try",
":",
"fp",
"=",
"open",
"(",
"vmstatFile",
",",
"'r'",
")",
"data",
"=",
"fp",
".",
"read",
"(",
")",
"fp",
".",
"close",
"(",
")",
"except",
":",
"raise",
"IOError",
... | 28.777778 | 14.777778 |
def handle_error(self, error=None):
"""Trap for TCPServer errors, otherwise continue."""
if _debug: TCPServerActor._debug("handle_error %r", error)
# pass along to the director
if error is not None:
self.director.actor_error(self, error)
else:
TCPServer.h... | [
"def",
"handle_error",
"(",
"self",
",",
"error",
"=",
"None",
")",
":",
"if",
"_debug",
":",
"TCPServerActor",
".",
"_debug",
"(",
"\"handle_error %r\"",
",",
"error",
")",
"# pass along to the director",
"if",
"error",
"is",
"not",
"None",
":",
"self",
"."... | 36.555556 | 13.666667 |
def _create_postgresql_pygresql(self, **kwargs):
"""
:rtype: Engine
"""
return self._ce(
self._ccs(self.DialectAndDriver.psql_pygresql), **kwargs
) | [
"def",
"_create_postgresql_pygresql",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_ce",
"(",
"self",
".",
"_ccs",
"(",
"self",
".",
"DialectAndDriver",
".",
"psql_pygresql",
")",
",",
"*",
"*",
"kwargs",
")"
] | 27.571429 | 14.428571 |
def get_updates(self, *args, **kwargs):
"""See :func:`get_updates`"""
return get_updates(*args, **self._merge_overrides(**kwargs)).run() | [
"def",
"get_updates",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"get_updates",
"(",
"*",
"args",
",",
"*",
"*",
"self",
".",
"_merge_overrides",
"(",
"*",
"*",
"kwargs",
")",
")",
".",
"run",
"(",
")"
] | 50 | 11.666667 |
def disable(name, no_block=False, root=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
contro... | [
"def",
"disable",
"(",
"name",
",",
"no_block",
"=",
"False",
",",
"root",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"_check_for_unit_changes",
"(",
"name",
")",
"if",
"name",
"in",
"_get_sysv_services",
"(",
"root",
... | 42.44898 | 24.44898 |
def hardware_custom_profile_kap_custom_profile_udld_udld_hello_interval(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
custom_profile = ET.SubElement(hardware, "... | [
"def",
"hardware_custom_profile_kap_custom_profile_udld_udld_hello_interval",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hardware",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hardware\"",... | 53.133333 | 22.666667 |
def first(self, timeout=None):
""" Wait for the first successful result to become available
:param timeout: Wait timeout, sec
:type timeout: float|int|None
:return: result, or None if all threads have failed
:rtype: *
"""
while True:
with self._jobfini... | [
"def",
"first",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"while",
"True",
":",
"with",
"self",
".",
"_jobfinished",
":",
"if",
"self",
".",
"_results",
"or",
"not",
"self",
".",
"_jobs",
".",
"unfinished_tasks",
":",
"break",
"self",
".",
... | 39.615385 | 11.538462 |
def parse_component(text, name=None, datatype='ST', version=None, encoding_chars=None,
validation_level=None, reference=None):
"""
Parse the given ER7-encoded component and return an instance of
:class:`Component <hl7apy.core.Component>`.
:type text: ``str``
:param text: the ER7... | [
"def",
"parse_component",
"(",
"text",
",",
"name",
"=",
"None",
",",
"datatype",
"=",
"'ST'",
",",
"version",
"=",
"None",
",",
"encoding_chars",
"=",
"None",
",",
"validation_level",
"=",
"None",
",",
"reference",
"=",
"None",
")",
":",
"version",
"=",... | 45.112903 | 26.564516 |
def on_for_degrees(self, speed, degrees, brake=True, block=True):
"""
Rotate the motor at ``speed`` for ``degrees``
``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue`
object, enabling use of other units.
"""
speed_sp = self._speed_native_units(speed)
... | [
"def",
"on_for_degrees",
"(",
"self",
",",
"speed",
",",
"degrees",
",",
"brake",
"=",
"True",
",",
"block",
"=",
"True",
")",
":",
"speed_sp",
"=",
"self",
".",
"_speed_native_units",
"(",
"speed",
")",
"self",
".",
"_set_rel_position_degrees_and_speed_sp",
... | 37.6 | 18 |
def recursive_unicode(obj):
"""Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries.
"""
if isinstance(obj, dict):
return dict((recursive_unicode(k), recursive_unicode(v)) for (k,v) in obj.iteritems())
elif isinstance(obj, list):
... | [
"def",
"recursive_unicode",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"(",
"recursive_unicode",
"(",
"k",
")",
",",
"recursive_unicode",
"(",
"v",
")",
")",
"for",
"(",
"k",
",",
"v",
")",
"... | 35.733333 | 16 |
def request_response(self):
"""Verify that a card is still present and get its operating mode.
The Request Response command returns the current operating
state of the card. The operating state changes with the
authentication process, a card is in Mode 0 after power-up or
a Polli... | [
"def",
"request_response",
"(",
"self",
")",
":",
"a",
",",
"b",
",",
"e",
"=",
"self",
".",
"pmm",
"[",
"3",
"]",
"&",
"7",
",",
"self",
".",
"pmm",
"[",
"3",
"]",
">>",
"3",
"&",
"7",
",",
"self",
".",
"pmm",
"[",
"3",
"]",
">>",
"6",
... | 45.409091 | 20.454545 |
def ms_pan(self, viewer, event, data_x, data_y):
"""A 'drag' or proportional pan, where the image is panned by
'dragging the canvas' up or down. The amount of the pan is
proportionate to the length of the drag.
"""
if not self.canpan:
return True
x, y = view... | [
"def",
"ms_pan",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
")",
":",
"if",
"not",
"self",
".",
"canpan",
":",
"return",
"True",
"x",
",",
"y",
"=",
"viewer",
".",
"get_last_win_xy",
"(",
")",
"if",
"event",
".",
"state... | 35.142857 | 15.904762 |
def compile(self, program: Program,
to_native_gates: bool = True,
optimize: bool = True) -> Union[BinaryExecutableResponse, PyQuilExecutableResponse]:
"""
A high-level interface to program compilation.
Compilation currently consists of two stages. Please see the ... | [
"def",
"compile",
"(",
"self",
",",
"program",
":",
"Program",
",",
"to_native_gates",
":",
"bool",
"=",
"True",
",",
"optimize",
":",
"bool",
"=",
"True",
")",
"->",
"Union",
"[",
"BinaryExecutableResponse",
",",
"PyQuilExecutableResponse",
"]",
":",
"flags... | 47.37037 | 29 |
def get_filter_list(p_expression):
"""
Returns a list of GrepFilters, OrdinalTagFilters or NegationFilters based
on the given filter expression.
The filter expression is a list of strings.
"""
result = []
for arg in p_expression:
# when a word starts with -, it should be negated
... | [
"def",
"get_filter_list",
"(",
"p_expression",
")",
":",
"result",
"=",
"[",
"]",
"for",
"arg",
"in",
"p_expression",
":",
"# when a word starts with -, it should be negated",
"is_negated",
"=",
"len",
"(",
"arg",
")",
">",
"1",
"and",
"arg",
"[",
"0",
"]",
... | 26.607143 | 17.107143 |
def rerouteTraveltime(self, vehID, currentTravelTimes=True):
"""rerouteTraveltime(string, bool) -> None Reroutes a vehicle. If
currentTravelTimes is True (default) then the current traveltime of the
edges is loaded and used for rerouting. If currentTravelTimes is False
custom travel time... | [
"def",
"rerouteTraveltime",
"(",
"self",
",",
"vehID",
",",
"currentTravelTimes",
"=",
"True",
")",
":",
"if",
"currentTravelTimes",
":",
"time",
"=",
"self",
".",
"_connection",
".",
"simulation",
".",
"getCurrentTime",
"(",
")",
"if",
"time",
"!=",
"self",... | 59.454545 | 24.181818 |
def unpublish(self):
"""
Unpublishes the resource.
"""
self._client._delete(
"{0}/published".format(
self.__class__.base_url(
self.sys['space'].id,
self.sys['id'],
environment_id=self._environment_id... | [
"def",
"unpublish",
"(",
"self",
")",
":",
"self",
".",
"_client",
".",
"_delete",
"(",
"\"{0}/published\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"base_url",
"(",
"self",
".",
"sys",
"[",
"'space'",
"]",
".",
"id",
",",
"self",
".",
"sy... | 24.764706 | 13.941176 |
def swap(self, a, b):
""" Swaps mem positions a and b
"""
self.mem[a], self.mem[b] = self.mem[b], self.mem[a]
self.asm[a], self.asm[b] = self.asm[b], self.asm[a] | [
"def",
"swap",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"self",
".",
"mem",
"[",
"a",
"]",
",",
"self",
".",
"mem",
"[",
"b",
"]",
"=",
"self",
".",
"mem",
"[",
"b",
"]",
",",
"self",
".",
"mem",
"[",
"a",
"]",
"self",
".",
"asm",
"["... | 37.8 | 11.4 |
def diff(full, dataset_uri, reference_dataset_uri):
"""Report the difference between two datasets.
1. Checks that the identifiers are identicial
2. Checks that the sizes are identical
3. Checks that the hashes are identical, if the '--full' option is used
If a differences is detected in step 1, st... | [
"def",
"diff",
"(",
"full",
",",
"dataset_uri",
",",
"reference_dataset_uri",
")",
":",
"def",
"echo_header",
"(",
"desc",
",",
"ds_name",
",",
"ref_ds_name",
",",
"prop",
")",
":",
"click",
".",
"secho",
"(",
"\"Different {}\"",
".",
"format",
"(",
"desc"... | 36.45283 | 21.339623 |
def find_defined_levels():
"""
Find the defined logging levels.
:returns: A dictionary with level names as keys and integers as values.
Here's what the result looks like by default (when
no custom levels or level names have been defined):
>>> find_defined_levels()
{'NOTSET': 0,
'DEBU... | [
"def",
"find_defined_levels",
"(",
")",
":",
"defined_levels",
"=",
"{",
"}",
"for",
"name",
"in",
"dir",
"(",
"logging",
")",
":",
"if",
"name",
".",
"isupper",
"(",
")",
":",
"value",
"=",
"getattr",
"(",
"logging",
",",
"name",
")",
"if",
"isinsta... | 25.192308 | 17.653846 |
def substitute_any_type(type_: Type, basic_types: Set[BasicType]) -> List[Type]:
"""
Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all
possible basic types and returns a list with all possible combinations. Note that this
substitution is unconstrained. That is, ... | [
"def",
"substitute_any_type",
"(",
"type_",
":",
"Type",
",",
"basic_types",
":",
"Set",
"[",
"BasicType",
"]",
")",
"->",
"List",
"[",
"Type",
"]",
":",
"if",
"type_",
"==",
"ANY_TYPE",
":",
"return",
"list",
"(",
"basic_types",
")",
"if",
"isinstance",... | 53.466667 | 24.4 |
def create(self):
"""
Create an instance of the Time Series Service with the typical
starting settings.
"""
self.service.create()
predix.config.set_env_value(self.use_class, 'ingest_uri',
self.get_ingest_uri())
predix.config.set_env_value(self.use... | [
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"service",
".",
"create",
"(",
")",
"predix",
".",
"config",
".",
"set_env_value",
"(",
"self",
".",
"use_class",
",",
"'ingest_uri'",
",",
"self",
".",
"get_ingest_uri",
"(",
")",
")",
"predix",
"."... | 36.75 | 17 |
def _fileToMatrix(file_name):
"""rudimentary method to read in data from a file"""
# TODO: np.loadtxt() might be an alternative
# try:
if 1 < 3:
lres = []
for line in open(file_name, 'r').readlines():
if len(line) > 0 and line[0] not in ('%', '#'):
lres.ap... | [
"def",
"_fileToMatrix",
"(",
"file_name",
")",
":",
"# TODO: np.loadtxt() might be an alternative",
"# try:",
"if",
"1",
"<",
"3",
":",
"lres",
"=",
"[",
"]",
"for",
"line",
"in",
"open",
"(",
"file_name",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"... | 35.666667 | 18.6 |
def _mergedict(a, b):
"""Recusively merge the 2 dicts.
Destructive on argument 'a'.
"""
for p, d1 in b.items():
if p in a:
if not isinstance(d1, dict):
continue
_mergedict(a[p], d1)
else:
a[p] = d1
return a | [
"def",
"_mergedict",
"(",
"a",
",",
"b",
")",
":",
"for",
"p",
",",
"d1",
"in",
"b",
".",
"items",
"(",
")",
":",
"if",
"p",
"in",
"a",
":",
"if",
"not",
"isinstance",
"(",
"d1",
",",
"dict",
")",
":",
"continue",
"_mergedict",
"(",
"a",
"[",... | 21.769231 | 15.384615 |
def slugable(self):
"""
A node is slugable in following cases:
1 - Node doesn't have children.
2 - Node has children but its page doesn't have a regex.
3 - Node has children, its page has regex but it doesn't show it.
4 - Node has children, its page shows his regex and no... | [
"def",
"slugable",
"(",
"self",
")",
":",
"if",
"self",
".",
"page",
":",
"if",
"self",
".",
"is_leaf_node",
"(",
")",
":",
"return",
"True",
"if",
"not",
"self",
".",
"is_leaf_node",
"(",
")",
"and",
"not",
"self",
".",
"page",
".",
"regex",
":",
... | 44.809524 | 20.428571 |
def from_subdir(cls, container, info_obj):
"""Create from subdirectory info object."""
return cls(container,
info_obj['subdir'],
obj_type=cls.type_cls.SUBDIR) | [
"def",
"from_subdir",
"(",
"cls",
",",
"container",
",",
"info_obj",
")",
":",
"return",
"cls",
"(",
"container",
",",
"info_obj",
"[",
"'subdir'",
"]",
",",
"obj_type",
"=",
"cls",
".",
"type_cls",
".",
"SUBDIR",
")"
] | 41.6 | 4.6 |
def setup_requires():
"""
Return required packages
Plus any version tests and warnings
"""
from pkg_resources import parse_version
required = ['cython>=0.24.0']
numpy_requirement = 'numpy>=1.7.1'
try:
import numpy
except Exception:
required.append(numpy_requirement)... | [
"def",
"setup_requires",
"(",
")",
":",
"from",
"pkg_resources",
"import",
"parse_version",
"required",
"=",
"[",
"'cython>=0.24.0'",
"]",
"numpy_requirement",
"=",
"'numpy>=1.7.1'",
"try",
":",
"import",
"numpy",
"except",
"Exception",
":",
"required",
".",
"appe... | 23.684211 | 17.052632 |
def _subtask_error(self, idx, error):
"""Receive an error from a single subtask."""
self.set_exception(error)
self.errbacks.clear() | [
"def",
"_subtask_error",
"(",
"self",
",",
"idx",
",",
"error",
")",
":",
"self",
".",
"set_exception",
"(",
"error",
")",
"self",
".",
"errbacks",
".",
"clear",
"(",
")"
] | 38 | 5.25 |
def get_vault_form(self, *args, **kwargs):
"""Pass through to provider VaultAdminSession.get_vault_form_for_update"""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.get_bin_form_for_update_template
# This method might be a bit sketchy. Time will tell.
i... | [
"def",
"get_vault_form",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Implemented from kitosid template for -",
"# osid.resource.BinAdminSession.get_bin_form_for_update_template",
"# This method might be a bit sketchy. Time will tell.",
"if",
"isinstance",
... | 58.111111 | 19.444444 |
def parse(self, stride=None):
"""Read and cache the file as a numpy array.
Store every *stride* line of data; if ``None`` then the class default is used.
The array is returned with column-first indexing, i.e. for a data file with
columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1... | [
"def",
"parse",
"(",
"self",
",",
"stride",
"=",
"None",
")",
":",
"if",
"stride",
"is",
"None",
":",
"stride",
"=",
"self",
".",
"stride",
"self",
".",
"corrupted_lineno",
"=",
"[",
"]",
"irow",
"=",
"0",
"# count rows of data",
"# cannot use numpy.loadtx... | 51.275362 | 23.086957 |
def p_taskvardecls(self, p):
'taskvardecls : taskvardecls taskvardecl'
p[0] = p[1] + (p[2],)
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_taskvardecls",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"(",
"p",
"[",
"2",
"]",
",",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 35.5 | 9 |
def get_raw_output(self, tile, _baselevel_readonly=False):
"""
Get output raw data.
This function won't work with multiprocessing, as it uses the
``threading.Lock()`` class.
Parameters
----------
tile : tuple, Tile or BufferedTile
If a tile index is ... | [
"def",
"get_raw_output",
"(",
"self",
",",
"tile",
",",
"_baselevel_readonly",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"tile",
",",
"(",
"BufferedTile",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"'tile' must be a tuple or Buffer... | 41.176471 | 22.647059 |
def subnet_group_present(name, subnet_ids=None, subnet_names=None,
description=None, tags=None, region=None,
key=None, keyid=None, profile=None):
'''
Ensure ElastiCache subnet group exists.
.. versionadded:: 2015.8.0
name
The name for the Elast... | [
"def",
"subnet_group_present",
"(",
"name",
",",
"subnet_ids",
"=",
"None",
",",
"subnet_names",
"=",
"None",
",",
"description",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
","... | 35.328125 | 29.078125 |
def extern_clone_val(self, context_handle, val):
"""Clone the given Handle."""
c = self._ffi.from_handle(context_handle)
return c.to_value(self._ffi.from_handle(val[0])) | [
"def",
"extern_clone_val",
"(",
"self",
",",
"context_handle",
",",
"val",
")",
":",
"c",
"=",
"self",
".",
"_ffi",
".",
"from_handle",
"(",
"context_handle",
")",
"return",
"c",
".",
"to_value",
"(",
"self",
".",
"_ffi",
".",
"from_handle",
"(",
"val",
... | 44.5 | 6.25 |
def preprocess(self, image, image_format):
"""
Preprocess an image.
An API hook for image pre-processing. Calls any image format specific
pre-processors (if defined). I.E. If `image_format` is 'JPEG', this
method will look for a method named `preprocess_JPEG`, if found
`... | [
"def",
"preprocess",
"(",
"self",
",",
"image",
",",
"image_format",
")",
":",
"save_kwargs",
"=",
"{",
"'format'",
":",
"image_format",
"}",
"# Ensuring image is properly rotated",
"if",
"hasattr",
"(",
"image",
",",
"'_getexif'",
")",
":",
"exif_datadict",
"="... | 40.555556 | 18.155556 |
def not_user_filter(config, message, fasnick=None, *args, **kw):
""" Everything except a particular user
Use this rule to exclude messages that are associated with one or more
users. Specify several users by separating them with a comma ','.
"""
fasnick = kw.get('fasnick', fasnick)
if not fasn... | [
"def",
"not_user_filter",
"(",
"config",
",",
"message",
",",
"fasnick",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"fasnick",
"=",
"kw",
".",
"get",
"(",
"'fasnick'",
",",
"fasnick",
")",
"if",
"not",
"fasnick",
":",
"return",
"... | 29.578947 | 23.052632 |
def udom83(text: str) -> str:
"""
Udom83 - It's a Thai soundex rule.
:param str text: Thai word
:return: Udom83 soundex
"""
if not text or not isinstance(text, str):
return ""
text = _RE_1.sub("ัน\\1", text)
text = _RE_2.sub("ั\\1", text)
text = _RE_3.sub("ัน\\1", text)
... | [
"def",
"udom83",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"text",
"or",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"\"\"",
"text",
"=",
"_RE_1",
".",
"sub",
"(",
"\"ัน\\\\1\", te",
"x",
")",
"",
"text",
... | 23.2 | 14.933333 |
def remove(self, document_id, namespace, timestamp):
"""Removes documents from Solr
The input is a python dictionary that represents a mongo document.
"""
self.solr.delete(id=u(document_id),
commit=(self.auto_commit_interval == 0)) | [
"def",
"remove",
"(",
"self",
",",
"document_id",
",",
"namespace",
",",
"timestamp",
")",
":",
"self",
".",
"solr",
".",
"delete",
"(",
"id",
"=",
"u",
"(",
"document_id",
")",
",",
"commit",
"=",
"(",
"self",
".",
"auto_commit_interval",
"==",
"0",
... | 40.428571 | 16.285714 |
def _set_matplotlib_default_backend():
"""
matplotlib will try to print to a display if it is available, but don't want
to run it in interactive mode. we tried setting the backend to 'Agg'' before
importing, but it was still resulting in issues. we replace the existing
backend with 'agg' in the defa... | [
"def",
"_set_matplotlib_default_backend",
"(",
")",
":",
"if",
"_matplotlib_installed",
"(",
")",
":",
"import",
"matplotlib",
"matplotlib",
".",
"use",
"(",
"'Agg'",
",",
"force",
"=",
"True",
")",
"config",
"=",
"matplotlib",
".",
"matplotlib_fname",
"(",
")... | 47.8 | 16.4 |
def encode_request(name, value_list):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(name, value_list))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(name)
client_message.appen... | [
"def",
"encode_request",
"(",
"name",
",",
"value_list",
")",
":",
"client_message",
"=",
"ClientMessage",
"(",
"payload_size",
"=",
"calculate_size",
"(",
"name",
",",
"value_list",
")",
")",
"client_message",
".",
"set_message_type",
"(",
"REQUEST_TYPE",
")",
... | 44.545455 | 8.636364 |
def xmlindent(elem, level=0, spacer=' '):
"""
Indents the inputted XML element based on the given indent level.
:param elem | <xml.etree.Element>
"""
i = "\n" + level * spacer
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + spacer
... | [
"def",
"xmlindent",
"(",
"elem",
",",
"level",
"=",
"0",
",",
"spacer",
"=",
"' '",
")",
":",
"i",
"=",
"\"\\n\"",
"+",
"level",
"*",
"spacer",
"if",
"len",
"(",
"elem",
")",
":",
"if",
"not",
"elem",
".",
"text",
"or",
"not",
"elem",
".",
"te... | 32.263158 | 13.526316 |
def update_order_by_id(cls, order_id, order, **kwargs):
"""Update Order
Update attributes of Order
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_order_by_id(order_id, order, async=Tru... | [
"def",
"update_order_by_id",
"(",
"cls",
",",
"order_id",
",",
"order",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_update_o... | 41.909091 | 20.272727 |
def _get_form_or_formset(self, request, obj, **kwargs):
"""
Generic code shared by get_form and get_formset.
"""
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields(request, obj))
... | [
"def",
"_get_form_or_formset",
"(",
"self",
",",
"request",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"exclude",
"is",
"None",
":",
"exclude",
"=",
"[",
"]",
"else",
":",
"exclude",
"=",
"list",
"(",
"self",
".",
"exclude",
... | 43.1 | 17.2 |
def close_umanager(self, force=False):
"""Used to close an uManager session.
:param force: try to close a session regardless of a connection object internal state
"""
if not (force or self.umanager_opened):
return
# make sure we've got a fresh prompt
... | [
"def",
"close_umanager",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"(",
"force",
"or",
"self",
".",
"umanager_opened",
")",
":",
"return",
"# make sure we've got a fresh prompt",
"self",
".",
"ser",
".",
"write",
"(",
"self",
".",
"cr... | 40.85 | 20.15 |
def listsubmenus(self, window_name, object_name):
"""
List children of menu item
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either f... | [
"def",
"listsubmenus",
"(",
"self",
",",
"window_name",
",",
"object_name",
")",
":",
"menu_handle",
"=",
"self",
".",
"_get_menu_handle",
"(",
"window_name",
",",
"object_name",
")",
"role",
",",
"label",
"=",
"self",
".",
"_ldtpize_accessible",
"(",
"menu_ha... | 39.125 | 15.325 |
def mean(self):
"""return the median value"""
# XXX rename this method
if len(self.values) > 0:
return sorted(self.values)[len(self.values) / 2]
else:
return None | [
"def",
"mean",
"(",
"self",
")",
":",
"# XXX rename this method",
"if",
"len",
"(",
"self",
".",
"values",
")",
">",
"0",
":",
"return",
"sorted",
"(",
"self",
".",
"values",
")",
"[",
"len",
"(",
"self",
".",
"values",
")",
"/",
"2",
"]",
"else",
... | 30.285714 | 15 |
def view(model: "Model", *functions: Callable) -> Optional[Callable]:
"""A decorator for registering a callback to a model
Parameters:
model: the model object whose changes the callback should respond to.
Examples:
.. code-block:: python
from spectate import mvc
i... | [
"def",
"view",
"(",
"model",
":",
"\"Model\"",
",",
"*",
"functions",
":",
"Callable",
")",
"->",
"Optional",
"[",
"Callable",
"]",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"Model",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a Model, not %r... | 24.25 | 20.78125 |
def parse_frame(self, buf: bytes) -> List[Tuple[bool, Optional[int],
bytearray,
Optional[bool]]]:
"""Return the next frame from the socket."""
frames = []
if self._tail:
buf, self.... | [
"def",
"parse_frame",
"(",
"self",
",",
"buf",
":",
"bytes",
")",
"->",
"List",
"[",
"Tuple",
"[",
"bool",
",",
"Optional",
"[",
"int",
"]",
",",
"bytearray",
",",
"Optional",
"[",
"bool",
"]",
"]",
"]",
":",
"frames",
"=",
"[",
"]",
"if",
"self"... | 41.833333 | 16.913333 |
def _parse_texlipse_config(self):
'''
Read the project name from the texlipse
config file ".texlipse".
'''
# If Eclipse's workspace refresh, the
# ".texlipse"-File will be newly created,
# so try again after short sleep if
# the file is still missing.
... | [
"def",
"_parse_texlipse_config",
"(",
"self",
")",
":",
"# If Eclipse's workspace refresh, the",
"# \".texlipse\"-File will be newly created,",
"# so try again after short sleep if",
"# the file is still missing.",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"'.texlipse'"... | 37.285714 | 13.5 |
def temporary_unavailable(request, template_name='503.html'):
"""
Default 503 handler, which looks for the requested URL in the
redirects table, redirects if found, and displays 404 page if not
redirected.
Templates: ``503.html``
Context:
request_path
The path of the request... | [
"def",
"temporary_unavailable",
"(",
"request",
",",
"template_name",
"=",
"'503.html'",
")",
":",
"context",
"=",
"{",
"'request_path'",
":",
"request",
".",
"path",
",",
"}",
"return",
"http",
".",
"HttpResponseTemporaryUnavailable",
"(",
"render_to_string",
"("... | 30 | 20.823529 |
def tables(self, **kw):
"""Creates a result set of tables in the database that match the
given criteria.
:param table: the table tname
:param catalog: the catalog name
:param schema: the schmea name
:param tableType: one of TABLE, VIEW, SYSTEM TABLE ...
"""
... | [
"def",
"tables",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"fut",
"=",
"self",
".",
"_run_operation",
"(",
"self",
".",
"_impl",
".",
"tables",
",",
"*",
"*",
"kw",
")",
"return",
"fut"
] | 34.727273 | 12.818182 |
def strnumlist(prefix: str, numbers: List[int], suffix: str = "") -> List[str]:
"""
Makes a string of the format ``<prefix><number><suffix>`` for every number
in ``numbers``, and returns them as a list.
"""
return ["{}{}{}".format(prefix, num, suffix) for num in numbers] | [
"def",
"strnumlist",
"(",
"prefix",
":",
"str",
",",
"numbers",
":",
"List",
"[",
"int",
"]",
",",
"suffix",
":",
"str",
"=",
"\"\"",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"\"{}{}{}\"",
".",
"format",
"(",
"prefix",
",",
"num",
... | 47.666667 | 18.666667 |
def _solve(self):
"""
Calculates the correct position of the port and keeps it aligned with the binding rect
"""
# As the size of the containing state may has changed we need to update the distance to the border
self.update_distance_to_border()
px, py = self._point
... | [
"def",
"_solve",
"(",
"self",
")",
":",
"# As the size of the containing state may has changed we need to update the distance to the border",
"self",
".",
"update_distance_to_border",
"(",
")",
"px",
",",
"py",
"=",
"self",
".",
"_point",
"nw_x",
",",
"nw_y",
",",
"se_x... | 48.818182 | 20.545455 |
def source_raw_reset(self):
"""Return input and raw source and perform a full reset.
"""
out = self.source
out_r = self.source_raw
self.reset()
return out, out_r | [
"def",
"source_raw_reset",
"(",
"self",
")",
":",
"out",
"=",
"self",
".",
"source",
"out_r",
"=",
"self",
".",
"source_raw",
"self",
".",
"reset",
"(",
")",
"return",
"out",
",",
"out_r"
] | 29 | 10.285714 |
def cross(a, b):
r"""Cross product of two 3d vectors."""
if isinstance(a, Mul):
a = a.expand()
avect = 1
aivect = -1
for ai, fact in enumerate(a.args):
if isinstance(fact, Vector3D):
avect = fact
aivect = ai
break
... | [
"def",
"cross",
"(",
"a",
",",
"b",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"Mul",
")",
":",
"a",
"=",
"a",
".",
"expand",
"(",
")",
"avect",
"=",
"1",
"aivect",
"=",
"-",
"1",
"for",
"ai",
",",
"fact",
"in",
"enumerate",
"(",
"a",
"."... | 27.09375 | 16.0625 |
def send(self, msg_string, immediate=True):
"""Send the email via the MailHost tool
"""
try:
mailhost = api.get_tool("MailHost")
mailhost.send(msg_string, immediate=immediate)
except SMTPException as e:
logger.error(e)
return False
... | [
"def",
"send",
"(",
"self",
",",
"msg_string",
",",
"immediate",
"=",
"True",
")",
":",
"try",
":",
"mailhost",
"=",
"api",
".",
"get_tool",
"(",
"\"MailHost\"",
")",
"mailhost",
".",
"send",
"(",
"msg_string",
",",
"immediate",
"=",
"immediate",
")",
... | 31.230769 | 11.384615 |
def get_apps_tools():
"""Get applications' tools and their paths.
Return a dict with application names as keys and paths to tools'
directories as values. Applications without tools are omitted.
"""
tools_paths = {}
for app_config in apps.get_app_configs():
proc_path = os.path.join(app_... | [
"def",
"get_apps_tools",
"(",
")",
":",
"tools_paths",
"=",
"{",
"}",
"for",
"app_config",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
":",
"proc_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"app_config",
".",
"path",
",",
"'tools'",
")",
"if",... | 36 | 20.909091 |
def update(self, defaults=values.unset):
"""
Update the DefaultsInstance
:param dict defaults: A JSON string that describes the default task links.
:returns: Updated DefaultsInstance
:rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsInstance
"""
return... | [
"def",
"update",
"(",
"self",
",",
"defaults",
"=",
"values",
".",
"unset",
")",
":",
"return",
"self",
".",
"_proxy",
".",
"update",
"(",
"defaults",
"=",
"defaults",
",",
")"
] | 35.1 | 17.9 |
def set(self, key: str, value: str, opt: dict = None) -> None:
"""
设置 cookie.value 并设置属性
"""
self[key] = value
if opt is not None:
self[key].update(opt) | [
"def",
"set",
"(",
"self",
",",
"key",
":",
"str",
",",
"value",
":",
"str",
",",
"opt",
":",
"dict",
"=",
"None",
")",
"->",
"None",
":",
"self",
"[",
"key",
"]",
"=",
"value",
"if",
"opt",
"is",
"not",
"None",
":",
"self",
"[",
"key",
"]",
... | 28.285714 | 9.714286 |
def addldapgrouplink(self, group_id, cn, group_access, provider):
"""
Add LDAP group link
:param id: The ID of a group
:param cn: The CN of a LDAP group
:param group_access: Minimum access level for members of the LDAP group
:param provider: LDAP provider for the LDAP gr... | [
"def",
"addldapgrouplink",
"(",
"self",
",",
"group_id",
",",
"cn",
",",
"group_access",
",",
"provider",
")",
":",
"data",
"=",
"{",
"'id'",
":",
"group_id",
",",
"'cn'",
":",
"cn",
",",
"'group_access'",
":",
"group_access",
",",
"'provider'",
":",
"pr... | 41 | 22.411765 |
def _station_load(network, station, crit_stations):
"""
Checks for over-loading of stations.
Parameters
----------
network : :class:`~.grid.network.Network`
station : :class:`~.grid.components.LVStation` or :class:`~.grid.components.MVStation`
crit_stations : :pandas:`pandas.DataFrame<dataf... | [
"def",
"_station_load",
"(",
"network",
",",
"station",
",",
"crit_stations",
")",
":",
"if",
"isinstance",
"(",
"station",
",",
"LVStation",
")",
":",
"grid_level",
"=",
"'lv'",
"else",
":",
"grid_level",
"=",
"'mv'",
"# maximum allowed apparent power of station ... | 44.564103 | 22.25641 |
def _full_kind(details):
"""
Determine the full kind (including a group if applicable) for some failure
details.
:see: ``v1.Status.details``
"""
kind = details[u"kind"]
if details.get(u"group") is not None:
kind += u"." + details[u"group"]
return kind | [
"def",
"_full_kind",
"(",
"details",
")",
":",
"kind",
"=",
"details",
"[",
"u\"kind\"",
"]",
"if",
"details",
".",
"get",
"(",
"u\"group\"",
")",
"is",
"not",
"None",
":",
"kind",
"+=",
"u\".\"",
"+",
"details",
"[",
"u\"group\"",
"]",
"return",
"kind... | 25.636364 | 15.454545 |
def pdist(objects, dmeasure, diagval = numpy.inf):
"""
Compute the pair-wise distances between arbitrary objects.
Notes
-----
``dmeasure`` is assumed to be *symmetry* i.e. between object *a* and object *b* the
function will be called only ones.
Parameters
----------
objects... | [
"def",
"pdist",
"(",
"objects",
",",
"dmeasure",
",",
"diagval",
"=",
"numpy",
".",
"inf",
")",
":",
"out",
"=",
"numpy",
".",
"zeros",
"(",
"[",
"len",
"(",
"objects",
")",
"]",
"*",
"2",
",",
"numpy",
".",
"float",
")",
"numpy",
".",
"fill_diag... | 32.535714 | 21.607143 |
def deprecated_func(func):
"""Deprecates a function, printing a warning on the first usage."""
# We use a mutable container here to work around Py2's lack of
# the `nonlocal` keyword.
first_usage = [True]
@functools.wraps(func)
def wrapper(*args, **kwargs):
if first_usage[0]:
... | [
"def",
"deprecated_func",
"(",
"func",
")",
":",
"# We use a mutable container here to work around Py2's lack of",
"# the `nonlocal` keyword.",
"first_usage",
"=",
"[",
"True",
"]",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
... | 29.722222 | 18.444444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.