content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def save_figure(path: str) -> None:
"""Saves the current figure to the specified path"""
logging.info(f'Saving image: {path}')
plt.savefig(path, dpi=300, bbox_inches='tight') | 5,332,800 |
def merge_dictionaries(dict1, dict2):
""" Merges two dictionaries handling embedded lists and
dictionaries.
In a case of simple type, values from dict1 are preserved.
Args:
dict1, dict2 dictionaries to merge
Return merged dictionaries
"""
for k2, v2 in dict2.items():
if k2 no... | 5,332,801 |
def build(model_def, model_name, optimizer, loss_name, custom_objects=None):
"""build keras model instance in FastEstimator
Args:
model_def (function): function definition of tf.keras model or path of model file(h5)
model_name (str, list, tuple): model name(s)
optimizer (str, optimizer,... | 5,332,802 |
def check_audio_file(audio_file):
"""
Check if the audio file contents and format match the needs of the speech service. Currently we only support
16 KHz, 16 bit, MONO, PCM audio format. All others will be rejected.
:param audio_file: file to check
:return: audio duration, if file matches the format... | 5,332,803 |
def uniform(name):
"""
Calls the findUniform function from util.py to return the uniform bounds for the given molecule.
Input: name of molecule
Output: array of length [2] with the upper and lower bounds for the uniform prior
"""
prior = findUniform(name, 'd_h')
return prior | 5,332,804 |
def merge_two_dicts(x, y):
"""Merges two dicts, returning a new copy."""
z = x.copy()
z.update(y)
return z | 5,332,805 |
def num_utterances(dataset: ds.DatasetSplit):
"""Returns the total number of utterances in the dataset."""
return sum([len(interaction) for interaction in dataset.examples]) | 5,332,806 |
def __virtual__():
"""
Only return if requests and boto are installed.
"""
if HAS_LIBS:
return __virtualname__
else:
return False | 5,332,807 |
def register():
"""Register user"""
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
username = request.form.get("username")
email = request.form.get("email")
password = request.form.get("password")
# Logs user into database
... | 5,332,808 |
def _csd_multitaper(X, sfreq, n_times, window_fun, eigvals, freq_mask, n_fft,
adaptive):
"""Compute cross spectral density (CSD) using multitaper module.
Computes the CSD for a single epoch of data.
Parameters
----------
X : ndarray, shape (n_channels, n_times)
The time... | 5,332,809 |
def test_list_base64_binary_length_nistxml_sv_iv_list_base64_binary_length_1_2(mode, save_output, output_format):
"""
Type list/base64Binary is restricted by facet length with value 5.
"""
assert_bindings(
schema="nistData/list/base64Binary/Schema+Instance/NISTSchema-SV-IV-list-base64Binary-leng... | 5,332,810 |
def _build_tmp_access_args(method, ip, ttl, port, direction, comment):
"""
Builds the cmd args for temporary access/deny opts.
"""
opt = _get_opt(method)
args = "{0} {1} {2}".format(opt, ip, ttl)
if port:
args += " -p {0}".format(port)
if direction:
args += " -d {0}".format(d... | 5,332,811 |
def print_useful_remote_info(manager, experiment_name) -> None:
""" Once the local process of the remote run is over,
this information is shown to the user.
"""
logger.info("###########################################################")
logger.info(" IMPORTANT")
logger.info("... | 5,332,812 |
def add_two_values(value1, value2):
""" Adds two integers
Arguments:
value1: first integer value e.g. 10
value2: second integer value e.g. 2
"""
return value1 + value2 | 5,332,813 |
def test_four_snps_two_independent_trees_perfect_two_snps_not_causal():
"""
Two independent causal SNPs each sharing a haplotype with another, different SNP
via perfect phenotype associations plus an extra non-causal SNP (so five SNPs total)
Y = 0.5 * ( X1 && X3 ) + 0.5 * ( X2 && X4 )
This should yi... | 5,332,814 |
def init_filters(namespace=None):
"""Filters have an optional init method that runs before the site
is built.
"""
if namespace is None:
namespace = bf.config.filters
for name, filt in list(namespace.items()):
if "mod" in filt \
and type(filt.mod).__name__ == "module"\... | 5,332,815 |
def combine_nearby_breakends(events, distance=5000):
"""
1d clustering, prioritizing assembled breakpoint coords
"""
breakends = []
positions = get_positions(events)
for (chrom, orientation), cur_events in positions.groupby(["chrom", "orientation"]):
cur_events = cur_events.sort_value... | 5,332,816 |
def label_list(repo=None):
"""Dump labels within the given repo(s)."""
api = github.api(config=None) # TODO: config object
for idx, reponame in enumerate(repo or []):
if idx:
click.echo('')
dump_labels(api, reponame) | 5,332,817 |
def get_mongo_database(connection, database_name):
""" Access the database
Args:
connection (MongoClient): Mongo connection to the database
database_name (str): database to be accessed
Returns:
Database: the Database object
"""
try:
return connection.get_database(da... | 5,332,818 |
def make_mappings() -> Dict[str, Callable[[], None]]:
"""サンプル名と実行する関数のマッピングを生成します"""
# noinspection PyDictCreation
m = {}
extlib.regist_modules(m)
return m | 5,332,819 |
def S(state):
"""Stringify state
"""
if state == State.IDLE: return "IDLE"
if state == State.TAKING_OFF: return "TAKING_OFF"
if state == State.HOVERING: return "HOVERING"
if state == State.WAITING_ON_ASSIGNMENT: return "WAITING_ON_ASSIGNMENT"
if state == State.FLYING: return "FLYING"
if ... | 5,332,820 |
def sram_cacti(
mem_sz_bytes=16, # in byte
origin_config_file=None,
target_config_file=None,
result_file=None
):
"""
run the cacti with input configuration, work for SRAM, whose size is either calculated to match the bw or pre-specified
"""
original = open(origin_config_file, 'r')
ta... | 5,332,821 |
def eval_classif_cross_val_roc(clf_name, classif, features, labels,
cross_val, path_out=None, nb_steps=100):
""" compute mean ROC curve on cross-validation schema
http://scikit-learn.org/0.15/auto_examples/plot_roc_crossval.html
:param str clf_name: name of selected classifi... | 5,332,822 |
def trace_get_watched_net(trace, i):
"""
trace_get_watched_net(Int_trace trace, unsigned int i) -> Int_net
Parameters
----------
trace: Int_trace
i: unsigned int
"""
return _api.trace_get_watched_net(trace, i) | 5,332,823 |
def dist_batch_tasks_for_all_layer_mdl_vs_adapted_mdl(
mdl: nn.Module,
spt_x: Tensor, spt_y: Tensor, qry_x: Tensor, qry_y: Tensor,
layer_names: list[str],
inner_opt: DifferentiableOptimizer,
fo: bool,
nb_inner_train_steps: int,
criterion: nn.Module,
metric... | 5,332,824 |
async def send_image_to_room(client, room_id, image):
"""Send image to single room.
Arguments:
---------
client (nio.AsyncClient): The client to communicate with Matrix
room_id (str): The ID of the room to send the message to
image (str): file name/path of image
"""
logger.debug(f"send... | 5,332,825 |
def on_connect(client, _userdata, _flags, _respons_code):
""" MQTT on connect """
logger.info('MQTT Connected. Subscribe "%s"', MQTT_TOPIC)
client.subscribe(MQTT_TOPIC) | 5,332,826 |
def simplify(ply_path, save_ply_path=None, target_perc=0.01, meshlabserver_path="meshlabserver"):
""" simplify mesh (load ply_path, simplify, and save to save_ply_path)
"""
script = \
"""
<!DOCTYPE FilterScript>
<FilterScript>
<filter name="Simplification: Quadric Edge Collapse Decimation">
<... | 5,332,827 |
def adjust_payload(tree: FilterableIntervalTree,
a_node: FilterableIntervalTreeNode,
adjustment_interval: Interval,
adjustments: dict,
filter_vector_generator: Callable[[dict], int]=None)\
-> List[FilterableIntervalTreeNode]:
"""
... | 5,332,828 |
def _read_cropped() -> Tuple[np.ndarray, np.ndarray]:
"""Reads the cropped data and labels.
"""
print('\nReading cropped images.')
path_cropped = os.path.join(DATA_FOLDER, FOLDER_CROPPED)
result = _recursive_read_cropped(path_cropped)
print('Done reading cropped images.')
return result | 5,332,829 |
def get_max(data, **kwargs):
"""
Assuming the dataset is loaded as type `np.array`, and has shape
(num_samples, num_features).
:param data: Provided dataset, assume each row is a data sample and \
each column is one feature.
:type `np.ndarray`
:param kwargs: Dictionary of differential priv... | 5,332,830 |
def find_u_from_v(matrix, v, singular_value):
"""
Finds the u column vector of the U matrix in the SVD UΣV^T.
Parameters
----------
matrix : numpy.ndarray
Matrix for which the SVD is calculated
v : numpy.ndarray
A column vector of V matrix, it is the eigenvector of the Gramian ... | 5,332,831 |
def transform(dataset, perm_idx, model, view):
"""
for view1 utterance, simply encode using view1 encoder
for view 2 utterances:
- encode each utterance, using view 1 encoder, to get utterance embeddings
- take average of utterance embeddings to form view 2 embedding
"""
model.eval()
lat... | 5,332,832 |
def double(items: List[str]) -> List[str]:
"""
Returns a new list that is the input list, repeated twice.
"""
return items + items | 5,332,833 |
def system_from_problem(problem: Problem) -> System:
"""Extracts the "system" part of a problem.
Args:
problem: Problem description
Returns:
A :class:`System` object containing a copy of the relevant parts of the problem.
"""
return System(
id=problem.id,
name=proble... | 5,332,834 |
def get_service_endpoints(ksc, service_type, region_name):
"""Get endpoints for a given service type from the Keystone catalog.
:param ksc: An instance of a Keystone client.
:type ksc: :class: `keystoneclient.v3.client.Client`
:param str service_type: An endpoint service type to use.
:param str reg... | 5,332,835 |
def test_bubblesort_order():
"""Check that bubble sort works.
"""
length = 5
test_list = [(length - 1 - i) for i in range(length)]
ordered_list = [i for i in range(length)]
util.bubblesort(test_list)
assert ordered_list == test_list | 5,332,836 |
def get_task_for_node(node_id):
""" Get a new task or previously assigned task for node """
# get ACTIVE task that was previously assigned to this node
query = Task.query.filter_by(node_id=node_id).filter_by(status=TaskStatus.ACTIVE)
task = query.first()
if task:
return task
node = Nod... | 5,332,837 |
def save_fields(df):
"""List of Well model from dataframe"""
# load fields from db
start = time.time()
counter = 0
for index, row in enumerate(df['name']):
field_name = df['name'][index]
if field_name.strip() != '' and field_name is not None:
field, created = OilField.obj... | 5,332,838 |
async def test_edit_message_live_location_by_user(bot: Bot):
""" editMessageLiveLocation method test """
from .types.dataset import MESSAGE_WITH_LOCATION, LOCATION
msg = types.Message(**MESSAGE_WITH_LOCATION)
location = types.Location(**LOCATION)
# editing user's message
async with FakeTelegram... | 5,332,839 |
def loadProfileInfo(profileInfoPath, remote=None):
"""
Load profile information from a profileInfo.py file, set a default application information
file, and set the profile information's host if the application is running remotely
@param remote: Remote environment information if a remote host is passed to the p... | 5,332,840 |
def open_process(verbose, args, outputs):
""" Run the given arguments as a subprocess. Time out after TIMEOUT
seconds and report failures or stdout. """
report_output(outputs["stdout"],
verbose, "Writing", args)
proc = None
if outputs["stderr"] is not None:
try:
... | 5,332,841 |
def cik_list():
"""Get CIK list and use it as a fixture."""
return UsStockList() | 5,332,842 |
def get_eval_config(hidden_dim,
max_input_length=None,
num_input_timesteps=None,
model_temporal_relations=True,
node_position_dim=1,
num_input_propagation_steps=None,
token_vocab_size=None,
... | 5,332,843 |
def service_start():
"""Connect grpc service
"""
while True:
try:
logger.debug('wait until triggered')
# wait until service-request triggered(eg. kws detected)
serviceflag.wait()
logger.debug('service starting...')
grpc_request()
... | 5,332,844 |
def classNew(u_id):
"""
Allow an ADMIN to create a new class (ADMIN ONLY)
Returns: none
"""
myDb, myCursor = dbConnect()
data = request.get_json()
createNewClass(myCursor, myDb, data)
dbDisconnect(myCursor, myDb)
return dumps({}) | 5,332,845 |
def show(width, similar_list, by_ratio, show_differences, _argv):
"""show matched images"""
check_type_width(width) # fail fast
# Process all images, show user each sequence one by one
for similar_pair in similar_list:
if not similar_pair is None:
images = compute_image_differen... | 5,332,846 |
def copy_func(f):
"""Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)."""
g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__,
argdefs=f.__defaults__,
closure=f.__closure__)
g = functools.update_wrapper(g, f)
g.__kwdef... | 5,332,847 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the Keba charging station sensors from config entry."""
keba: KebaKeContact = hass.data[DOMAIN][KEBA_CONNECTION]
entities: list[KebaSensor] = []
wallbox... | 5,332,848 |
def augment(img_list: list, hflip: bool = True, rot: bool = True) -> List[np.ndarray]:
"""
Augments the image inorder to add robustness to the model
@param img_list: The List of images
@param hflip: If True, add horizontal flip
@param rot: If True, add 90 degrees rotation
@return: A list of the ... | 5,332,849 |
def write_load_config(repo_dir, saved_state_path, changed_files=[]):
"""
Writes a .hhconfig that allows hh_client to launch hh_server from a saved
state archive.
repo_dir: Repository to run hh_server on
saved_state_path: Path to file containing saved server state
changed_files: list of strings
... | 5,332,850 |
def _neurovault_collections(parts, query):
"""Mocks the Neurovault API behind the `/api/collections/` path.
parts: the parts of the URL path after "collections"
ie [], ["<somecollectionid>"], or ["<somecollectionid>", "images"]
query: the parsed query string, e.g. {"offset": "15", "limit": "5"}
... | 5,332,851 |
def display_states():
""" Display the states"""
storage_states = storage.all(State)
return render_template('7-states_list.html', states=storage_states) | 5,332,852 |
def setAMtrajectoryFromPoints(phase, L, dL, timeline, overwriteInit = True, overwriteFinal = True):
"""
Define the AM value and it's time derivative trajectories as a linear interpolation between each points
Also set the initial / final values for L and dL to match the ones in the trajectory
:param pha... | 5,332,853 |
def recompress_folder(folders, path, extension):
"""Recompress folder"""
dest = runez.SYS_INFO.platform_id.composed_basename("cpython", path.name, extension=extension)
dest = folders.dist / dest
runez.compress(path, dest, logger=print)
return dest | 5,332,854 |
def guessMimetype(filename):
"""Return the mime-type for `filename`."""
path = pathlib.Path(filename) if not isinstance(filename, pathlib.Path) else filename
with path.open("rb") as signature:
# Since filetype only reads 262 of file many mp3s starting with null bytes will not find
# a head... | 5,332,855 |
def flag_last_object(seq):
""" Treat the last object in an iterable differently """
seq = iter(seq) # ensure this is an iterator
_a = next(seq)
for _b in seq:
yield _a, False
_a = _b
yield _a, True | 5,332,856 |
def collectMessages():
""" A generic stimulus invocation """
global rmlEngine
try:
stimuli = []
rawRequest = request.POST.dict
for rawKey in rawRequest.keys():
keyVal = rawKey
jsonPayload = json.loads(keyVal)
try:
actionID ... | 5,332,857 |
def filter_ptr_checks(props):
"""This function will filter out extra pointer checks.
Our support to primitives and overflow pointer checks is unstable and
can result in lots of spurious failures. By default, we filter them out.
"""
def not_extra_check(prop):
return extract_property_... | 5,332,858 |
def makeKeylistObj(keylist_fname, includePrivate=False):
"""Return a new unsigned keylist object for the keys described in
'mirror_fname'.
"""
keys = []
def Key(obj): keys.append(obj)
preload = {'Key': Key}
r = readConfigFile(keylist_fname, (), (), preload)
klist = []
for k in ke... | 5,332,859 |
def getwpinfo(id,wps):
"""Help function to create description of WP inputs."""
try:
wpmin = max([w for w in wps if 'loose' in w.lower()],key=lambda x: len(x)) # get loose WP with most 'V's
wpmax = max([w for w in wps if 'tight' in w.lower()],key=lambda x: len(x)) # get tight WP with most 'V's
info = f"... | 5,332,860 |
def build_word_dg(target_word, model, depth, model_vocab=None, boost_counter=None, topn=5):
""" Accept a target_word and builds a directed graph based on
the results returned by model.similar_by_word. Weights are initialized
to 1. Starts from the target_word and gets similarity results for it's children
... | 5,332,861 |
def train(network, num_epochs, train_fn, train_batches, test_fn=None,
validation_batches=None, threads=None, early_stop=np.inf,
early_stop_acc=False, save_epoch_params=False, callbacks=None,
acc_func=onehot_acc, train_acc=False):
"""
Train a neural network by updating its parameter... | 5,332,862 |
def sample_normal_gamma(mu, lmbd, alpha, beta):
""" https://en.wikipedia.org/wiki/Normal-gamma_distribution
"""
tau = np.random.gamma(alpha, beta)
mu = np.random.normal(mu, 1.0 / np.sqrt(lmbd * tau))
return mu, tau | 5,332,863 |
async def _common_discover_entities(
current_entity_platform: EntityPlatform,
config_entry: ConfigEntry,
source_objects: Iterable[TObject],
object_code_getter: Callable[[TObject], TIdentifier],
entity_cls: Type[TSensor],
final_config: Optional[ConfigType] = None,
... | 5,332,864 |
def _dice(terms):
"""
Returns the elements of iterable *terms* in tuples of every possible length
and range, without changing the order. This is useful when parsing a list of
undelimited terms, which may span multiple tokens. For example:
>>> _dice(["a", "b", "c"])
[('a', 'b', 'c'), ('a', 'b'),... | 5,332,865 |
def test_call_wiz_cli_when_open_raises_error(
mocker, mock_stdin, mock_open):
"""
Calling wiz-cli with an error is raised opening the JSON file.
"""
valid_json = '{"key": "value"}'
mock_open.side_effect = OSError
mock_stdin.name = '<stdin>'
mock_stdin.read.return_value = valid_json... | 5,332,866 |
def parse_date(val, format):
"""
Attempts to parse the given string date according to the
provided format, raising InvalidDateError in case of problems.
@param str val (e.g. 2014-08-12)
@param str format (e.g. %Y-%m-%d)
@return datetime.date
"""
try:
return datetime.strptime(val... | 5,332,867 |
def test_deserialize_dictionary_items():
"""
deserializes the given dictionary items from dictionary.
"""
values = DTO(bool_value='true', datetime_value='2000-10-20T12:10:43+00:00',
date_value='2004-11-01', invalid_date_value='2008-08-1',
list_value=['1', 'False '], li... | 5,332,868 |
def get_capture_dimensions(capture):
"""Get the dimensions of a capture"""
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
return width, height | 5,332,869 |
def run_system_optimization(des_vars, subsystems, scalers, loop_number):
"""Method to run the top-level system optimization based on the disciplinary surrogate models.
:param des_vars: definition of design variables
:type des_vars: dict
:param subsystems: definition of the disciplinary surrogate models... | 5,332,870 |
def analyze_lines(msarc, trcdict, slit, pixcen, order=2, function='legendre', maskval=-999999.9):
"""
.. todo::
This needs a docstring!
"""
# Analyze each spectral line
aduse = trcdict["aduse"]
arcdet = trcdict["arcdet"]
xtfits = trcdict["xtfit"]
ytfits = trcdict["ytfit"]
wma... | 5,332,871 |
def ad_modify_user_pwd_by_mail(user_mail_addr, old_password, new_password):
"""
通过mail修改某个用户的密码
:param user_mail_addr:
:return:
"""
conn = __ad_connect()
user_dn = ad_get_user_dn_by_mail(user_mail_addr)
result = conn.extend.microsoft.modify_password(user="%s" % user_dn, new_password="%s"... | 5,332,872 |
def write_flow(flow: np.ndarray, flow_file: str) -> None:
"""Write the flow in disk.
This function is modified from
https://lmb.informatik.uni-freiburg.de/resources/datasets/IO.py
Copyright (c) 2011, LMB, University of Freiburg.
Args:
flow (ndarray): The optical flow that will be saved.
... | 5,332,873 |
def batch_generator(batch_size=64):
"""
Generate the training batch.
"""
while True:
X_batch = []
y_batch = []
data = get_batch_data(batch_size)
for img_file, steer in data:
im = load_img(img_file)
im, steer = random_transform_img(im, steer)
... | 5,332,874 |
def markup_record(record_text, record_nr, modifiers, targets, output_dict):
""" Takes current Patient record, applies context algorithm,
and appends result to output_dict
"""
# Is used to collect multiple sentence markups. So records can be complete
context = pyConText.ConTextDocument()
# Split... | 5,332,875 |
def print_class_based_stats(class2stats):
""" Print statistics of class-based evaluation results """
for class_name in class2stats:
correct_count = np.sum(class2stats[class_name])
total_count = len(class2stats[class_name])
class_acc = np.average(class2stats[class_name])
class_acc... | 5,332,876 |
def del_account(account):
"""
function to delete a saved account
"""
account.delete_account() | 5,332,877 |
def write_pymods_from_comp(the_parsed_component_xml , opt , topology_model):
"""
Writes python modules for a component xml
"the_parsed_component_xml"
"""
global BUILD_ROOT
global DEPLOYMENT
global VERBOSE
parsed_port_xml_list = []
parsed_serializable_xml_list = []
#uses the ... | 5,332,878 |
def get_file_name(file_name):
"""
Returns a Testsuite name
"""
testsuite_stack = next(iter(list(filter(lambda x: file_name in x.filename.lower(), inspect.stack()))), None)
if testsuite_stack:
if '/' in testsuite_stack.filename:
split_character = '/'
else:
sp... | 5,332,879 |
def set_defaults(project=None, connection=None):
"""Set defaults either explicitly or implicitly as fall-back.
Uses the arguments to call the individual default methods.
:type project: string
:param project: Optional. The name of the project to connect to.
:type connection: :class:`gcloud.pubsub.... | 5,332,880 |
def Hcolloc(outf, (prefixes,topics,segments)):
"""this is the regular colloc grammar.
it ignores topics.
It generates words via two levels of hierarchy (as a control for the HT models)."""
outf.write("1 1 Collocs --> Collocs Colloc\n")
for prefix in prefixes:
outf.write("1 1 Collocs --... | 5,332,881 |
def track_edge_matrix_by_spt(batch_track_bbox, batch_track_frames, history_window_size=50):
"""
:param batch_track_bbox: B, M, T, 4 (x, y, w, h)
:return:
"""
B, M, T, _ = batch_track_bbox.size()
batch_track_xy = batch_track_bbox[:, :, :, :2]
batch_track_wh = batch_track_bbox[:, :, :, 2:]
... | 5,332,882 |
def _file(space, fname, flags=0, w_ctx=None):
""" file - Reads entire file into an array
'FILE_USE_INCLUDE_PATH': 1,
'FILE_IGNORE_NEW_LINES': 2,
'FILE_SKIP_EMPTY_LINES': 4,
'FILE_NO_DEFAULT_CONTEXT': 16,
"""
if not is_in_basedir(space, 'file', fname):
space.ec.warn("... | 5,332,883 |
def prepare_features(tx_nan, degree, mean_nan=None, mean=None, std=None):
"""Clean and prepare for learning. Mean imputing, missing value indicator, standardize."""
# Get column means, if necessary
if mean_nan is None: mean_nan = np.nanmean(tx_nan,axis=0)
# Replace NaNs
tx_val = np.where(np.isnan(... | 5,332,884 |
def _write_matt2(model, name, mids, nmaterials, op2, op2_ascii, endian):
"""writes the MATT2"""
#Record - MATT2(803,8,102)
#Word Name Type Description
#1 MID I Material identification number
#2 TID(15) I TABLEMi entry identification numbers
#17 UNDEF None
key = (803, 8, 102)
nfields = 17... | 5,332,885 |
def process_gen(job_obj, gen_log_loc, gen_log_name):
"""
Runs after a rocoto workflow has been generated
Checks to see if an error has occurred
"""
logger = logging.getLogger('BUILD/PROCESS_GEN')
gen_log = f'{gen_log_loc}/{gen_log_name}'
error_string = 'ERROR'
error_msg = 'err_msg'
g... | 5,332,886 |
def all_subclasses(cls):
"""Returns all known (imported) subclasses of a class."""
return cls.__subclasses__() + [g for s in cls.__subclasses__()
for g in all_subclasses(s)] | 5,332,887 |
def _find_popular_codon(aa):
"""
This function returns popular codon from a 4+ fold degenerative codon.
:param aa: dictionary containing amino acid information.
:return:
"""
codons = [c[:2] for c in aa["codons"]]
counts = []
for i in range(len(codons)):
pc = codons[i]
cou... | 5,332,888 |
def extract_feature_variables2NetCDF(res='4x5',
interpolate_nans=True,
add_derivative_vars=True):
"""
Construct a NetCDF of feature variables for testing
Parameters
-------
res (str): horizontal resolution of dataset (e.g. 4x... | 5,332,889 |
def initialize_cluster_details(scale_version, cluster_name, username,
password, scale_profile_path,
scale_replica_config):
""" Initialize cluster details.
:args: scale_version (string), cluster_name (string),
username (string), password (s... | 5,332,890 |
def test_extract_lambda():
"""
`extract_lambda` should support all possible orderings of the variables it
encounters.
"""
expr = Expression.fromstring(r"foo(\a.a,\a.a)")
extracted = extract_lambda(expr)
eq_(len(extracted), 2) | 5,332,891 |
def load(data_home=None):
"""Load RWC-Genre dataset
Args:
data_home (str): Local path where the dataset is stored.
If `None`, looks for the data in the default directory, `~/mir_datasets`
Returns:
(dict): {`track_id`: track data}
"""
if data_home is None:
data_... | 5,332,892 |
def collate_spectra_by_source(source_list, tolerance, unit=u.arcsec):
"""Given a list of spec1d files from PypeIt, group the spectra within the
files by their source object. The grouping is done by comparing the
position of each spectra (using either pixel or RA/DEC) using a given tolerance.
Args:
... | 5,332,893 |
def tolist(obj):
"""
Convert given `obj` to list.
If `obj` is not a list, return `[obj]`, else return `obj` itself.
"""
if not isinstance(obj, list):
return [obj]
return obj | 5,332,894 |
def bip44_tree(config: dict, cls=hierarchy.Node) -> hierarchy.Node:
"""
Return the root node of a BIP44-compatible partially ordered hierarchy.
https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
The `config` parameter is a dictionary of the following form:
- the keys of the dictionary a... | 5,332,895 |
def delete_useless_vrrp_subnets(client, to_delete, project_id):
"""
:param 'Client' client
:param dict((prefix_length, type, master_region, slave_region),
(state:quantity)) to_delete
:rtype: list
"""
result = []
vrrp_subnets = client.vrrp.list(project_id=project_id)
for k... | 5,332,896 |
def test_first():
"""
Returns first element of sequence
"""
assert fandango.functional.first((a for a in (1,2,3))) is 1 | 5,332,897 |
def test_case_0():
"""test_case_0."""
assert increment_string("foo") == "foo1" | 5,332,898 |
def test_atomic_g_month_enumeration_4_nistxml_sv_iv_atomic_g_month_enumeration_5_5(mode, save_output, output_format):
"""
Type atomic/gMonth is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/gMonth/Schema+Instance/NISTSchema-SV-IV-atomic-gMonth-enumeration-5.xsd",
... | 5,332,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.