content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def hide_ticks(ax=None):
"""Remove x and y ticks from axes object.
Arguments
---------
ax: matplotlib.axes, defaults to current axes
"""
if ax is None:
ax = plt.gca()
ax.set_xticks([])
ax.set_yticks([]) | 5,289,900 |
def configure_logging(log=None):
"""
Configures logging.
:param bool log: whether to log to a file
"""
if log:
logging.basicConfig(level=logging.DEBUG, filename=log,
filemode='w',
format='%(asctime)s %(levelname)-8s %(message)s')
... | 5,289,901 |
def process_way_chunk(nodes_dict, csv_way_nodes, build_way_csv_writer, build_areas_csv_writer):
"""
Process a chunk of nodes loaded in-memory. Associated then with ways and write lines and polygons to a csv file.
:param nodes_dict: A chunk of nodes loaded in memory.
:param csv_way_nodes: The csv that co... | 5,289,902 |
def get_attachment(msg, file_filter=default_attach_filter):
"""
获取邮件里的附件
:param msg:
:param file_filter:
:return:
"""
attachments = []
for part in msg.walk():
if part.get_content_maintype() == 'multipart': continue
if part.get_content_maintype() == 'text': continue
... | 5,289,903 |
def zero_dihedral_contribution(openmm_system: openmm.System, dihedral_indices: Tuple[int, int]):
"""
Author Simon Boothroyd
Link gist.github.com/SimonBoothroyd/667b50314c628aabe5064f0defb6ad8e
Zeroes out the contributions of a particular dihedral to the total potential
energy for a given OpenMM syst... | 5,289,904 |
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Tensorflow Faster R-CNN demo')
parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16 res101]',
choices=NETS.keys(), default='res101')
parser.add_argument('--dataset', ... | 5,289,905 |
def search_specific(name_or_address):
"""
Allows for direct searches through the URL (not the same as the API)
"""
user = http_auth.username()
answer = {}
answer[name_or_address] = str(searcher.query(name_or_address)).split(' ', 1)[1]
return render_template('search_results.html', title='Sear... | 5,289,906 |
def find_unused_port(addr="localhost", start=53589, track=True):
"""Find an unused port starting at `start` port
If track=False the returned port will not be marked as in-use and the code
will rely entirely on the ability to connect to addr:port as detection
mechanism. Note this may cause problems if p... | 5,289,907 |
def roman_int(n, oldstyle=False):
"""Yield the Roman numeral representation of n. This routine is a
straightforward translation of the code from section 69 of TeX82, where
it is prefaced by the following comment:
Readers who like puzzles might enjoy trying to figure out how
this tricky cod... | 5,289,908 |
def create_GBM(s0, mu, sigma):
"""
Generates a price following a Geometric Brownian Motion process based on the input of the arguments:
- s0: Asset inital price.
- mu: Interest rate expressed annual terms.
- sigma: Volatility expressed annual terms.
"""
sp = s0
# Generate stock value for the current s... | 5,289,909 |
def parametrize(metafunc, argnames, argvalues, indirect=False, ids=None, scope=None, **kwargs):
"""
This alternate implementation of metafunc.parametrize creates a list of calls that is not just the cartesian
product of all parameters (like the pytest behaviour). Instead, it offers an alternate list of call... | 5,289,910 |
def partial_to_query_filter(partial: Expression, model: Model, **kwargs):
"""
Convert a partial expression to a django query ``Q`` object.
Example expression structure::
Expression(And, [
Expression(Isa, [
Variable('_this'),
Pattern(test_app::Post, {})])... | 5,289,911 |
def test_hash_recalculation():
"""Tests hash recalculation at the node_34 and root after modifying the hash stored by leaf_4
"""
new_leaf = Leaf(
hashfunc=HASH,
encoding=ENCODING,
record=b'new record...'
)
node_34.set_right(new_leaf)
node_34.recalculate_hash(hashfunc=H... | 5,289,912 |
def test_logger_info():
"""
GIVEN
WHEN logger.info is called
THEN message is shown
"""
logger = get_logger()
with LogCapture() as capture:
logger.info("Test Output")
capture.check(("root", "info", "Test Output")) | 5,289,913 |
def closer_than(x1, y1, x2, y2, limitsq):
"""
Helper function to determine whether the square of the distance
between points (x1,y1) and (x2,y2) is less than or equal to limitsq.
The squares of the distances are compared to save computation time.
:Parameters:
x1: float
X ... | 5,289,914 |
def stroll(
roots='.',
topdown=True,
onerror=None,
followlinks=False,
include=None,
exclude=dotfile,
directories=False,
relative=False,
with_root=None,
sort=True,
suffix=None,
separator=FILE_SEPARATOR,
ignore_missing_roots=False,
):
"""
Directory walker that i... | 5,289,915 |
def get_cloudrun_revisions(cloudrun: Resource, project_id: str) -> List[Dict]:
"""
Returns a list of Cloud Run Revisions for a given project.
:type cloudrun: Resource
:param cloudrun: The cloudrun resource created by googleapiclient.discovery.build()
:type project_id: str
:... | 5,289,916 |
def do_rss_latest(parser, token):
"""
A template tag to grab the latest articles from a given feed.
The first argument is the category.
The second argument is the number of items to retrieve.
The third argument (after 'as') is the variable to store the result in.
"""
try:
tag_name, ... | 5,289,917 |
def random_sequence(batch_size, seq_size, seq_length, random_state=None):
"""
Args:
batch_size: Number of different sequences of the same size.
seq_size: Number of amino acids that are posible at each residue.
seq_length: Length of each sequence.
Returns:
Generated PyTorch ... | 5,289,918 |
def tuple_record_generator(record_def, line_iterable):
"""
Returns a generator of tuples of fields according to the records definition object
- record_def: Record definition object that comply to the api is_record and to_tuple
- line_iterable: Collection of text lines representing records
... | 5,289,919 |
def center_crop_images(images, crop_resolution: int):
"""
Crops the center of the images
Args:
images: shape: (B, H, W, 3), H should be equal to W
crop_resolution: target resolution for the crop
Returns:
cropped images which has the shape: (B, crop_resolution, crop_resolution, 3... | 5,289,920 |
def update_time_estimation_model(strategy_id: str):
"""Updates the machine learning model for simulation time estimations."""
strategy_doc = sample_entry.Strategy.objects(id=strategy_id).first()
logger.info('Updating time predictions')
if strategy_doc.current_iteration >= 3:
sim_time_predictio... | 5,289,921 |
def _process_macros(mlist, macros, unit_name, unit_kind):
"""Process a macro definition and check for incompatible duplicate
definitions.
Positional arguments:
mlist - list of macro names to process
macros - dictionary with currently discovered macros
unit_name - the unit (library/application) ... | 5,289,922 |
def EER(roc):
"""
Obtain the EER for one fold
"""
far, frr = roc['far'].values, roc['frr'].values
def perp(a):
b = np.empty_like(a)
b[0] = -a[1]
b[1] = a[0]
return b
# line segment a given by endpoints a1, a2
# line segment b given by endpoints b1, b2
de... | 5,289,923 |
def test_lazy_op_divergence(op_test_data, order):
"""Test divergence operation in lazy context."""
eager_actx, lazy_actx, get_discr = op_test_data
discr = get_discr(order)
from grudge.trace_pair import interior_trace_pair
from grudge.dof_desc import as_dofdesc
from mirgecom.operators import div... | 5,289,924 |
def run_shell_command(arguments: List[str]) -> str:
"""Executes a shell command."""
if VERBOSE:
print(" ".join(arguments))
try:
output = subprocess.check_output(arguments).decode().strip()
except subprocess.CalledProcessError as error:
error_output = error.output.decode().strip()... | 5,289,925 |
def render(data: dict, path_to_j2: str):
"""Renders given Jinja2 template with given data (dict)
Args:
data: Dict object containing structured data valid for given Jinja template
path_to_j2: Filepath to Jinja template
"""
with open(path_to_j2) as file_:
print(Template(file_.read... | 5,289,926 |
def get_file_name(patch):
"""Return the name of the file to which the patch should be written"""
file_name = None
for line in patch:
if line.startswith('Patch-Filename: '):
file_name = line[len('Patch-Filename: '):]
break
# If no patch-filename header, munge the subject.
if not file_name:
... | 5,289,927 |
def generate_n_random_symbols(n):
"""Returns `n` random upper case ASCII symbols
Args:
number_of_symbols (int): Number of symbols required
Raises:
ValueError: If n is greater than 26 and less than 0
"""
if n in range(27):
upper_case_ascii_characters = [chr(i) for i in range... | 5,289,928 |
def GetActiveEditorDocument():
"""Returns the active editor document and view, or (None,None) if no
active document or its not an editor document.
"""
view = GetActiveView()
if view is None or isinstance(view, TreeView):
return (None, None)
doc = view.GetDocument()
if hasattr(doc, "MarkerAdd"): # Is it an Edit... | 5,289,929 |
def handle_gui_reading(
paths: List[str],
qt_viewer,
stack: bool,
plugin_name: Optional[str] = None,
error: Optional[ReaderPluginError] = None,
):
"""Present reader dialog to choose reader and open paths based on result.
This function is called whenever ViewerModel._open_or_get_error return... | 5,289,930 |
def _load_hess_inv(nrows, method, card):
"""loads inverse power"""
alpha_omega_default = None
LJ_default = None
if method == 'INV':
alpha_omega_default = 0.0
LJ_default = 1.0
alphaAjs = []
alphaBjs = []
omegaAjs = []
omegaBjs = []
#mblkszs = []
#iblkszs = []
... | 5,289,931 |
def default_exception_serializer(exception):
"""
The default exception serializer for user exceptions in eval.
"""
return '%s: %s' % (type(exception).__name__, str(exception)) | 5,289,932 |
def rload(path):
"""Load a dict of data from an R dump format file.
"""
with open(path, 'r') as fd:
lines = fd.readlines()
data = {}
for line in lines:
lhs, rhs = [item.strip() for item in line.split('<-')]
if rhs.startswith('structure'):
vals, dim = rhs.replace('... | 5,289,933 |
def test_atomic_integer_total_digits_nistxml_sv_iv_atomic_integer_total_digits_1_5(mode, save_output, output_format):
"""
Type atomic/integer is restricted by facet totalDigits with value 1.
"""
assert_bindings(
schema="nistData/atomic/integer/Schema+Instance/NISTSchema-SV-IV-atomic-integer-tota... | 5,289,934 |
def _read_locs(filepath, chs, egi_info):
"""Read channel locations."""
fname = op.join(filepath, 'coordinates.xml')
if not op.exists(fname):
return chs
numbers = np.array(egi_info['numbers'])
coordinates = parse(fname)
sensors = coordinates.getElementsByTagName('sensor')
for sensor i... | 5,289,935 |
def use_route_names_as_operation_ids(app: FastAPI) -> None:
"""
Simplify operation IDs so that generated API clients have simpler function
names.
Should be called only after all routes have been added.
"""
for route in app.routes:
if isinstance(route, APIRoute):
route.operat... | 5,289,936 |
def link_edges(strong_edges, weak_edges):
""" Find weak edges connected to strong edges and link them.
Iterate over each pixel in strong_edges and perform breadth first
search across the connected pixels in weak_edges to link them.
Here we consider a pixel (a, b) is connected to a pixel (c, d)
if (... | 5,289,937 |
def heading(angle):
"""
Computes cardinal direction based on heading/orientation. Assumes
robot heading is parallel to cartesian axes and 0 heading is south.
Args:
angle (float): Angle of yaw orientation
Returns:
(str): Cardinal direction
"""
if -5*np.pi/9 <= angle <= -4*np.pi/... | 5,289,938 |
def test_one_epoch(test_data, test_label, sess, ops, test_writer, log):
""" ops: dict mapping from string to tf ops """
is_training = False
total_correct = 0
total_seen = 0
loss_sum = 0
total_seen_class = [0 for _ in range(NUM_CLASSES)]
total_correct_class = [0 for _ in range(NUM_CLASSES)]... | 5,289,939 |
def check_project_unrar(summary_dict):
"""Checks summary dict against htslib details"""
fuzzer_list = []
for k in summary_dict:
if k != "MergedProjectProfile":
fuzzer_list.append(k)
if len(fuzzer_list) != 1:
guide_exit("unrar fuzzer count is wrong")
if summary_dict['unrar... | 5,289,940 |
def generate_root(name):
"""Generate a root path.
Args:
name (str): Name of the experiment.
Returns:
str: Root path.
"""
now = time.strftime("%Y-%m-%d_%H-%M-%S")
return os.path.join("_experiments", f"{now}_{slugify.slugify(name)}") | 5,289,941 |
def remove_candidates(orders, candidates_to_remove):
"""
Remove a set of candidates from a list representing a preference order.
"""
projection = []
for c_vote in orders:
temp_vote = copy.copy(c_vote)
for c_remove in candidates_to_remove:
temp_vote.remove(c_remove)
projection.append(temp_v... | 5,289,942 |
def timethis(func):
"""Report execution time of function."""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, f"took {end-start:3.2f}s")
return result
return wrapper | 5,289,943 |
def test_declination_2(mock_datetime):
"""
Geomag_Case(date=2015.0, lat=0.0, lon=0.0, alt=0.0, coord='D', D_deg='-5d', D_min='26m')
"""
d = declination(LatLon(lat=0.0, lon=0.0))
assert mock_datetime.mock_calls == [call.datetime.today()]
assert d == approx(math.radians(-(5 + 26 / 60)), rel=0.1 / ... | 5,289,944 |
def dummytable(numrows=100,
fields=(('foo', partial(random.randint, 0, 100)),
('bar', partial(random.choice, ('apples', 'pears',
'bananas', 'oranges'))),
('baz', random.random)),
wait=0, se... | 5,289,945 |
def scores_plot(scores, plot_num, threashold, title = ""):
"""Plotting the scores over episodes for different networks
Params
======
scores (list of dict): Containing at least 'scores', 'fc1_units', and 'fc2_units' for plotting
plot_num (int): dimensionality of plot (is N for an NxN plo... | 5,289,946 |
def rank(values, axis=0, method='average', na_option='keep',
ascending=True):
"""
"""
if values.ndim == 1:
f, values = _get_data_algo(values, _rank1d_functions)
ranks = f(values, ties_method=method, ascending=ascending)
elif values.ndim == 2:
f, values = _get_data_algo(... | 5,289,947 |
def workflow(self):
"""
Args:
self(gromozeka.primitives.Task):
Returns:
"""
(((print_something('hello') >
((reduce(lambda x, y: x | y, [get_something_from_api(name) for name in ('boo', 'gaa', 'goo')])) >>
print_something()))) >
print_something('good by')).apply_async() | 5,289,948 |
def one_move(pos=start, step=1):
"""
Make one move from the given position `pos`.
"""
board[pos[0]][pos[1]] = step
if step == cnt:
fmt = "{{:{}d}}".format(ceil(log10(rows*cols))+1)*cols
for i in range(rows):
print(fmt.format(*board[i]))
return True
step += 1
... | 5,289,949 |
def _get_mainfunc_from_js(js):
""" Return main signature decryption function from javascript as dict. """
dbg("Scanning js for main function.")
m = re.search(r'\w\.sig\|\|([$\w]+)\(\w+\.\w+\)', js)
funcname = m.group(1)
dbg("Found main function: %s", funcname)
function = _extract_function_from_j... | 5,289,950 |
def dissociate(op, args):
""" Given an associative operator, return a flattened list result """
result = []
def collect(subargs):
for arg in subargs:
if arg.func == op:
collect(arg.args)
else:
result.append(arg)
collect(args)
return r... | 5,289,951 |
def from_file(filename):
"""Return an `Archive` instance to handle the file *filename*"""
from pgxnclient.zip import ZipArchive
from pgxnclient.tar import TarArchive
for cls in (ZipArchive, TarArchive):
a = cls(filename)
if a.can_open():
return a
raise PgxnClientExcepti... | 5,289,952 |
def deserialize_population_frame(frame, inplace=False):
"""Deserializes a population `pd.DataFrame` from plain text.
Args:
frame: A `pd.DataFrame` produced by `serialize_population_frame`.
inplace: Whether to deserialize `frame` inplace instead of creating a copy.
Returns:
A `pd.DataFrame` with dese... | 5,289,953 |
def latent_kl(prior_mean, posterior_mean):
"""
:param prior_mean:
:param posterior_mean:
:return:
"""
kl = 0.5 * torch.pow(prior_mean - posterior_mean, 2)
kl = torch.sum(kl, dim=[1, 2, 3])
kl = torch.mean(kl)
return kl | 5,289,954 |
async def cmd_collection(ctx: discord.ext.commands.Context, *, collection_name: str):
"""
Get the details on a specific collection.
Usage:
/collection [collection_name]
Parameters:
collection_name: The name of the collection to get details on.
Examples:
/collection_name savy - W... | 5,289,955 |
def handle_args():
"""Reads the commandline args and adjusts initial values of globals values to match
:return: False if there was an error with the args, or True if args processed ok.
"""
global resize_output, resize_output_width, resize_output_height, min_score_percent, object_classifications_mask,\
... | 5,289,956 |
def query_index(index, query):
"""Returns search results for your given query"""
es = get_elastic_client()
if not es:
return []
search = es.search(
index=index,
body={
"query": {
"multi_match": {
"query": query,
... | 5,289,957 |
def sptldisc():
"""
sptldisc()
Defined at ../src/sptldisc.f lines 107-292
"""
_min3p.f90wrap_sptldisc() | 5,289,958 |
def get_db_dir():
"""
Just return the default dir listed above
:return: the default location for the sqllite database
"""
return defaultdir | 5,289,959 |
def channel_is_size(channel):
"""Checks if a channel is of set size (see: /setsize handler)"""
channel_number = bot.get_chat_members_count(channel)
if channel_number >= min_channel_size:
return True
else:
return False | 5,289,960 |
def numpy_to_predef_gtiff_fmt(
np_array_in, xll, yll, cellsz, path_gdb_out, name_raster_out,
ctrl_tif_export=False, path_gdb_fmt_in='', name_raster_fmt_in='',
path_folder_tif_tmp=''):
"""
This function exports a numpy array to an ArcGIS Raster.
As the ESRI ArcGIS function NumPyArrayT... | 5,289,961 |
def factorial(n):
"""
Calculate n!
Args:
n(int): factorial to be computed
Returns:
n!
"""
if n == 0:
return 1 # by definition of 0!
return n * factorial(n-1) | 5,289,962 |
def discover(scan_attempts=10, scan_interval=1):
"""Creates a Harmony client and initializes session.
Args:
scan_attempts (int): Number of times to scan the network
scan_interval (int): Seconds between running each network scan
Returns:
A list of Hub devices found and their configs... | 5,289,963 |
def get_nodal_averaged_stress(model, eid_to_nid_map, isubcase, options=None):
"""
Supports:
- plateStress
- solidStress
- compositePlateStress (NA)
options = {
'mode': 'derive/avg', # derive/avg, avg/derive
'layers' : 'max', # max, min, avg
#'ilayers' : None, #... | 5,289,964 |
def test_trivial():
"""
This is a trivial test that I'm using to check whether pytest can find the test
files correctly.
"""
assert True | 5,289,965 |
def getMonetaryQuantityQuantUnit(words):
"""
from training data:
count perc cum_sum cum_perc
kind_c
dollar 133 60.454545 133 60.454545
yuan 36 16.363636 169 76.818182
euro 23 10.454545 192 87.272727
pound ... | 5,289,966 |
def filter_python_model_benchmark_suite(device_info,
root_build_dir,
verbose=False):
"""Filters Python model benchmark suite for the given CPU/GPU target.
Args:
- device_info: an AndroidDeviceInfo object.
- root_build_dir: the root... | 5,289,967 |
def get_env_config(config_type: str, config_set: str, dist_name: str = None) -> dict:
"""Function for drawing some built-in configuration dictionaries
:param config_type: Type of configuration to draw.
:param config_set: Which set to draw from.
:param dist_name: Name of the distribution within a set.
... | 5,289,968 |
async def test_user_device_exists_abort(
opp: OpenPeerPower, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we abort flow if Agent device already configured."""
await init_integration(opp, aioclient_mock)
result = await opp.config_entries.flow.async_init(
config_flow.DOMAIN,
con... | 5,289,969 |
def task_on_callbacks(*task_args, **task_kwargs):
"""
A proxy for ``invoke.tasks.task`` parameterized decorator.
"""
def decorator(function):
"""
A decorator which wraps original Deferred-using function and converts
it into Invoke task.
"""
@wraps(function)
... | 5,289,970 |
def traj_loss_antithetic_es(
p_yses: Sequence[truncated_step_mod.TruncatedUnrollOut],
n_yses: Sequence[truncated_step_mod.TruncatedUnrollOut],
vec_pos: MetaParams,
std: float,
loss_type: str,
clip_loss_diff: Optional[float] = None,
) -> Tuple[jnp.ndarray, MetaParams, truncated_step_mod.Truncated... | 5,289,971 |
def compareMentorsAndTeams(mentor_sch, team_sch):
"""
Teams can only meet with the mentors when the mentors are available, so
for each mentor multiply the 0..1 mentor value against the team team
availability count to use the mentor schedule as a mask over the team
schedule.
We could rewr... | 5,289,972 |
def get_word_count(text, keywords):
"""
Args:
text (str):
keywords (list):
Returns:
"""
count_dict = {}
for keyword in keywords:
count_dict[keyword] = text.count(keyword)
return count_dict | 5,289,973 |
def handle_special_operator(formula, operator):
"""
如果有 "*-", "-*", "/-", "-/" 这些运算符,
提取负号,去掉重复的运算符
:param formula:
:param operator:
:return:
"""
temp = ""
regex = "\d*[.]?\d+"
opera = operator.replace("*", "[*]")
ret = re.compile(opera.join([regex, regex]))
wh... | 5,289,974 |
def cosmicmed(data, sigma=1.5):
"""
Precise cosmic ray elimination for measurements of the same point or very
similar spectras.
:type data: list[float]
:param data: List of spectras to remove cosmic rays.
:type sigma: float
:param sigma: Factor to modify the criteria to identify a cosm... | 5,289,975 |
def ditto(src, dest, norsrc=False):
""" Copies a file or directory tree from src path to dest path
src: source path as string
dest: destination path as string
norsrc: (bool) if True, uses --norsrc flag with ditto so it will not copy
resource fork or extended attributes. Ma... | 5,289,976 |
def schema(
var_name: str,
data_type: Any,
) -> str:
"""Returns a YAML-like string for our data type; these are used for
pretty-printing and comparison between the OpenAPI type
definitions and these Python data types, as part of
schema is a glorified repr of a data type, but it also includes a
... | 5,289,977 |
def get_user(username=None, email=None, apikey=None):
"""Return the user for the given username, email or apikey.
Return None if no such user.
"""
if username:
rows = flask.g.db.view("users", "username",
key=username.lower(), include_docs=True)
elif email:
... | 5,289,978 |
def resolveVarStrDashMuts(varStr):
"""If there is a sequence of mutations like T28144- followed by -28144C, get rid of the T>-
and replace the ->C with T>C. Get rid of solo basePos- because they can occur in very long
lists when samples have long stretches of Ns, not helpful."""
if (not varStr):
... | 5,289,979 |
def get_urls(text):
"""Extract urls from text.
Parameters
----------
text : text that contains url(s)
Returns
-------
links : a list of Links of urls in the text.
"""
# URL
URL_REGEX = r"""(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia... | 5,289,980 |
def main():
""" main entry point for module execution
"""
OnyxTrafficClassModule.main() | 5,289,981 |
def get_fund_id():
"""
Use this function when you want to find the fund_id using the fund name.
Returns
-------
fund_id: string
The CNPJ of the fund, that is the brazilian tax id and used in this
script as fund_id.
"""
funds = pd.read_sql("SELECT DISTINCT denom_social FROM... | 5,289,982 |
def test_genome():
"""Registry: loading a genome db or configuration by label"""
registry = Registry()
db = registry.genome('Osat')
assert 'accession' in db.config
assert db.config['accession'] == 'GCF_001433935.1'
registry.update('testdata/conf')
db = registry.genome('Osat')
assert 'ac... | 5,289,983 |
def convert_ESC50_to_hierarchical_dataset(input_dirpath,
output_dirpath,
wav_timelength):
"""! This function converts the ESC-50 dataset in a universal
dataset with all different sound classes in separate folders.
Args:
... | 5,289,984 |
def readJson(filename):
"""
Returns a list of all the objects in the .json set
"""
with open(filename, 'r') as f:
data = json.load(f)
info = str(data)
info.split(":")
keys = []
for i in data:
keys.append(i)
obj = []
for i in keys:
obj.append(d... | 5,289,985 |
def test_create_new_dynamic_view(empty_model: Model):
"""Test basic construction."""
view = DynamicView(description="Test view")
assert view.description == "Test view"
view.set_model(empty_model)
assert view.model is empty_model | 5,289,986 |
def prepare_wsss(side_length: int, stride: int) -> None:
"""
offline crop the images into wsss_valid_out_cam/crop_images
Args:
side_length (int): the crop image length
stride (int): the steps for cutting a new image
"""
validation_folder_name = 'wsss_valid'
validation_dataset_pa... | 5,289,987 |
async def game_over(_: models.User = Depends(dependencies.get_current_user)) -> Any:
"""
User completed answering all questions.
"""
await LOGGER.info("User completed answering all questions")
return {"message": "Congratulations, you have answered all questions!"} | 5,289,988 |
def convert_categorical(categorical):
"""
"""
cat = categorical.copy()
is_gridslice = '{' in cat.name
if is_gridslice:
resp_prefix = cat.name.split('[{')[0] + 'a'
else:
resp_prefix = categorical.name + 'a'
if not cat.dtype == 'object':
cat = cat.apply(lambda x:
... | 5,289,989 |
def make(model):
"""Create a new model to avoid overwriting the global variable."""
return copy.copy(model) if isinstance(model, Forward) else Backward(model) | 5,289,990 |
def requireIsIntNotZero( obj ):
"""
Throws an AssertionError if 'obj' is not of type 'int' or is zero.
"""
requireIsInt( obj )
requireMsg( isIntNotZero( obj ),
"variable must not be zero" ) | 5,289,991 |
def aggregate_mean(h):
"""mean aggregation"""
return torch.mean(h, dim=1) | 5,289,992 |
def rm2v(r):
"""
Wrapper for ERFA function ``eraRm2v``.
Parameters
----------
r : double array
Returns
-------
w : double array
Notes
-----
The ERFA documentation is below.
- - - - - - - -
e r a R m 2 v
- - - - - - - -
Express an r-matrix as an r-vector.... | 5,289,993 |
def collect_each_room(room:Selector,data_eachBuilding):
"""
这里是将每一个room的信息保存为一个列表
[
"A201",
"Red",
"Red",
"Red",
"Red",
"Red",
"Red",
"Red",
"Red",
"Green",
"Green",
"Green",
"Green",
... | 5,289,994 |
def get_conv_torch(mask):
""" Get 2d torch convolution with mask """
in_chan, out_chan = 1, 1
shape = mask.shape
l = T.nn.Conv3d(in_chan, out_chan, shape
, stride=shape
, padding=0
, bias = False
)
l.mu = ... | 5,289,995 |
def prepare_electrodes_positions(
configuration: str, n_sites: int = 384
) -> List[ActiveElectrode]:
"""
Defines the position along the probe (in coordinates from the first electrode)
of each active electrode
"""
if configuration == "b0":
Y = 20 * np.repeat(np.arange(0, int(n_sit... | 5,289,996 |
def submit_any_ingestion(ingestion_filename, ingestion_type, institution, project, server, env, validate_only,
upload_folder=None, no_query=False, subfolders=False):
"""
Does the core action of submitting a metadata bundle.
:param ingestion_filename: the name of the main data file ... | 5,289,997 |
def player_exists(selected_id: str, already_taken_ids: list = []):
"""Verifies if the player selected by the user exists.
Args:
selected_id (str): Player chosen by the user.
already_taken_ids (list, optional): List of ids the user cannot choose from. Defaults to [].
Returns:
bool: ... | 5,289,998 |
def run_postal_addresses_linker(**kwargs):
"""
A simple wrapper that allows running Postal Addresses linker.
:return: None
"""
settings = dict(inputFilename='delivery_point_addresses.csv', outname='DeliveryPointAddresses')
settings.update(kwargs)
linker = PostalAddressLinker(**settings)
... | 5,289,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.