content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def length(draw, min_value=0, max_value=None):
"""Generates the length for Blast+6 file format.
Arguments:
- `min_value`: Minimum value of length to generate.
- `max_value`: Maximum value of length to generate.
"""
return draw(integers(min_value=min_value, max_value=max_value)) | 46,500 |
def get_time_estimation():
"""
To check get_time_estimation function's activity
"""
expected_timestring = '0:00:02 < 0:00:19'
time_st = time.time()
time.sleep(2.2)
timestring = msd.get_time_estimation(time_st, count_ratio=20/200)
assert timestring == expected_timestring | 46,501 |
def test_encode_list():
"""
Test encode list values
"""
value = [15, True]
output = binary.encode(value)
expected_output = bytearray(b'\x0f\x00\x00\x00\x00\x00\x00\x00\x01')
assert output == expected_output, "Failed to encode list value to binary" | 46,502 |
def ppw(text):
"""PPW -- Percentage of Polysyllabic Words."""
ppw = None
polysyllabic_words_num = 0
words_num, words = word_counter(text, 'en')
for word in words:
if syllable_counter(word) >= 3:
polysyllabic_words_num += 1
if words_num != 0:
ppw = polysyllabic_words... | 46,503 |
def is_running_in_azure_ml(aml_run: Run = RUN_CONTEXT) -> bool:
"""
Returns True if the given run is inside of an AzureML machine, or False if it is on a machine outside AzureML.
When called without arguments, this functions returns True if the present code is running in AzureML.
Note that in runs with ... | 46,504 |
def format_test_case(test_case):
"""Format test case from `-[TestClass TestMethod]` to `TestClass_TestMethod`.
Args:
test_case: (basestring) Test case id in format `-[TestClass TestMethod]` or
`[TestClass/TestMethod]`
Returns:
(str) Test case id in format TestClass/TestMethod.
"""
tes... | 46,505 |
def _truncate_seed(seed):
"""
Truncate the seed with MAXINT32.
Args:
seed (int): The seed to be truncated.
Returns:
Integer. The seed with MAXINT32.
"""
return seed % _MAXINT32 | 46,506 |
def run_local(ctx, config):
"""
Run Least Cost Xmission locally using config
Parameters
----------
ctx : click.ctx
click ctx object
config : reVX.config.least_cost_xmission.LeastCostXmissionConfig
Least Cost Xmission config object.
"""
ctx.obj['NAME'] = config.name
c... | 46,507 |
def get_default_device():
""" Using GPU if available or CPU """
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu') | 46,508 |
def build_stateless_broadcaster():
"""Just tff.federated_broadcast with empty state, to use as a default."""
return tff.utils.StatefulBroadcastFn(
initialize_fn=lambda: (),
next_fn=lambda state, value: ( # pylint: disable=g-long-lambda
state, tff.federated_broadcast(value))) | 46,509 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | 46,510 |
def find_mo(search_paths=None) -> Union[Path, None]:
"""
Args:
search_paths: paths where ModelOptimizer may be found. If None only default paths is used.
Returns:
path to the ModelOptimizer or None if it wasn't found.
"""
default_mo_path = ('intel', 'openvino', 'deployment_tools', '... | 46,511 |
def test_allocate():
# type: () -> None
"""Checks allocate creates empty array as intended."""
assert memory.allocate(0) is None
assert memory.allocate(8) == [None] * 8
assert memory.allocate(16) == [None] * 16 | 46,512 |
def autoaugment(dataset_path, repeat_num=1, batch_size=32, target="Ascend"):
"""
define dataset with autoaugment
"""
if target == "Ascend":
device_num, rank_id = _get_rank_info()
else:
init("nccl")
rank_id = get_rank()
device_num = get_group_size()
if device_num ... | 46,513 |
def dropout_mask(x, sz, dropout):
""" Applies a dropout mask whose size is determined by passed argument 'sz'.
Args:
x (torch.Tensor): A torch Variable object
sz (tuple(int, int, int)): The expected size of the new tensor
dropout (float): The dropout fraction to apply
This method us... | 46,514 |
def two_body_mc_force_en_jit(bond_array_1, c1, etypes1,
bond_array_2, c2, etypes2,
d1, sig, ls, r_cut, cutoff_func,
nspec, spec_mask, bond_mask):
"""Multicomponent two-body force/energy kernel accelerated with
Numba's njit de... | 46,515 |
def customize_hrm_programme(**attr):
"""
Customize hrm_programme controller
"""
# Organisation needs to be an NS/Branch
ns_only(current.s3db.hrm_programme.organisation_id,
required=False,
branches=False,
)
return attr | 46,516 |
def freq_count(line, wrddict, win, ctxcounter, wrdcounter):
"""
Counts words and context words of a string.
line: The sentence as a string.
wrddict: Word index mapping.
win: Word context window size.
ctxcounter: Context Counter.
wrdcounter: Word Counter.
"""
if not (isinstance(line, ... | 46,517 |
def _onehot_encoding_unk(x, allowable_set):
"""Maps inputs not in the allowable set to the last element."""
if x not in allowable_set:
x = allowable_set[-1]
return list(map(lambda s: x == s, allowable_set)) | 46,518 |
def info():
"""Prints detailed information about the MySQL Shell plugin support.
Returns:
None
"""
print(
"""
The MySQL Shell allows extending its base functionality through the creation
of plugins.
A plugin is a folder containing the code that provides the functionality to
be made ava... | 46,519 |
def test_service_torsiondrive_duplicates(torsiondrive_fixture):
"""Ensure that duplicates are properly caught and yield the same results without calculation"""
spin_up_test, client = torsiondrive_fixture
# Run the test without modifications
_ = spin_up_test()
# Augment the input for torsion drive... | 46,520 |
def getChironSpec(obnm, normalized=True, slit='slit', normmech='flat', returnFlat=False):
"""PURPOSE: To retrieve a CHIRON spectrum given the observation
name (obnm)."""
#extract the date (yymmdd) from the obnm:
date = re.search(r'chi(\d{6})', obnm).group(1)
#extract the core of the obnm. This wil... | 46,521 |
def plot_contamination_statistics(ax, test_features_df, prediction_type_nos):
"""
plot displaying total number of events and number of events correctly classified for each event type.
Parameters
----------
ax: matplotlib.axes
axes on which plot is to be made
"""
performance_statisti... | 46,522 |
def api_routes(api_classes, base_path='/_ah/api', regex='[^/]+'):
"""Creates webapp2 routes for the given Endpoints v1 services.
Args:
api_classes: A list of protorpc.remote.Service classes to create routes for.
base_path: The base path under which all service paths should exist. If
unspecified, defa... | 46,523 |
def WrapReportText(text):
"""Helper to allow report string wrapping (e.g. wrap and indent).
Actually invokes textwrap.fill() which returns a string instead of a list.
We always double-indent our wrapped blocks.
Args:
text: String text to be wrapped.
Returns:
String of wrapped and indented text.
"... | 46,524 |
def log(s, *args, **kwargs):
"""Log to STDOUT."""
if args:
s = s % args
elif kwargs:
s = s % kwargs
print(s, file=sys.stdout) | 46,525 |
def point_in_wave(point_x, frequency, amplitude, offset_x, offset_y):
"""Returns the specified point x in the wave of specified parameters."""
return (math.sin((math.pi * point_x)/frequency + offset_x) * amplitude) + offset_y | 46,526 |
def tile(A, reps):
"""
Construct an array by repeating A the number of times given by reps.
If `reps` has length ``d``, the result will have dimension of
``max(d, A.ndim)``.
If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, ... | 46,527 |
def get_super_user_token(endpoint):
"""
Gets the initialized super user token.
This is one time, cant get the token again once initialized.
Args:
endpoint (str): Quay Endpoint url
Returns:
str: Super user token
"""
data = (
f'{{"username": "{constants.QUAY_SUPERUSER... | 46,528 |
def to_input_variable(sequences, vocab, cuda=False, training=True):
"""
given a list of sequences,
return a tensor of shape (max_sent_len, batch_size)
"""
word_ids = word2id(sequences, vocab)
sents_t, masks = input_transpose(word_ids, vocab['<pad>'])
if type(sents_t[0][0]) != list:
... | 46,529 |
def test_PoseidonStorage():
"""
test of PoseidonStorage class that
brokers communication with the mongodb container.
client.address tests connection to database and returns
tuple of host and port. default port for mongodb
is 27017.
"""
ps = PoseidonStorage()
assert isinstance(ps.clie... | 46,530 |
def create_extreme_conditions_test_matrix(model, filename=None):
"""
Creates an empty test matrix for evaluating extreme conditions tests.
After running this function, the user should edit the file and save with
a separate filename to avoid overwriting.
Todo: it would be good to make this automati... | 46,531 |
def map_to_docs(solr_response):
"""
Response mapper that only returns the list of result documents.
"""
return solr_response['response']['docs'] | 46,532 |
def get_config_type(service_name):
"""
get the config type based on service_name
"""
if service_name == "HDFS":
type = "hdfs-site"
elif service_name == "HDFS":
type = "core-site"
elif service_name == "MAPREDUCE":
type = "mapred-site"
elif service_name == "HBASE":
type = "hbase-site... | 46,533 |
def regression_model(X, y, alpha=.5):
"""
trains a simple ridge regession model
Args:
X:
y:
alpha:
Returns: model
"""
reg = linear_model.Ridge(alpha=alpha, fit_intercept=True)
# reg = linear_model.Lasso(alpha = alpha,fit_intercept = True)
reg.fit(X, y)
r... | 46,534 |
def array2d_export(f, u2d, fmt=None, **kwargs):
"""
export helper for Util2d instances
Parameters
----------
f : str
filename or existing export instance type (NetCdf only for now)
u2d : Util2d instance
fmt : str
output format flag. 'vtk' will export to vtk
**kwargs : ke... | 46,535 |
def not_daily(request):
"""
Several timedelta-like and DateOffset instances that are _not_
compatible with Daily frequencies.
"""
return request.param | 46,536 |
def get_dummies(
data,
prefix=None,
prefix_sep="_",
dummy_na=False,
columns=None,
sparse=False,
drop_first=False,
dtype=None,
) -> "DataFrame":
"""
Convert categorical variable into dummy/indicator variables.
Parameters
----------
data : array-like, Series, or DataFr... | 46,537 |
def get_call_xlsx(call, submitted=False, proposals=None):
"""Return the content of an XLSX file for all proposals in a call.
Optionally only the submitted ones.
Optionally for the given list proposals.
"""
if proposals is None:
title = f"Proposals in {call['identifier']}"
proposals =... | 46,538 |
def using(enum_cls: EnumClass) -> None:
"""
like c++ using?
"""
global sys
assert isinstance(enum_cls, EnumClass) and not isinstance(
enum_cls, EnumVariantClass
)
scope = sys._getframe(1).f_locals
for name, varnt in enum_cls._enum_varnts_.items():
scope[name] = varnt | 46,539 |
def example_filename(fn):
"""
Return the full path of a data file that ships with gffutils.
"""
return os.path.join(HERE, 'test', 'data', fn) | 46,540 |
def to_array(t):
"""
Converts a taco tensor to a NumPy array.
This always copies the tensor. To avoid the copy for dense tensors, see the notes section.
Parameters
-----------
t: tensor
A taco tensor to convert to a NumPy array.
Notes
-------
Dense tensors export python's ... | 46,541 |
def main() -> None:
"""
Main entry point for this script to generate the models.py from models.yml.
Example: The FQField some_model/some_attribute and its reverse part are defined
like this:
some_model:
some_attribute:
type: relation
to:
collecti... | 46,542 |
def perform_operation(operator_sign: str, num1: float, num2: float) -> float:
"""
Perform the operation on the two numbers.
Parameters
----------
operator_sign : str
Plus, minus, multiplication or division.
num1 : float
Number 1.
num2 : float
Number 2.
Returns
... | 46,543 |
def whitespace_tokenize(subtokens):
"""An implementation of BERT's whitespace tokenizer that preserves space."""
return split_subtokens_on(
subtokens, lambda char: char.isspace(), are_good=True) | 46,544 |
def create_excel(dfs, campus, config, debug):
"""Will create Excel reports for sharing details from Google Docs"""
if debug:
print("Creating Excel report for {}".format(campus), flush=True)
dfs["award_report"].to_csv("award_table_for_excel.csv", index=False)
dfs["student_report"].to_csv("st... | 46,545 |
def create_reference_image(product_id, reference_image_id, gcs_uri):
"""Create a reference image.
Args:
project_id: Id of the project.
location: A compute region name.
product_id: Id of the product.
reference_image_id: Id of the reference image.
gcs_uri: Google Cloud Stor... | 46,546 |
def moon_phase(
ephemerides: skyfield.jpllib.SpiceKernel, time: skyfield.timelib.Timescale
) -> float:
"""Calculate the phase angle of the Moon.
This will be 0 degrees at new moon, 90 degrees at first quarter, 180
degrees at full moon, etc.
"""
sun = ephemerides[Planets.SUN.value]
earth = ... | 46,547 |
def report(branch_file_score):
"""
print out pylint result for each file
"""
print "\n\n\n!---------- Detail score for branch {} ----------!\n".format(sys.argv[4])
for k, v in branch_file_score.items():
print k, "\n", v[1]
print "\n\n\n!---------- Summary score for branch {} -------... | 46,548 |
def fib_functools(n):
"""Return nth fibonacci number starting at fib(1) == 0 using functools
decorator."""
# incorrect fib, but the tests expect it
if n == 0: return 1
if n in [1, 2]:
return n-1
return fib(n - 1) + fib(n - 2) | 46,549 |
def sync_filter(func, *iterables):
"""
Filter multiple iterable at once, selecting values at index i
such that func(iterables[0][i], iterables[1][i], ...) is True
"""
return tuple(zip(*tuple(i for i in zip(*iterables) if func(*i)))) or ((),) * len(
iterables
) | 46,550 |
def CopyBaseRevisionFile():
"""Copy the BASE_REV_FILE from the WebKit checkout to the merge branch.
If options.real is False, log the copy but do not actually perform it.
Raises:
CommandError if the file copy fails.
"""
logging.info('Copying %s to %s' % (BASE_REV_FILE, OldDir()))
if options.real:
... | 46,551 |
def visit_hostname(hostname):
"""
Have a chance to visit a hostname before actually using it.
:param hostname: The original hostname.
:returns: The hostname with the necessary changes.
"""
for processor in [hostname_ssl_migration, hostname_tld_migration, ]:
hostname = processor(hostname... | 46,552 |
async def wait_for_other(client):
"""Await other tasks except the current one."""
base_tasks = aio.all_tasks()
async def wait_for_other():
ignore = list(base_tasks) + [aio.current_task()]
while len(tasks := [t for t in aio.all_tasks() if t not in ignore]):
await aio.gather(*task... | 46,553 |
def catch_signal(signal):
"""Catch django signal and return the mocked call."""
handler = mock.Mock()
signal.connect(handler)
yield handler
signal.disconnect(handler) | 46,554 |
def test_two_related_w_ac(family_with_trials, capsys):
"""Test two related experiments with --collapse and --all."""
orion.core.cli.main(["status", "--collapse", "--all"])
captured = capsys.readouterr().out
expected = """\
test_double_exp-v1
==================
id status
... | 46,555 |
def horizontal_check_and_fix():
"""
Karel is moving horizontal, checking and fixing columns in every 4 moves.
"""
while front_is_clear():
check_and_put_beeper()
# move to the next column.
for i in range(4):
move()
check_and_put_beeper() | 46,556 |
def run_weighted_rrn_price_targeting_scenarios(data_dir, scenario_dir, tmp_dir, output_dir):
"""
Run model using weighted RRN price targets
Parameters
----------
data_dir : str
Root directory containing files used to construct model cases
scenario_dir : str
Directory containing... | 46,557 |
def find_stored_stat(directory, this_func, oresult):
"""
Compute stats from the data saved in a directory
Input:
directory -- location of json files to be scanned.
this_func -- function to be run against the entries found
oresult -- dictionary saving the results of this_func calls
... | 46,558 |
def register_series(series, ref, pipeline):
"""Register a series to a reference image.
Parameters
----------
series : Nifti1Image object
The data is 4D with the last dimension separating different 3D volumes
ref : Nifti1Image or integer or iterable
Returns
-------
transformed_li... | 46,559 |
def normal27(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2):
"""
for source and destination id generation
"""
"""
for type of banking work,label of fraud and type of fraud
"""
idvariz=random.choice(zz2)
idgirande=ra... | 46,560 |
def linear_diophantine(a, b, c):
"""Solve ax + by = c, where x, y are integers
1. solution exists iff c % gcd(a,b) = 0
2. all solutions have form (x0 + b'k, y0 - a'k)
Returns
-------
None if no solutions exists
(x0, y0, a', b') otherwise
"""
# d = pa + qb
p, q, d = extended_euc... | 46,561 |
def count_per_packet_loss(organization_id, asset_type=None, asset_status=None,
data_collector_ids=None,
gateway_ids=None, device_ids=None,
min_signal_strength=None, max_signal_strength=None,
min_packet_loss=None, max_packet_loss=None):
... | 46,562 |
def test_search_geometry_and_iterator_methods(catalog):
""" Tests search with a geometry and test methods of CatalogSearchIterator
"""
search_geometry = Geometry(TEST_BBOX.geometry, crs=TEST_BBOX.crs)
search_iterator = catalog.search(
collection=DataCollection.SENTINEL2_L1C,
time=('2021... | 46,563 |
def sample_nodes(g, p):
"""
Obtains a sampled network via Bernoulli node sampling.
For each node in g, sample it with probability p, and add edge (i, j) only if both nodes i and j have been sampled.
Parameters
----------------
g: a networkx graph object
p: sampling probability for each node... | 46,564 |
def JAlien(commands: str = '') -> int:
"""Main entry-point for interaction with AliEn"""
global AlienSessionInfo, _JSON_OUT
import_aliases()
wb = None
# Command mode interaction
if commands:
AlienSessionInfo['exitcode'] = ProcessCommandChain(wb, commands)
return AlienSessionInfo... | 46,565 |
def _slug_strip(value, separator=None):
"""
Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' separator with the new separator.
"""
if separator == '-'... | 46,566 |
def get_segments_loudness_max(h5, songidx=0):
"""
Get segments loudness max array. Takes care of the proper indexing if we are in aggregate
file. By default, return the array for the first song in the h5 file.
To get a regular numpy ndarray, cast the result to: numpy.array( )
"""
if h5.root.anal... | 46,567 |
def take_along_axis(arr, indices, axis):
"""
Takes values from the input array by matching 1d index and data slices.
This iterates over matching 1d slices oriented along the specified axis in the
index and data arrays, and uses the former to look up values in the latter.
These slices can be differe... | 46,568 |
def set_shared_steemd_instance(steemd_instance):
""" This method allows us to override default steem instance for all users of
_shared_steemd_instance.
"""
global _shared_steemd_instance
_shared_steemd_instance = steemd_instance | 46,569 |
def _is_possible_grab(grid_world, agent_id, object_id, grab_range, max_objects):
""" Private MATRX method.
Checks if an :class:`matrx.objects.env_object.EnvObject` can be
grabbed by an agent.
Parameters
----------
grid_world : GridWorld
The :class:`matrx.grid_world.GridWorld` instance ... | 46,570 |
def euclidean_distance_matrix(embeddings):
"""Get euclidean distance matrix based on embeddings
Args:
embeddings (:obj:`numpy.ndarray`): A `ndarray` of shape
`[num_sensors, dim]` that translates each sensor into a vector
embedding.
Returns:
A `ndarray` of shape `[nu... | 46,571 |
def get_actor_id(name):
"""
Get TMDB id for an actor based on their name.
If more than one result (likely), fetches the
first match. TMDB results are sorted by popularity,
so first match is likely to be the one wanted.
"""
search = tmdb.Search()
search.person(query=name)
# get id o... | 46,572 |
async def test_fan_basic(hass, hk_driver, events):
"""Test fan with char state."""
entity_id = "fan.demo"
hass.states.async_set(entity_id, STATE_ON, {ATTR_SUPPORTED_FEATURES: 0})
await hass.async_block_till_done()
acc = Fan(hass, hk_driver, "Fan", entity_id, 1, None)
hk_driver.add_accessory(acc... | 46,573 |
def p_stmt_sassign(p):
"""
stmt : NUMBER ':' ID ASSIGN aexp ';'
"""
p[0] = SAssign(AVariable(p[3]), p[5], label=p[1]) | 46,574 |
def generate_prompt(
test_case_path, prompt_path, solutions_path, tokenizer, starter_path=None
):
"""
Generate a prompt for a given test case.
Original version from https://github.com/hendrycks/apps/blob/main/eval/generate_gpt_codes.py#L51.
"""
_input = "\nQUESTION:\n"
with open(prompt_path,... | 46,575 |
def buckets_readme_cmd():
"""
Print a blank bucket README tempate. This can then be filled out and ploaded to a bucket.
"""
sys.stdout.write( yaml.dump( policies.buckets_readme()) ) | 46,576 |
def TestSConstruct(scons_globals):
"""Test SConstruct file.
Args:
scons_globals: Global variables dict from the SConscript file.
"""
# Get globals from SCons
Environment = scons_globals['Environment']
base_env = Environment(tools=['component_setup'])
base_env.Append(BUILD_COMPONENTS=['SConscript'])... | 46,577 |
def projects_upload_to(instance, filename):
"""construct path to uploaded project archives"""
today = timezone.now().strftime("%Y/%m")
return "projects/{date}/{slug}/{filename}".format(
date=today, slug=instance.project.slug, filename=filename) | 46,578 |
def test_valid_port(device, port):
"""
Test if the blink_led() function works when passing a valid port.
"""
result = device.blink_led(port)
assert result is None | 46,579 |
def assign_employee(id):
"""
Assign a department and a role to an employee
"""
check_admin()
employee = Employee.query.get_or_404(id)
form = EmployeeAssignForm(obj=employee)
employee.department = form.department.data
employee.role = form.role.data
db.session.add(employee)
... | 46,580 |
def autofocus(field, nm, res, ival, roi=None,
metric="average gradient", minimizer="lmfit",
minimizer_kwargs=None, padding=True, num_cpus=1):
"""Numerical autofocusing of a field using the Helmholtz equation.
Parameters
----------
field: 1d or 2d ndarray
Electric fie... | 46,581 |
def ZeroPaddedRoundsError(handler=None):
"""error raised if hash was recognized but contained zero-padded rounds field"""
return MalformedHashError(handler, "zero-padded rounds") | 46,582 |
def get_adj_mat(G):
"""Represent ppi network as adjacency matrix
Parameters
----------
G : networkx graph
ppi network, see get_ppi()
Returns
-------
adj : square sparse scipy matrix
(i,j) has a 1 if there is an interaction reported by irefindex
ids : list
same length as adj, ith index con... | 46,583 |
def load_ndarray_list(fname):
"""Load a list of arrays saved by `save_ndarray_list`.
Parameters
----------
fname : string
filename to load.
Returns
-------
la : list of np.ndarrays
The list of loaded numpy arrays. This should be identical tp
what was saved by `save_nd... | 46,584 |
def save_result(data, format, options=UNSET) -> ProcessBuilder:
"""
Save processed data to storage
:param data: The data to save.
:param format: The file format to save to. It must be one of the values that the server reports as
supported output file formats, which usually correspond to the sho... | 46,585 |
def load_suites_from_classes(classes):
# type: (Sequence[Any]) -> List[Suite]
"""
Load a list of suites from a list of classes.
"""
return list(
filter(
lambda suite: not suite.hidden, map(load_suite_from_class, classes)
)
) | 46,586 |
def enter_(event):
""" Sends the command to the terminal"""
event.cli.set_return_value(event.cli.current_buffer) | 46,587 |
def update(quantized_model, distilD):
"""
Update activation range according to distilled data
quantized_model: a quantized model whose activation range to be updated
distilD: distilled data
"""
print('******updateing BN stats...', end='')
with torch.no_grad():
for batch_idx, inputs ... | 46,588 |
def get_dummies(data: pandas.core.series.Series):
"""
usage.dask: 2
"""
... | 46,589 |
def norm(x: numpy.ndarray, ord: int, axis: None):
"""
usage.scipy: 1
"""
... | 46,590 |
def save_chunks(chunk_sound, out_path, video_id):
""" Saves chunked speech intervals as WAV file.
:param chunk_sound: A parselmouth.praat Sound object
# :param adjustment: The padding time on either side of target speech
:param out_path: The output path of the wav file
:param video_id: The original... | 46,591 |
def _get_color(value):
"""To make positive DFCs plot green, negative DFCs plot red."""
green, red = sns.color_palette()[2:4]
if value >= 0:
return green
return red | 46,592 |
def parse_feed(feed: str) -> list:
"""
Parses a TV Show *feed*, returning the episode files included in that feed.
:param feed: the feed to parse
:return: list of episode files included in *feed*
"""
try:
root = ElementTree.fromstring(feed)
except ElementTree.ParseError as error:
... | 46,593 |
def disable(modeMotor: apt.Motor) -> None:
"""Disable THORLABS motor.
Parameters
----------
modeMotor : Motor
THORLABS mode motor.
Notes
-----
The THORLABS motor must be enabled before motion control is available.
"""
modeMotor.disable() | 46,594 |
def interpolation_toroidal_plane(phi=-2.38,t=130,Nr=1000,Nz=1000,R=(1.82,2.3),
Z=(-0.25,0.25)):
""" Create a R-Z mesh and interpolate the data on it.
Is useful for checking if the data are well interpolated
:param float phi: Toroidal plane to compute
:param int t: Time ... | 46,595 |
def release_job(job_id):
"""
Release a job
:param job_id: int, job id
:return: if success, return 1, else return 0
"""
import subprocess
try:
step_process = subprocess.Popen(('qrls', str(job_id)), shell=False, stdout=subprocess.PIPE,
stderr=sub... | 46,596 |
def head_finder(board_matrix):
"""
Function:
head_finder()
Description:
this will find the head of your snake
Input:
board_matrix:
This is an list of lists that represents the current board of Battle snake. Follows board_matrix[y][x]
Output:
head_xy:
... | 46,597 |
def copy_emb_weights(embedding, idx2word, embedding_weights, emb_index_dict, vocab_size):
"""Copy from embs weights of words that appear in our short vocabulary (idx2word)."""
c = 0
for i in range(vocab_size):
w = idx2word[i]
g = emb_index_dict.get(w, emb_index_dict.get(w.lower()))
i... | 46,598 |
def do_IRGAcheck(cf,ds):
"""
Purpose:
Decide which IRGA check routine to use depending on the setting
of the "irga_type" key in the [Options] section of the control
file. The default is Li7500.
Usage:
Author: PRI
Date: September 2015
"""
irga_list = ["li7500","li7500a","li750... | 46,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.