content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _test():
"""Run the Bio.Motif module's doctests.
This will try and locate the unit tests directory, and run the doctests
from there in order that the relative paths used in the examples work.
"""
import doctest
import os
if os.path.isdir(os.path.join("..","..","Tests")) :
print ... | 1,300 |
def allocate_memory_addresses(instructions: list[Instruction], reserved_memory_names: set[str]):
"""
Allocate memory addresses for SharedName and Slice, and replace AddressOf and MemoryOf with PrimitiveValue.
"""
allocated_before: tuple[int, int] | None = None # (bank_id, address)
def malloc(size:... | 1,301 |
def find_blobs(B):
"""find and return all blobs in the image, using
eight-connectivity. returns a labeled image, the
bounding boxes of the blobs, and the blob masks cropped
to those bounding boxes"""
B = np.array(B).astype(bool)
labeled, objects = label_blobs(B)
blobs = [labeled[obj] == ix +... | 1,302 |
def showOperandLines(rh):
"""
Produce help output related to operands.
Input:
Request Handle
"""
if rh.function == 'HELP':
rh.printLn("N", " For the MakeVM function:")
else:
rh.printLn("N", "Sub-Functions(s):")
rh.printLn("N", " directory - " +
"Cre... | 1,303 |
def star_dist(a, n_rays=32, mode='cpp'):
"""'a' assumbed to be a label image with integer values that encode object ids. id 0 denotes background."""
n_rays >= 3 or _raise(ValueError("need 'n_rays' >= 3"))
if mode == 'python':
return _py_star_dist(a, n_rays)
elif mode == 'cpp':
return _... | 1,304 |
def main(source_file, dump_dir):
"""
Read triplets from source_file and dump graph in dump_dir
"""
print("Reading Entire Data...")
all_triplets = list(tqdm(read_stuffie_output(source_file), ascii=True, disable=False))
print("Reading Complete...")
create_graphs_multicore(all_triplets, dump_d... | 1,305 |
def run_tasks(simulation_tasks, local_working_dir, s3_io, logger,
max_concurrency):
"""Runs a CBM3 project simulation task
:: Example simulation_tasks
simulation_tasks = [
{"project_code": "AB",
"simulation_ids": [1, 2]},
{"project_... | 1,306 |
def get_bond_enthalpy(element1: str, element2: str, bond='single bond') -> int:
"""Utility function that retrieves the bond enthalpy between element1 and element2 (regardless or order)
An optional argument, bond, describing the bond (single, double, triple) could be specified
If not specified, bond defaults... | 1,307 |
def approx_sample(num_items: int, num_samples: int) -> np.array:
"""Fast approximate downsampling."""
if num_items <= num_samples:
return np.ones(num_items, dtype=np.bool8)
np.random.seed(125)
# Select each xy with probability (downsample_to / len(x)) to yield
# approximately downsample_to selections.
f... | 1,308 |
def load_accessions(args):
"""
Process a set of accession records and load to the database
"""
AccessionRecord = namedtuple(
"AccessionRecord",
"batch sourcefile sourceline filename bytes timestamp md5 relpath"
)
def iter_accession_records_from(catalog_file):
"""
... | 1,309 |
def extract_out_cos(transmat, cos, state):
""" Helper function for building HMMs from matrices: Used for
transition matrices with 'cos' transition classes.
Extract outgoing transitions for 'state' from the complete list
of transition matrices
Allocates: .out_id vector and .out_a array (of size cos... | 1,310 |
def import_statistics(sourcefile,starttime):
"""
Forms a dictionary for MarkovModel from the source csv file
input
--------
sourcefile: Source csv file for Markov Model
starttime : For which hour the optimization is run
Returns a dictionary statistics2
keys are (time,iniSt... | 1,311 |
def image_repository_validation(func):
"""
Wrapper Validation function that will run last after the all cli parmaters have been loaded
to check for conditions surrounding `--image-repository`, `--image-repositories`, and `--resolve-image-repos`. The
reason they are done last instead of in callback funct... | 1,312 |
def safe_encode(text, incoming=None,
encoding='utf-8', errors='strict'):
"""Encodes incoming str/unicode using `encoding`.
If incoming is not specified, text is expected to be encoded with
current python's default encoding. (`sys.getdefaultencoding`)
:param incoming: Text's current enc... | 1,313 |
def _scan(fin):
"""Scan a clustal format MSA file and yield tokens.
The basic file structure is
begin_document
header?
(begin_block
(seq_id seq seq_index?)+
match_line?
end_block)*
end_document
... | 1,314 |
def create_source_location_str(frame, key):
"""Return string to use as source location key
Keyword arguments:
frame -- List of frame records
key -- Key of the frame with method call
Takes frame and key (usually 1, since 0 is the frame in which getcurrentframe() was called)
Extr... | 1,315 |
def uv_lines(reglist, uv='uv', sty={}, npoints=1001, inf=50., eps=1e-24):
"""
"""
for reg in reglist:
for b in reg.blocks:
smin, smax, ds = -5., 25., 1.
vals = np.arange(smin, smax, ds)
cm = plt.cm.gist_rainbow
cv = np.linspace(0,1,len(vals))
for i in range(len(vals)):
style1 = dict(c=cm(cv[i]),... | 1,316 |
def test_init_handle_validation_error(
cd_tmp_path: Path,
cp_config: CpConfigTypeDef,
mocker: MockerFixture,
) -> None:
"""Test init handle ValidationError."""
mocker.patch(
f"{MODULE}.Runway",
spec=Runway,
spec_set=True,
init=Mock(side_effect=ValidationError([], Mock... | 1,317 |
def printPageHeader(pageName, pageTitle="", initScript=None, otherHeaders=[],
hideSavedSearches=False, hideNamedBugs=False,
showSavedSearchSaver=False, showNamedBugSaver=False, bugView=None,
bugid=None):
"""
Print out the standard page headers.
"""... | 1,318 |
def rand_initialisation(X, n_clusters, seed, cste):
""" Initialize vector centers from X randomly """
index = [];
repeat = n_clusters;
# Take one index
if seed is None:
idx = np.random.RandomState().randint(X.shape[0]);
else:
idx = np.random.RandomState(seed+cste).randint(X... | 1,319 |
def l2_hinge_loss(X, Y, W, C, N):
"""
Computes the L2 regularized Hinge Loss function, and its gradient over a mini-batch of data.
:param X: The feature matrix of size (F+1, N).
:param Y: The label vector of size (N, 1).
:param W: The weight vector of size (F+1, 1).
:param C: A hyperparameter of... | 1,320 |
def args():
"""Setup argument Parsing."""
parser = argparse.ArgumentParser(
usage='%(prog)s',
description='OpenStack Inventory Generator',
epilog='Inventory Generator Licensed "Apache 2.0"')
parser.add_argument(
'-f',
'--file',
help='Inventory file.',
... | 1,321 |
def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
"""
Raise an assertion if two objects are not equal up to desired precision.
The test verifies identical shapes and verifies values with
abs(desired-actual) < 0.5 * 10**(-decimal)
Given two array_like objects, check that the... | 1,322 |
def train_val_test_split(dataframe, val_ratio=.2, test_ratio=.2):
"""
Takes a dataframe and returns a random train/validate/test split
param test_ratio: the percentage of data to put into the test portion
- must be between 0.0 and 1.0
param val_ratio: the percentage of data to put into the val... | 1,323 |
def diff_pf_potential(phi):
""" Derivative of the phase field potential. """
return phi**3-phi | 1,324 |
def process_image(image, label, height=224, width=224):
""" Resize the images to a fixes input size,
and rescale the input channels to a range of [-1,1].
Args:
image: "tensor, float32", image input.
label: "tensor, int64", image label.
height: "int64", (224, 224, 3) -> (height, 224, 3).
wid... | 1,325 |
def run_server(hostname, port, commandQueue):
"""
Runs a server and listen for commands sent to the crazyflie
:param hostname:
:param port:
:param commandQueue:
:return:
"""
server = HTTPServer((hostname, port), CrazyHandler)
server.commandQueue = commandQueue
server.serve_forev... | 1,326 |
def astz(data):
"""
[X] ASTZ - Request actual status
STBY (dyno stopping) or
SSIM (road load) or
SMTR (constant speed) or
SRPM (constant RPM) or
SKZK (constant motor force)
"""
responds = data.split(" ")
if len(responds) > 2:
if responds... | 1,327 |
def get_peer_snappi_chassis(conn_data, dut_hostname):
"""
Get the Snappi chassis connected to the DUT
Note that a DUT can only be connected to a Snappi chassis
Args:
conn_data (dict): the dictionary returned by conn_graph_fact.
Example format of the conn_data is given below:
{u... | 1,328 |
def gen_hwpc_report():
"""
Return a well formated HWPCReport
"""
cpua = create_core_report('1', 'e0', '0')
cpub = create_core_report('2', 'e0', '1')
cpuc = create_core_report('1', 'e0', '2')
cpud = create_core_report('2', 'e0', '3')
cpue = create_core_report('1', 'e1', '0')
cpuf = cr... | 1,329 |
def special_crossentropy(y_true, y_pred):
"""特殊的交叉熵
"""
task = K.cast(y_true < 1.5, K.floatx())
mask = K.constant([[0, 0, 1, 1, 1]])
y_pred_1 = y_pred - mask * 1e12
y_pred_2 = y_pred - (1 - mask) * 1e12
y_pred = task * y_pred_1 + (1 - task) * y_pred_2
y_true = K.cast(y_true, 'int32')
... | 1,330 |
def nonensembled_map_fns(data_config):
"""Input pipeline functions which are not ensembled."""
common_cfg = data_config.common
map_fns = [
data_transforms.correct_msa_restypes,
data_transforms.add_distillation_flag(False),
data_transforms.cast_64bit_ints,
data_transforms.squ... | 1,331 |
def _getMark(text):
"""
Return the mark or text entry on a line. Praat escapes double-quotes
by doubling them, so doubled double-quotes are read as single
double-quotes. Newlines within an entry are allowed.
"""
line = text.readline()
# check that the line begins with a valid entry type
... | 1,332 |
def get_screen_resolution_str():
"""
Get a regexp like string with your current screen resolution.
:return: String with your current screen resolution.
"""
sizes = [
[800, [600]],
[1024, [768]],
[1280, [720, 768]],
[1366, [768]],
[1920, [1080, 1200]],
]
... | 1,333 |
def page_body_id(context):
"""
Get the CSS class for a given page.
"""
path = slugify_url(context.request.path)
if not path:
path = "home"
return "page-{}".format(path) | 1,334 |
def main():
"""Go Main Go"""
mesosite = get_dbconn('mesosite')
mcursor = mesosite.cursor()
print(('%5s %5s %5s %5s %5s %5s %5s %5s'
) % ("NWSLI", "LOW", "ACTN", "BANK",
"FLOOD", "MOD", "MAJOR", "REC"))
net = sys.argv[1]
nt = NetworkTable(net)
for sid in nt.sts:
... | 1,335 |
def check_product_out_of_range_formatter_ref_error_task(infiles, outfile, ignored_filter):
"""
{path[2][0]} when len(path) == 1
"""
with open(outfile, "w") as p:
pass | 1,336 |
def load_centers(network, name, eps):
"""Load values of centers from the specified network by name.
:param network: Network to load center values
:param name: Name of parameter with centers
:return: Normalized centers
"""
assert name in network.params.keys(), 'Cannot find name: {} in params'.f... | 1,337 |
def naive_sort_w_matrix(array):
"""
:param array: array to be sorted
:return: a sorted version of the array, greatest to least, with the appropriate permutation matrix
"""
size = len(array)
def make_transposition(i, j):
mat = np.identity(size)
mat[i, i] = 0
mat[j, j] ... | 1,338 |
def plot_route(cities, route, name='diagram.png', ax=None):
"""Отрисовка маршрута"""
mpl.rcParams['agg.path.chunksize'] = 10000
if not ax:
fig = plt.figure(figsize=(5, 5), frameon=False)
axis = fig.add_axes([0, 0, 1, 1])
axis.set_aspect('equal', adjustable='datalim')
plt.ax... | 1,339 |
def sync(event, context):
"""Sync projects with cloud datastore."""
del event, context #unused
client = ndb.Client()
with client.context():
github_client = Github(get_access_token())
repo = github_client.get_repo('google/oss-fuzz')
projects = get_projects(repo)
sync_projects(projects) | 1,340 |
def aes_cbc_mac(
key: bytes, b: bytes, iv: bytes=None,
pad=False
) -> bytes:
"""
AES CBC-MAC.
:param key: The verification key.
:param b: The buffer to be authenticated.
:param iv: The initial vector.
:param pad: Whether to apply PKCS-7 padding to the buffer.
:return: A vali... | 1,341 |
def seamus():
"""
Preview for Seamus page
"""
context = make_context()
# Read the books JSON into the page.
with open('www/static-data/books.json', 'rb') as readfile:
books_data = json.load(readfile)
books = sorted(books_data, key=lambda k: k['title'])
# Harvest long tag na... | 1,342 |
def get_model_opt(model_path):
""" Get the options to initialize a model evaluator
"""
opt_path = os.path.dirname(model_path.rstrip('/')) + '/opt.json'
# load the options used while training the model
opt = json.load(open(opt_path))
opt = dotdict(opt)
opt.load_weights_folder = model_path
... | 1,343 |
def resolve_alias(term: str) -> str:
"""
Resolves search term aliases (e.g., 'loc' for 'locations').
"""
if term in ("loc", "location"):
return "locations"
elif term == "kw":
return "keywords"
elif term == "setting":
return "setting"
elif term == "character":
... | 1,344 |
def to_number(value: Union[Any, Iterable[Any]], default: Any = math.nan) -> Union[NumberType, List[NumberType]]:
""" Attempts to convert the passed object to a number.
Returns
-------
value: Scalar
* list,tuple,set -> list of Number
* int,float -> int, float
* str -> int, float
* generic -> floa... | 1,345 |
def save_snapshot(graph,
epoch,
result_subdir,
graph_ema=None,
model_name=None,
is_best=False,
state=None):
"""
Save snapshot
:param graph: model
:type graph: torch.nn.Module
:param epoch: ep... | 1,346 |
def secretValue(value=None, bits=64):
"""
A single secret value
bits: how many bits long the value is
value: if not None, then a specific (concrete or symbolic) value which this value takes on
"""
return AbstractNonPointer(bits=bits, value=value, secret=True) | 1,347 |
def reload_api():
"""
Reinitialize the API client with a new API key. This method may block if no
valid keys are currently available.
"""
global API
API = TwitterSearch(*KEYS.advance().splitlines()) | 1,348 |
def year_frac(d_end, d_start=0,
dates_string=False, trading_calendar=True):
""" :returns year fraction between 2 (business) dates
:params dates are datetimes, if string then insert dates_string=True
"""
delta_days = days_between(d_end, d_start, dates_string, trading_calendar)
year... | 1,349 |
def _indent(s):
# type: (str) -> int
"""
Compute the indentation of s, or None of an empty line.
Example:
>>> _indent("foo")
0
>>> _indent(" bar")
4
>>> _indent(" ")
>>> _indent("")
"""
t = s.lstrip()
return len(s) - len(t) if t else None | 1,350 |
def normalize_middle_high_german(
text: str,
to_lower_all: bool = True,
to_lower_beginning: bool = False,
alpha_conv: bool = True,
punct: bool = True,
):
"""Normalize input string.
to_lower_all: convert whole text to lowercase
alpha_conv: convert alphabet to canonical form
punct: re... | 1,351 |
def _convert_format(input_format, reverse=0):
"""Convert FITS format spec to record format spec. Do the opposite
if reverse = 1.
"""
fmt = input_format
(repeat, dtype, option) = _parse_tformat(fmt)
if reverse == 0:
if dtype in _fits2rec.keys(): # FITS form... | 1,352 |
def _module(root_pkg, name):
"""Imports the module, catching `ImportError`
Args:
root_pkg (str): top level package
name(str): unqualified name of the module to be imported
Returns:
module: imported module
"""
def _match_exc(e):
return re.search(
' {}$|{}... | 1,353 |
def clean_elec_demands_dirpath(tmp_path: Path) -> Path:
"""Create a temporary, empty directory called 'processed'.
Args:
tmp_path (Path): see https://docs.pytest.org/en/stable/tmpdir.html
Returns:
Path: Path to a temporary, empty directory called 'processed'.
"""
dirpath = tmp_path... | 1,354 |
def get_file_from_project(proj: Project, file_path):
"""
Returns a file object (or None, if error) from the HEAD of the default
branch in the repo. The default branch is usually 'main'.
"""
try:
file = proj.files.raw(file_path=file_path, ref=proj.default_branch)
LintReport.trace(f'Ac... | 1,355 |
def test_dataset_compute_response(fractal_compute_server):
""" Tests that the full compute response is returned when calling Dataset.compute """
client = ptl.FractalClient(fractal_compute_server)
# Build a dataset
ds = ptl.collections.Dataset("ds",
client,
... | 1,356 |
def get_logger_by_name(name: str):
"""
Gets the logger given the type of logger
:param name: Name of the value function needed
:type name: string
:returns: Logger
"""
if name not in logger_registry.keys():
raise NotImplementedError
else:
return logger_registry[name] | 1,357 |
def gen_appr_():
""" 16 consonants """
appr_ = list(voiced_approximant)
appr_.extend(unvoiced_approximant)
appr_.extend(voiced_lateral_approximant)
return appr_ | 1,358 |
def convert_unit(
to_convert: Union[float, int, Iterable[Union[float, int, Iterable]]],
old_unit: Union[str, float, int],
new_unit: Union[str, float, int],
) -> Union[float, tuple]:
"""
Convert a number or sequence of numbers from one unit to another.
If either unit is a number it will be tre... | 1,359 |
def image_preprocess(image, image_size: Union[int, Tuple[int, int]]):
"""Preprocess image for inference.
Args:
image: input image, can be a tensor or a numpy arary.
image_size: single integer of image size for square image or tuple of two
integers, in the format of (image_height, image_width).
Ret... | 1,360 |
def create_cluster_meta(cluster_groups):
"""Return a ClusterMeta instance with cluster group support."""
meta = ClusterMeta()
meta.add_field('group')
cluster_groups = cluster_groups or {}
data = {c: {'group': v} for c, v in cluster_groups.items()}
meta.from_dict(data)
return meta | 1,361 |
def dict_has_key_and_value_include_str(the_dict,key,str):
"""指定字典中包括键,并且键值包含某个字符片段"""
if the_dict.__contains__(key):
if str in the_dict[key]:
return True
return False | 1,362 |
def get_confinement_values_by_hand():
"""MSDs in this dataset are too incomplete/noisy to be very confident of
any automatic method to call confinement levels. this function allows you
to specify them by hand."""
confinements = {}
cmap = cmap_from_list(mscd_unbound_only.reset_index()['meiosis'].uniq... | 1,363 |
def get_list_size(ls:List[Any]) -> float:
"""Return size in memory of a list and all its elements"""
return reduce(lambda x, y: x + y, (sys.getsizeof(v) for v in ls), 0) + sys.getsizeof(ls) | 1,364 |
def get_wrapper_depth(wrapper):
"""Return depth of wrapper function."""
return wrapper.__wrapped__.__wrappers__ + (1 - wrapper.__depth__) | 1,365 |
def get_formsets(what, extra=0, **kwargs):
"""Returns a list of formset instances"""
try:
related_fields = {}
relation_config = get_form_config('Relations', **kwargs)
operation = 'create' if 'Create' in what else 'update'
for relation in relation_config:
field_config... | 1,366 |
def round_even(number):
"""Takes a number and returns it rounded even"""
# decimal.getcontext() -> ROUND_HALF_EVEN is default
return Decimal(number).quantize(0) | 1,367 |
def mquiver(xs, ys, v, **kw):
"""wrapper function for quiver
xs and ys are arrays of x's and y's
v is a function R^2 -> R^2, representing vector field
kw are passed to quiver verbatim"""
X,Y = np.meshgrid(xs, ys)
V = [[v(x,y) for x in xs] for y in ys]
VX = [[w[0] for w in q] for q in V]
... | 1,368 |
def _build_conditional_single(cond, vals, model_cls=None):
"""
Builds the single conditional portion of a where clause.
Args:
cond (()/[]): The tuple/list containing the elements for a single
conditional statement. See Model.query_direct() docs for full details
on the format.
v... | 1,369 |
def isNullOutpoint(tx):
"""
isNullOutpoint determines whether or not a previous transaction output point
is set.
"""
nullInOP = tx.txIn[0].previousOutPoint
if (
nullInOP.index == wire.MaxUint32
and nullInOP.hash == ByteArray(0, length=HASH_SIZE)
and nullInOP.tree == wire.... | 1,370 |
def cmyk_to_rgb(c, m, y, k):
"""
"""
r = (1.0 - c) * (1.0 - k)
g = (1.0 - m) * (1.0 - k)
b = (1.0 - y) * (1.0 - k)
return r, g, b | 1,371 |
def get_by_id(group_id: int, db: Session = Depends(get_db), member: MemberModel = Depends(get_active_member)):
"""Get group by id"""
item = service.get_by_id(db, group_id)
return item | 1,372 |
def get_jasperdr(version,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create Jasper DR model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
... | 1,373 |
def productionadjustment():
# TODO: get route to display
"""Renders the home page."""
return render_template(
'productionadjustment.html',
title='Production Adjustment',
year=datetime.now().year,
wellsel=bigagg
) | 1,374 |
def upload_directory_targetid(token, local_dir, target_folder_id, skip_existed=False, show_skip_info=True, fencrypt=None):
"""
token: request_token
local_dir: 需要上传的文件夹, 如r"d:\to_be_uploaded"
target_folder_path: 上传的目标位置的父文件夹id
这个函数不是递归函数,使用os.walk mkdir_p upload完成上传任务
如果目标文件夹已经存在,会pri... | 1,375 |
def thumbnail_download(data, k, url, mongo):
"""
缩略图下载
:return: 返回信息
"""
if data['thumbnail_urls'] is not None:
logging.debug(r'开始下载缩略图: %s' % data['thumbnail_urls'])
mongo.update(url, COD.REDTHU)
try:
referer = url if k != '163' else None # 网易的图片不加refere... | 1,376 |
def inMandelSet(x: int, y: int, max_iteration: int) -> int:
"""inMandelSet determines if complex(x,y) is in the mandelbrot set."""
z = 0
for k in range(max_iteration):
z = z ** 2 + complex(x,y)
if abs(z) > 2: return k
return k | 1,377 |
def pytest_configure(config):
"""Configure pytest options."""
# Fixtures
for fixture in ('matplotlib_config',):
config.addinivalue_line('usefixtures', fixture)
warning_lines = r"""
error::
ignore:.*`np.bool` is a deprecated alias.*:DeprecationWarning
ignore:.*String decoding changed... | 1,378 |
def isBinaryPalindrome(num):
"""assumes num is an integer
returns True if num in binary form is a palindrome, else False"""
return str(bin(num))[2::] == str(bin(num))[:1:-1] | 1,379 |
def modify_last_edit(entry_id: int, database: str = None):
"""Updates the database to reflect the last time the given entry was changed
:param entry_id: an int representing the given entry
:param database: a Connection or str representing the database that is being modified
"""
db = connect(databas... | 1,380 |
def main():
"""The main CLI entry-point."""
import thermos.commands
import os,pip
options = docopt(__doc__, version=VERSION)
def create_structure():
app_name = options['<appname>']
if not os.path.exists(app_name):
os.makedirs(app_name)
os.chdir(os.getcwd(... | 1,381 |
def mprv_from_entropy(entropy: GenericEntropy,
passphrase: str,
lang: str,
xversion: bytes) -> bytes:
"""Return a BIP32 master private key from entropy."""
mnemonic = mnemonic_from_entropy(entropy, lang)
mprv = mprv_from_mnemonic(mnemonic, p... | 1,382 |
def analyze_audio(audio_filename, target_freq=TARGET_FREQS, win_size=5000, step=200, min_delay=BEEP_DURATION, sensitivity=250, verbose=True):
"""
Analyze the given audio file to find the tone markers, with the respective frequency and time position.
:param str audio_filename: The Audio filename to analyze to find t... | 1,383 |
def read_usgs_file(file_name):
"""
Reads a USGS JSON data file (from https://waterdata.usgs.gov/nwis)
Parameters
----------
file_name : str
Name of USGS JSON data file
Returns
-------
data : pandas DataFrame
Data indexed by datetime with columns named according... | 1,384 |
def action_about(sender):
"""Open the "About" view."""
about_view.present('sheet', hide_close_button=True) | 1,385 |
def get_cantus_firmus(notes):
"""
Given a list of notes as integers, will return the lilypond notes
for the cantus firmus.
"""
result = ""
# Ensure the notes are in range
normalised = [note for note in notes if note > 0 and note < 18]
if not normalised:
return result
# Set th... | 1,386 |
def get_wildcard_values(config):
"""Get user-supplied wildcard values."""
return dict(wc.split("=") for wc in config.get("wildcards", [])) | 1,387 |
def predict(model_filepath, config, input_data):
"""Return prediction from user input."""
# Load model
model = Model.load(model_filepath + config['predicting']['model_name'])
# Predict
prediction = int(np.round(model.predict(input_data), -3)[0])
return prediction | 1,388 |
def Print_Beeper(scanDIM=1):
"""Prints pv to copy/paste into the beeper"""
branch=CheckBranch()
if branch == "c":
print("29idcEA:det1:Acquire")
scanIOC=BL_ioc()
pv="29id"+scanIOC+":scan"+str(scanDIM)+".FAZE"
print(pv)
print("ID29:BusyRecord") | 1,389 |
def main() -> int:
"""Runs protoc as configured by command-line arguments."""
parser = _argument_parser()
args = parser.parse_args()
if args.plugin_path is None and args.language not in BUILTIN_PROTOC_LANGS:
parser.error(
f'--plugin-path is required for --language {args.language}')... | 1,390 |
def gauss3D_FIT(xyz, x0, y0, z0, sigma_x, sigma_y, sigma_z):
"""
gauss3D_FIT((x,y,z),x0,y0,z0,sigma_x,sigma_y,sigma_z)
Returns the value of a gaussian at a 2D set of points for the given
standard deviations with maximum normalized to 1.
The Gaussian axes are assumed to be 90 degrees from each o... | 1,391 |
async def tell(message: str) -> None:
"""Send a message to the user.
Args:
message: The message to send to the user.
"""
return await interaction_context().tell(message) | 1,392 |
def PGetDim (inFFT):
"""
Get dimension of an FFT
returns array of 7 elements
* inFFT = Python Obit FFT
"""
################################################################
# Checks
if not PIsA(inFFT):
raise TypeError("inFFT MUST be a Python Obit FFT")
return Obit.FFTGet... | 1,393 |
def score_detail(fpl_data):
"""
convert fpl_data into Series
Index- multi-index of team, pos, player, opp, minutes
"""
l =[]
basic_index = ["player", "opp", "minutes"]
for i in range(len(fpl_data["elements"])):
ts=achived_from(fpl_data, i, True)
name = (fpl_data["elements"][i... | 1,394 |
def edition_view(measurement, workspace, exopy_qtbot):
"""Start plugins and add measurements before creating the execution view.
"""
pl = measurement.plugin
pl.edited_measurements.add(measurement)
measurement.root_task.add_child_task(0, BreakTask(name='Test'))
item = MeasurementEditorDockItem(... | 1,395 |
def addPlayer(name, addr_text, address, ad):
# pylint: disable=unused-argument
# address is part of call back
"""Add the player name and mac address to players global variable
and the name and rssi (if present) to on-screen list."""
rssi = ad.rssi if ad else None
players.append((name, addr_... | 1,396 |
def menu_items():
""" Add a menu item which allows users to specify their session directory
"""
def change_session_folder():
global session_dir
path = str(QtGui.QFileDialog.getExistingDirectory(None,
'Browse to new session folder -'))
... | 1,397 |
def calculate_pair_energy_np(coordinates, i_particle, box_length, cutoff):
"""
Calculates the interaction energy of one particle with all others in system.
Parameters:
```````````
coordinates : np.ndarray
2D array of [x,y,z] coordinates for all particles in the system
i_part... | 1,398 |
def inside_loop(iter):
"""
>>> inside_loop([1,2,3])
3
>>> inside_loop([])
Traceback (most recent call last):
...
UnboundLocalError: local variable 'i' referenced before assignment
"""
for i in iter:
pass
return i | 1,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.