text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def handle(app):
# TODO: for this to work properly we need a generator registry
# generator, lifecycle etc.
# list of tuples (label, value)
# TODO customize & use own style
default_choices = [
{
'name': 'Install a generator',
'value': 'install'
},
{
... | [
"def",
"handle",
"(",
"app",
")",
":",
"# TODO: for this to work properly we need a generator registry",
"# generator, lifecycle etc.",
"# list of tuples (label, value)",
"# TODO customize & use own style",
"default_choices",
"=",
"[",
"{",
"'name'",
":",
"'Install a generator'",
... | 25.177778 | 22.2 |
def get_remote_file_size(self, url):
"""Gets the filesize of a remote file """
try:
req = urllib.request.urlopen(url)
return int(req.getheader('Content-Length').strip())
except urllib.error.HTTPError as error:
logger.error('Error retrieving size of the remote ... | [
"def",
"get_remote_file_size",
"(",
"self",
",",
"url",
")",
":",
"try",
":",
"req",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"url",
")",
"return",
"int",
"(",
"req",
".",
"getheader",
"(",
"'Content-Length'",
")",
".",
"strip",
"(",
")",
... | 48.5 | 14 |
def editLogSettings(self, logLocation, logLevel="WARNING", maxLogFileAge=90):
"""
edits the log settings for the portal site
Inputs:
logLocation - file path to where you want the log files saved
on disk
logLevel - this is the level of detail save... | [
"def",
"editLogSettings",
"(",
"self",
",",
"logLocation",
",",
"logLevel",
"=",
"\"WARNING\"",
",",
"maxLogFileAge",
"=",
"90",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/settings/edit\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"log... | 40.833333 | 18.416667 |
def stop(self):
""" Stop this animated progress, and block until it is finished. """
super().stop()
while not self.stopped:
# stop() should block, so printing afterwards isn't interrupted.
sleep(0.001)
# Retrieve the latest exception, if any.
exc = self.ex... | [
"def",
"stop",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"stop",
"(",
")",
"while",
"not",
"self",
".",
"stopped",
":",
"# stop() should block, so printing afterwards isn't interrupted.",
"sleep",
"(",
"0.001",
")",
"# Retrieve the latest exception, if any.",
"... | 36.8 | 15.6 |
def t_ID(self, t):
r'`[^`]*`|[a-zA-Z_][a-zA-Z_0-9:@]*'
res = self.oper.get(t.value, None) # Check for reserved words
if res is None:
res = t.value.upper()
if res == 'FALSE':
t.type = 'BOOL'
t.value = False
elif res == '... | [
"def",
"t_ID",
"(",
"self",
",",
"t",
")",
":",
"res",
"=",
"self",
".",
"oper",
".",
"get",
"(",
"t",
".",
"value",
",",
"None",
")",
"# Check for reserved words\r",
"if",
"res",
"is",
"None",
":",
"res",
"=",
"t",
".",
"value",
".",
"upper",
"(... | 30.470588 | 13.647059 |
def pileup(self, locus):
'''
Given a 1-base locus, return the Pileup at that locus.
Raises a KeyError if this PileupCollection does not have a Pileup at
the specified locus.
'''
locus = to_locus(locus)
if len(locus.positions) != 1:
raise ValueError("N... | [
"def",
"pileup",
"(",
"self",
",",
"locus",
")",
":",
"locus",
"=",
"to_locus",
"(",
"locus",
")",
"if",
"len",
"(",
"locus",
".",
"positions",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Not a single-base locus: %s\"",
"%",
"locus",
")",
"return... | 34.636364 | 20.818182 |
def __attr_name(self, name):
""" Return suitable and valid attribute name. This method replaces dash char to underscore. If name
is invalid ValueError exception is raised
:param name: cookie attribute name
:return: str
"""
if name not in self.cookie_attr_value_compliance.keys():
suggested_name = name.re... | [
"def",
"__attr_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"cookie_attr_value_compliance",
".",
"keys",
"(",
")",
":",
"suggested_name",
"=",
"name",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
".",
"lower",
"(",... | 38.461538 | 15.692308 |
def cleanup_sweep_threads():
'''
Not used. Keeping this function in case we decide not to use
daemonized threads and it becomes necessary to clean up the
running threads upon exit.
'''
for dict_name, obj in globals().items():
if isinstance(obj, (TimedDict,)):
logging.info(
... | [
"def",
"cleanup_sweep_threads",
"(",
")",
":",
"for",
"dict_name",
",",
"obj",
"in",
"globals",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"TimedDict",
",",
")",
")",
":",
"logging",
".",
"info",
"(",
"'Stopping ... | 34.230769 | 18.076923 |
def get_source(self, doc):
"""
Grab contents of 'doc' and return it
:param doc: The active document
:return:
"""
start_iter = doc.get_start_iter()
end_iter = doc.get_end_iter()
source = doc.get_text(start_iter, end_iter, False)
return source | [
"def",
"get_source",
"(",
"self",
",",
"doc",
")",
":",
"start_iter",
"=",
"doc",
".",
"get_start_iter",
"(",
")",
"end_iter",
"=",
"doc",
".",
"get_end_iter",
"(",
")",
"source",
"=",
"doc",
".",
"get_text",
"(",
"start_iter",
",",
"end_iter",
",",
"F... | 27.636364 | 11.272727 |
def do_add_auth(self, params):
"""
\x1b[1mNAME\x1b[0m
add_auth - Authenticates the session
\x1b[1mSYNOPSIS\x1b[0m
add_auth <scheme> <credential>
\x1b[1mEXAMPLES\x1b[0m
> add_auth digest super:s3cr3t
"""
self._zk.add_auth(params.scheme, params.credential) | [
"def",
"do_add_auth",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"_zk",
".",
"add_auth",
"(",
"params",
".",
"scheme",
",",
"params",
".",
"credential",
")"
] | 22.538462 | 16.538462 |
def disconnect(self, abandon_session=False):
""" Disconnects from the Responsys soap service
Calls the service logout method and destroys the client's session information. Returns
True on success, False otherwise.
"""
self.connected = False
if (self.session and self.sess... | [
"def",
"disconnect",
"(",
"self",
",",
"abandon_session",
"=",
"False",
")",
":",
"self",
".",
"connected",
"=",
"False",
"if",
"(",
"self",
".",
"session",
"and",
"self",
".",
"session",
".",
"is_expired",
")",
"or",
"abandon_session",
":",
"try",
":",
... | 37 | 19.117647 |
def add_caption(self, image, caption, colour=None):
""" Add a caption to the image """
if colour is None:
colour = "white"
width, height = image.size
draw = ImageDraw.Draw(image)
draw.font = self.font
draw.font = self.font
draw.text((width // 1... | [
"def",
"add_caption",
"(",
"self",
",",
"image",
",",
"caption",
",",
"colour",
"=",
"None",
")",
":",
"if",
"colour",
"is",
"None",
":",
"colour",
"=",
"\"white\"",
"width",
",",
"height",
"=",
"image",
".",
"size",
"draw",
"=",
"ImageDraw",
".",
"D... | 23.875 | 19.25 |
def make_filter_string(cls, filter_specification):
"""
Converts the given filter specification to a CQL filter expression.
"""
registry = get_current_registry()
visitor_cls = registry.getUtility(IFilterSpecificationVisitor,
name=EXPRESSIO... | [
"def",
"make_filter_string",
"(",
"cls",
",",
"filter_specification",
")",
":",
"registry",
"=",
"get_current_registry",
"(",
")",
"visitor_cls",
"=",
"registry",
".",
"getUtility",
"(",
"IFilterSpecificationVisitor",
",",
"name",
"=",
"EXPRESSION_KINDS",
".",
"CQL"... | 43.9 | 11.9 |
def get_tickers_from_file(self, filename):
"""Load ticker list from txt file"""
if not os.path.exists(filename):
log.error("Ticker List file does not exist: %s", filename)
tickers = []
with io.open(filename, 'r') as fd:
for ticker in fd:
tickers.a... | [
"def",
"get_tickers_from_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"log",
".",
"error",
"(",
"\"Ticker List file does not exist: %s\"",
",",
"filename",
")",
"tickers",
"=",
"[",
... | 35.6 | 13 |
def contains(self, obj):
"""Return whether this Wikicode object contains *obj*.
If *obj* is a :class:`.Node` or :class:`.Wikicode` object, then we
search for it exactly among all of our children, recursively.
Otherwise, this method just uses :meth:`.__contains__` on the string.
... | [
"def",
"contains",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"(",
"Node",
",",
"Wikicode",
")",
")",
":",
"return",
"obj",
"in",
"self",
"try",
":",
"self",
".",
"_do_strong_search",
"(",
"obj",
",",
"recursive",
... | 38 | 19.214286 |
def cat_trials(x3d):
"""Concatenate trials along time axis.
Parameters
----------
x3d : array, shape (t, m, n)
Segmented input data with t trials, m signals, and n samples.
Returns
-------
x2d : array, shape (m, t * n)
Trials are concatenated along the second axis.
See... | [
"def",
"cat_trials",
"(",
"x3d",
")",
":",
"x3d",
"=",
"atleast_3d",
"(",
"x3d",
")",
"t",
"=",
"x3d",
".",
"shape",
"[",
"0",
"]",
"return",
"np",
".",
"concatenate",
"(",
"np",
".",
"split",
"(",
"x3d",
",",
"t",
",",
"0",
")",
",",
"axis",
... | 22.518519 | 22.333333 |
def run(self, *args):
"""Merge unique identities using a matching algorithm."""
params = self.parser.parse_args(args)
code = self.unify(params.matching, params.sources,
params.fast_matching, params.no_strict,
params.interactive, params.recove... | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"code",
"=",
"self",
".",
"unify",
"(",
"params",
".",
"matching",
",",
"params",
".",
"sources",
",",
"params",
".",
... | 33.5 | 23 |
def errors(self):
"""
Get the errors of the tag.
If invalid then the list will consist of errors containing each a code and message explaining the error.
Each error also refers to the respective (sub)tag(s).
:return: list of errors of the tag. If the tag is valid, it returns an ... | [
"def",
"errors",
"(",
"self",
")",
":",
"errors",
"=",
"[",
"]",
"data",
"=",
"self",
".",
"data",
"error",
"=",
"self",
".",
"error",
"# Check if the tag is grandfathered and if the grandfathered tag is deprecated (e.g. no-nyn).",
"if",
"'record'",
"in",
"data",
":... | 41.666667 | 20.422222 |
def compute_fitness_cdf(chromosomes, ga):
"""
Return a list of fitness-weighted cumulative probabilities for a set of chromosomes.
chromosomes: chromosomes to use for fitness-based calculations
ga: ``algorithms.BaseGeneticAlgorithm`` used to obtain fitness values using its ``eval_fitness`` method... | [
"def",
"compute_fitness_cdf",
"(",
"chromosomes",
",",
"ga",
")",
":",
"ga",
".",
"sort",
"(",
"chromosomes",
")",
"fitness",
"=",
"[",
"ga",
".",
"eval_fitness",
"(",
"c",
")",
"for",
"c",
"in",
"chromosomes",
"]",
"min_fit",
"=",
"min",
"(",
"fitness... | 36.761905 | 22.571429 |
def merge(self, b, a=DEFAULT):
"""Merges b into a recursively, if a is not given: merges into self.
also merges lists and:
* merge({a:a},{a:b}) = {a:[a,b]}
* merge({a:[a]},{a:b}) = {a:[a,b]}
* merge({a:a},{a:[b]}) = {a:[a,b]}
* merge({a:[a]},{a:[b]}) = {a... | [
"def",
"merge",
"(",
"self",
",",
"b",
",",
"a",
"=",
"DEFAULT",
")",
":",
"if",
"a",
"is",
"DEFAULT",
":",
"a",
"=",
"self",
"for",
"key",
"in",
"b",
":",
"if",
"key",
"in",
"a",
":",
"if",
"isinstance",
"(",
"a",
"[",
"key",
"]",
",",
"di... | 40.962963 | 15.962963 |
def get_best(self):
"""Finds the optimal number of features
:return: optimal number of features and ranking
"""
svc = SVC(kernel="linear")
rfecv = RFECV(
estimator=svc,
step=1,
cv=StratifiedKFold(self.y_train, 2),
scoring="log_loss"... | [
"def",
"get_best",
"(",
"self",
")",
":",
"svc",
"=",
"SVC",
"(",
"kernel",
"=",
"\"linear\"",
")",
"rfecv",
"=",
"RFECV",
"(",
"estimator",
"=",
"svc",
",",
"step",
"=",
"1",
",",
"cv",
"=",
"StratifiedKFold",
"(",
"self",
".",
"y_train",
",",
"2"... | 31.769231 | 12.076923 |
def file_to_base64(path_or_obj, max_mb=None):
"""converts contents of a file to base64 encoding
:param str_or_object path_or_obj: fool pathname string for a file or a file like object that supports read
:param int max_mb: maximum number in MegaBytes to accept
:param float lon2: longitude of second plac... | [
"def",
"file_to_base64",
"(",
"path_or_obj",
",",
"max_mb",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"path_or_obj",
",",
"'read'",
")",
":",
"rt",
"=",
"read_file",
"(",
"path_or_obj",
")",
"else",
":",
"rt",
"=",
"path_or_obj",
".",
"read",
... | 43.736842 | 23.736842 |
def prepare(bedfile):
"""
Remove prepended tags in gene names.
"""
pf = bedfile.rsplit(".", 1)[0]
abedfile = pf + ".a.bed"
bbedfile = pf + ".b.bed"
fwa = open(abedfile, "w")
fwb = open(bbedfile, "w")
bed = Bed(bedfile)
seen = set()
for b in bed:
accns = b.accn.split(... | [
"def",
"prepare",
"(",
"bedfile",
")",
":",
"pf",
"=",
"bedfile",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"abedfile",
"=",
"pf",
"+",
"\".a.bed\"",
"bbedfile",
"=",
"pf",
"+",
"\".b.bed\"",
"fwa",
"=",
"open",
"(",
"abedfile",
",... | 25.787879 | 15.727273 |
def make_repr(*args, **kwargs):
"""Returns __repr__ method which returns ASCII
representaion of the object with given fields.
Without arguments, ``make_repr`` generates a method
which outputs all object's non-protected (non-undercored)
arguments which are not callables.
Accepts ``*args``, whic... | [
"def",
"make_repr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"method",
"(",
"self",
")",
":",
"cls_name",
"=",
"self",
".",
"__class__",
".",
"__name__",
"if",
"args",
":",
"field_names",
"=",
"args",
"else",
":",
"def",
"undercore... | 28.973684 | 20.697368 |
def ensure_annotations(f):
"""
Decorator to be used on functions with annotations. Runs type checks to enforce annotations. Raises
:class:`EnsureError` if any argument passed to *f* is not of the type specified by the annotation. Also raises
:class:`EnsureError` if the return value of *f* is not of the ... | [
"def",
"ensure_annotations",
"(",
"f",
")",
":",
"if",
"f",
".",
"__defaults__",
":",
"for",
"rpos",
",",
"value",
"in",
"enumerate",
"(",
"f",
".",
"__defaults__",
")",
":",
"pos",
"=",
"f",
".",
"__code__",
".",
"co_argcount",
"-",
"len",
"(",
"f",... | 35.510204 | 23.265306 |
def this_year(self):
""" Get AnnouncementRequests from this school year only. """
start_date, end_date = get_date_range_this_year()
return Announcement.objects.filter(added__gte=start_date, added__lte=end_date) | [
"def",
"this_year",
"(",
"self",
")",
":",
"start_date",
",",
"end_date",
"=",
"get_date_range_this_year",
"(",
")",
"return",
"Announcement",
".",
"objects",
".",
"filter",
"(",
"added__gte",
"=",
"start_date",
",",
"added__lte",
"=",
"end_date",
")"
] | 57.75 | 20.75 |
def func_span(func, tags=None, require_active_trace=False):
"""
Creates a new local span for execution of the given `func`.
The returned span is best used as a context manager, e.g.
.. code-block:: python
with func_span('my_function'):
return my_function(...)
At this time the ... | [
"def",
"func_span",
"(",
"func",
",",
"tags",
"=",
"None",
",",
"require_active_trace",
"=",
"False",
")",
":",
"current_span",
"=",
"get_current_span",
"(",
")",
"if",
"current_span",
"is",
"None",
"and",
"require_active_trace",
":",
"@",
"contextlib2",
".",
... | 36.970588 | 20.735294 |
def dict_matches_params_deep(params_dct, dct):
"""
Filters deeply by comparing dct to filter_dct's value at each depth. Whenever a mismatch occurs the whole
thing returns false
:param params_dct: dict matching any portion of dct. E.g. filter_dct = {foo: {bar: 1}} would allow
{foo: {bar: 1, car: 2}} ... | [
"def",
"dict_matches_params_deep",
"(",
"params_dct",
",",
"dct",
")",
":",
"def",
"recurse_if_param_exists",
"(",
"params",
",",
"key",
",",
"value",
")",
":",
"\"\"\"\n If a param[key] exists, recurse. Otherwise return True since there is no param to contest value\n ... | 40 | 23.178571 |
def make_sparse(arr, kind='block', fill_value=None, dtype=None, copy=False):
"""
Convert ndarray to sparse format
Parameters
----------
arr : ndarray
kind : {'block', 'integer'}
fill_value : NaN or another value
dtype : np.dtype, optional
copy : bool, default False
Returns
... | [
"def",
"make_sparse",
"(",
"arr",
",",
"kind",
"=",
"'block'",
",",
"fill_value",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"arr",
"=",
"_sanitize_values",
"(",
"arr",
")",
"if",
"arr",
".",
"ndim",
">",
"1",
":",... | 28.924528 | 20.169811 |
def get_color_func(self, word):
"""Returns a single_color_func associated with the word"""
try:
color_func = next(
color_func for (color_func, words) in self.color_func_to_words
if word in words)
except StopIteration:
color_func = self.defa... | [
"def",
"get_color_func",
"(",
"self",
",",
"word",
")",
":",
"try",
":",
"color_func",
"=",
"next",
"(",
"color_func",
"for",
"(",
"color_func",
",",
"words",
")",
"in",
"self",
".",
"color_func_to_words",
"if",
"word",
"in",
"words",
")",
"except",
"Sto... | 35.2 | 16.6 |
def color_normalize(src, mean, std=None):
"""Normalize src with mean and std.
Parameters
----------
src : NDArray
Input image
mean : NDArray
RGB mean to be subtracted
std : NDArray
RGB standard deviation to be divided
Returns
-------
NDArray
An `NDAr... | [
"def",
"color_normalize",
"(",
"src",
",",
"mean",
",",
"std",
"=",
"None",
")",
":",
"if",
"mean",
"is",
"not",
"None",
":",
"src",
"-=",
"mean",
"if",
"std",
"is",
"not",
"None",
":",
"src",
"/=",
"std",
"return",
"src"
] | 20.318182 | 19.772727 |
def _clean_tmp_dirs(self):
"""
Remove temporary dir associated with this backend instance.
:return: None
"""
def onerror(fnc, path, excinfo):
# we might not have rights to do this, the files could be owned by root
self.logger.info("we were not able to re... | [
"def",
"_clean_tmp_dirs",
"(",
"self",
")",
":",
"def",
"onerror",
"(",
"fnc",
",",
"path",
",",
"excinfo",
")",
":",
"# we might not have rights to do this, the files could be owned by root",
"self",
".",
"logger",
".",
"info",
"(",
"\"we were not able to remove tempor... | 32.933333 | 21.733333 |
def decode_payload(cls, request):
"""Decode task payload.
HugeTask controls its own payload entirely including urlencoding.
It doesn't depend on any particular web framework.
Args:
request: a webapp Request instance.
Returns:
A dict of str to str. The same as the params argument to __... | [
"def",
"decode_payload",
"(",
"cls",
",",
"request",
")",
":",
"# TODO(user): Pass mr_id into headers. Otherwise when payload decoding",
"# failed, we can't abort a mr.",
"if",
"request",
".",
"headers",
".",
"get",
"(",
"cls",
".",
"PAYLOAD_VERSION_HEADER",
")",
"!=",
"c... | 35.913043 | 21.391304 |
def _reset_state(self):
"""! @brief Clear all state variables. """
self._builders = {}
self._total_data_size = 0
self._progress_offset = 0
self._current_progress_fraction = 0 | [
"def",
"_reset_state",
"(",
"self",
")",
":",
"self",
".",
"_builders",
"=",
"{",
"}",
"self",
".",
"_total_data_size",
"=",
"0",
"self",
".",
"_progress_offset",
"=",
"0",
"self",
".",
"_current_progress_fraction",
"=",
"0"
] | 34.833333 | 7.833333 |
def zinb_ll(data, P, R, Z):
"""
Returns the zero-inflated negative binomial log-likelihood of the data.
"""
lls = nb_ll(data, P, R)
clusters = P.shape[1]
for c in range(clusters):
pass
return lls | [
"def",
"zinb_ll",
"(",
"data",
",",
"P",
",",
"R",
",",
"Z",
")",
":",
"lls",
"=",
"nb_ll",
"(",
"data",
",",
"P",
",",
"R",
")",
"clusters",
"=",
"P",
".",
"shape",
"[",
"1",
"]",
"for",
"c",
"in",
"range",
"(",
"clusters",
")",
":",
"pass... | 24.777778 | 15.666667 |
def _build_extra_predicate(self, extra_predicate):
""" This method is a good one to extend if you want to create a queue which always applies an extra predicate. """
if extra_predicate is None:
return ''
# if they don't have a supported format seq, wrap it for them
if not is... | [
"def",
"_build_extra_predicate",
"(",
"self",
",",
"extra_predicate",
")",
":",
"if",
"extra_predicate",
"is",
"None",
":",
"return",
"''",
"# if they don't have a supported format seq, wrap it for them",
"if",
"not",
"isinstance",
"(",
"extra_predicate",
"[",
"1",
"]",... | 45.75 | 22.916667 |
def _collect_dirty_tabs(self, skip=None, tab_range=None):
"""
Collects the list of dirty tabs
:param skip: Tab to skip (used for close_others).
"""
widgets = []
filenames = []
if tab_range is None:
tab_range = range(self.count())
for i in tab_... | [
"def",
"_collect_dirty_tabs",
"(",
"self",
",",
"skip",
"=",
"None",
",",
"tab_range",
"=",
"None",
")",
":",
"widgets",
"=",
"[",
"]",
"filenames",
"=",
"[",
"]",
"if",
"tab_range",
"is",
"None",
":",
"tab_range",
"=",
"range",
"(",
"self",
".",
"co... | 33.363636 | 12.363636 |
def book_hotel(intent_request):
"""
Performs dialog management and fulfillment for booking a hotel.
Beyond fulfillment, the implementation for this intent demonstrates the following:
1) Use of elicitSlot in slot validation and re-prompting
2) Use of sessionAttributes to pass information that can be... | [
"def",
"book_hotel",
"(",
"intent_request",
")",
":",
"location",
"=",
"try_ex",
"(",
"lambda",
":",
"intent_request",
"[",
"'currentIntent'",
"]",
"[",
"'slots'",
"]",
"[",
"'Location'",
"]",
")",
"checkin_date",
"=",
"try_ex",
"(",
"lambda",
":",
"intent_r... | 44.357143 | 28.7 |
def lharmonicmean (inlist):
"""
Calculates the harmonic mean of the values in the passed list.
That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list.
Usage: lharmonicmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + 1.0/item
return len(inlist) / sum | [
"def",
"lharmonicmean",
"(",
"inlist",
")",
":",
"sum",
"=",
"0",
"for",
"item",
"in",
"inlist",
":",
"sum",
"=",
"sum",
"+",
"1.0",
"/",
"item",
"return",
"len",
"(",
"inlist",
")",
"/",
"sum"
] | 25.636364 | 16.181818 |
def execute(self, name, command):
"""
execute the command on the named host
:param name: the name of the host in config
:param command: the command to be executed
:return:
"""
if name in ["localhost"]:
r = '\n'.join(Shell.sh("-c", command).split()[-1:... | [
"def",
"execute",
"(",
"self",
",",
"name",
",",
"command",
")",
":",
"if",
"name",
"in",
"[",
"\"localhost\"",
"]",
":",
"r",
"=",
"'\\n'",
".",
"join",
"(",
"Shell",
".",
"sh",
"(",
"\"-c\"",
",",
"command",
")",
".",
"split",
"(",
")",
"[",
... | 33.916667 | 13.416667 |
def delete(self):
"""Submits a deletion request for this `Resource` instance as
a ``DELETE`` request to its URL."""
response = self.http_request(self._url, 'DELETE')
if response.status != 204:
self.raise_http_error(response) | [
"def",
"delete",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"http_request",
"(",
"self",
".",
"_url",
",",
"'DELETE'",
")",
"if",
"response",
".",
"status",
"!=",
"204",
":",
"self",
".",
"raise_http_error",
"(",
"response",
")"
] | 43.833333 | 8.166667 |
def delete(self, template_id):
"""
Delete a specific template.
:param template_id: The unique id for the template.
:type template_id: :py:class:`str`
"""
self.template_id = template_id
return self._mc_client._delete(url=self._build_path(template_id)) | [
"def",
"delete",
"(",
"self",
",",
"template_id",
")",
":",
"self",
".",
"template_id",
"=",
"template_id",
"return",
"self",
".",
"_mc_client",
".",
"_delete",
"(",
"url",
"=",
"self",
".",
"_build_path",
"(",
"template_id",
")",
")"
] | 33.222222 | 12.333333 |
def channels_open(self, room_id, **kwargs):
"""Adds the channel back to the user’s list of channels."""
return self.__call_api_post('channels.open', roomId=room_id, kwargs=kwargs) | [
"def",
"channels_open",
"(",
"self",
",",
"room_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'channels.open'",
",",
"roomId",
"=",
"room_id",
",",
"kwargs",
"=",
"kwargs",
")"
] | 64.333333 | 15.333333 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'title') and self.title is not None:
_dict['title'] = self.title
if hasattr(self, 'hash') and self.hash is not None:
_dict['hash'] = self.hash
return _d... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'title'",
")",
"and",
"self",
".",
"title",
"is",
"not",
"None",
":",
"_dict",
"[",
"'title'",
"]",
"=",
"self",
".",
"title",
"if",
"hasattr",
... | 39.5 | 13.375 |
def get_macs(vm_):
'''
Return a list off MAC addresses from the named vm
CLI Example:
.. code-block:: bash
salt '*' virt.get_macs <vm name>
'''
macs = []
nics = get_nics(vm_)
if nics is None:
return None
for nic in nics:
macs.append(nic)
return macs | [
"def",
"get_macs",
"(",
"vm_",
")",
":",
"macs",
"=",
"[",
"]",
"nics",
"=",
"get_nics",
"(",
"vm_",
")",
"if",
"nics",
"is",
"None",
":",
"return",
"None",
"for",
"nic",
"in",
"nics",
":",
"macs",
".",
"append",
"(",
"nic",
")",
"return",
"macs"... | 16.666667 | 24.777778 |
def run_parallel(workflow, n_threads):
"""Run a workflow in parallel threads.
:param workflow: Workflow or PromisedObject to evaluate.
:param n_threads: number of threads to use (in addition to the scheduler).
:returns: evaluated workflow.
"""
scheduler = Scheduler()
threaded_worker = Queue... | [
"def",
"run_parallel",
"(",
"workflow",
",",
"n_threads",
")",
":",
"scheduler",
"=",
"Scheduler",
"(",
")",
"threaded_worker",
"=",
"Queue",
"(",
")",
">>",
"thread_pool",
"(",
"*",
"repeat",
"(",
"worker",
",",
"n_threads",
")",
")",
"return",
"scheduler... | 35.833333 | 16.25 |
def get_input(self, more=False):
"""Prompt for code input."""
received = None
try:
received = self.prompt.input(more)
except KeyboardInterrupt:
print()
printerr("KeyboardInterrupt")
except EOFError:
print()
self.exit_run... | [
"def",
"get_input",
"(",
"self",
",",
"more",
"=",
"False",
")",
":",
"received",
"=",
"None",
"try",
":",
"received",
"=",
"self",
".",
"prompt",
".",
"input",
"(",
"more",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
")",
"printerr",
"(",
... | 28.9375 | 12.5625 |
def _get_file_paths(self, tax_ids, file_type):
"""
Assemble file paths from tax ids
Args:
:param tax_ids (list) list of taxa
Returns:
:return file dict
"""
file_paths = dict()
if file_type not in self.files:
raise KeyError("file... | [
"def",
"_get_file_paths",
"(",
"self",
",",
"tax_ids",
",",
"file_type",
")",
":",
"file_paths",
"=",
"dict",
"(",
")",
"if",
"file_type",
"not",
"in",
"self",
".",
"files",
":",
"raise",
"KeyError",
"(",
"\"file type {} not configured\"",
".",
"format",
"("... | 36.85 | 13.35 |
def cal_k_vinet(p, k):
"""
calculate bulk modulus in GPa
:param p: pressure in GPa
:param k: [v0, k0, k0p]
:return: bulk modulus at high pressure in GPa
"""
v = cal_v_vinet(p, k)
return cal_k_vinet_from_v(v, k[0], k[1], k[2]) | [
"def",
"cal_k_vinet",
"(",
"p",
",",
"k",
")",
":",
"v",
"=",
"cal_v_vinet",
"(",
"p",
",",
"k",
")",
"return",
"cal_k_vinet_from_v",
"(",
"v",
",",
"k",
"[",
"0",
"]",
",",
"k",
"[",
"1",
"]",
",",
"k",
"[",
"2",
"]",
")"
] | 24.9 | 12.3 |
def has_overflow(self, params):
""" detect inf and nan """
is_not_finite = 0
for param in params:
if param.grad_req != 'null':
grad = param.list_grad()[0]
is_not_finite += mx.nd.contrib.isnan(grad).sum()
is_not_finite += mx.nd.contrib.i... | [
"def",
"has_overflow",
"(",
"self",
",",
"params",
")",
":",
"is_not_finite",
"=",
"0",
"for",
"param",
"in",
"params",
":",
"if",
"param",
".",
"grad_req",
"!=",
"'null'",
":",
"grad",
"=",
"param",
".",
"list_grad",
"(",
")",
"[",
"0",
"]",
"is_not... | 36 | 12.769231 |
def create_commit(self, message, tree, parents, author={}, committer={}):
"""Create a commit on this repository.
:param str message: (required), commit message
:param str tree: (required), SHA of the tree object this
commit points to
:param list parents: (required), SHAs of ... | [
"def",
"create_commit",
"(",
"self",
",",
"message",
",",
"tree",
",",
"parents",
",",
"author",
"=",
"{",
"}",
",",
"committer",
"=",
"{",
"}",
")",
":",
"json",
"=",
"None",
"if",
"message",
"and",
"tree",
"and",
"isinstance",
"(",
"parents",
",",
... | 53.037037 | 24.037037 |
def syllabify(self, word):
"""Splits input Latin word into a list of syllables, based on
the language syllables loaded for the Syllabifier instance"""
prefixes = self.language['single_syllable_prefixes']
prefixes.sort(key=len, reverse=True)
# Check if word is in exception dict... | [
"def",
"syllabify",
"(",
"self",
",",
"word",
")",
":",
"prefixes",
"=",
"self",
".",
"language",
"[",
"'single_syllable_prefixes'",
"]",
"prefixes",
".",
"sort",
"(",
"key",
"=",
"len",
",",
"reverse",
"=",
"True",
")",
"# Check if word is in exception dictio... | 50.678322 | 26.097902 |
def edmcompletion(A, reordered = True, **kwargs):
"""
Euclidean distance matrix completion. The routine takes an EDM-completable
cspmatrix :math:`A` and returns a dense EDM :math:`X`
that satisfies
.. math::
P( X ) = A
:param A: :py:class:`cspmatrix`
:param reo... | [
"def",
"edmcompletion",
"(",
"A",
",",
"reordered",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"A",
",",
"cspmatrix",
")",
"and",
"A",
".",
"is_factor",
"is",
"False",
",",
"\"A must be a cspmatrix\"",
"tol",
"=",
"kwarg... | 34.859155 | 22.943662 |
def rollback(self, transaction = None):
"""Roll back a transaction."""
if not self.in_transaction:
raise NotInTransaction
for collection, store in self.stores.items():
store.rollback()
indexes = self.indexes[collection]
indexes_to_rebuild = []
... | [
"def",
"rollback",
"(",
"self",
",",
"transaction",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"in_transaction",
":",
"raise",
"NotInTransaction",
"for",
"collection",
",",
"store",
"in",
"self",
".",
"stores",
".",
"items",
"(",
")",
":",
"store",... | 43.166667 | 10.388889 |
def cors_allow_any(request, response):
"""
Add headers to permit CORS requests from any origin, with or without credentials,
with any headers.
"""
origin = request.META.get('HTTP_ORIGIN')
if not origin:
return response
# From the CORS spec: The string "*" cannot be used for a resour... | [
"def",
"cors_allow_any",
"(",
"request",
",",
"response",
")",
":",
"origin",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_ORIGIN'",
")",
"if",
"not",
"origin",
":",
"return",
"response",
"# From the CORS spec: The string \"*\" cannot be used for a resource th... | 38.380952 | 21.142857 |
def get_Callable_args_res(clb):
"""Python version independent function to obtain the parameters
of a typing.Callable object. Returns as tuple: args, result.
Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
"""
try:
return clb.__args__, clb.__result__
except AttributeError:
# P... | [
"def",
"get_Callable_args_res",
"(",
"clb",
")",
":",
"try",
":",
"return",
"clb",
".",
"__args__",
",",
"clb",
".",
"__result__",
"except",
"AttributeError",
":",
"# Python 3.6",
"return",
"clb",
".",
"__args__",
"[",
":",
"-",
"1",
"]",
",",
"clb",
"."... | 37.1 | 12.7 |
def load_model(itos_filename, classifier_filename, num_classes):
"""Load the classifier and int to string mapping
Args:
itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
classifier_filename (str): The filename of the trained classifier
Returns:
... | [
"def",
"load_model",
"(",
"itos_filename",
",",
"classifier_filename",
",",
"num_classes",
")",
":",
"# load the int to string mapping file",
"itos",
"=",
"pickle",
".",
"load",
"(",
"Path",
"(",
"itos_filename",
")",
".",
"open",
"(",
"'rb'",
")",
")",
"# turn ... | 38.939394 | 28.484848 |
def with_wrapper(self, wrapper=None, name=None):
""" Copy this BarSet, and return a new BarSet with the specified
name and wrapper.
If no name is given, `{self.name}_custom_wrapper` is used.
If no wrapper is given, the new BarSet will have no wrapper.
"""
name... | [
"def",
"with_wrapper",
"(",
"self",
",",
"wrapper",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"'{}_custom_wrapper'",
".",
"format",
"(",
"self",
".",
"name",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
... | 53.75 | 16.125 |
def resolve_inputs(self, layers):
'''Resolve the names of inputs for this layer into shape tuples.
Parameters
----------
layers : list of :class:`Layer`
A list of the layers that are available for resolving inputs.
Raises
------
theanets.util.Configu... | [
"def",
"resolve_inputs",
"(",
"self",
",",
"layers",
")",
":",
"resolved",
"=",
"{",
"}",
"for",
"name",
",",
"shape",
"in",
"self",
".",
"_input_shapes",
".",
"items",
"(",
")",
":",
"if",
"shape",
"is",
"None",
":",
"name",
",",
"shape",
"=",
"se... | 32.368421 | 18.894737 |
def p_UnionMemberType_anyType(p):
"""UnionMemberType : any "[" "]" TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.Array(t=model.SimpleType(
type=model.SimpleType.ANY)), p[4]) | [
"def",
"p_UnionMemberType_anyType",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"helper",
".",
"unwrapTypeSuffix",
"(",
"model",
".",
"Array",
"(",
"t",
"=",
"model",
".",
"SimpleType",
"(",
"type",
"=",
"model",
".",
"SimpleType",
".",
"ANY",
")",
... | 45.75 | 8.25 |
def compatcallback(f):
""" Compatibility callback decorator for older click version.
Click 1.0 does not have a version string stored, so we need to
use getattr here to be safe.
"""
if getattr(click, '__version__', '0.0') >= '2.0':
return f
return update_wrapper(lambda ctx, value: f(ctx,... | [
"def",
"compatcallback",
"(",
"f",
")",
":",
"if",
"getattr",
"(",
"click",
",",
"'__version__'",
",",
"'0.0'",
")",
">=",
"'2.0'",
":",
"return",
"f",
"return",
"update_wrapper",
"(",
"lambda",
"ctx",
",",
"value",
":",
"f",
"(",
"ctx",
",",
"None",
... | 36.555556 | 17.444444 |
def run(self):
"""
Performs the actual FEFF run
Returns:
(subprocess.Popen) Used for monitoring.
"""
with open(self.output_file, "w") as f_std, \
open(self.stderr_file, "w", buffering=1) as f_err:
# Use line buffering for stderr
... | [
"def",
"run",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"output_file",
",",
"\"w\"",
")",
"as",
"f_std",
",",
"open",
"(",
"self",
".",
"stderr_file",
",",
"\"w\"",
",",
"buffering",
"=",
"1",
")",
"as",
"f_err",
":",
"# Use line buffe... | 32.214286 | 18.928571 |
def NgramScorer(frequency_map):
"""Compute the score of a text by using the frequencies of ngrams.
Example:
>>> fitness = NgramScorer(english.unigrams)
>>> fitness("ABC")
-4.3622319742618245
Args:
frequency_map (dict): ngram to frequency mapping
"""
# Calculate the ... | [
"def",
"NgramScorer",
"(",
"frequency_map",
")",
":",
"# Calculate the log probability",
"length",
"=",
"len",
"(",
"next",
"(",
"iter",
"(",
"frequency_map",
")",
")",
")",
"# TODO: 0.01 is a magic number. Needs to be better than that.",
"floor",
"=",
"math",
".",
"l... | 37.36 | 22.76 |
def from_spec(spec):
"""
Creates an exploration object from a specification dict.
"""
exploration = util.get_object(
obj=spec,
predefined_objects=tensorforce.core.explorations.explorations
)
assert isinstance(exploration, Exploration)
retur... | [
"def",
"from_spec",
"(",
"spec",
")",
":",
"exploration",
"=",
"util",
".",
"get_object",
"(",
"obj",
"=",
"spec",
",",
"predefined_objects",
"=",
"tensorforce",
".",
"core",
".",
"explorations",
".",
"explorations",
")",
"assert",
"isinstance",
"(",
"explor... | 32.4 | 15.4 |
def view_structure(self, only_chains=None, opacity=1.0, recolor=False, gui=False):
"""Use NGLviewer to display a structure in a Jupyter notebook
Args:
only_chains (str, list): Chain ID or IDs to display
opacity (float): Opacity of the structure
recolor (bool): If str... | [
"def",
"view_structure",
"(",
"self",
",",
"only_chains",
"=",
"None",
",",
"opacity",
"=",
"1.0",
",",
"recolor",
"=",
"False",
",",
"gui",
"=",
"False",
")",
":",
"# TODO: show_structure_file does not work for MMTF files - need to check for that and load accordingly",
... | 39.659574 | 26.382979 |
def dskgtl(keywrd):
"""
Retrieve the value of a specified DSK tolerance or margin parameter.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskgtl_c.html
:param keywrd: Code specifying parameter to retrieve.
:type keywrd: int
:return: Value of parameter.
:rtype: float
... | [
"def",
"dskgtl",
"(",
"keywrd",
")",
":",
"keywrd",
"=",
"ctypes",
".",
"c_int",
"(",
"keywrd",
")",
"dpval",
"=",
"ctypes",
".",
"c_double",
"(",
"0",
")",
"libspice",
".",
"dskgtl_c",
"(",
"keywrd",
",",
"ctypes",
".",
"byref",
"(",
"dpval",
")",
... | 30.066667 | 18.066667 |
def list_subscriptions(self, service):
"""Asks for a list of all subscribed accounts and devices, along with their statuses."""
data = {
'service': service,
}
return self._perform_post_request(self.list_subscriptions_endpoint, data, self.token_header) | [
"def",
"list_subscriptions",
"(",
"self",
",",
"service",
")",
":",
"data",
"=",
"{",
"'service'",
":",
"service",
",",
"}",
"return",
"self",
".",
"_perform_post_request",
"(",
"self",
".",
"list_subscriptions_endpoint",
",",
"data",
",",
"self",
".",
"toke... | 48.333333 | 21 |
def _construct_version(self, function, intrinsics_resolver):
"""Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes.
Old versions will not be deleted without a direct reference from the CloudFormation template.
:param model.lambda_.LambdaFunctio... | [
"def",
"_construct_version",
"(",
"self",
",",
"function",
",",
"intrinsics_resolver",
")",
":",
"code_dict",
"=",
"function",
".",
"Code",
"if",
"not",
"code_dict",
":",
"raise",
"ValueError",
"(",
"\"Lambda function code must be a valid non-empty dictionary\"",
")",
... | 64.45098 | 40.686275 |
async def set_state(self, parameter):
"""Set switch to desired state."""
command_send = CommandSend(pyvlx=self.pyvlx, node_id=self.node_id, parameter=parameter)
await command_send.do_api_call()
if not command_send.success:
raise PyVLXException("Unable to send command")
... | [
"async",
"def",
"set_state",
"(",
"self",
",",
"parameter",
")",
":",
"command_send",
"=",
"CommandSend",
"(",
"pyvlx",
"=",
"self",
".",
"pyvlx",
",",
"node_id",
"=",
"self",
".",
"node_id",
",",
"parameter",
"=",
"parameter",
")",
"await",
"command_send"... | 46.875 | 11.625 |
def get_users(self, search=None, page=1, per_page=20, **kwargs):
"""
Returns a list of users from the Gitlab server
:param search: Optional search query
:param page: Page number (default: 1)
:param per_page: Number of items to list per page (default: 20, max: 100)
:retur... | [
"def",
"get_users",
"(",
"self",
",",
"search",
"=",
"None",
",",
"page",
"=",
"1",
",",
"per_page",
"=",
"20",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"search",
":",
"return",
"self",
".",
"get",
"(",
"'/users'",
",",
"page",
"=",
"page",
",",
... | 42.928571 | 21.642857 |
def delete_milestone_request(session, milestone_request_id):
"""
Delete a milestone request
"""
params_data = {
'action': 'delete',
}
# POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=
# delete
endpoint = 'milestone_requests/{}'.format(milestone_request_i... | [
"def",
"delete_milestone_request",
"(",
"session",
",",
"milestone_request_id",
")",
":",
"params_data",
"=",
"{",
"'action'",
":",
"'delete'",
",",
"}",
"# POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=",
"# delete",
"endpoint",
"=",
"'milestone_re... | 35.894737 | 16 |
def dms_to_degrees(v):
"""Convert degree/minute/second to decimal degrees."""
d = float(v[0][0]) / float(v[0][1])
m = float(v[1][0]) / float(v[1][1])
s = float(v[2][0]) / float(v[2][1])
return d + (m / 60.0) + (s / 3600.0) | [
"def",
"dms_to_degrees",
"(",
"v",
")",
":",
"d",
"=",
"float",
"(",
"v",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"/",
"float",
"(",
"v",
"[",
"0",
"]",
"[",
"1",
"]",
")",
"m",
"=",
"float",
"(",
"v",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"/... | 33.857143 | 8.714286 |
def lastElementChild(self):
"""Finds the last child node of that element which is a
Element node Note the handling of entities references is
different than in the W3C DOM element traversal spec since
we don't have back reference from entities content to
entities referenc... | [
"def",
"lastElementChild",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlLastElementChild",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"return",
"None",
"__tmp",
"=",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__t... | 46.2 | 13.6 |
def get_client(provider, token=''):
"Return the API client for the given provider."
cls = OAuth2Client
if provider.request_token_url:
cls = OAuthClient
return cls(provider, token) | [
"def",
"get_client",
"(",
"provider",
",",
"token",
"=",
"''",
")",
":",
"cls",
"=",
"OAuth2Client",
"if",
"provider",
".",
"request_token_url",
":",
"cls",
"=",
"OAuthClient",
"return",
"cls",
"(",
"provider",
",",
"token",
")"
] | 33 | 10.666667 |
def _build_type(type_, value, property_path=None):
""" Builds the schema definition based on the given type for the given value.
:param type_: The type of the value
:param value: The value to build the schema definition for
:param List[str] property_path: The property path of the current type,
... | [
"def",
"_build_type",
"(",
"type_",
",",
"value",
",",
"property_path",
"=",
"None",
")",
":",
"if",
"not",
"property_path",
":",
"property_path",
"=",
"[",
"]",
"for",
"(",
"type_check",
",",
"builder",
")",
"in",
"(",
"(",
"is_enum_type",
",",
"_build_... | 36.419355 | 16.483871 |
def is_article(self, response, url):
"""
Tests if the given response is an article by calling and checking
the heuristics set in config.cfg and sitelist.json
:param obj response: The response of the site.
:param str url: The base_url (needed to get the site-specific config
... | [
"def",
"is_article",
"(",
"self",
",",
"response",
",",
"url",
")",
":",
"site",
"=",
"self",
".",
"__sites_object",
"[",
"url",
"]",
"heuristics",
"=",
"self",
".",
"__get_enabled_heuristics",
"(",
"url",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"... | 42.09375 | 20.40625 |
def ethernet_adapters(self, ethernet_adapters):
"""
Sets the number of Ethernet adapters for this IOU VM.
:param ethernet_adapters: number of adapters
"""
self._ethernet_adapters.clear()
for _ in range(0, ethernet_adapters):
self._ethernet_adapters.append(Et... | [
"def",
"ethernet_adapters",
"(",
"self",
",",
"ethernet_adapters",
")",
":",
"self",
".",
"_ethernet_adapters",
".",
"clear",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"ethernet_adapters",
")",
":",
"self",
".",
"_ethernet_adapters",
".",
"append",... | 48.0625 | 31.8125 |
def _normalize_stack(graphobjs):
"""Convert runs of qQ's in the stack into single graphobjs"""
for operands, operator in graphobjs:
operator = str(operator)
if re.match(r'Q*q+$', operator): # Zero or more Q, one or more q
for char in operator: # Split into individual
... | [
"def",
"_normalize_stack",
"(",
"graphobjs",
")",
":",
"for",
"operands",
",",
"operator",
"in",
"graphobjs",
":",
"operator",
"=",
"str",
"(",
"operator",
")",
"if",
"re",
".",
"match",
"(",
"r'Q*q+$'",
",",
"operator",
")",
":",
"# Zero or more Q, one or m... | 44.777778 | 12 |
def get_id2config_mapping(self):
"""
returns a dict where the keys are the config_ids and the values
are the actual configurations
"""
new_dict = {}
for k, v in self.data.items():
new_dict[k] = {}
new_dict[k]['config'] = copy.deepcopy(v.config)
try:
new_dict[k]['config_info'] = copy.deepcopy(v.... | [
"def",
"get_id2config_mapping",
"(",
"self",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"new_dict",
"[",
"k",
"]",
"=",
"{",
"}",
"new_dict",
"[",
"k",
"]",
"[",
"'config'",
... | 25.571429 | 17.428571 |
def irafcrop(self, irafcropstring):
"""
This is a wrapper around crop(), similar to iraf imcopy,
using iraf conventions (100:199 will be 100 pixels, not 99).
"""
irafcropstring = irafcropstring[1:-1] # removing the [ ]
ranges = irafcropstring.split(",")
xr = range... | [
"def",
"irafcrop",
"(",
"self",
",",
"irafcropstring",
")",
":",
"irafcropstring",
"=",
"irafcropstring",
"[",
"1",
":",
"-",
"1",
"]",
"# removing the [ ]",
"ranges",
"=",
"irafcropstring",
".",
"split",
"(",
"\",\"",
")",
"xr",
"=",
"ranges",
"[",
"0",
... | 36.142857 | 11 |
def autochisq_from_precomputed(sn, corr_sn, hautocorr, indices,
stride=1, num_points=None, oneside=None,
twophase=True, maxvalued=False):
"""
Compute correlation (two sided) between template and data
and compares with autocorrelation of the template: C(t) = IFFT... | [
"def",
"autochisq_from_precomputed",
"(",
"sn",
",",
"corr_sn",
",",
"hautocorr",
",",
"indices",
",",
"stride",
"=",
"1",
",",
"num_points",
"=",
"None",
",",
"oneside",
"=",
"None",
",",
"twophase",
"=",
"True",
",",
"maxvalued",
"=",
"False",
")",
":"... | 38.714286 | 19.339286 |
def win_encode(s):
"""Encode unicodes for process arguments on Windows."""
if isinstance(s, unicode):
return s.encode(locale.getpreferredencoding(False))
elif isinstance(s, bytes):
return s
elif s is not None:
raise TypeError('Expected bytes or text, but got %r' % (s,)) | [
"def",
"win_encode",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"return",
"s",
".",
"encode",
"(",
"locale",
".",
"getpreferredencoding",
"(",
"False",
")",
")",
"elif",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",... | 37.875 | 16.25 |
def from_detections_assignment(detections_1, detections_2, assignments):
"""
Creates traces out of given assignment and cell data.
"""
traces = []
for d1n, d2n in six.iteritems(assignments):
# check if the match is between existing cells
if d1n < len(dete... | [
"def",
"from_detections_assignment",
"(",
"detections_1",
",",
"detections_2",
",",
"assignments",
")",
":",
"traces",
"=",
"[",
"]",
"for",
"d1n",
",",
"d2n",
"in",
"six",
".",
"iteritems",
"(",
"assignments",
")",
":",
"# check if the match is between existing c... | 37.083333 | 21.916667 |
def require_email_confirmation(self):
""" Mark email as unconfirmed"""
self.email_confirmed = False
self.email_link = self.generate_hash(50)
now = datetime.datetime.utcnow()
self.email_link_expires = now + datetime.timedelta(hours=24) | [
"def",
"require_email_confirmation",
"(",
"self",
")",
":",
"self",
".",
"email_confirmed",
"=",
"False",
"self",
".",
"email_link",
"=",
"self",
".",
"generate_hash",
"(",
"50",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"self"... | 45 | 7.166667 |
def purge_duplicates(list_in):
"""Remove duplicates from list while preserving order.
Parameters
----------
list_in: Iterable
Returns
-------
list
List of first occurences in order
"""
_list = []
for item in list_in:
if item not in _list:
_list.appen... | [
"def",
"purge_duplicates",
"(",
"list_in",
")",
":",
"_list",
"=",
"[",
"]",
"for",
"item",
"in",
"list_in",
":",
"if",
"item",
"not",
"in",
"_list",
":",
"_list",
".",
"append",
"(",
"item",
")",
"return",
"_list"
] | 19.294118 | 19.941176 |
def _n_parameters(self):
"""Return the number of free parameters in the model."""
ndim = self.means_.shape[1]
if self.covariance_type == 'full':
cov_params = self.n_components * ndim * (ndim + 1) / 2.
elif self.covariance_type == 'diag':
cov_params = self.n_compon... | [
"def",
"_n_parameters",
"(",
"self",
")",
":",
"ndim",
"=",
"self",
".",
"means_",
".",
"shape",
"[",
"1",
"]",
"if",
"self",
".",
"covariance_type",
"==",
"'full'",
":",
"cov_params",
"=",
"self",
".",
"n_components",
"*",
"ndim",
"*",
"(",
"ndim",
... | 47.769231 | 9.153846 |
def notification_factory(code, subcode):
"""Returns a `Notification` message corresponding to given codes.
Parameters:
- `code`: (int) BGP error code
- `subcode`: (int) BGP error sub-code
"""
notification = BGPNotification(code, subcode)
if not notification.reason:
raise ValueError(... | [
"def",
"notification_factory",
"(",
"code",
",",
"subcode",
")",
":",
"notification",
"=",
"BGPNotification",
"(",
"code",
",",
"subcode",
")",
"if",
"not",
"notification",
".",
"reason",
":",
"raise",
"ValueError",
"(",
"'Invalid code/sub-code.'",
")",
"return"... | 29.916667 | 13.083333 |
def keyPressEvent(self, event):
"""
Qt override.
"""
if event.key() in [Qt.Key_Enter, Qt.Key_Return]:
QTableWidget.keyPressEvent(self, event)
# To avoid having to enter one final tab
self.setDisabled(True)
self.setDisabled(False)
... | [
"def",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"key",
"(",
")",
"in",
"[",
"Qt",
".",
"Key_Enter",
",",
"Qt",
".",
"Key_Return",
"]",
":",
"QTableWidget",
".",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
"# To a... | 35.083333 | 10.083333 |
def read_array(path, mmap_mode=None):
"""Read a .npy array."""
file_ext = op.splitext(path)[1]
if file_ext == '.npy':
return np.load(path, mmap_mode=mmap_mode)
raise NotImplementedError("The file extension `{}` ".format(file_ext) +
"is not currently supported.") | [
"def",
"read_array",
"(",
"path",
",",
"mmap_mode",
"=",
"None",
")",
":",
"file_ext",
"=",
"op",
".",
"splitext",
"(",
"path",
")",
"[",
"1",
"]",
"if",
"file_ext",
"==",
"'.npy'",
":",
"return",
"np",
".",
"load",
"(",
"path",
",",
"mmap_mode",
"... | 44.285714 | 12.285714 |
def t2T(self, seg, t):
"""returns the path parameter T which corresponds to the segment
parameter t. In other words, for any Path object, path, and any
segment in path, seg, T(t) = path.t2T(seg, t) is the unique
reparameterization such that path.point(T(t)) == seg.point(t) for all
... | [
"def",
"t2T",
"(",
"self",
",",
"seg",
",",
"t",
")",
":",
"self",
".",
"_calc_lengths",
"(",
")",
"# Accept an index or a segment for seg",
"if",
"isinstance",
"(",
"seg",
",",
"int",
")",
":",
"seg_idx",
"=",
"seg",
"else",
":",
"try",
":",
"seg_idx",
... | 40.608696 | 18.478261 |
def get_orthology_matrix(self, pid_cutoff=None, bitscore_cutoff=None, evalue_cutoff=None, filter_condition='OR',
remove_strains_with_no_orthology=True,
remove_strains_with_no_differences=False,
remove_genes_not_in_base_model=True):
... | [
"def",
"get_orthology_matrix",
"(",
"self",
",",
"pid_cutoff",
"=",
"None",
",",
"bitscore_cutoff",
"=",
"None",
",",
"evalue_cutoff",
"=",
"None",
",",
"filter_condition",
"=",
"'OR'",
",",
"remove_strains_with_no_orthology",
"=",
"True",
",",
"remove_strains_with_... | 71.313433 | 47.149254 |
def password_length_needed(entropybits: Union[int, float], chars: str) -> int:
"""Calculate the length of a password for a given entropy and chars."""
if not isinstance(entropybits, (int, float)):
raise TypeError('entropybits can only be int or float')
if entropybits < 0:
raise ValueError('e... | [
"def",
"password_length_needed",
"(",
"entropybits",
":",
"Union",
"[",
"int",
",",
"float",
"]",
",",
"chars",
":",
"str",
")",
"->",
"int",
":",
"if",
"not",
"isinstance",
"(",
"entropybits",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"raise",
"... | 44.928571 | 14.714286 |
def enable_gui(gui=None, app=None):
"""Switch amongst GUI input hooks by name.
"""
# Deferred import
from pydev_ipython.inputhook import enable_gui as real_enable_gui
try:
return real_enable_gui(gui, app)
except ValueError as e:
raise UsageError("%... | [
"def",
"enable_gui",
"(",
"gui",
"=",
"None",
",",
"app",
"=",
"None",
")",
":",
"# Deferred import",
"from",
"pydev_ipython",
".",
"inputhook",
"import",
"enable_gui",
"as",
"real_enable_gui",
"try",
":",
"return",
"real_enable_gui",
"(",
"gui",
",",
"app",
... | 35.444444 | 10.666667 |
def update(self, *args, **kwargs):
"""Update ConfigMap from mapping/iterable.
If the key exists the entry is updated else it is added.
Args:
*args: variable length argument list. A valid argument is a two item
tuple/list. The first item is the key and the second i... | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
",",
"v",
"in",
"args",
":",
"self",
"[",
"k",
"]",
"=",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"self",
"[",
"... | 36.857143 | 22.071429 |
def add_pooling_with_padding_types(builder, name, height, width, stride_height, stride_width,
layer_type, padding_type, input_name, output_name,
padding_top = 0, padding_bottom = 0, padding_left = 0, padding_right = 0,
same_padding_asymmetry_mode = 'BOTTOM_RIGHT_HEAVY',
exclude_pad_a... | [
"def",
"add_pooling_with_padding_types",
"(",
"builder",
",",
"name",
",",
"height",
",",
"width",
",",
"stride_height",
",",
"stride_width",
",",
"layer_type",
",",
"padding_type",
",",
"input_name",
",",
"output_name",
",",
"padding_top",
"=",
"0",
",",
"paddi... | 46.142857 | 27.693878 |
def spkssb(targ, et, ref):
"""
Return the state (position and velocity) of a target body
relative to the solar system barycenter.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkssb_c.html
:param targ: Target body.
:type targ: int
:param et: Target epoch.
:type et: float
... | [
"def",
"spkssb",
"(",
"targ",
",",
"et",
",",
"ref",
")",
":",
"targ",
"=",
"ctypes",
".",
"c_int",
"(",
"targ",
")",
"et",
"=",
"ctypes",
".",
"c_double",
"(",
"et",
")",
"ref",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ref",
")",
"starg",
"=",... | 29.545455 | 13 |
def _run_cheroot(app, config, mode):
"""Run WsgiDAV using cheroot.server if Cheroot is installed."""
assert mode == "cheroot"
try:
from cheroot import server, wsgi
# from cheroot.ssl.builtin import BuiltinSSLAdapter
# import cheroot.ssl.pyopenssl
except ImportError:
... | [
"def",
"_run_cheroot",
"(",
"app",
",",
"config",
",",
"mode",
")",
":",
"assert",
"mode",
"==",
"\"cheroot\"",
"try",
":",
"from",
"cheroot",
"import",
"server",
",",
"wsgi",
"# from cheroot.ssl.builtin import BuiltinSSLAdapter",
"# import cheroot.ssl.p... | 33.725 | 21.6375 |
def get_built_image_info(self):
"""
query docker about built image
:return dict
"""
logger.info("getting information about built image '%s'", self.image)
image_info = self.tasker.get_image_info_by_image_name(self.image)
items_count = len(image_info)
if it... | [
"def",
"get_built_image_info",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"getting information about built image '%s'\"",
",",
"self",
".",
"image",
")",
"image_info",
"=",
"self",
".",
"tasker",
".",
"get_image_info_by_image_name",
"(",
"self",
".",
"im... | 44.555556 | 22.333333 |
def jackknife_indexes(data):
"""
Given data points data, where axis 0 is considered to delineate points, return
a list of arrays where each array is a set of jackknife indexes.
For a given set of data Y, the jackknife sample J[i] is defined as the data set
Y with the ith data point deleted.
"""
base = np.a... | [
"def",
"jackknife_indexes",
"(",
"data",
")",
":",
"base",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"len",
"(",
"data",
")",
")",
"return",
"(",
"np",
".",
"delete",
"(",
"base",
",",
"i",
")",
"for",
"i",
"in",
"base",
")"
] | 37.4 | 17 |
def PathCollection(mode="agg", *args, **kwargs):
"""
mode: string
- "raw" (speed: fastest, size: small, output: ugly, no dash,
no thickness)
- "agg" (speed: medium, size: medium output: nice, some flaws, no dash)
- "agg+" (speed: slow, size: big, output: perfect, no dash)... | [
"def",
"PathCollection",
"(",
"mode",
"=",
"\"agg\"",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mode",
"==",
"\"raw\"",
":",
"return",
"RawPathCollection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"elif",
"mode",
"==",
"\"agg... | 36.642857 | 16.928571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.