text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _summary_sim(sim, pars, probs):
"""Summarize chains together and separately
REF: rstan/rstan/R/misc.R
Parameters are unraveled in *column-major order*.
Parameters
----------
sim : dict
dict from from a stanfit fit object, i.e., fit['sim']
pars : Iterable of str
paramet... | [
"def",
"_summary_sim",
"(",
"sim",
",",
"pars",
",",
"probs",
")",
":",
"# NOTE: this follows RStan rather closely. Some of the calculations here",
"probs_len",
"=",
"len",
"(",
"probs",
")",
"n_chains",
"=",
"len",
"(",
"sim",
"[",
"'samples'",
"]",
")",
"# tidx ... | 42.635135 | 0.001239 |
def _extract_user_info(user):
"""
Creates a new user class with extracted user attributes for later use.
A new user object is needed to avoid overwritting of e.g. ``user.records``.
"""
temp_user = User()
copy_attributes = [
'antennas', 'name', 'night_start', 'night_end', 'weekend', 'hom... | [
"def",
"_extract_user_info",
"(",
"user",
")",
":",
"temp_user",
"=",
"User",
"(",
")",
"copy_attributes",
"=",
"[",
"'antennas'",
",",
"'name'",
",",
"'night_start'",
",",
"'night_end'",
",",
"'weekend'",
",",
"'home'",
"]",
"for",
"attr",
"in",
"copy_attri... | 30 | 0.002309 |
def on_epoch_end(self, epoch: int, smooth_loss: Tensor, last_metrics: MetricsList, **kwargs: Any) -> bool:
"Add a line with `epoch` number, `smooth_loss` and `last_metrics`."
last_metrics = ifnone(last_metrics, [])
stats = [str(stat) if isinstance(stat, int) else '#na#' if stat is None else f'{s... | [
"def",
"on_epoch_end",
"(",
"self",
",",
"epoch",
":",
"int",
",",
"smooth_loss",
":",
"Tensor",
",",
"last_metrics",
":",
"MetricsList",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"bool",
":",
"last_metrics",
"=",
"ifnone",
"(",
"last_metrics",
","... | 72.875 | 0.010169 |
def combine_dfs(dfs, names, method):
"""Combine dataframes.
Combination is either done simple by just concatenating the DataFrames
or performs tracking by adding the name of the dataset as a column."""
if method == "track":
res = list()
for df, identifier in zip(dfs, names):
... | [
"def",
"combine_dfs",
"(",
"dfs",
",",
"names",
",",
"method",
")",
":",
"if",
"method",
"==",
"\"track\"",
":",
"res",
"=",
"list",
"(",
")",
"for",
"df",
",",
"identifier",
"in",
"zip",
"(",
"dfs",
",",
"names",
")",
":",
"df",
"[",
"\"dataset\""... | 37.615385 | 0.001996 |
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 | 0.001767 |
def assert_valid(self, instance, value=None):
"""Returns True if the Property is valid on a HasProperties instance
Raises a ValueError if the value required and not set, not valid,
not correctly coerced, etc.
.. note::
Unlike :code:`validate`, this method requires instance... | [
"def",
"assert_valid",
"(",
"self",
",",
"instance",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"instance",
".",
"_get",
"(",
"self",
".",
"name",
")",
"if",
"value",
"is",
"None",
"and",
"self",
".",
"requ... | 38.166667 | 0.00213 |
def go(function_expr, **kwargs):
"""
CloudAux.go(
'list_aliases',
**{
'account_number': '000000000000',
'assume_role': 'role_name',
'session_name': 'cloudaux',
'region': 'us-east-1',
'tech': 'kms',
... | [
"def",
"go",
"(",
"function_expr",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'.'",
"in",
"function_expr",
":",
"tech",
",",
"service_type",
",",
"function_name",
"=",
"function_expr",
".",
"split",
"(",
"'.'",
")",
"else",
":",
"tech",
"=",
"kwargs",
"... | 33.485714 | 0.001658 |
def add_remote_provider(self, provider, client, path):
"""Adds a remote configuration source.
Remote Providers are searched in the order they are added.
provider is a string value, "etcd", "consul" and "zookeeper" are
currently supported.
client is a client object
path is... | [
"def",
"add_remote_provider",
"(",
"self",
",",
"provider",
",",
"client",
",",
"path",
")",
":",
"if",
"provider",
"not",
"in",
"constants",
".",
"SUPPORTED_REMOTE_PROVIDERS",
":",
"raise",
"errors",
".",
"UnsupportedRemoteProviderError",
"(",
"provider",
")",
... | 45.354839 | 0.001393 |
def remove_action(i):
"""
Input: {
(repo_uoa) - repo UOA
module_uoa - normally should be 'module' already
data_uoa - UOA of the module to be created
func - action
}
Output: {
return - return code = 0, if ... | [
"def",
"remove_action",
"(",
"i",
")",
":",
"# Check if global writing is allowed",
"r",
"=",
"check_writing",
"(",
"{",
"}",
")",
"if",
"r",
"[",
"'return'",
"]",
">",
"0",
":",
"return",
"r",
"o",
"=",
"i",
".",
"get",
"(",
"'out'",
",",
"''",
")",... | 24.154762 | 0.034564 |
def setStimDuration(self):
"""Sets the duration of the StimulusModel from values pulled from
this widget"""
duration = self.ui.durSpnbx.value()
self.tone.setDuration(duration) | [
"def",
"setStimDuration",
"(",
"self",
")",
":",
"duration",
"=",
"self",
".",
"ui",
".",
"durSpnbx",
".",
"value",
"(",
")",
"self",
".",
"tone",
".",
"setDuration",
"(",
"duration",
")"
] | 40.6 | 0.009662 |
def double(window, config):
"""Double theme
==================
= Header =
==================
= items =
==================
= footer =
==================
"""
cordx = round(config.get('cordx', 0))
color = config.get('color', red)
icon = config.get('... | [
"def",
"double",
"(",
"window",
",",
"config",
")",
":",
"cordx",
"=",
"round",
"(",
"config",
".",
"get",
"(",
"'cordx'",
",",
"0",
")",
")",
"color",
"=",
"config",
".",
"get",
"(",
"'color'",
",",
"red",
")",
"icon",
"=",
"config",
".",
"get",... | 30.413043 | 0.000693 |
def _decode_repeated_field(message, field, value_list):
"""Decode repeated field."""
if field.type == FieldDescriptor.TYPE_MESSAGE:
for value in value_list:
decode(getattr(message, field.name).add(), value)
else:
try:
for value in value_list:
if field.... | [
"def",
"_decode_repeated_field",
"(",
"message",
",",
"field",
",",
"value_list",
")",
":",
"if",
"field",
".",
"type",
"==",
"FieldDescriptor",
".",
"TYPE_MESSAGE",
":",
"for",
"value",
"in",
"value_list",
":",
"decode",
"(",
"getattr",
"(",
"message",
",",... | 46.894737 | 0.0011 |
def is_installable_file(path):
# type: (PipfileType) -> bool
"""Determine if a path can potentially be installed"""
from packaging import specifiers
if isinstance(path, Mapping):
path = convert_entry_to_path(path)
# If the string starts with a valid specifier operator, test if it is a vali... | [
"def",
"is_installable_file",
"(",
"path",
")",
":",
"# type: (PipfileType) -> bool",
"from",
"packaging",
"import",
"specifiers",
"if",
"isinstance",
"(",
"path",
",",
"Mapping",
")",
":",
"path",
"=",
"convert_entry_to_path",
"(",
"path",
")",
"# If the string sta... | 33.880952 | 0.001366 |
def get_similar(self, results=15, start=0, buckets=None, limit=False, cache=True, max_familiarity=None, min_familiarity=None, \
max_hotttnesss=None, min_hotttnesss=None, min_results=None, reverse=False, artist_start_year_before=None, \
artist_start_year_after=None,artist_end_year... | [
"def",
"get_similar",
"(",
"self",
",",
"results",
"=",
"15",
",",
"start",
"=",
"0",
",",
"buckets",
"=",
"None",
",",
"limit",
"=",
"False",
",",
"cache",
"=",
"True",
",",
"max_familiarity",
"=",
"None",
",",
"min_familiarity",
"=",
"None",
",",
"... | 45.457143 | 0.012304 |
def _write_avg_gradient(self)->None:
"Writes the average of the gradients to Tensorboard."
avg_gradient = sum(x.data.mean() for x in self.gradients)/len(self.gradients)
self._add_gradient_scalar('avg_gradient', scalar_value=avg_gradient) | [
"def",
"_write_avg_gradient",
"(",
"self",
")",
"->",
"None",
":",
"avg_gradient",
"=",
"sum",
"(",
"x",
".",
"data",
".",
"mean",
"(",
")",
"for",
"x",
"in",
"self",
".",
"gradients",
")",
"/",
"len",
"(",
"self",
".",
"gradients",
")",
"self",
".... | 64.5 | 0.015326 |
def complete(self, word, state):
"""Return the next possible completion for ``word``.
This is called successively with ``state == 0, 1, 2, ...`` until it
returns ``None``.
The completion should begin with ``word``.
:param word: the word to complete
:param state: an int... | [
"def",
"complete",
"(",
"self",
",",
"word",
",",
"state",
")",
":",
"try",
":",
"import",
"rl",
"# TODO: doing this manually right now, but may make sense to",
"# exploit",
"rl",
".",
"completion",
".",
"suppress_append",
"=",
"True",
"except",
"ImportError",
":",
... | 30.758621 | 0.002174 |
def trim_sparse(M, n_std=3, s_min=None, s_max=None):
"""Apply the trimming procedure to a sparse matrix.
"""
try:
from scipy.sparse import coo_matrix
except ImportError as e:
print(str(e))
print("I am peforming dense normalization by default.")
return trim_dense(M.todens... | [
"def",
"trim_sparse",
"(",
"M",
",",
"n_std",
"=",
"3",
",",
"s_min",
"=",
"None",
",",
"s_max",
"=",
"None",
")",
":",
"try",
":",
"from",
"scipy",
".",
"sparse",
"import",
"coo_matrix",
"except",
"ImportError",
"as",
"e",
":",
"print",
"(",
"str",
... | 33.230769 | 0.001125 |
def get_terminal_size(default_rows=25, default_cols=80):
"""
Returns the number of lines and columns of the current terminal.
It attempts several strategies to determine the size and if all fail,
it returns (80, 25).
:rtype: int, int
:return: The rows and columns of the terminal.
"""
#... | [
"def",
"get_terminal_size",
"(",
"default_rows",
"=",
"25",
",",
"default_cols",
"=",
"80",
")",
":",
"# Collect a list of viable input channels that may tell us something",
"# about the terminal dimensions.",
"fileno_list",
"=",
"[",
"]",
"try",
":",
"fileno_list",
".",
... | 28.337079 | 0.000383 |
def shuffle_album(
self, album, *, num_songs=100, only_library=False, recently_played=None
):
"""Get a listing of album shuffle/mix songs.
Parameters:
album (dict): An album dict.
num_songs (int, Optional): The maximum number of songs to return from the station.
Default: ``100``
only_library (bool,... | [
"def",
"shuffle_album",
"(",
"self",
",",
"album",
",",
"*",
",",
"num_songs",
"=",
"100",
",",
"only_library",
"=",
"False",
",",
"recently_played",
"=",
"None",
")",
":",
"station_info",
"=",
"{",
"'seed'",
":",
"{",
"'albumId'",
":",
"album",
"[",
"... | 26.857143 | 0.033362 |
def initialize_bfd(self, abfd):
"""Initialize underlying libOpcodes library using BFD."""
self._ptr = _opcodes.initialize_bfd(abfd._ptr)
# Already done inside opcodes.c
#self.architecture = abfd.architecture
#self.machine = abfd.machine
#self.endian = abfd.... | [
"def",
"initialize_bfd",
"(",
"self",
",",
"abfd",
")",
":",
"self",
".",
"_ptr",
"=",
"_opcodes",
".",
"initialize_bfd",
"(",
"abfd",
".",
"_ptr",
")",
"# Already done inside opcodes.c",
"#self.architecture = abfd.architecture",
"#self.machine = abfd.machine",
"#self.e... | 39.6875 | 0.010769 |
def show_stack_depth(self, record, frame):
"""
Compute the maximum stack depth to show requested by any hooks,
returning -1 if there are none matching, or if we've already emitted
one for the line of code referred to.
"""
logger = self
depths = [-1]
msg =... | [
"def",
"show_stack_depth",
"(",
"self",
",",
"record",
",",
"frame",
")",
":",
"logger",
"=",
"self",
"depths",
"=",
"[",
"-",
"1",
"]",
"msg",
"=",
"record",
".",
"getMessage",
"(",
")",
"# For each logger in the hierarchy",
"while",
"logger",
":",
"to_ma... | 39.666667 | 0.001641 |
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_lis... | [
"def",
"file_dict",
"(",
"*",
"packages",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"[",
"]",
"ret",
"=",
"{",
"}",
"pkgs",
"=",
"{",
"}",
"cmd",
"=",
"'dpkg -l {0}'",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"packages",
")",
")",
"... | 31.307692 | 0.000794 |
def strip_tags(s):
"""Resolve HTML entities and remove tags from a string."""
def handle_match(m):
name = m.group(1)
if name in html_entities:
return unichr(html_entities[name])
if name[:2] in ("#x", "#X"):
try:
return unichr(int(name[2:], 16))
... | [
"def",
"strip_tags",
"(",
"s",
")",
":",
"def",
"handle_match",
"(",
"m",
")",
":",
"name",
"=",
"m",
".",
"group",
"(",
"1",
")",
"if",
"name",
"in",
"html_entities",
":",
"return",
"unichr",
"(",
"html_entities",
"[",
"name",
"]",
")",
"if",
"nam... | 29.85 | 0.001623 |
def check_corrupted_files_cmd(java_home, files):
"""Check the file corruption of the specified files.
:param java_home: the JAVA_HOME
:type java_home: string
:param files: list of files to be checked
:type files: list of string
"""
files_str = ",".join(files)
check_command = CHECK_COMMA... | [
"def",
"check_corrupted_files_cmd",
"(",
"java_home",
",",
"files",
")",
":",
"files_str",
"=",
"\",\"",
".",
"join",
"(",
"files",
")",
"check_command",
"=",
"CHECK_COMMAND",
".",
"format",
"(",
"ionice",
"=",
"IONICE",
",",
"java_home",
"=",
"java_home",
"... | 31.761905 | 0.001456 |
def mst(infile, spec_name='unknown', dir_path=".", input_dir_path="",
meas_file="measurements.txt", samp_infile="samples.txt",
user="", specnum=0, samp_con="1", labfield=0.5,
location='unknown', syn=False, data_model_num=3):
"""
Convert MsT data (T,M) to MagIC measurements format files
... | [
"def",
"mst",
"(",
"infile",
",",
"spec_name",
"=",
"'unknown'",
",",
"dir_path",
"=",
"\".\"",
",",
"input_dir_path",
"=",
"\"\"",
",",
"meas_file",
"=",
"\"measurements.txt\"",
",",
"samp_infile",
"=",
"\"samples.txt\"",
",",
"user",
"=",
"\"\"",
",",
"spe... | 37.262009 | 0.001141 |
def get_target_n(self):
''' getter '''
if isinstance(self.__target_n, int) is False:
raise TypeError("The type of __target_n must be int.")
return self.__target_n | [
"def",
"get_target_n",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"__target_n",
",",
"int",
")",
"is",
"False",
":",
"raise",
"TypeError",
"(",
"\"The type of __target_n must be int.\"",
")",
"return",
"self",
".",
"__target_n"
] | 38.8 | 0.010101 |
def main(args=None):
"""Entry point for pkginfo tool
"""
options, paths = _parse_options(args)
format = getattr(options, 'output', 'simple')
formatter = _FORMATTERS[format](options)
for path in paths:
meta = get_metadata(path, options.metadata_version)
if meta is None:
... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"options",
",",
"paths",
"=",
"_parse_options",
"(",
"args",
")",
"format",
"=",
"getattr",
"(",
"options",
",",
"'output'",
",",
"'simple'",
")",
"formatter",
"=",
"_FORMATTERS",
"[",
"format",
"]",
"... | 29.809524 | 0.001548 |
def analyze_chunks(data, freq, bits, chunksize=512):
"""Cut the one channel data in chunks and analyzes them separately.
Making the chunksize a power of two works fastest.
"""
res = []
while data != []:
f = find_frequencies(data[:chunksize], freq, bits)
res.append(sorted(find_notes(... | [
"def",
"analyze_chunks",
"(",
"data",
",",
"freq",
",",
"bits",
",",
"chunksize",
"=",
"512",
")",
":",
"res",
"=",
"[",
"]",
"while",
"data",
"!=",
"[",
"]",
":",
"f",
"=",
"find_frequencies",
"(",
"data",
"[",
":",
"chunksize",
"]",
",",
"freq",
... | 36 | 0.002463 |
def get_item(self, item_url, force_download=False):
""" Retrieve the item metadata from the server, as an Item object
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:rtype: Item
:returns: the corresponding metadata, as an Item object
... | [
"def",
"get_item",
"(",
"self",
",",
"item_url",
",",
"force_download",
"=",
"False",
")",
":",
"item_url",
"=",
"str",
"(",
"item_url",
")",
"if",
"(",
"self",
".",
"use_cache",
"and",
"not",
"force_download",
"and",
"self",
".",
"cache",
".",
"has_item... | 33.892857 | 0.002049 |
def validate_args(args):
"""Validate provided arguments and act on --help."""
if args.list_embedding_sources:
print('Listing all sources for {} embeddings.'.format(
args.embedding_name))
print('Specify --embedding-name if you wish to '
'list sources of other embeddings'... | [
"def",
"validate_args",
"(",
"args",
")",
":",
"if",
"args",
".",
"list_embedding_sources",
":",
"print",
"(",
"'Listing all sources for {} embeddings.'",
".",
"format",
"(",
"args",
".",
"embedding_name",
")",
")",
"print",
"(",
"'Specify --embedding-name if you wish... | 44.21875 | 0.000692 |
def mdct(x, L):
"""Modified Discrete Cosine Transform (MDCT)
Returns the Modified Discrete Cosine Transform with fixed
window size L of the signal x.
The window is based on a sine window.
Parameters
----------
x : ndarray, shape (N,)
The signal
L : int
The window lengt... | [
"def",
"mdct",
"(",
"x",
",",
"L",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"N",
"=",
"x",
".",
"size",
"# Number of frequency channels",
"K",
"=",
"L",
"//",
"2",
"# Test length",
"if",
"N",... | 20.948718 | 0.000584 |
def execute(query, auth=None, client=urllib_request.build_opener()):
"""Execute a query, returning its result
Parameters
----------
query: Query[T]
The query to resolve
auth: ~typing.Tuple[str, str] \
or ~typing.Callable[[Request], Request] or None
This may be:
* A ... | [
"def",
"execute",
"(",
"query",
",",
"auth",
"=",
"None",
",",
"client",
"=",
"urllib_request",
".",
"build_opener",
"(",
")",
")",
":",
"exec_fn",
"=",
"getattr",
"(",
"type",
"(",
"query",
")",
",",
"'__execute__'",
",",
"_default_execute_method",
")",
... | 30.148148 | 0.00119 |
def entity_types(self):
"""List entity types in workspace."""
r = fapi.get_entity_types(self.namespace, self.name, self.api_url)
fapi._check_response_code(r, 200)
return r.json().keys() | [
"def",
"entity_types",
"(",
"self",
")",
":",
"r",
"=",
"fapi",
".",
"get_entity_types",
"(",
"self",
".",
"namespace",
",",
"self",
".",
"name",
",",
"self",
".",
"api_url",
")",
"fapi",
".",
"_check_response_code",
"(",
"r",
",",
"200",
")",
"return"... | 42.6 | 0.009217 |
def is_more_sonorous(self, other):
'''
compare this phoneme to another for sonority.
Used for SSP considerations.
'''
return True if isinstance(other, Consonant) and self[Manner] > other[Manner] else False | [
"def",
"is_more_sonorous",
"(",
"self",
",",
"other",
")",
":",
"return",
"True",
"if",
"isinstance",
"(",
"other",
",",
"Consonant",
")",
"and",
"self",
"[",
"Manner",
"]",
">",
"other",
"[",
"Manner",
"]",
"else",
"False"
] | 35.833333 | 0.036364 |
def patch():
"""
patch the built-in `urllib/httplib/httplib.client` methods for tracing.
"""
if getattr(httplib, PATCH_FLAG, False):
return
# we set an attribute to avoid multiple wrapping
setattr(httplib, PATCH_FLAG, True)
wrapt.wrap_function_wrapper(
httplib_client_module,... | [
"def",
"patch",
"(",
")",
":",
"if",
"getattr",
"(",
"httplib",
",",
"PATCH_FLAG",
",",
"False",
")",
":",
"return",
"# we set an attribute to avoid multiple wrapping",
"setattr",
"(",
"httplib",
",",
"PATCH_FLAG",
",",
"True",
")",
"wrapt",
".",
"wrap_function_... | 24.923077 | 0.001486 |
def getvar(root, name, vtype='', dimensions=(), digits=0, fill_value=None,
source=None):
"""
Return a variable from a NCFile or NCPackage instance. If the variable
doesn't exists create it.
Keyword arguments:
root -- the root descriptor returned by the 'open' function
name -- the nam... | [
"def",
"getvar",
"(",
"root",
",",
"name",
",",
"vtype",
"=",
"''",
",",
"dimensions",
"=",
"(",
")",
",",
"digits",
"=",
"0",
",",
"fill_value",
"=",
"None",
",",
"source",
"=",
"None",
")",
":",
"return",
"root",
".",
"getvar",
"(",
"name",
","... | 48.4375 | 0.001266 |
def view_atype(self, atype):
"""View the given atype on the atype page
:param atype: the atype to view
:type atype: :class:`jukeboxcore.djadapter.models.Atype`
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_prj:
return
l... | [
"def",
"view_atype",
"(",
"self",
",",
"atype",
")",
":",
"if",
"not",
"self",
".",
"cur_prj",
":",
"return",
"log",
".",
"debug",
"(",
"'Viewing atype %s'",
",",
"atype",
".",
"name",
")",
"self",
".",
"cur_atype",
"=",
"None",
"self",
".",
"pages_tab... | 36.888889 | 0.001957 |
def _pack_edition(self):
"""
Pack the values of the five arguments into the simple edition
component. If all the values are blank, just return a blank.
:returns: "edition", "sw_edition", "target_sw", "target_hw" and "other"
attributes packed in a only value
:rtype: s... | [
"def",
"_pack_edition",
"(",
"self",
")",
":",
"COMP_KEYS",
"=",
"(",
"CPEComponent",
".",
"ATT_EDITION",
",",
"CPEComponent",
".",
"ATT_SW_EDITION",
",",
"CPEComponent",
".",
"ATT_TARGET_SW",
",",
"CPEComponent",
".",
"ATT_TARGET_HW",
",",
"CPEComponent",
".",
... | 34.30137 | 0.000776 |
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(SubjectKey=self.subject_key)
params['mdsol:SubjectKeyType'] = self.subject_key_type
if self.transaction_type is not None:
params["TransactionType"] = self.transaction_type
# mixins
... | [
"def",
"build",
"(",
"self",
",",
"builder",
")",
":",
"params",
"=",
"dict",
"(",
"SubjectKey",
"=",
"self",
".",
"subject_key",
")",
"params",
"[",
"'mdsol:SubjectKeyType'",
"]",
"=",
"self",
".",
"subject_key_type",
"if",
"self",
".",
"transaction_type",
... | 28.205882 | 0.002016 |
def get_unique_schema_name(components, name, counter=0):
"""Function to generate a unique name based on the provided name and names
already in the spec. Will append a number to the name to make it unique if
the name is already in the spec.
:param Components components: instance of the components of th... | [
"def",
"get_unique_schema_name",
"(",
"components",
",",
"name",
",",
"counter",
"=",
"0",
")",
":",
"if",
"name",
"not",
"in",
"components",
".",
"_schemas",
":",
"return",
"name",
"if",
"not",
"counter",
":",
"# first time through recursion",
"warnings",
"."... | 45.565217 | 0.001869 |
def check_metadata(self):
'''Ensure that the metadata in our file is self-consistent.'''
assert self.header.point_count == self.point_used, (
'inconsistent point count! {} header != {} POINT:USED'.format(
self.header.point_count,
self.point_used,
)... | [
"def",
"check_metadata",
"(",
"self",
")",
":",
"assert",
"self",
".",
"header",
".",
"point_count",
"==",
"self",
".",
"point_used",
",",
"(",
"'inconsistent point count! {} header != {} POINT:USED'",
".",
"format",
"(",
"self",
".",
"header",
".",
"point_count",... | 41.755556 | 0.00208 |
def resizeEvent(self, event):
"""
Overloads the resize event to auto-resize the rich text label to the
size of this QPushButton.
:param event | <QResizeEvent>
"""
super(XPushButton, self).resizeEvent(event)
if self._richTextLabel:
... | [
"def",
"resizeEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"XPushButton",
",",
"self",
")",
".",
"resizeEvent",
"(",
"event",
")",
"if",
"self",
".",
"_richTextLabel",
":",
"self",
".",
"_richTextLabel",
".",
"resize",
"(",
"event",
".",
... | 32.909091 | 0.010753 |
def translate(value):
"""
Translates given schema from "pythonic" syntax to a validator.
Usage::
>>> translate(str)
IsA(str)
>>> translate('hello')
IsA(str, default='hello')
"""
if isinstance(value, BaseValidator):
return value
if value is None:
... | [
"def",
"translate",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"BaseValidator",
")",
":",
"return",
"value",
"if",
"value",
"is",
"None",
":",
"return",
"Anything",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"type",
")",
":",
... | 28.345455 | 0.00062 |
def fullselection(self) -> selectiontools.Selection:
"""A |Selection| object containing all |Element| and |Node| objects
defined by |XMLInterface.selections| and |XMLInterface.devices|.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> ... | [
"def",
"fullselection",
"(",
"self",
")",
"->",
"selectiontools",
".",
"Selection",
":",
"fullselection",
"=",
"selectiontools",
".",
"Selection",
"(",
"'fullselection'",
")",
"for",
"selection",
"in",
"self",
".",
"selections",
":",
"fullselection",
"+=",
"sele... | 42.791667 | 0.001905 |
def idents_from_label(lab, subtopic=False):
'''Returns the "ident" of a label.
If ``subtopic`` is ``True``, then a pair of pairs is returned,
where each pair corresponds to the content id and subtopic id in
the given label.
Otherwise, a pair of pairs is returned, but the second element of each
... | [
"def",
"idents_from_label",
"(",
"lab",
",",
"subtopic",
"=",
"False",
")",
":",
"if",
"not",
"subtopic",
":",
"return",
"(",
"lab",
".",
"content_id1",
",",
"None",
")",
",",
"(",
"lab",
".",
"content_id2",
",",
"None",
")",
"else",
":",
"return",
"... | 32.4 | 0.001499 |
def decode_sql(self, sql):
"""Base64 decode a string. This should only be used for sql in calls.
:param str sql: The base64 encoded form of the original utf-8 string
:return str: The decoded utf-8 string
"""
# JSON is defined as using "unicode", we'll go a step further and
... | [
"def",
"decode_sql",
"(",
"self",
",",
"sql",
")",
":",
"# JSON is defined as using \"unicode\", we'll go a step further and",
"# mandate utf-8 (though for the base64 part, it doesn't really matter!)",
"base64_sql_bytes",
"=",
"to_unicode",
"(",
"sql",
")",
".",
"encode",
"(",
... | 41.45 | 0.002358 |
def _resolve_model(obj):
"""
Resolve supplied `obj` to a Django model class.
`obj` must be a Django model class itself, or a string
representation of one. Useful in situations like GH #1225 where
Django may not have resolved a string-based reference to a model in
another model's foreign key de... | [
"def",
"_resolve_model",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
"and",
"len",
"(",
"obj",
".",
"split",
"(",
"'.'",
")",
")",
"==",
"2",
":",
"app_name",
",",
"model_name",
"=",
"obj",
".",
"spli... | 41.863636 | 0.001062 |
def distance_calc(s1, s2):
"""
Calculate Levenshtein distance between two words.
:param s1: first word
:type s1 : str
:param s2: second word
:type s2 : str
:return: distance between two word
References :
1- https://stackoverflow.com/questions/2460177/edit-distance-in-python
2- ... | [
"def",
"distance_calc",
"(",
"s1",
",",
"s2",
")",
":",
"if",
"len",
"(",
"s1",
")",
">",
"len",
"(",
"s2",
")",
":",
"s1",
",",
"s2",
"=",
"s2",
",",
"s1",
"distances",
"=",
"range",
"(",
"len",
"(",
"s1",
")",
"+",
"1",
")",
"for",
"i2",
... | 28.607143 | 0.002415 |
def _from_gerror(cls, error, own=True):
"""Creates a GError exception and takes ownership if own is True"""
if not own:
error = error.copy()
self = cls()
self._error = error
return self | [
"def",
"_from_gerror",
"(",
"cls",
",",
"error",
",",
"own",
"=",
"True",
")",
":",
"if",
"not",
"own",
":",
"error",
"=",
"error",
".",
"copy",
"(",
")",
"self",
"=",
"cls",
"(",
")",
"self",
".",
"_error",
"=",
"error",
"return",
"self"
] | 25.666667 | 0.008368 |
def IMTF(v):
"""In place inverse move to front transform.
"""
#mtf is initialized virtually with range(infinity)
mtf = []
for i, vi in enumerate(v):
#get old value from mtf. If never seen, take virtual value
try: value = mtf.pop(vi)
except Inde... | [
"def",
"IMTF",
"(",
"v",
")",
":",
"#mtf is initialized virtually with range(infinity)",
"mtf",
"=",
"[",
"]",
"for",
"i",
",",
"vi",
"in",
"enumerate",
"(",
"v",
")",
":",
"#get old value from mtf. If never seen, take virtual value",
"try",
":",
"value",
"=",
"mt... | 35 | 0.017131 |
def _set_arg(self, a, s="main", c=False):
"""
Set a single argument.
:param a: argparse.Action instance
:param s: config section title
:param c: use class' ConfigParser instance to get parameters
"""
# if action of an argument that suppresses any other, j... | [
"def",
"_set_arg",
"(",
"self",
",",
"a",
",",
"s",
"=",
"\"main\"",
",",
"c",
"=",
"False",
")",
":",
"# if action of an argument that suppresses any other, just return",
"if",
"a",
".",
"dest",
"is",
"SUPPRESS",
"or",
"a",
".",
"default",
"is",
"SUPPRESS",
... | 44.128571 | 0.00095 |
def verify_environments():
"""
For each environment verify hash comments and report failures.
If any failure occured, exit with code 1.
"""
env_confs = discover(
os.path.join(
OPTIONS['base_dir'],
'*.' + OPTIONS['in_ext'],
)
)
success = True
for co... | [
"def",
"verify_environments",
"(",
")",
":",
"env_confs",
"=",
"discover",
"(",
"os",
".",
"path",
".",
"join",
"(",
"OPTIONS",
"[",
"'base_dir'",
"]",
",",
"'*.'",
"+",
"OPTIONS",
"[",
"'in_ext'",
"]",
",",
")",
")",
"success",
"=",
"True",
"for",
"... | 36.730769 | 0.00102 |
def JUMPI(self, dest, cond):
"""Conditionally alter the program counter"""
self.pc = Operators.ITEBV(256, cond != 0, dest, self.pc + self.instruction.size)
#This set ups a check for JMPDEST in the next instruction if cond != 0
self._set_check_jmpdest(cond != 0) | [
"def",
"JUMPI",
"(",
"self",
",",
"dest",
",",
"cond",
")",
":",
"self",
".",
"pc",
"=",
"Operators",
".",
"ITEBV",
"(",
"256",
",",
"cond",
"!=",
"0",
",",
"dest",
",",
"self",
".",
"pc",
"+",
"self",
".",
"instruction",
".",
"size",
")",
"#Th... | 57.8 | 0.013652 |
def allocation(node,format,h):
'''
Allocation provides a snapshot of how shards have located around the
cluster and the state of disk usage
'''
try:
response = base.es.cat.allocation(node_id=node,bytes=format, h=h, format='json')
table = base.draw_table(response)
except Exception... | [
"def",
"allocation",
"(",
"node",
",",
"format",
",",
"h",
")",
":",
"try",
":",
"response",
"=",
"base",
".",
"es",
".",
"cat",
".",
"allocation",
"(",
"node_id",
"=",
"node",
",",
"bytes",
"=",
"format",
",",
"h",
"=",
"h",
",",
"format",
"=",
... | 31.083333 | 0.013021 |
def to_dict(self):
"""
Prepare a JSON serializable dict for read-only purposes.
Includes storages and IP-addresses.
Use prepare_post_body for POST and .save() for PUT.
"""
fields = dict(vars(self).items())
if self.populated:
fields['ip_addresses'] = ... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"fields",
"=",
"dict",
"(",
"vars",
"(",
"self",
")",
".",
"items",
"(",
")",
")",
"if",
"self",
".",
"populated",
":",
"fields",
"[",
"'ip_addresses'",
"]",
"=",
"[",
"]",
"fields",
"[",
"'storage_devices'",
... | 32.741935 | 0.001914 |
def smooth_magseries_gaussfilt(mags, windowsize, windowfwhm=7):
'''This smooths the magseries with a Gaussian kernel.
Parameters
----------
mags : np.array
The input mags/flux time-series to smooth.
windowsize : int
This is a odd integer containing the smoothing window size.
... | [
"def",
"smooth_magseries_gaussfilt",
"(",
"mags",
",",
"windowsize",
",",
"windowfwhm",
"=",
"7",
")",
":",
"convkernel",
"=",
"Gaussian1DKernel",
"(",
"windowfwhm",
",",
"x_size",
"=",
"windowsize",
")",
"smoothed",
"=",
"convolve",
"(",
"mags",
",",
"convker... | 24.222222 | 0.001471 |
def send(self, data):
"""Send `data' to the server.
``data`` can be a string object, a bytes object, an array object, a
file-like object that supports a .read() method, or an iterable object.
"""
if self.sock is None:
if self.auto_open:
self.connect()... | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"sock",
"is",
"None",
":",
"if",
"self",
".",
"auto_open",
":",
"self",
".",
"connect",
"(",
")",
"else",
":",
"raise",
"NotConnected",
"(",
")",
"if",
"self",
".",
"debuglevel",... | 36.22449 | 0.001097 |
def matches(self, s, parseAll=True):
"""Method for quick testing of a parser against a test string. Good for simple
inline microtests of sub expressions while building up larger parser, as in:
expr = Word(nums)
assert expr.matches("100")
Param... | [
"def",
"matches",
"(",
"self",
",",
"s",
",",
"parseAll",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"parseString",
"(",
"_ustr",
"(",
"s",
")",
",",
"parseAll",
"=",
"parseAll",
")",
"return",
"True",
"except",
"ParseBaseException",
":",
"return"... | 34.266667 | 0.015152 |
def get_network_project(network_id, **kwargs):
"""
get the project that a network is in
"""
net_proj = db.DBSession.query(Project).join(Network, and_(Project.id==Network.id, Network.id==network_id)).first()
if net_proj is None:
raise HydraError("Network %s not found"% network_id)
... | [
"def",
"get_network_project",
"(",
"network_id",
",",
"*",
"*",
"kwargs",
")",
":",
"net_proj",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Project",
")",
".",
"join",
"(",
"Network",
",",
"and_",
"(",
"Project",
".",
"id",
"==",
"Network",
".",
... | 29.545455 | 0.014925 |
def adjustSizeConstraint(self):
"""
Adjusts the min/max size based on the current tab.
"""
widget = self.currentWidget()
if not widget:
return
offw = 4
offh = 4
#if self.tabBar().isVisible():
# offh += 20 # tab ... | [
"def",
"adjustSizeConstraint",
"(",
"self",
")",
":",
"widget",
"=",
"self",
".",
"currentWidget",
"(",
")",
"if",
"not",
"widget",
":",
"return",
"offw",
"=",
"4",
"offh",
"=",
"4",
"#if self.tabBar().isVisible():",
"# offh += 20 # tab bar height",
"minw",
"... | 31.590909 | 0.009777 |
def spectral_density_count(wav, area):
"""Flux equivalencies between PHOTLAM and count/OBMAG.
Parameters
----------
wav : `~astropy.units.quantity.Quantity`
Quantity associated with values being converted
(e.g., wavelength or frequency).
area : `~astropy.units.quantity.Quantity`
... | [
"def",
"spectral_density_count",
"(",
"wav",
",",
"area",
")",
":",
"from",
".",
"binning",
"import",
"calculate_bin_widths",
",",
"calculate_bin_edges",
"wav",
"=",
"wav",
".",
"to",
"(",
"u",
".",
"AA",
",",
"equivalencies",
"=",
"u",
".",
"spectral",
"(... | 26.410256 | 0.000936 |
def remote_jupyter_proxy_url(port):
"""
Callable to configure Bokeh's show method when a proxy must be
configured.
If port is None we're asking about the URL
for the origin header.
"""
base_url = os.environ['EXTERNAL_URL']
host = urllib.parse.urlparse(base_url).netloc
# If port is ... | [
"def",
"remote_jupyter_proxy_url",
"(",
"port",
")",
":",
"base_url",
"=",
"os",
".",
"environ",
"[",
"'EXTERNAL_URL'",
"]",
"host",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"base_url",
")",
".",
"netloc",
"# If port is None we're asking for the URL orig... | 30.136364 | 0.001462 |
def visual_search(
self, accept_language=None, content_type=None, user_agent=None, client_id=None, client_ip=None, location=None, market=None, safe_search=None, set_lang=None, knowledge_request=None, image=None, custom_headers=None, raw=False, **operation_config):
"""Visual Search API lets you disco... | [
"def",
"visual_search",
"(",
"self",
",",
"accept_language",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"user_agent",
"=",
"None",
",",
"client_id",
"=",
"None",
",",
"client_ip",
"=",
"None",
",",
"location",
"=",
"None",
",",
"market",
"=",
"N... | 65.407407 | 0.000837 |
def update_ds_ids_from_file_handlers(self):
"""Update DatasetIDs with information from loaded files.
This is useful, for example, if dataset resolution may change
depending on what files were loaded.
"""
for file_handlers in self.file_handlers.values():
fh = file_ha... | [
"def",
"update_ds_ids_from_file_handlers",
"(",
"self",
")",
":",
"for",
"file_handlers",
"in",
"self",
".",
"file_handlers",
".",
"values",
"(",
")",
":",
"fh",
"=",
"file_handlers",
"[",
"0",
"]",
"# update resolution in the dataset IDs for this files resolution",
"... | 40.153846 | 0.001871 |
def tolist(expr, **kwargs):
"""
Pack all data in the sequence into a list
:param expr:
:param unique: make every elements in the sequence to be unique
:return:
"""
unique = kwargs.get('unique', kwargs.get('_unique', False))
output_type = None
if isinstance(expr, (SequenceExpr, Seque... | [
"def",
"tolist",
"(",
"expr",
",",
"*",
"*",
"kwargs",
")",
":",
"unique",
"=",
"kwargs",
".",
"get",
"(",
"'unique'",
",",
"kwargs",
".",
"get",
"(",
"'_unique'",
",",
"False",
")",
")",
"output_type",
"=",
"None",
"if",
"isinstance",
"(",
"expr",
... | 33.538462 | 0.002232 |
def get(name, rc_file='~/.odoorpcrc'):
"""Return the session configuration identified by `name`
from the `rc_file` file.
>>> import odoorpc
>>> from pprint import pprint as pp
>>> pp(odoorpc.session.get('foo')) # doctest: +SKIP
{'database': 'db_name',
'host': 'localhost',
'passwd':... | [
"def",
"get",
"(",
"name",
",",
"rc_file",
"=",
"'~/.odoorpcrc'",
")",
":",
"conf",
"=",
"ConfigParser",
"(",
")",
"conf",
".",
"read",
"(",
"[",
"os",
".",
"path",
".",
"expanduser",
"(",
"rc_file",
")",
"]",
")",
"if",
"not",
"conf",
".",
"has_se... | 27.927273 | 0.000629 |
def accept(self, discovery: ControllerDiscovery):
"""
Returns True if the supplied ControllerDiscovery matches this requirement, False otherwise
"""
if self.require_class is not None and not isinstance(discovery.controller, self.require_class):
return False
if self.sn... | [
"def",
"accept",
"(",
"self",
",",
"discovery",
":",
"ControllerDiscovery",
")",
":",
"if",
"self",
".",
"require_class",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"discovery",
".",
"controller",
",",
"self",
".",
"require_class",
")",
":",
"re... | 46.583333 | 0.008772 |
def density_contour(self, *args, **kwargs):
"""
Estimates point density of the given linear orientation measurements
(Interpreted as poles, lines, rakes, or "raw" longitudes and latitudes
based on the `measurement` keyword argument.) and plots contour lines of
the resulting densi... | [
"def",
"density_contour",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lon",
",",
"lat",
",",
"totals",
",",
"kwargs",
"=",
"self",
".",
"_contour_helper",
"(",
"args",
",",
"kwargs",
")",
"return",
"self",
".",
"contour",
"(",
... | 45.688406 | 0.000466 |
def compile_emoticons(emoticons_list):
"""
Compile a new list of emoticon tuples.
Each tuple contains a compiled regular expression
of the emoticon, and the html version of the emoticon.
"""
emoticons_compiled = []
for emoticons, image in emoticons_list:
for emoticon in emoticons:
... | [
"def",
"compile_emoticons",
"(",
"emoticons_list",
")",
":",
"emoticons_compiled",
"=",
"[",
"]",
"for",
"emoticons",
",",
"image",
"in",
"emoticons_list",
":",
"for",
"emoticon",
"in",
"emoticons",
":",
"context",
"=",
"{",
"'name'",
":",
"emoticon",
",",
"... | 38.111111 | 0.001422 |
def _learn(self, batch, activations):
"""
Learns a single iteration on the provided batch and activations.
:param batch: (array) Training batch, of dimension (filterDim,
batchSize)
:param activations:(array) Computed activations, of dimension (outputDim,
... | [
"def",
"_learn",
"(",
"self",
",",
"batch",
",",
"activations",
")",
":",
"batchResiduals",
"=",
"batch",
"-",
"self",
".",
"basis",
".",
"dot",
"(",
"activations",
")",
"loss",
"=",
"np",
".",
"mean",
"(",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",... | 39.772727 | 0.002232 |
def fromFile(cls, filename):
"""From File
Loads a JSON file and creates a Node instance from it
Args:
filename (str): The filename to load
Returns:
_NodeInterface
"""
# Load the file
oFile = open(filename)
# Convert it to a dictionary
dDetails = JSON.decodef(oFile)
# Create and return th... | [
"def",
"fromFile",
"(",
"cls",
",",
"filename",
")",
":",
"# Load the file",
"oFile",
"=",
"open",
"(",
"filename",
")",
"# Convert it to a dictionary",
"dDetails",
"=",
"JSON",
".",
"decodef",
"(",
"oFile",
")",
"# Create and return the new instance",
"return",
"... | 16.9 | 0.042017 |
def is_name_revoked( self, name ):
"""
Determine if a name is revoked at this block.
"""
name = self.get_name( name )
if name is None:
return False
if name['revoked']:
return True
else:
return False | [
"def",
"is_name_revoked",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"get_name",
"(",
"name",
")",
"if",
"name",
"is",
"None",
":",
"return",
"False",
"if",
"name",
"[",
"'revoked'",
"]",
":",
"return",
"True",
"else",
":",
"return... | 23.416667 | 0.023973 |
def load(self, name):
"""
If not yet in the cache, load the named template and compiles it,
placing it into the cache.
If in cache, return the cached template.
"""
if self.reload:
self._maybe_purge_cache()
template = self.cache.get(name)
if ... | [
"def",
"load",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"reload",
":",
"self",
".",
"_maybe_purge_cache",
"(",
")",
"template",
"=",
"self",
".",
"cache",
".",
"get",
"(",
"name",
")",
"if",
"template",
":",
"return",
"template",
"path"... | 26.896552 | 0.002475 |
def get_time_series(sdat, var, tstart, tend):
"""Extract or compute and rescale a time series.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
var (str): time series name, a key of :data:`stagpy.phyvars.TIME`
or :data:`stagpy.phyvars.TIME_EXTRA`.
... | [
"def",
"get_time_series",
"(",
"sdat",
",",
"var",
",",
"tstart",
",",
"tend",
")",
":",
"tseries",
"=",
"sdat",
".",
"tseries_between",
"(",
"tstart",
",",
"tend",
")",
"if",
"var",
"in",
"tseries",
".",
"columns",
":",
"series",
"=",
"tseries",
"[",
... | 41.358974 | 0.000606 |
def update(self, user, identity):
"""
Update specified identity for the specified user
:param user: User object or id
:param identity: Identity object to be updated.
:return: The updated Identity
"""
return UserIdentityRequest(self).put(self.endpoint.update, user... | [
"def",
"update",
"(",
"self",
",",
"user",
",",
"identity",
")",
":",
"return",
"UserIdentityRequest",
"(",
"self",
")",
".",
"put",
"(",
"self",
".",
"endpoint",
".",
"update",
",",
"user",
",",
"identity",
")"
] | 35.888889 | 0.009063 |
def emit_save_figure(self):
"""
Emit a signal when the toolbutton to save the figure is clicked.
"""
self.sig_save_figure.emit(self.canvas.fig, self.canvas.fmt) | [
"def",
"emit_save_figure",
"(",
"self",
")",
":",
"self",
".",
"sig_save_figure",
".",
"emit",
"(",
"self",
".",
"canvas",
".",
"fig",
",",
"self",
".",
"canvas",
".",
"fmt",
")"
] | 37.6 | 0.010417 |
def upsert_smart_invite(self, smart_invite_id, recipient, event, callback_url=None, organizer=None):
""" Creates or updates smart invite.
:param string smart_invite_id - A String uniquely identifying the event for your
application (note: this is NOT an ID generated
by Cronofy... | [
"def",
"upsert_smart_invite",
"(",
"self",
",",
"smart_invite_id",
",",
"recipient",
",",
"event",
",",
"callback_url",
"=",
"None",
",",
"organizer",
"=",
"None",
")",
":",
"event",
"[",
"'start'",
"]",
"=",
"format_event_time",
"(",
"event",
"[",
"'start'"... | 53.790323 | 0.002061 |
def write_exc_info(self, exc_info=None):
"""Write exception information to the response.
Only one of this and ``write_result`` may be called.
:param exc_info:
3-tuple of exception information. If omitted, the last exception
will be retrieved using ``sys.exc_info()``.
... | [
"def",
"write_exc_info",
"(",
"self",
",",
"exc_info",
"=",
"None",
")",
":",
"exc_info",
"=",
"exc_info",
"or",
"sys",
".",
"exc_info",
"(",
")",
"exc",
"=",
"exc_info",
"[",
"1",
"]",
"self",
".",
"code",
"=",
"StatusCode",
".",
"error",
"for",
"sp... | 37.772727 | 0.002347 |
def execute_javascript(self, *args, **kwargs):
'''
Execute a javascript string in the context of the browser tab.
'''
ret = self.__exec_js(*args, **kwargs)
return ret | [
"def",
"execute_javascript",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"self",
".",
"__exec_js",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"ret"
] | 24.428571 | 0.039548 |
def panel(panel_id):
"""Display (and add pending updates to) a specific gene panel."""
panel_obj = store.gene_panel(panel_id) or store.panel(panel_id)
if request.method == 'POST':
raw_hgnc_id = request.form['hgnc_id']
if '|' in raw_hgnc_id:
raw_hgnc_id = raw_hgnc_id.split(' | ', ... | [
"def",
"panel",
"(",
"panel_id",
")",
":",
"panel_obj",
"=",
"store",
".",
"gene_panel",
"(",
"panel_id",
")",
"or",
"store",
".",
"panel",
"(",
"panel_id",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"raw_hgnc_id",
"=",
"request",
".",
"... | 43.552632 | 0.001773 |
def deblend_sources(data, segment_img, npixels, filter_kernel=None,
labels=None, nlevels=32, contrast=0.001,
mode='exponential', connectivity=8, relabel=True):
"""
Deblend overlapping sources labeled in a segmentation image.
Sources are deblended using a combination ... | [
"def",
"deblend_sources",
"(",
"data",
",",
"segment_img",
",",
"npixels",
",",
"filter_kernel",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"nlevels",
"=",
"32",
",",
"contrast",
"=",
"0.001",
",",
"mode",
"=",
"'exponential'",
",",
"connectivity",
"=",... | 42.338462 | 0.000533 |
def vm_netstats(vm_=None, **kwargs):
'''
Return combined network counters used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overr... | [
"def",
"vm_netstats",
"(",
"vm_",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_info",
"(",
"dom",
")",
":",
"'''\n Compute network stats of a domain\n '''",
"nics",
"=",
"_get_nics",
"(",
"dom",
")",
"ret",
"=",
"{",
"'rx_bytes'",
"... | 27.632911 | 0.000442 |
def integrate_auto_switch(odes, kw, x, y0, params=(), **kwargs):
""" Auto-switching between formulations of ODE system.
In case one has a formulation of a system of ODEs which is preferential in
the beginning of the integration, this function allows the user to run the
integration with this system wher... | [
"def",
"integrate_auto_switch",
"(",
"odes",
",",
"kw",
",",
"x",
",",
"y0",
",",
"params",
"=",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"x_arr",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"if",
"x_arr",
".",
"shape",
"[",
"-",
"1",
"]",
... | 41.684783 | 0.002038 |
def close(self, reply_code=0, reply_text='', class_id=0, method_id=0):
'''
Close this channel. Caller has the option of specifying the reason for
closure and the class and method ids of the current frame in which an
error occurred. If in the event of an exception, the channel will be
... | [
"def",
"close",
"(",
"self",
",",
"reply_code",
"=",
"0",
",",
"reply_text",
"=",
"''",
",",
"class_id",
"=",
"0",
",",
"method_id",
"=",
"0",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"'channel'",
",",
"None",
")",
"or",
"self",
".",
"... | 42.305556 | 0.001284 |
def _translate_to(coordinates, to):
"""Translate a set of coordinates to a location.
Parameters
----------
coordinates : np.ndarray, shape=(n,3), dtype=float
The coordinates being translated.
to : np.ndarray, shape=(3,), dtype=float
The new average position of the coordinates.
... | [
"def",
"_translate_to",
"(",
"coordinates",
",",
"to",
")",
":",
"coordinates",
"-=",
"np",
".",
"mean",
"(",
"coordinates",
",",
"axis",
"=",
"0",
")",
"return",
"Translation",
"(",
"to",
")",
".",
"apply_to",
"(",
"coordinates",
")"
] | 31.384615 | 0.002381 |
def delete_long_poll_channel(self, **kwargs): # noqa: E501
"""Delete notification Long Poll channel # noqa: E501
To delete a notification Long Poll channel. This is required to change the channel from Long Poll to a callback. You should not make a GET `/v2/notification/pull` call for 2 minutes after ... | [
"def",
"delete_long_poll_channel",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
"delete_long_pol... | 69.3 | 0.001423 |
def putmask(self, mask, new, align=True, inplace=False, axis=0,
transpose=False):
""" putmask the data to the block; it is possible that we may create a
new dtype of block
return the resulting block(s)
Parameters
----------
mask : the condition to respe... | [
"def",
"putmask",
"(",
"self",
",",
"mask",
",",
"new",
",",
"align",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"axis",
"=",
"0",
",",
"transpose",
"=",
"False",
")",
":",
"new_values",
"=",
"self",
".",
"values",
"if",
"inplace",
"else",
"se... | 33.468468 | 0.000784 |
def input_json(i):
"""
Input: {
text - text to print
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
string
... | [
"def",
"input_json",
"(",
"i",
")",
":",
"t",
"=",
"i",
"[",
"'text'",
"]",
"out",
"(",
"t",
")",
"s",
"=",
"''",
"while",
"True",
":",
"r",
"=",
"inp",
"(",
"{",
"'text'",
":",
"''",
"}",
")",
"if",
"r",
"[",
"'return'",
"]",
">",
"0",
"... | 19.581395 | 0.040724 |
def get_alarm(name, region=None, key=None, keyid=None, profile=None):
'''
Get alarm details. Also can be used to check to see if an alarm exists.
CLI example::
salt myminion boto_cloudwatch.get_alarm myalarm region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile... | [
"def",
"get_alarm",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
... | 33.5625 | 0.001812 |
def overall_accuracy(ref_voicing, ref_cent, est_voicing, est_cent,
cent_tolerance=50):
"""Compute the overall accuracy given two pitch (frequency) sequences in cents
and matching voicing indicator sequences. The first pitch and voicing
arrays are treated as the reference (truth), and th... | [
"def",
"overall_accuracy",
"(",
"ref_voicing",
",",
"ref_cent",
",",
"est_voicing",
",",
"est_cent",
",",
"cent_tolerance",
"=",
"50",
")",
":",
"validate_voicing",
"(",
"ref_voicing",
",",
"est_voicing",
")",
"validate",
"(",
"ref_voicing",
",",
"ref_cent",
","... | 40.103448 | 0.000839 |
def parse_raxml(handle):
"""Parse RAxML's summary output.
*handle* should be an open file handle containing the RAxML
output. It is parsed and a dictionary returned.
"""
s = ''.join(handle.readlines())
result = {}
try_set_fields(result, r'(?P<program>RAxML version [0-9.]+)', s)
try_set... | [
"def",
"parse_raxml",
"(",
"handle",
")",
":",
"s",
"=",
"''",
".",
"join",
"(",
"handle",
".",
"readlines",
"(",
")",
")",
"result",
"=",
"{",
"}",
"try_set_fields",
"(",
"result",
",",
"r'(?P<program>RAxML version [0-9.]+)'",
",",
"s",
")",
"try_set_fiel... | 48.088235 | 0.0006 |
def get_path(root, path, default=_UNSET):
"""Retrieve a value from a nested object via a tuple representing the
lookup path.
>>> root = {'a': {'b': {'c': [[1], [2], [3]]}}}
>>> get_path(root, ('a', 'b', 'c', 2, 0))
3
The path format is intentionally consistent with that of
:func:`remap`.
... | [
"def",
"get_path",
"(",
"root",
",",
"path",
",",
"default",
"=",
"_UNSET",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"basestring",
")",
":",
"path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"cur",
"=",
"root",
"try",
":",
"for",
"seg",
... | 35.982759 | 0.000466 |
def render_POST(self, request):
"""Dispatch Method called by twisted render, creates a
request/response handler chain.
request -- twisted.web.server.Request
"""
from twisted.internet.defer import maybeDeferred
chain = self.factory.newInstance()
data = re... | [
"def",
"render_POST",
"(",
"self",
",",
"request",
")",
":",
"from",
"twisted",
".",
"internet",
".",
"defer",
"import",
"maybeDeferred",
"chain",
"=",
"self",
".",
"factory",
".",
"newInstance",
"(",
")",
"data",
"=",
"request",
".",
"content",
".",
"re... | 39.625 | 0.010786 |
def connect(self):
# type: () -> None
"""
Connect to server
Returns:
None
"""
if self.connection_type.lower() == 'ssl':
self.server = smtplib.SMTP_SSL(host=self.host, port=self.port, local_hostname=self.local_hostname,
... | [
"def",
"connect",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"self",
".",
"connection_type",
".",
"lower",
"(",
")",
"==",
"'ssl'",
":",
"self",
".",
"server",
"=",
"smtplib",
".",
"SMTP_SSL",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",... | 46.526316 | 0.008869 |
def partition_chem_env(self, n_sphere=4,
use_lookup=None):
"""This function partitions the molecule into subsets of the
same chemical environment.
A chemical environment is specified by the number of
surrounding atoms of a certain kind around an atom with a
... | [
"def",
"partition_chem_env",
"(",
"self",
",",
"n_sphere",
"=",
"4",
",",
"use_lookup",
"=",
"None",
")",
":",
"if",
"use_lookup",
"is",
"None",
":",
"use_lookup",
"=",
"settings",
"[",
"'defaults'",
"]",
"[",
"'use_lookup'",
"]",
"def",
"get_chem_env",
"(... | 40.145161 | 0.001176 |
def run_sync(self):
"""Synchronously run pantsd."""
# Switch log output to the daemon's log stream from here forward.
self._close_stdio()
with self._pantsd_logging() as (log_stream, log_filename):
# Register an exiter using os._exit to ensure we only close stdio streams once.
ExceptionSink.... | [
"def",
"run_sync",
"(",
"self",
")",
":",
"# Switch log output to the daemon's log stream from here forward.",
"self",
".",
"_close_stdio",
"(",
")",
"with",
"self",
".",
"_pantsd_logging",
"(",
")",
"as",
"(",
"log_stream",
",",
"log_filename",
")",
":",
"# Registe... | 46.717949 | 0.016667 |
def mean(data, channels=None):
"""
Calculate the mean of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list o... | [
"def",
"mean",
"(",
"data",
",",
"channels",
"=",
"None",
")",
":",
"# Slice data to take statistics from",
"if",
"channels",
"is",
"None",
":",
"data_stats",
"=",
"data",
"else",
":",
"data_stats",
"=",
"data",
"[",
":",
",",
"channels",
"]",
"# Calculate a... | 28.074074 | 0.001276 |
def _raise_connection_failure(address, error):
"""Convert a socket.error to ConnectionFailure and raise it."""
host, port = address
# If connecting to a Unix socket, port will be None.
if port is not None:
msg = '%s:%d: %s' % (host, port, error)
else:
msg = '%s: %s' % (host, error)
... | [
"def",
"_raise_connection_failure",
"(",
"address",
",",
"error",
")",
":",
"host",
",",
"port",
"=",
"address",
"# If connecting to a Unix socket, port will be None.",
"if",
"port",
"is",
"not",
"None",
":",
"msg",
"=",
"'%s:%d: %s'",
"%",
"(",
"host",
",",
"po... | 46.15 | 0.001062 |
def _get_modified_recids_invenio2(from_date):
"""Get record ids for Invenio 2."""
from invenio.legacy.search_engine import search_pattern
from invenio.modules.records.models import Record
date = datetime.datetime.strptime(from_date, '%Y-%m-%d %H:%M:%S')
return set(
(x[0]
for x in R... | [
"def",
"_get_modified_recids_invenio2",
"(",
"from_date",
")",
":",
"from",
"invenio",
".",
"legacy",
".",
"search_engine",
"import",
"search_pattern",
"from",
"invenio",
".",
"modules",
".",
"records",
".",
"models",
"import",
"Record",
"date",
"=",
"datetime",
... | 41.3 | 0.00237 |
def VCStoreRefs(self):
"""
Microsoft Visual C++ store references Libraries
"""
if self.vc_ver < 14.0:
return []
return [os.path.join(self.si.VCInstallDir, r'Lib\store\references')] | [
"def",
"VCStoreRefs",
"(",
"self",
")",
":",
"if",
"self",
".",
"vc_ver",
"<",
"14.0",
":",
"return",
"[",
"]",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"si",
".",
"VCInstallDir",
",",
"r'Lib\\store\\references'",
")",
"]"
] | 32.285714 | 0.008621 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.