text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def calc_qdgz1_qdgz2_v1(self):
"""Seperate total direct flow into a small and a fast component.
Required control parameters:
|A1|
|A2|
Required flux sequence:
|QDGZ|
Calculated state sequences:
|QDGZ1|
|QDGZ2|
Basic equation:
:math:`QDGZ2 = \\frac{(QDGZ-A2)^2... | [
"def",
"calc_qdgz1_qdgz2_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"sta",
"=",
"self",
".",
"sequences",
".",
"states",
".... | 34.158879 | 18.672897 |
def get_env_macros(self, data):
"""Get all environment macros from data
For each object in data ::
* Fetch all macros in object.__class__.macros
* Fetch all customs macros in o.custom
:param data: data to get macro
:type data:
:return: dict with macro name as ke... | [
"def",
"get_env_macros",
"(",
"self",
",",
"data",
")",
":",
"env",
"=",
"{",
"}",
"for",
"obj",
"in",
"data",
":",
"cls",
"=",
"obj",
".",
"__class__",
"macros",
"=",
"cls",
".",
"macros",
"for",
"macro",
"in",
"macros",
":",
"if",
"macro",
".",
... | 35.121212 | 17.787879 |
def count_list(the_list):
"""
Generates a count of the number of times each unique item appears in a list
"""
count = the_list.count
result = [(item, count(item)) for item in set(the_list)]
result.sort()
return result | [
"def",
"count_list",
"(",
"the_list",
")",
":",
"count",
"=",
"the_list",
".",
"count",
"result",
"=",
"[",
"(",
"item",
",",
"count",
"(",
"item",
")",
")",
"for",
"item",
"in",
"set",
"(",
"the_list",
")",
"]",
"result",
".",
"sort",
"(",
")",
... | 29.75 | 16.75 |
def send(self, cmd):
""" Send a command to the bridge.
:param cmd: List of command bytes.
"""
self._bridge.send(cmd, wait=self.wait, reps=self.reps) | [
"def",
"send",
"(",
"self",
",",
"cmd",
")",
":",
"self",
".",
"_bridge",
".",
"send",
"(",
"cmd",
",",
"wait",
"=",
"self",
".",
"wait",
",",
"reps",
"=",
"self",
".",
"reps",
")"
] | 29.333333 | 14 |
def _copy_selection(self, *event):
"""Copies the current selection to the clipboard.
"""
if react_to_event(self.view, self.view.editor, event):
logger.debug("copy selection")
global_clipboard.copy(self.model.selection)
return True | [
"def",
"_copy_selection",
"(",
"self",
",",
"*",
"event",
")",
":",
"if",
"react_to_event",
"(",
"self",
".",
"view",
",",
"self",
".",
"view",
".",
"editor",
",",
"event",
")",
":",
"logger",
".",
"debug",
"(",
"\"copy selection\"",
")",
"global_clipboa... | 40.571429 | 8.857143 |
def when_children_replaced ( self, object, listener, remove ):
""" Sets up or removes a listener for children being replaced on a
specified object.
"""
object.on_trait_change( listener, "subgraphs", remove = remove,
dispatch = "fast_ui" )
objec... | [
"def",
"when_children_replaced",
"(",
"self",
",",
"object",
",",
"listener",
",",
"remove",
")",
":",
"object",
".",
"on_trait_change",
"(",
"listener",
",",
"\"subgraphs\"",
",",
"remove",
"=",
"remove",
",",
"dispatch",
"=",
"\"fast_ui\"",
")",
"object",
... | 55.583333 | 17 |
def show_periodical_tree_by_issn(issn):
"""
Render tree using ISSN.
"""
trees = tree_handler().trees_by_issn(issn)
if not trees:
abort(404, "Dokument s ISSN '%s' není dostupný." % issn)
return render_trees(
trees,
partial(web_tools.compose_tree_path, issn=True)
) | [
"def",
"show_periodical_tree_by_issn",
"(",
"issn",
")",
":",
"trees",
"=",
"tree_handler",
"(",
")",
".",
"trees_by_issn",
"(",
"issn",
")",
"if",
"not",
"trees",
":",
"abort",
"(",
"404",
",",
"\"Dokument s ISSN '%s' není dostupný.\" %",
"i",
"sn)",
"",
"ret... | 23.461538 | 18.384615 |
def _split(self, split_cls, editor_buffer=None):
"""
Split horizontal or vertical.
(when editor_buffer is None, show the current buffer there as well.)
"""
if editor_buffer is None:
editor_buffer = self.active_window.editor_buffer
active_split = self._get_act... | [
"def",
"_split",
"(",
"self",
",",
"split_cls",
",",
"editor_buffer",
"=",
"None",
")",
":",
"if",
"editor_buffer",
"is",
"None",
":",
"editor_buffer",
"=",
"self",
".",
"active_window",
".",
"editor_buffer",
"active_split",
"=",
"self",
".",
"_get_active_spli... | 36.238095 | 15.285714 |
def get_composition_search_session(self, proxy):
"""Gets a composition search session.
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionSearchSession) - a
CompositionSearchSession
raise: OperationFailed - unable to complete request
r... | [
"def",
"get_composition_search_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_composition_search",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"ImportError",
":... | 38.791667 | 15.958333 |
def setSample(self, sample):
"""Set sample points from the population. Should be a RDD"""
if not isinstance(sample, RDD):
raise TypeError("samples should be a RDD, received %s" % type(sample))
self._sample = sample | [
"def",
"setSample",
"(",
"self",
",",
"sample",
")",
":",
"if",
"not",
"isinstance",
"(",
"sample",
",",
"RDD",
")",
":",
"raise",
"TypeError",
"(",
"\"samples should be a RDD, received %s\"",
"%",
"type",
"(",
"sample",
")",
")",
"self",
".",
"_sample",
"... | 49.2 | 13.2 |
def novatel_diag_send(self, timeStatus, receiverStatus, solStatus, posType, velType, posSolAge, csFails, force_mavlink1=False):
'''
Transmits the diagnostics data from the Novatel OEMStar GPS
timeStatus : The Time Status. See Table 8 page 27 Novatel OEMSta... | [
"def",
"novatel_diag_send",
"(",
"self",
",",
"timeStatus",
",",
"receiverStatus",
",",
"solStatus",
",",
"posType",
",",
"velType",
",",
"posSolAge",
",",
"csFails",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
... | 77.714286 | 55.142857 |
def get_column_cursor_position(self, column):
"""
Return the relative cursor position for this column at the current
line. (It will stay between the boundaries of the line in case of a
larger number.)
"""
line_length = len(self.current_line)
current_column = self.... | [
"def",
"get_column_cursor_position",
"(",
"self",
",",
"column",
")",
":",
"line_length",
"=",
"len",
"(",
"self",
".",
"current_line",
")",
"current_column",
"=",
"self",
".",
"cursor_position_col",
"column",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"line_len... | 38.090909 | 14.090909 |
def contains_point( self, x, y ):
"""Is the point (x,y) on this curve?"""
return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0 | [
"def",
"contains_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"(",
"y",
"*",
"y",
"-",
"(",
"x",
"*",
"x",
"*",
"x",
"+",
"self",
".",
"__a",
"*",
"x",
"+",
"self",
".",
"__b",
")",
")",
"%",
"self",
".",
"__p",
"==",
"0"
... | 51.333333 | 15 |
def to_json(self):
"""Returns an input shard state for the remaining inputs.
Returns:
A JSON serializable version of the remaining input to read.
"""
params = dict(self.__params) # Shallow copy.
if self._PROTOTYPE_REQUEST_PARAM in params:
prototype_request = params[self._PROTOTYPE_REQ... | [
"def",
"to_json",
"(",
"self",
")",
":",
"params",
"=",
"dict",
"(",
"self",
".",
"__params",
")",
"# Shallow copy.",
"if",
"self",
".",
"_PROTOTYPE_REQUEST_PARAM",
"in",
"params",
":",
"prototype_request",
"=",
"params",
"[",
"self",
".",
"_PROTOTYPE_REQUEST_... | 37.571429 | 20.857143 |
def do_chan_log_all(self, line):
"""Set the channel log level to ALL_COMMS. Command syntax is: chan_log_all"""
self.application.channel.SetLogFilters(openpal.LogFilters(opendnp3.levels.ALL_COMMS))
print('Channel log filtering level is now: {0}'.format(opendnp3.levels.ALL_COMMS)) | [
"def",
"do_chan_log_all",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"application",
".",
"channel",
".",
"SetLogFilters",
"(",
"openpal",
".",
"LogFilters",
"(",
"opendnp3",
".",
"levels",
".",
"ALL_COMMS",
")",
")",
"print",
"(",
"'Channel log filteri... | 75 | 27.75 |
def evolved_transformer_big_tpu():
"""Big parameters for Evolved Transformer model on TPU."""
hparams = add_evolved_transformer_hparams(transformer.transformer_big_tpu())
hparams.learning_rate_constant = 1 / hparams.learning_rate_warmup_steps ** 0.5
hparams.learning_rate_schedule = (
"constant*single_cycl... | [
"def",
"evolved_transformer_big_tpu",
"(",
")",
":",
"hparams",
"=",
"add_evolved_transformer_hparams",
"(",
"transformer",
".",
"transformer_big_tpu",
"(",
")",
")",
"hparams",
".",
"learning_rate_constant",
"=",
"1",
"/",
"hparams",
".",
"learning_rate_warmup_steps",
... | 49.142857 | 16 |
def acquire(self, blocking=True,
delay=DELAY_INCREMENT, max_delay=MAX_DELAY,
timeout=None):
"""Attempt to acquire the given lock.
:param blocking: whether to wait forever to try to acquire the lock
:type blocking: bool
:param delay: when blocking this is ... | [
"def",
"acquire",
"(",
"self",
",",
"blocking",
"=",
"True",
",",
"delay",
"=",
"DELAY_INCREMENT",
",",
"max_delay",
"=",
"MAX_DELAY",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"delay",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Delay must be greater... | 42.928571 | 17.214286 |
def expire_at(self, key, _time):
""" Sets the expiration time of @key to @_time
@_time: absolute Unix timestamp (seconds since January 1, 1970)
"""
return self._client.expireat(self.get_key(key), round(_time)) | [
"def",
"expire_at",
"(",
"self",
",",
"key",
",",
"_time",
")",
":",
"return",
"self",
".",
"_client",
".",
"expireat",
"(",
"self",
".",
"get_key",
"(",
"key",
")",
",",
"round",
"(",
"_time",
")",
")"
] | 48.2 | 14.4 |
def merge_versioned(releases, schema=None, merge_rules=None):
"""
Merges a list of releases into a versionedRelease.
"""
if not merge_rules:
merge_rules = get_merge_rules(schema)
merged = OrderedDict()
for release in sorted(releases, key=lambda release: release['date']):
release... | [
"def",
"merge_versioned",
"(",
"releases",
",",
"schema",
"=",
"None",
",",
"merge_rules",
"=",
"None",
")",
":",
"if",
"not",
"merge_rules",
":",
"merge_rules",
"=",
"get_merge_rules",
"(",
"schema",
")",
"merged",
"=",
"OrderedDict",
"(",
")",
"for",
"re... | 30.564103 | 16.25641 |
def resize(self, size:Union[int,TensorImageSize])->'Image':
"Resize the image to `size`, size can be a single int."
assert self._flow is None
if isinstance(size, int): size=(self.shape[0], size, size)
if tuple(size)==tuple(self.shape): return self
self.flow = _affine_grid(size)
... | [
"def",
"resize",
"(",
"self",
",",
"size",
":",
"Union",
"[",
"int",
",",
"TensorImageSize",
"]",
")",
"->",
"'Image'",
":",
"assert",
"self",
".",
"_flow",
"is",
"None",
"if",
"isinstance",
"(",
"size",
",",
"int",
")",
":",
"size",
"=",
"(",
"sel... | 47.428571 | 16 |
def _check_roSet(orb,kwargs,funcName):
"""Function to check whether ro is set, because it's required for funcName"""
if not orb._roSet and kwargs.get('ro',None) is None:
warnings.warn("Method %s(.) requires ro to be given at Orbit initialization or at method evaluation; using default ro which is %f kpc"... | [
"def",
"_check_roSet",
"(",
"orb",
",",
"kwargs",
",",
"funcName",
")",
":",
"if",
"not",
"orb",
".",
"_roSet",
"and",
"kwargs",
".",
"get",
"(",
"'ro'",
",",
"None",
")",
"is",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"Method %s(.) requires ro to be... | 74.8 | 29.4 |
def wasb_read(self, remote_log_location, return_error=False):
"""
Returns the log found at the remote_log_location. Returns '' if no
logs are found or there is an error.
:param remote_log_location: the log's location in remote storage
:type remote_log_location: str (path)
... | [
"def",
"wasb_read",
"(",
"self",
",",
"remote_log_location",
",",
"return_error",
"=",
"False",
")",
":",
"try",
":",
"return",
"self",
".",
"hook",
".",
"read_file",
"(",
"self",
".",
"wasb_container",
",",
"remote_log_location",
")",
"except",
"AzureHttpErro... | 45.222222 | 17.444444 |
def cross_validation(learner, dataset, k=10, trials=1):
"""Do k-fold cross_validate and return their mean.
That is, keep out 1/k of the examples for testing on each of k runs.
Shuffle the examples first; If trials>1, average over several shuffles."""
if k is None:
k = len(dataset.examples)
i... | [
"def",
"cross_validation",
"(",
"learner",
",",
"dataset",
",",
"k",
"=",
"10",
",",
"trials",
"=",
"1",
")",
":",
"if",
"k",
"is",
"None",
":",
"k",
"=",
"len",
"(",
"dataset",
".",
"examples",
")",
"if",
"trials",
">",
"1",
":",
"return",
"mean... | 45.5 | 14.642857 |
async def uvarint(self, elem):
"""
Uvarint untouched
:param elem:
:return:
"""
if self.writing:
return await dump_varint(self.iobj, elem)
else:
return await load_varint(self.iobj) | [
"async",
"def",
"uvarint",
"(",
"self",
",",
"elem",
")",
":",
"if",
"self",
".",
"writing",
":",
"return",
"await",
"dump_varint",
"(",
"self",
".",
"iobj",
",",
"elem",
")",
"else",
":",
"return",
"await",
"load_varint",
"(",
"self",
".",
"iobj",
"... | 25 | 13.2 |
def build_upstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate:
"""Build an edge predicate that pass for relations for which one of the given nodes is the object."""
nodes = set(nodes)
def upstream_filter(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool:
"""Pass for r... | [
"def",
"build_upstream_edge_predicate",
"(",
"nodes",
":",
"Iterable",
"[",
"BaseEntity",
"]",
")",
"->",
"EdgePredicate",
":",
"nodes",
"=",
"set",
"(",
"nodes",
")",
"def",
"upstream_filter",
"(",
"graph",
":",
"BELGraph",
",",
"u",
":",
"BaseEntity",
",",... | 52.666667 | 25.888889 |
def spline_interpolate(x_axis, y_axis, x_new_axis):
"""Interpolate a y = f(x) function using Spline interpolation algorithm,
x_new_axis has to be in range of x_axis.
`Spline interpolation <https://en.wikipedia.org/wiki/Spline_interpolation>`_
is a popular interpolation method. Way more accurate than l... | [
"def",
"spline_interpolate",
"(",
"x_axis",
",",
"y_axis",
",",
"x_new_axis",
")",
":",
"f",
"=",
"interp1d",
"(",
"x_axis",
",",
"y_axis",
",",
"kind",
"=",
"\"cubic\"",
")",
"return",
"f",
"(",
"x_new_axis",
")"
] | 42.3 | 18.3 |
def main(argString=None):
"""The main function of this module.
:param argString: the options.
:type argString: list
These are the steps:
1. Runs a plate bias analysis using Plink
(:py:func:`executePlateBiasAnalysis`).
2. Extracts the list of significant markers after plate bias analys... | [
"def",
"main",
"(",
"argString",
"=",
"None",
")",
":",
"# Getting and checking the options",
"args",
"=",
"parseArgs",
"(",
"argString",
")",
"checkArgs",
"(",
"args",
")",
"logger",
".",
"info",
"(",
"\"Options used:\"",
")",
"for",
"key",
",",
"value",
"i... | 31 | 18.725 |
def rem_active_module(module):
'''Remove a module from CPENV_ACTIVE_MODULES environment variable'''
modules = set(get_active_modules())
modules.discard(module)
new_modules_path = os.pathsep.join([m.path for m in modules])
os.environ['CPENV_ACTIVE_MODULES'] = str(new_modules_path) | [
"def",
"rem_active_module",
"(",
"module",
")",
":",
"modules",
"=",
"set",
"(",
"get_active_modules",
"(",
")",
")",
"modules",
".",
"discard",
"(",
"module",
")",
"new_modules_path",
"=",
"os",
".",
"pathsep",
".",
"join",
"(",
"[",
"m",
".",
"path",
... | 42.142857 | 20.428571 |
def img_from_vgg(x):
'''Decondition an image from the VGG16 model.'''
x = x.transpose((1, 2, 0))
x[:, :, 0] += 103.939
x[:, :, 1] += 116.779
x[:, :, 2] += 123.68
x = x[:,:,::-1] # to RGB
return x | [
"def",
"img_from_vgg",
"(",
"x",
")",
":",
"x",
"=",
"x",
".",
"transpose",
"(",
"(",
"1",
",",
"2",
",",
"0",
")",
")",
"x",
"[",
":",
",",
":",
",",
"0",
"]",
"+=",
"103.939",
"x",
"[",
":",
",",
":",
",",
"1",
"]",
"+=",
"116.779",
"... | 27.125 | 15.875 |
def get_library_mapping(logger, prod_folder, token, host):
"""
returns a pair of library mappings, the first mapping library uri to a
library name for all libraries in the production folder, and the second
mapping library name to info for libraries in the production folder with
parsable versions
... | [
"def",
"get_library_mapping",
"(",
"logger",
",",
"prod_folder",
",",
"token",
",",
"host",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"host",
"+",
"'/api/1.2/libraries/list'",
",",
"auth",
"=",
"(",
"'token'",
",",
"token",
")",
",",
")",
"if",
... | 37.611111 | 16.833333 |
def render_impl(self, template, context, **opts):
"""
Render given template file and return the result.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param opts: Options such as:
- at_pa... | [
"def",
"render_impl",
"(",
"self",
",",
"template",
",",
"context",
",",
"*",
"*",
"opts",
")",
":",
"return",
"self",
".",
"_render",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"template",
")",
",",
"context",
",",
"True",
",",
"*",
"*",
"opts"... | 42.058824 | 17.941176 |
def web(port, debug=False, theme="modern", ssh_config=None):
"""Starts the web UI."""
from storm import web as _web
_web.run(port, debug, theme, ssh_config) | [
"def",
"web",
"(",
"port",
",",
"debug",
"=",
"False",
",",
"theme",
"=",
"\"modern\"",
",",
"ssh_config",
"=",
"None",
")",
":",
"from",
"storm",
"import",
"web",
"as",
"_web",
"_web",
".",
"run",
"(",
"port",
",",
"debug",
",",
"theme",
",",
"ssh... | 41.25 | 7.75 |
def apply_optimization(self, update_embedding_with, grad, **kwargs):
"""
Calculating (Obtaining) the learning rate (eta) and apply optimizations
on the embedding states by the specified method.
Parameters
----------
update_embedding_with : function
Function u... | [
"def",
"apply_optimization",
"(",
"self",
",",
"update_embedding_with",
",",
"grad",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"linesearch",
":",
"return",
"self",
".",
"_apply_linesearch_optimzation",
"(",
"update_embedding_with",
",",
"grad",
",",
... | 40.962963 | 23.037037 |
def write(url, content, **args):
"""Put an object into a ftp URL."""
relay = urlparse.urlparse(args.pop('relay', 'lmtp://localhot'))
try:
smtplib_SMTPS = functools.partial(smtplib.SMTP_SSL,
keyfile=args.pop('keyfile', None),
... | [
"def",
"write",
"(",
"url",
",",
"content",
",",
"*",
"*",
"args",
")",
":",
"relay",
"=",
"urlparse",
".",
"urlparse",
"(",
"args",
".",
"pop",
"(",
"'relay'",
",",
"'lmtp://localhot'",
")",
")",
"try",
":",
"smtplib_SMTPS",
"=",
"functools",
".",
"... | 44.288889 | 17.555556 |
def _get_item(self, question_id):
"""we need a middle-man method to convert the unique "assessment-session"
authority question_ids into "real" itemIds
BUT this also has to return the "magic" item, so we can't rely
on
question = self.get_question(question_id)
... | [
"def",
"_get_item",
"(",
"self",
",",
"question_id",
")",
":",
"question_map",
"=",
"self",
".",
"_get_question_map",
"(",
"question_id",
")",
"# Throws NotFound()",
"real_question_id",
"=",
"Id",
"(",
"question_map",
"[",
"'questionId'",
"]",
")",
"return",
"se... | 53.75 | 18.916667 |
def bulk_copy(self, ids):
"""Bulk copy a set of results.
:param ids: Int list of result IDs.
:return: :class:`results.Result <results.Result>` list
"""
schema = ResultSchema()
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | [
"def",
"bulk_copy",
"(",
"self",
",",
"ids",
")",
":",
"schema",
"=",
"ResultSchema",
"(",
")",
"return",
"self",
".",
"service",
".",
"bulk_copy",
"(",
"self",
".",
"base",
",",
"self",
".",
"RESOURCE",
",",
"ids",
",",
"schema",
")"
] | 35.75 | 15.625 |
def is_in_virtualenv():
"""
Check virtualenv membership dynamically
:return: True or false depending on whether we are in a regular virtualenv or not
:rtype: bool
"""
pipenv_active = os.environ.get("PIPENV_ACTIVE", False)
virtual_env = None
use_system = False
ignore_virtualenvs = b... | [
"def",
"is_in_virtualenv",
"(",
")",
":",
"pipenv_active",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PIPENV_ACTIVE\"",
",",
"False",
")",
"virtual_env",
"=",
"None",
"use_system",
"=",
"False",
"ignore_virtualenvs",
"=",
"bool",
"(",
"os",
".",
"environ... | 34.647059 | 21.941176 |
def GetStoredHostname(self):
"""Retrieves the stored hostname.
The hostname is determined based on the preprocessing information
that is stored inside the storage file.
Returns:
str: hostname.
"""
store_number = len(self._hostnames)
return self._hostnames.get(store_number, None) | [
"def",
"GetStoredHostname",
"(",
"self",
")",
":",
"store_number",
"=",
"len",
"(",
"self",
".",
"_hostnames",
")",
"return",
"self",
".",
"_hostnames",
".",
"get",
"(",
"store_number",
",",
"None",
")"
] | 27.727273 | 16.636364 |
def floor(x, context=None):
"""
Return the next lower or equal integer to x.
If the result is not exactly representable, it will be rounded according to
the current context.
Note that it's possible for the result to be larger than ``x``. See the
documentation of the :func:`ceil` function for ... | [
"def",
"floor",
"(",
"x",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_rint_floor",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
")",
",",
"context",
... | 27.545455 | 23.272727 |
def renames(from_path, to_path, user=None):
"""
Rename ``from_path`` to ``to_path``, creating parents as needed.
"""
to_dir = path.dirname(to_path)
if to_dir:
mkdir(to_dir, user=user)
rename(from_path, to_path, user=user) | [
"def",
"renames",
"(",
"from_path",
",",
"to_path",
",",
"user",
"=",
"None",
")",
":",
"to_dir",
"=",
"path",
".",
"dirname",
"(",
"to_path",
")",
"if",
"to_dir",
":",
"mkdir",
"(",
"to_dir",
",",
"user",
"=",
"user",
")",
"rename",
"(",
"from_path"... | 30.75 | 9 |
def to_bqm(self, model):
"""Given a pysmt model, return a bqm.
Adds the values of the biases as determined by the SMT solver to a bqm.
Args:
model: A pysmt model.
Returns:
:obj:`dimod.BinaryQuadraticModel`
"""
linear = ((v, float(model.get_py_v... | [
"def",
"to_bqm",
"(",
"self",
",",
"model",
")",
":",
"linear",
"=",
"(",
"(",
"v",
",",
"float",
"(",
"model",
".",
"get_py_value",
"(",
"bias",
")",
")",
")",
"for",
"v",
",",
"bias",
"in",
"self",
".",
"linear",
".",
"items",
"(",
")",
")",
... | 33.263158 | 23.368421 |
def fai_from_bam(ref_file, bam_file, out_file, data):
"""Create a fai index with only contigs in the input BAM file.
"""
contigs = set([x.contig for x in idxstats(bam_file, data)])
if not utils.file_uptodate(out_file, bam_file):
with open(ref.fasta_idx(ref_file, data["config"])) as in_handle:
... | [
"def",
"fai_from_bam",
"(",
"ref_file",
",",
"bam_file",
",",
"out_file",
",",
"data",
")",
":",
"contigs",
"=",
"set",
"(",
"[",
"x",
".",
"contig",
"for",
"x",
"in",
"idxstats",
"(",
"bam_file",
",",
"data",
")",
"]",
")",
"if",
"not",
"utils",
"... | 52.166667 | 16.25 |
def add_group(data_api, data_setters, group_index):
"""Add the data for a whole group.
:param data_api the data api from where to get the data
:param data_setters the class to push the data to
:param group_index the index for this group"""
group_type_ind = data_api.group_type_list[group_index]
a... | [
"def",
"add_group",
"(",
"data_api",
",",
"data_setters",
",",
"group_index",
")",
":",
"group_type_ind",
"=",
"data_api",
".",
"group_type_list",
"[",
"group_index",
"]",
"atom_count",
"=",
"len",
"(",
"data_api",
".",
"group_list",
"[",
"group_type_ind",
"]",
... | 60.192308 | 22.653846 |
def _split_cell(cell, module):
""" Split a hybrid %%sql cell into the Python code and the queries.
Populates a module with the queries.
Args:
cell: the contents of the %%sql cell.
module: the module that the contents will populate.
Returns:
The default (last) query for the module.
"""
line... | [
"def",
"_split_cell",
"(",
"cell",
",",
"module",
")",
":",
"lines",
"=",
"cell",
".",
"split",
"(",
"'\\n'",
")",
"code",
"=",
"None",
"last_def",
"=",
"-",
"1",
"name",
"=",
"None",
"define_wild_re",
"=",
"re",
".",
"compile",
"(",
"'^DEFINE\\s+.*$'"... | 39.809524 | 24.261905 |
def _redis_notifier(state):
"""Notify of configuration update through redis.
Arguments:
state (_WaffleState): Object that contains reference to app and its
configstore.
"""
tstamp = time.time()
state._tstamp = tstamp
conf = state.app.config
# Notify timestamp
r = re... | [
"def",
"_redis_notifier",
"(",
"state",
")",
":",
"tstamp",
"=",
"time",
".",
"time",
"(",
")",
"state",
".",
"_tstamp",
"=",
"tstamp",
"conf",
"=",
"state",
".",
"app",
".",
"config",
"# Notify timestamp",
"r",
"=",
"redis",
".",
"client",
".",
"Stric... | 28.642857 | 19 |
def main(command_line=True, **kwargs):
"""
NAME
jr6_jr6_magic.py
DESCRIPTION
converts JR6 .jr6 format files to magic_measurements format files
SYNTAX
jr6_jr6_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify i... | [
"def",
"main",
"(",
"command_line",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# initialize some stuff",
"noave",
"=",
"0",
"#volume=2.5**3 #default volume is a 2.5cm cube",
"volume",
"=",
"2.5",
"*",
"1e-6",
"#default volume is a 2.5 cm cube, translated to meters c... | 40.420863 | 20.471223 |
def sql_datetime_literal(dt: DateTimeLikeType,
subsecond: bool = False) -> str:
"""
Transforms a Python object that is of duck type ``datetime.datetime`` into
an ANSI SQL literal string, like ``'2000-12-31 23:59:59'``, or if
``subsecond=True``, into the (non-ANSI) format
``'... | [
"def",
"sql_datetime_literal",
"(",
"dt",
":",
"DateTimeLikeType",
",",
"subsecond",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"# ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt",
"# <timestamp string>",
"# ... the subsecond part is non-ANSI",
"fmt",... | 45.692308 | 15.230769 |
def _compute_edges(self):
"""Compute the edges of the current surface.
Returns:
Tuple[~curve.Curve, ~curve.Curve, ~curve.Curve]: The edges of
the surface.
"""
nodes1, nodes2, nodes3 = _surface_helpers.compute_edge_nodes(
self._nodes, self._degree
... | [
"def",
"_compute_edges",
"(",
"self",
")",
":",
"nodes1",
",",
"nodes2",
",",
"nodes3",
"=",
"_surface_helpers",
".",
"compute_edge_nodes",
"(",
"self",
".",
"_nodes",
",",
"self",
".",
"_degree",
")",
"edge1",
"=",
"_curve_mod",
".",
"Curve",
"(",
"nodes1... | 39.357143 | 19.857143 |
def coverage(args):
"""
%prog coverage fastafile ctg bedfile1 bedfile2 ..
Plot coverage from a set of BED files that contain the read mappings. The
paired read span will be converted to a new bedfile that contain the happy
mates. ctg is the chr/scf/ctg that you want to plot the histogram on.
I... | [
"def",
"coverage",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"bed",
"import",
"mates",
",",
"bedpe",
"p",
"=",
"OptionParser",
"(",
"coverage",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--ymax\"",
",",
"default",
"=",
"None... | 33.246753 | 19.922078 |
def access_token(self):
"""return an Oauth 2.0 Bearer access token if it can be found"""
access_token = self.get_auth_bearer()
if not access_token:
access_token = self.query_kwargs.get('access_token', '')
if not access_token:
access_token = self.body_kwarg... | [
"def",
"access_token",
"(",
"self",
")",
":",
"access_token",
"=",
"self",
".",
"get_auth_bearer",
"(",
")",
"if",
"not",
"access_token",
":",
"access_token",
"=",
"self",
".",
"query_kwargs",
".",
"get",
"(",
"'access_token'",
",",
"''",
")",
"if",
"not",... | 40.666667 | 17.111111 |
def get_property(host=None, admin_username=None, admin_password=None, property=None):
'''
.. versionadded:: Fluorine
Return specific property
host
The chassis host.
admin_username
The username used to access the chassis.
admin_password
The password used to access the ... | [
"def",
"get_property",
"(",
"host",
"=",
"None",
",",
"admin_username",
"=",
"None",
",",
"admin_password",
"=",
"None",
",",
"property",
"=",
"None",
")",
":",
"if",
"property",
"is",
"None",
":",
"raise",
"SaltException",
"(",
"'No property specified!'",
"... | 25.033333 | 25.566667 |
def fit_pRF_radius(ctx, retinotopy=Ellipsis, mask=None, weight=Ellipsis, slope_only=False):
'''
fit_pRF_radius(ctx) fits a line, m*eccen + b, to the pRF radius and yields the tuple (m, b).
The following options may be given:
* retinotopy (default: Ellipsis) specifies the prefix for the retinotopy (pa... | [
"def",
"fit_pRF_radius",
"(",
"ctx",
",",
"retinotopy",
"=",
"Ellipsis",
",",
"mask",
"=",
"None",
",",
"weight",
"=",
"Ellipsis",
",",
"slope_only",
"=",
"False",
")",
":",
"rdat",
"=",
"retinotopy_data",
"(",
"ctx",
",",
"retinotopy",
")",
"if",
"'radi... | 53.131579 | 25.815789 |
def save(self, refreshing=None, next_action=None, json_last_refresh=None, data_blob=None):
"""
save or update the component on the Ariane server cache
:param refreshing: the new refreshing value - default None and ignored
:param next_action: the new next action - default None and ignored... | [
"def",
"save",
"(",
"self",
",",
"refreshing",
"=",
"None",
",",
"next_action",
"=",
"None",
",",
"json_last_refresh",
"=",
"None",
",",
"data_blob",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"InjectorCachedComponent.save\"",
")",
"ret",
"=",
"... | 46.75 | 25.386364 |
def csiszar_vimco(f,
p_log_prob,
q,
num_draws,
num_batch_draws=1,
seed=None,
name=None):
"""Use VIMCO to lower the variance of gradient[csiszar_function(Avg(logu))].
This function generalizes VIMCO [(Mnih an... | [
"def",
"csiszar_vimco",
"(",
"f",
",",
"p_log_prob",
",",
"q",
",",
"num_draws",
",",
"num_batch_draws",
"=",
"1",
",",
"seed",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
... | 39.55102 | 23.132653 |
def get_db_driver(uri, username=None, password=None, encrypted=True, max_pool_size=50, trust=0):
"""
:param uri: Bolt uri
:type uri: str
:param username: Neo4j username
:type username: str
:param password: Neo4j password
:type password: str
:param encrypted: Use TLS
:type encrypted: ... | [
"def",
"get_db_driver",
"(",
"uri",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"encrypted",
"=",
"True",
",",
"max_pool_size",
"=",
"50",
",",
"trust",
"=",
"0",
")",
":",
"return",
"GraphDatabase",
".",
"driver",
"(",
"uri",
",",... | 39.157895 | 18.315789 |
def QAM_bb(N_symb,Ns,mod_type='16qam',pulse='rect',alpha=0.35):
"""
QAM_BB_TX: A complex baseband transmitter
x,b,tx_data = QAM_bb(K,Ns,M)
//////////// Inputs //////////////////////////////////////////////////
N_symb = the number of symbols to process
Ns = number of samples per symbol
... | [
"def",
"QAM_bb",
"(",
"N_symb",
",",
"Ns",
",",
"mod_type",
"=",
"'16qam'",
",",
"pulse",
"=",
"'rect'",
",",
"alpha",
"=",
"0.35",
")",
":",
"# Filter the impulse train waveform with a square root raised",
"# cosine pulse shape designed as follows:",
"# Design the filter... | 37.520548 | 16.643836 |
def roster(self, year):
"""Returns the roster table for the given year.
:year: The year for which we want the roster; defaults to current year.
:returns: A DataFrame containing roster information for that year.
"""
doc = self.get_year_doc('{}_roster'.format(year))
roster... | [
"def",
"roster",
"(",
"self",
",",
"year",
")",
":",
"doc",
"=",
"self",
".",
"get_year_doc",
"(",
"'{}_roster'",
".",
"format",
"(",
"year",
")",
")",
"roster_table",
"=",
"doc",
"(",
"'table#games_played_team'",
")",
"df",
"=",
"sportsref",
".",
"utils... | 47.35 | 19.25 |
def _uminumaxvmin(self,*args,**kwargs):
"""
NAME:
_uminumaxvmin
PURPOSE:
evaluate u_min, u_max, and v_min
INPUT:
Either:
a) R,vR,vT,z,vz
b) Orbit instance: initial condition used if that's it, orbit(t)
if there... | [
"def",
"_uminumaxvmin",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"delta",
"=",
"kwargs",
".",
"pop",
"(",
"'delta'",
",",
"self",
".",
"_delta",
")",
"if",
"(",
"(",
"self",
".",
"_c",
"and",
"not",
"(",
"'c'",
"in",
"k... | 42.695652 | 14.565217 |
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provide... | [
"def",
"get_configured_provider",
"(",
")",
":",
"return",
"config",
".",
"is_provider_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
"__virtualname__",
",",
"(",
"'auth'",
",",
"'region_name'",
")",
",",
"log_message",
"=",
"False",
",",
")"... | 34.272727 | 16.090909 |
def start_monitor(self):
"""Start the monitor."""
stdout_file, stderr_file = self.new_log_files("monitor")
process_info = ray.services.start_monitor(
self._redis_address,
stdout_file=stdout_file,
stderr_file=stderr_file,
autoscaling_config=self._ra... | [
"def",
"start_monitor",
"(",
"self",
")",
":",
"stdout_file",
",",
"stderr_file",
"=",
"self",
".",
"new_log_files",
"(",
"\"monitor\"",
")",
"process_info",
"=",
"ray",
".",
"services",
".",
"start_monitor",
"(",
"self",
".",
"_redis_address",
",",
"stdout_fi... | 50.363636 | 16.909091 |
def _get_hashed_path(self, path):
"""Returns an md5 hash for the specified file path."""
return self._get_path('%s.pkl' % hashlib.md5(path.encode("utf-8")).hexdigest()) | [
"def",
"_get_hashed_path",
"(",
"self",
",",
"path",
")",
":",
"return",
"self",
".",
"_get_path",
"(",
"'%s.pkl'",
"%",
"hashlib",
".",
"md5",
"(",
"path",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"hexdigest",
"(",
")",
")"
] | 60.666667 | 18 |
def new_result(self, data_mode='value', time_mode='framewise'):
'''
Create a new result
Attributes
----------
data_object : MetadataObject
id_metadata : MetadataObject
audio_metadata : MetadataObject
frame_metadata : MetadataObject
label_metadata ... | [
"def",
"new_result",
"(",
"self",
",",
"data_mode",
"=",
"'value'",
",",
"time_mode",
"=",
"'framewise'",
")",
":",
"from",
"datetime",
"import",
"datetime",
"result",
"=",
"AnalyzerResult",
"(",
"data_mode",
"=",
"data_mode",
",",
"time_mode",
"=",
"time_mode... | 37.586957 | 20.5 |
def write_pkg_file(self, file):
"""Write the PKG-INFO format data to a file object.
"""
version = self.get_metadata_version()
if six.PY2:
def write_field(key, value):
file.write("%s: %s\n" % (key, self._encode_field(value)))
else:
def write_field(key, value):
... | [
"def",
"write_pkg_file",
"(",
"self",
",",
"file",
")",
":",
"version",
"=",
"self",
".",
"get_metadata_version",
"(",
")",
"if",
"six",
".",
"PY2",
":",
"def",
"write_field",
"(",
"key",
",",
"value",
")",
":",
"file",
".",
"write",
"(",
"\"%s: %s\\n\... | 32.72973 | 16.567568 |
def _convert_nominal_form( analysis ):
''' Converts nominal categories of the input analysis.
Performs one-to-one conversions only. '''
assert FORM in analysis, '(!) The input analysis does not contain "'+FORM+'" key.'
for idx, pattern_items in enumerate(_noun_conversion_rules):
pattern_str... | [
"def",
"_convert_nominal_form",
"(",
"analysis",
")",
":",
"assert",
"FORM",
"in",
"analysis",
",",
"'(!) The input analysis does not contain \"'",
"+",
"FORM",
"+",
"'\" key.'",
"for",
"idx",
",",
"pattern_items",
"in",
"enumerate",
"(",
"_noun_conversion_rules",
")"... | 53.555556 | 18.666667 |
def run(self, conf, arg, err):
"""
WeldContext is currently hidden from the Python API. We create a new
context per Weld run and give ownership of it to the resulting value.
NOTE: This can leak the context if the result of the Weld run is an
error.
"""
weld_conte... | [
"def",
"run",
"(",
"self",
",",
"conf",
",",
"arg",
",",
"err",
")",
":",
"weld_context_new",
"=",
"weld",
".",
"weld_context_new",
"weld_context_new",
".",
"argtypes",
"=",
"[",
"c_weld_conf",
"]",
"weld_context_new",
".",
"restype",
"=",
"c_weld_context",
... | 41.6 | 16.9 |
def staticMovingAverage2(x, N=3, mode='reflect'):
"""
moving average filter for 1d arrays
supported modes for boundary handling: 'reflect' , 'constant'
"""
assert N > 1
x2 = np.empty(shape=x.shape[0] + N, dtype=x.dtype)
start = N - 2
if N == 2:
start = 1
end = N - start
... | [
"def",
"staticMovingAverage2",
"(",
"x",
",",
"N",
"=",
"3",
",",
"mode",
"=",
"'reflect'",
")",
":",
"assert",
"N",
">",
"1",
"x2",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"+",
"N",
",",
"dtype",
"=",
"x... | 25.382353 | 18.558824 |
def repair(source, validate_archive=False):
"""Use auditwheel (https://github.com/pypa/auditwheel)
to attempt and repair all wheels in a wagon.
The repair process will:
1. Extract the wagon and its metadata
2. Repair all wheels
3. Update the metadata with the new wheel names and platform
4... | [
"def",
"repair",
"(",
"source",
",",
"validate_archive",
"=",
"False",
")",
":",
"_assert_auditwheel_exists",
"(",
")",
"logger",
".",
"info",
"(",
"'Repairing: %s'",
",",
"source",
")",
"processed_source",
"=",
"get_source",
"(",
"source",
")",
"metadata",
"=... | 33.380952 | 13.452381 |
async def teardown_conn(self, context):
"""Teardown a connection from a client."""
client_id = context.user_data
self._logger.info("Tearing down client connection: %s", client_id)
if client_id not in self.clients:
self._logger.warning("client_id %s did not exist in teardown... | [
"async",
"def",
"teardown_conn",
"(",
"self",
",",
"context",
")",
":",
"client_id",
"=",
"context",
".",
"user_data",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Tearing down client connection: %s\"",
",",
"client_id",
")",
"if",
"client_id",
"not",
"in",
"s... | 38.3 | 19.7 |
def load_dict(self, source, namespace=''):
""" Load values from a dictionary structure. Nesting can be used to
represent namespaces.
>>> c = ConfigDict()
>>> c.load_dict({'some': {'namespace': {'key': 'value'} } })
{'some.namespace.key': 'value'}
"""
... | [
"def",
"load_dict",
"(",
"self",
",",
"source",
",",
"namespace",
"=",
"''",
")",
":",
"for",
"key",
",",
"value",
"in",
"source",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"str",
")",
":",
"nskey",
"=",
"(",
"namespace",
... | 39.833333 | 13.166667 |
def _psicomputations(self, kern, Z, variational_posterior, return_psi2_n=False):
"""
Z - MxQ
mu - NxQ
S - NxQ
"""
variance, lengthscale = kern.variance, kern.lengthscale
N,M,Q = self.get_dimensions(Z, variational_posterior)
self._initGPUCache(N,M,Q)
... | [
"def",
"_psicomputations",
"(",
"self",
",",
"kern",
",",
"Z",
",",
"variational_posterior",
",",
"return_psi2_n",
"=",
"False",
")",
":",
"variance",
",",
"lengthscale",
"=",
"kern",
".",
"variance",
",",
"kern",
".",
"lengthscale",
"N",
",",
"M",
",",
... | 58.567568 | 35.756757 |
def parse_code(self):
"""
Read the source code and return all the import statements.
Returns:
list of dict: the import statements.
"""
code = open(self.path, encoding='utf-8').read()
try:
body = ast.parse(code).body
except SyntaxError:
... | [
"def",
"parse_code",
"(",
"self",
")",
":",
"code",
"=",
"open",
"(",
"self",
".",
"path",
",",
"encoding",
"=",
"'utf-8'",
")",
".",
"read",
"(",
")",
"try",
":",
"body",
"=",
"ast",
".",
"parse",
"(",
"code",
")",
".",
"body",
"except",
"Syntax... | 29.470588 | 13.588235 |
def is_multifile_object_without_children(self, location: str) -> bool:
"""
Returns True if an item with this location is present as a multifile object without children.
For this implementation, this means that there is a file with the appropriate name but without extension
:param locati... | [
"def",
"is_multifile_object_without_children",
"(",
"self",
",",
"location",
":",
"str",
")",
"->",
"bool",
":",
"# (1) Find the base directory and base name",
"if",
"isdir",
"(",
"location",
")",
":",
"# special case: parent location is the root folder where all the files are.... | 48.888889 | 30.222222 |
def download_file_job(entry, directory, checksums, filetype='genbank', symlink_path=None):
"""Generate a DownloadJob that actually triggers a file download."""
pattern = NgdConfig.get_fileending(filetype)
filename, expected_checksum = get_name_and_checksum(checksums, pattern)
base_url = convert_ftp_url(... | [
"def",
"download_file_job",
"(",
"entry",
",",
"directory",
",",
"checksums",
",",
"filetype",
"=",
"'genbank'",
",",
"symlink_path",
"=",
"None",
")",
":",
"pattern",
"=",
"NgdConfig",
".",
"get_fileending",
"(",
"filetype",
")",
"filename",
",",
"expected_ch... | 44.375 | 19.75 |
def random_uniform(attrs, inputs, proto_obj):
"""Draw random samples from a uniform distribtuion."""
try:
from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
except ImportError:
raise ImportError("Onnx and protobuf need to be installed. "
"Instructions to install - http... | [
"def",
"random_uniform",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"try",
":",
"from",
"onnx",
".",
"mapping",
"import",
"TENSOR_TYPE_TO_NP_TYPE",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"Onnx and protobuf need to be installed. \"",... | 53.4 | 21.4 |
def fact(name, puppet=False):
'''
Run facter for a specific fact
CLI Example:
.. code-block:: bash
salt '*' puppet.fact kernel
'''
opt_puppet = '--puppet' if puppet else ''
ret = __salt__['cmd.run_all'](
'facter {0} {1}'.format(opt_puppet, name),
python_she... | [
"def",
"fact",
"(",
"name",
",",
"puppet",
"=",
"False",
")",
":",
"opt_puppet",
"=",
"'--puppet'",
"if",
"puppet",
"else",
"''",
"ret",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"'facter {0} {1}'",
".",
"format",
"(",
"opt_puppet",
",",
"name",
"... | 21.857143 | 20.904762 |
def get_project(self, project_id):
""" Get project info """
try:
result = self._request('/getproject/',
{'projectid': project_id})
return TildaProject(**result)
except NetworkError:
return [] | [
"def",
"get_project",
"(",
"self",
",",
"project_id",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"_request",
"(",
"'/getproject/'",
",",
"{",
"'projectid'",
":",
"project_id",
"}",
")",
"return",
"TildaProject",
"(",
"*",
"*",
"result",
")",
"exce... | 34.875 | 12.125 |
def jr6_jr6(mag_file, dir_path=".", input_dir_path="",
meas_file="measurements.txt", spec_file="specimens.txt",
samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
specnum=1, samp_con='1', location='unknown', lat='', lon='',
noave=False, meth_code="L... | [
"def",
"jr6_jr6",
"(",
"mag_file",
",",
"dir_path",
"=",
"\".\"",
",",
"input_dir_path",
"=",
"\"\"",
",",
"meas_file",
"=",
"\"measurements.txt\"",
",",
"spec_file",
"=",
"\"specimens.txt\"",
",",
"samp_file",
"=",
"\"samples.txt\"",
",",
"site_file",
"=",
"\"s... | 42.581749 | 20.087452 |
def community_topic_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/topics#show-topic"
api_path = "/api/v2/community/topics/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"community_topic_show",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/community/topics/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"(",
... | 53.6 | 13.6 |
def init_state_from_encoder(self, encoder_outputs, encoder_valid_length=None):
"""Initialize the state from the encoder outputs.
Parameters
----------
encoder_outputs : list
encoder_valid_length : NDArray or None
Returns
-------
decoder_states : list
... | [
"def",
"init_state_from_encoder",
"(",
"self",
",",
"encoder_outputs",
",",
"encoder_valid_length",
"=",
"None",
")",
":",
"mem_value",
",",
"rnn_states",
"=",
"encoder_outputs",
"batch_size",
",",
"_",
",",
"mem_size",
"=",
"mem_value",
".",
"shape",
"attention_v... | 37.965517 | 16.517241 |
def targeted_dropout(inputs,
k,
keep_prob,
targeting_fn,
is_training,
do_prune=False):
"""Applies targeted dropout.
Applies dropout at a rate of `1 - keep_prob` to only those elements of
`inputs` marked by `t... | [
"def",
"targeted_dropout",
"(",
"inputs",
",",
"k",
",",
"keep_prob",
",",
"targeting_fn",
",",
"is_training",
",",
"do_prune",
"=",
"False",
")",
":",
"if",
"not",
"is_training",
"and",
"do_prune",
":",
"k",
"=",
"tf",
".",
"round",
"(",
"to_float",
"("... | 37.619048 | 22.071429 |
def update_roles(self, roles='view'):
""" Updates the roles of this permission
:return: Success / Failure
:rtype: bool
"""
if not self.object_id:
return False
url = self.build_url(self._endpoints.get('permission').format(
driveitem_id=self.drivei... | [
"def",
"update_roles",
"(",
"self",
",",
"roles",
"=",
"'view'",
")",
":",
"if",
"not",
"self",
".",
"object_id",
":",
"return",
"False",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'permission'",
")",
".",
... | 29.52 | 17.64 |
def getComponentByName(self, name, default=noValue, instantiate=True):
"""Returns |ASN.1| type component by name.
Equivalent to Python :class:`dict` subscription operation (e.g. `[]`).
Parameters
----------
name: :class:`str`
|ASN.1| type component name
Key... | [
"def",
"getComponentByName",
"(",
"self",
",",
"name",
",",
"default",
"=",
"noValue",
",",
"instantiate",
"=",
"True",
")",
":",
"if",
"self",
".",
"_componentTypeLen",
":",
"idx",
"=",
"self",
".",
"componentType",
".",
"getPositionByName",
"(",
"name",
... | 35.361111 | 25.388889 |
def copy(self, **replacements):
"""Returns a clone of this JarDependency with the given replacements kwargs overlaid."""
cls = type(self)
kwargs = self._asdict()
for key, val in replacements.items():
if key == 'excludes':
val = JarDependency._prepare_excludes(val)
kwargs[key] = val
... | [
"def",
"copy",
"(",
"self",
",",
"*",
"*",
"replacements",
")",
":",
"cls",
"=",
"type",
"(",
"self",
")",
"kwargs",
"=",
"self",
".",
"_asdict",
"(",
")",
"for",
"key",
",",
"val",
"in",
"replacements",
".",
"items",
"(",
")",
":",
"if",
"key",
... | 37.909091 | 8.818182 |
def wns_send_message(
uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
Sends a notification request to WNS.
There are four notification types that WNS can send: toast, tile, badge and raw.
Toast, tile, and badge can all be customized to use different
templates/icons/sounds/lau... | [
"def",
"wns_send_message",
"(",
"uri",
",",
"message",
"=",
"None",
",",
"xml_data",
"=",
"None",
",",
"raw_data",
"=",
"None",
",",
"application_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Create a simple toast notification",
"if",
"message",
":... | 34.857143 | 24.31746 |
def page(self, status=values.unset, phone_number=values.unset,
incoming_phone_number_sid=values.unset, friendly_name=values.unset,
unique_name=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of Ho... | [
"def",
"page",
"(",
"self",
",",
"status",
"=",
"values",
".",
"unset",
",",
"phone_number",
"=",
"values",
".",
"unset",
",",
"incoming_phone_number_sid",
"=",
"values",
".",
"unset",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"unique_name",
... | 45.421053 | 23.842105 |
def get_yaml_decorators(rq):
"""
Returns the yaml decorator metadata only (this is needed by triple pattern fragments)
"""
# glogger.debug('Guessing decorators for query {}'.format(rq))
if not rq:
return None
if isinstance(rq, dict) and 'grlc' in rq: # json query (sparql transformer)
... | [
"def",
"get_yaml_decorators",
"(",
"rq",
")",
":",
"# glogger.debug('Guessing decorators for query {}'.format(rq))",
"if",
"not",
"rq",
":",
"return",
"None",
"if",
"isinstance",
"(",
"rq",
",",
"dict",
")",
"and",
"'grlc'",
"in",
"rq",
":",
"# json query (sparql tr... | 38.057143 | 22.685714 |
def open_tablebase(directory: PathLike, *, load_wdl: bool = True, load_dtz: bool = True, max_fds: Optional[int] = 128, VariantBoard: Type[chess.Board] = chess.Board) -> Tablebase:
"""
Opens a collection of tables for probing. See
:class:`~chess.syzygy.Tablebase`.
.. note::
Generally probing re... | [
"def",
"open_tablebase",
"(",
"directory",
":",
"PathLike",
",",
"*",
",",
"load_wdl",
":",
"bool",
"=",
"True",
",",
"load_dtz",
":",
"bool",
"=",
"True",
",",
"max_fds",
":",
"Optional",
"[",
"int",
"]",
"=",
"128",
",",
"VariantBoard",
":",
"Type",
... | 49.882353 | 29.411765 |
def register(cls, namespace, name):
"""Class decorator"""
def func(kind):
cls._FOREIGN[(namespace, name)] = kind()
return kind
return func | [
"def",
"register",
"(",
"cls",
",",
"namespace",
",",
"name",
")",
":",
"def",
"func",
"(",
"kind",
")",
":",
"cls",
".",
"_FOREIGN",
"[",
"(",
"namespace",
",",
"name",
")",
"]",
"=",
"kind",
"(",
")",
"return",
"kind",
"return",
"func"
] | 25.857143 | 16 |
def is_unitary(self, atol=None, rtol=None):
"""Return True if QuantumChannel is a unitary channel."""
try:
op = self.to_operator()
return op.is_unitary(atol=atol, rtol=rtol)
except QiskitError:
return False | [
"def",
"is_unitary",
"(",
"self",
",",
"atol",
"=",
"None",
",",
"rtol",
"=",
"None",
")",
":",
"try",
":",
"op",
"=",
"self",
".",
"to_operator",
"(",
")",
"return",
"op",
".",
"is_unitary",
"(",
"atol",
"=",
"atol",
",",
"rtol",
"=",
"rtol",
")... | 37.142857 | 11.285714 |
def add_line(psr,f,A,offset=0.5):
"""
Add a line of frequency `f` [Hz] and amplitude `A` [s],
with origin at a fraction `offset` through the dataset.
"""
t = psr.toas()
t0 = offset * (N.max(t) - N.min(t))
sine = A * N.cos(2 * math.pi * f * day * (t - t0))
psr.stoas[:] += sine / day | [
"def",
"add_line",
"(",
"psr",
",",
"f",
",",
"A",
",",
"offset",
"=",
"0.5",
")",
":",
"t",
"=",
"psr",
".",
"toas",
"(",
")",
"t0",
"=",
"offset",
"*",
"(",
"N",
".",
"max",
"(",
"t",
")",
"-",
"N",
".",
"min",
"(",
"t",
")",
")",
"si... | 28.181818 | 15.272727 |
def parse_sgf_to_examples(sgf_path):
"""Return supervised examples from positions
NOTE: last move is not played because no p.next_move after.
"""
return zip(*[(p.position, p.next_move, p.result)
for p in sgf_wrapper.replay_sgf_file(sgf_path)]) | [
"def",
"parse_sgf_to_examples",
"(",
"sgf_path",
")",
":",
"return",
"zip",
"(",
"*",
"[",
"(",
"p",
".",
"position",
",",
"p",
".",
"next_move",
",",
"p",
".",
"result",
")",
"for",
"p",
"in",
"sgf_wrapper",
".",
"replay_sgf_file",
"(",
"sgf_path",
")... | 33.875 | 18 |
def release_address(self, address):
"""
Release a previously allocated address returned by C{allocate_address}.
@return: C{True} if the operation succeeded.
"""
query = self.query_factory(
action="ReleaseAddress", creds=self.creds, endpoint=self.endpoint,
... | [
"def",
"release_address",
"(",
"self",
",",
"address",
")",
":",
"query",
"=",
"self",
".",
"query_factory",
"(",
"action",
"=",
"\"ReleaseAddress\"",
",",
"creds",
"=",
"self",
".",
"creds",
",",
"endpoint",
"=",
"self",
".",
"endpoint",
",",
"other_param... | 38.909091 | 15.818182 |
def _initstr(modname, imports, from_imports, inject_execstr, withheader=True):
""" Calls the other string makers """
header = _make_module_header() if withheader else ''
import_str = _make_imports_str(imports, modname)
fromimport_str = _make_fromimport_str(from_imports, modname)
initstr ... | [
"def",
"_initstr",
"(",
"modname",
",",
"imports",
",",
"from_imports",
",",
"inject_execstr",
",",
"withheader",
"=",
"True",
")",
":",
"header",
"=",
"_make_module_header",
"(",
")",
"if",
"withheader",
"else",
"''",
"import_str",
"=",
"_make_imports_str",
"... | 39 | 18.583333 |
def close(self):
"""close()
Disconnects the object from the bus.
"""
os.close(self._fd)
self._fd = -1
self._addr = -1
self._pec = 0 | [
"def",
"close",
"(",
"self",
")",
":",
"os",
".",
"close",
"(",
"self",
".",
"_fd",
")",
"self",
".",
"_fd",
"=",
"-",
"1",
"self",
".",
"_addr",
"=",
"-",
"1",
"self",
".",
"_pec",
"=",
"0"
] | 20 | 15.222222 |
def name(self):
"""
Similar to :attr:`complete`, but return the whole word, for
example::
subrout
would return `subroutine`.
"""
if hasattr(self._element, "name"):
return self._element.name
else:
return str(self._element) | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"_element",
",",
"\"name\"",
")",
":",
"return",
"self",
".",
"_element",
".",
"name",
"else",
":",
"return",
"str",
"(",
"self",
".",
"_element",
")"
] | 23.307692 | 16.692308 |
def load_reconstruction(folder, slice_start=0, slice_end=-1):
"""Load a volume from folder, also returns the corresponding partition.
Parameters
----------
folder : str
Path to the folder where the DICOM files are stored.
slice_start : int
Index of the first slice to use. Used for s... | [
"def",
"load_reconstruction",
"(",
"folder",
",",
"slice_start",
"=",
"0",
",",
"slice_end",
"=",
"-",
"1",
")",
":",
"file_names",
"=",
"sorted",
"(",
"[",
"f",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"folder",
")",
"if",
"f",
".",
"endswith",
... | 35.411765 | 22.333333 |
def list_receivers(self):
"""
Prints a list of all registered receivers. Including signal, plugin name and description.
"""
print("Receiver list")
print("*************\n")
for key, receiver in self.app.signals.receivers.items():
print("%s <-- %s (%s):\n %s\n"... | [
"def",
"list_receivers",
"(",
"self",
")",
":",
"print",
"(",
"\"Receiver list\"",
")",
"print",
"(",
"\"*************\\n\"",
")",
"for",
"key",
",",
"receiver",
"in",
"self",
".",
"app",
".",
"signals",
".",
"receivers",
".",
"items",
"(",
")",
":",
"pr... | 48.272727 | 19.545455 |
def _negf(ins):
''' Changes sign of top of the stack (48 bits)
'''
output = _float_oper(ins.quad[2])
output.append('call __NEGF')
output.extend(_fpush())
REQUIRES.add('negf.asm')
return output | [
"def",
"_negf",
"(",
"ins",
")",
":",
"output",
"=",
"_float_oper",
"(",
"ins",
".",
"quad",
"[",
"2",
"]",
")",
"output",
".",
"append",
"(",
"'call __NEGF'",
")",
"output",
".",
"extend",
"(",
"_fpush",
"(",
")",
")",
"REQUIRES",
".",
"add",
"(",... | 26.625 | 15.875 |
def _check_seismogenic_depths(self, upper_depth, lower_depth):
'''
Checks the seismic depths for physical consistency
:param float upper_depth:
Upper seismogenic depth (km)
:param float lower_depth:
Lower seismogenic depth (km)
'''
# Simple check ... | [
"def",
"_check_seismogenic_depths",
"(",
"self",
",",
"upper_depth",
",",
"lower_depth",
")",
":",
"# Simple check on depths",
"if",
"upper_depth",
":",
"if",
"upper_depth",
"<",
"0.",
":",
"raise",
"ValueError",
"(",
"'Upper seismogenic depth must be greater than'",
"'... | 36.740741 | 18.666667 |
def get_cached_colour(element, orbital, colours=None, cache=None):
"""Get a colour for a particular elemental and orbital combination.
If the element is not specified in the colours dictionary, the cache is
checked. If this element-orbital combination has not been chached before,
a new colour is drawn ... | [
"def",
"get_cached_colour",
"(",
"element",
",",
"orbital",
",",
"colours",
"=",
"None",
",",
"cache",
"=",
"None",
")",
":",
"if",
"cache",
"is",
"None",
":",
"cache",
"=",
"colour_cache",
"def",
"_get_colour_with_cache",
"(",
"element",
",",
"orbital",
"... | 39.936709 | 23.253165 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.