content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def log_sum_exp(input, dim=None, keepdim=False):
"""Numerically stable LogSumExp.
Args:
input (Tensor)
dim (int): Dimension along with the sum is performed
keepdim (bool): Whether to retain the last dimension on summing
Returns:
Equivalent of log(sum(exp(inputs), dim=dim, k... | 5,324,300 |
def train_epoch_ch3(net, train_iter, loss, updater): # @save
"""训练模型一个迭代周期(定义见第3章)"""
# 将模型设置为训练模式
if isinstance(net, torch.nn.Module):
net.train()
# 训练损失总和、训练准确度总和、样本数
metric = Accumulator(3)
for X, y in train_iter:
# 计算梯度并更新参数
y_hat = net(X)
l = loss(y_hat, y)
... | 5,324,301 |
def get_defined_names_for_position(scope, position=None, start_scope=None):
"""
Return filtered version of ``scope.get_defined_names()``.
This function basically does what :meth:`scope.get_defined_names
<parsing_representation.Scope.get_defined_names>` does.
- If `position` is given, delete all na... | 5,324,302 |
def create_topic(project, topic_name):
"""Create a new Pub/Sub topic."""
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project, topic_name)
topic = publisher.create_topic(topic_path)
print('Topic created: {}'.format(topic)) | 5,324,303 |
def test_recursive_formatter_format_args_no_index():
"""Format a string with positional args and auto index."""
formatter = RecursiveFormatter()
assert (formatter.format('{} arb {} string', 'a', 'b', 'c')
== 'a arb b string') | 5,324,304 |
def update(
card_id: int,
owner: str = typer.Option(None, "-o", "--owner"),
summary: List[str] = typer.Option(None, "-s", "--summary"),
):
"""Modify a card in db with given id with new info."""
summary = " ".join(summary) if summary else None
with cards_db() as db:
try:
db.up... | 5,324,305 |
def eliminate_from_neighbors(csp, var) :
"""
Eliminates incompatible values from var's neighbors' domains, modifying
the original csp. Returns an alphabetically sorted list of the neighboring
variables whose domains were reduced, with each variable appearing at most
once. If no domains were reduce... | 5,324,306 |
def intermediate(
raw_seqs: List[str],
can_seqs: List[str],
indices: List[int],
seq_idx: int,
subjs: dict,
ents: dict,
kb: dict = None,
sep_char: str = SEP_CHAR,
join_char: str = JOIN_SUBJ_CHAR,
... | 5,324,307 |
def make_screen_hicolor(screen):
"""returns a screen to pass to MainLoop init
with 256 colors.
"""
screen.set_terminal_properties(256)
screen.reset_default_terminal_palette()
return screen | 5,324,308 |
def shadow(trajectorys, fcast, theta_levels, dtheta, start_time, chosen_time_index, folder, strapp):
"""
Shitty hack to return sum of shadows
Chosen_time_index
trajectorys deliberately misspelt
definitely move somewhere else when done
"""
masks = []
for theta_level in theta_levels:
... | 5,324,309 |
def cached_object_arg_test(x):
"""takes a MyTestClass instance and returns a string"""
return str(x) | 5,324,310 |
def calculate_news_id(title: str = "", description: str = "") -> hex:
"""
Calculate an idempotency ID of a piece of news, by taking and summing the unicode values
of each character (in lower case if applicable) in title and description
and representing the final value in hex.
Example:
asser... | 5,324,311 |
def set_type_of_process(process_type, param=None):
"""
This function is used to set which is the type of the current process, test, train or val
and also the details of each since there could be many vals and tests for a single
experiment.
NOTE: AFTER CALLING THIS FUNCTION, THE CONFIGURATION CLOSES... | 5,324,312 |
def retrieve_artifact(artifact_id):
"""
Allows the client side API call to "retrieve" the artifact.
Returns:
type: str
String representing JSON object which contains the result of
the "artifact retrieve {uuid}" if the call was a success; else,
JSON object which contains ... | 5,324,313 |
def ip_network(addr):
"""Wrapper for ipaddress.ip_network which supports scoped addresses"""
idx = addr.find('/')
if idx >= 0:
addr, mask = addr[:idx], addr[idx:]
else:
mask = ''
return ipaddress.ip_network(_normalize_scoped_ip(addr) + mask) | 5,324,314 |
def ShowRoleDetails(roles):
"""
List all the Roles in Tetration Appliance
Role ID | Role Name | Description | Ability
"""
headers = ['Role ID', 'Name', 'Description']
data_list = []
data_list.append ([roles['id'],
roles['name'], roles['description']])
tabl... | 5,324,315 |
def evaluate(env, agent, n_games=1, greedy=False, t_max=10000):
""" Plays n_games full games. If greedy, picks actions as argmax(qvalues). Returns mean reward. """
rewards = []
for _ in range(n_games):
s = env.reset()
reward = 0
for _ in range(t_max):
qvalues = agent.get_... | 5,324,316 |
def kabsch(query, target, operator=True):
"""Compute the RMSD between two structures with he Kabsch algorithm
Parameters
----------
query : np.ndarray, ndim=2, shape=[n_atoms, 3]
The set of query points
target : np.ndarray, ndim=2, shape=[n_atoms, 3]
The set of reference points to a... | 5,324,317 |
def test_register():
"""testing the create user function"""
response = client.get("/register")
assert response.status_code == 200, response.template
response = client.post(
"/register",
data={
"username": "test4",
"email": "test4@example.com",
"passw... | 5,324,318 |
def GetConfig(user_config):
"""Load and return benchmark config.
Args:
user_config: user supplied configuration (flags and config file)
Returns:
loaded benchmark configuration
"""
return configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) | 5,324,319 |
def get_postgres_data():
"""
reads in movie and ratings data for all users using the postgres database
Parameters: -
Returns: dataframe with movie IDs, ratings, user IDs;
number of unique movies in database
"""
engine = create_engine(CONN, encoding='latin1', echo=False)
df_ratings_proxy... | 5,324,320 |
def test_observation_statistics_gmi(tmpdir):
"""
Ensure that TrainingDataStatistics class reproduces statistic of
MHS bin file for an ocean surface.
"""
files = [DATA_PATH / "gmi" / "pp" / "GMIERA5_190101_027510.pp"] * 2
stats = [ObservationStatistics(conditional=1),
ZonalDistribut... | 5,324,321 |
def adriatic_name(p, i, j, a):
""" Return the name for given parameters of Adriatic indices"""
#(j)
name1 = {1:'Randic type ',\
2:'sum ',\
3:'inverse sum ', \
4:'misbalance ', \
5:'inverse misbalance ', \
6:'min-max ', \
7:'max-mi... | 5,324,322 |
def handle_command(cmd):
"""Handle keypress commands"""
if cmd == "mute":
pyautogui.press("volumemute")
elif cmd == "toggle":
pyautogui.press("space")
elif cmd == "seek_left":
pyautogui.press("left")
elif cmd == "seek_right":
pyautogui.press("right")
elif cmd == "... | 5,324,323 |
def add_certificate(cluster_name, data):
""" Add a certificate to a cluster reference in the Asperathos section.
Normal response codes: 202
Error response codes: 400, 401
"""
return u.render(api.add_certificate(cluster_name, data)) | 5,324,324 |
def _make_histogram(values, bins):
"""Converts values into a histogram proto using logic from
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/lib/histogram/histogram.cc"""
values = values.reshape(-1)
counts, limits = np.histogram(values, bins=bins)
limits = limits[1:]
sum_s... | 5,324,325 |
def test_multiple_files_check(paths, expected_exit_code):
"""Unsorted files should be checked."""
paths_unsorted = [os.path.join(PATH_EXAMPLES, path) for path in paths]
runner = CliRunner()
result = runner.invoke(cli, ["--check"] + paths_unsorted)
assert result.exit_code == expected_exit_code, resu... | 5,324,326 |
def generate_spec(nu1, nu2, dist):
"""
Generate a fake spectrum under the assumptions of
the standard accretion disk model.
dist needs to be in cm
returns spectrum with luminosity at the source of
the object
"""
freq = np.linspace(nu1, nu2, 1e3)
return [freq, (freq**(1./3.))] | 5,324,327 |
def dearomatize():
"""
Dearomatize structure
---
tags:
- indigo
parameters:
- name: json_request
in: body
required: true
schema:
id: IndigoDearomatizeRequest
properties:
struct:
type: string
required: tru... | 5,324,328 |
def isTree(rootFile,pathSplit):
"""
Return True if the object, corresponding to (rootFile,pathSplit), inherits from TTree
"""
if pathSplit == []: return False # the object is the rootFile itself
else: return isTreeKey(getKey(rootFile,pathSplit)) | 5,324,329 |
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // args.lr_adjust))
for param_group in optimizer.param_groups:
param_group['lr'] = lr | 5,324,330 |
def create_server(host="localhost", remote_port=22, local_port=2222):
"""
Creates and returns a TCP Server thread
:param str host: the host to open the port forwarding from
:param int remote_port: the remote ort to be forward to locally
:param int local_port: the local port to open to forward to
... | 5,324,331 |
def exit_with_error_output(error):
"""
Exits the program with an exit status of 1 and
prints out the error message in a red color.
:param error: The error that occurred. This could be
a string or anything that can be converted to a string.
"""
click.secho(str(error), fg="red")
exit(... | 5,324,332 |
def output_to_df(record):
"""Converts list of records to DataFrame"""
df = pd.DataFrame(record, columns=["line_count_python", "author_name"])
return df | 5,324,333 |
def test_generate_spectra_dataset():
"""
A function that tests that the interpolatespectra.generate_spectra_dataset
function is behaving as expected.
"""
spectra_count = 20
x_data, y_data, label = interpolatespectra.generate_spectra_dataset(HDF5_FILENAME,
... | 5,324,334 |
def sanitize_tx_data(
unspents,
outputs,
fee,
leftover,
combine=True,
message=None,
compressed=True,
absolute_fee=False,
min_change=0,
version='main',
message_is_hex=False,
):
"""
sanitize_tx_data()
fee is in satoshis per byte.
"""
outputs = outputs.copy... | 5,324,335 |
def create_csrf_disabled_registrationform():
"""Create a registration form with CSRF disabled."""
return create_registrationform(**_get_csrf_disabled_param()) | 5,324,336 |
def calc_a_lzc(ts, norm_factor=None):
"""
Calculates lempel-ziv complexity of a single time series.
:param ts: a time-series: nx1
:param norm_factor: the normalization factor. If none, the output will not be normalized
:return: the lempel-ziv complexity
"""
bin_ts = np.char.mod('%i', ts >= n... | 5,324,337 |
def run_train_model(args):
"""
:param args:
:return:
"""
logger = args.module_logger
_ = create_filepath(args.modelout, logger)
logger.debug('Loading model specification from {}'.format(args.modelspec))
model_spec = json.load(open(args.modelspec))
model = load_model(model_spec['modul... | 5,324,338 |
def rbd_command(command_args, pool_name=None):
"""
Run a rbd CLI operation directly. This is a fallback to allow
manual execution of arbitrary commands in case the user wants to
do something that is absent or broken in Calamari proper.
:param pool_name: Ceph pool name, or None to run without... | 5,324,339 |
def get_twitter_auth():
"""
Setup Twitter authentication.
Return: tweepy.OAuthHandler object
"""
try:
consumer_key = "YOUR_KEY"
consumer_secret = "CONSUMER SECRET"
access_token = "ACCESS TOKEM"
access_secret = "ACCESS SECRET"
except KeyError:
sys... | 5,324,340 |
def aggregate_roles_iteration(roles, parameters=None):
"""
Single iteration of the roles aggregation algorithm
Parameters
--------------
roles
Roles
parameters
Parameters of the algorithm
Returns
--------------
agg_roles
(Partially aggregated) roles
"""
... | 5,324,341 |
def run_example():
"""Extract frames from the video and creates thumbnails for one of each"""
# Extract frames from video
print("Extract frames from video")
# frames = video_to_frames('/home/anley1/aa20/Dataset/Videos/%s' % video_name)
# Walk through all files in directory
target_dir = "/home/anley1... | 5,324,342 |
def convertToOneHot(vector, num_classes=None):
"""
Converts an input 1-D vector of integers into an output
2-D array of one-hot vectors, where an i'th input value
of j will set a '1' in the i'th row, j'th column of the
output array.
Example:
v = np.array((1, 0, 4))
one_hot_v = c... | 5,324,343 |
def open_signal(file, sr):
"""
Open a txt file where the signal is
Parameters:
file: Address where the file is located
sr: Sampling rate
Return:
signal: The numpy-shaped signal
t: Time vector
"""
signal = np.loadtxt(file, comm... | 5,324,344 |
def flops_elu(module: nn.ELU, input: Tensor, output: Tensor) -> int:
"""FLOPs estimation for `torch.nn.ELU`"""
# For each element, compare it to 0, exp it, sub 1, mul by alpha, compare it to 0 and sum both
return input.numel() * 6 | 5,324,345 |
def gen_DFSC_MitEx(backend: Backend, **kwargs) -> MitEx:
"""
Produces a MitEx object that applies DFSC characteriastion to all experiment results.
:param backend: Backend experiments are run through.
:type backend: Backend
:key experiment_mitex: MitEx object observable experiments are run through
... | 5,324,346 |
def dumps(pif, **kwargs):
"""
Convert a single Physical Information Object, or a list of such objects, into a JSON-encoded string.
:param pif: Object or list of objects to serialize.
:param kwargs: Any options available to json.dumps().
"""
return json.dumps(pif, cls=PifEncoder, **kwargs) | 5,324,347 |
def drop_database():
"""Drop all SQL database tables."""
if input('Are you really sure to delete all SQL database tables? [y/N]:').lower() == 'y':
db.drop_all()
print('SQL Database\'s tables dropped')
else:
print('Aborted!') | 5,324,348 |
def replace_digits_with_zero(data):
"""Follow the paper's implementation
"""
new_data = []
for words, tags in data:
new_words = []
for w in words:
new_w = "0" if is_number(w) else w
new_words.append(new_w)
new_tags = list(tags)
new_data.append((new... | 5,324,349 |
def main(args=None):
"""
The parser entrypoint
If it gets called without arguments argparse will use 'sys.argv'.
"""
args = get_options(args)
try:
result = parse_week(args.filename)
printer = PrettyPrinter(width=120)
printer.pprint(result)
except IOError as exc:
... | 5,324,350 |
def gcd(number1: int, number2: int) -> int:
"""Counts a greatest common divisor of two numbers.
:param number1: a first number
:param number2: a second number
:return: greatest common divisor"""
number_pair = (min(abs(number1), abs(number2)), max(abs(number1), abs(number2)))
while number_pair[... | 5,324,351 |
def main(argv=sys.argv):
""" The main script """
args = parse_args(argv)
model_file = args.model_filename
model_delete(model_file) | 5,324,352 |
def message_counter_down_timer(strMsg="Calling ClointFusion Function in (seconds)",start_value=5):
"""
Function to show count-down timer. Default is 5 seconds.
Ex: message_counter_down_timer()
"""
CONTINUE = True
layout = [[sg.Text(strMsg,justification='c')],[sg.Text('',size=(10, 0),font=(... | 5,324,353 |
def get_overlapping_timestamps(timestamps: list, starttime: int, endtime: int):
"""
Find the timestamps in the provided list of timestamps that fall between starttime/endtime. Return these timestamps
as a list. First timestamp in the list is always the nearest to the starttime without going over.
Par... | 5,324,354 |
def get_field_h5files(sdir, prefix_dirs="ph"):
"""Return names of field h5 files in a directory
Parameters
----------
sdir: str
Path to the search directory
prefix_dirs: str
If no matching files are found in sdir, search
subdirectories whose name starts with this string.
... | 5,324,355 |
def calc_war_battingfactor(oba,mlb,league,parkfactor,batting):
"""
oba: instance of wOBAWeightSim
mlb: instance of BattingSim
league: DataFrame
parkfactor: DataFrame
batting: DataFrame
-----------------------------------------
returns: DataFrame with column [BattingFactor]
"""
# ... | 5,324,356 |
def test_duplicate_remote_param(session, param, expected):
"""
with duplicated params, value of last param is used
"""
assert get_total(session, params=param) == expected | 5,324,357 |
def average_implied_variance(asset: Asset, tenor: str, strike_reference: EdrDataReference, relative_strike: Real, *,
source: str = None, real_time: bool = False) -> Series:
"""
Historic weighted average implied variance for the underlying assets of an equity index.
:param asset... | 5,324,358 |
def test_union_any_uri_float_enumeration_2_nistxml_sv_iv_union_any_uri_float_enumeration_3_4(mode, save_output, output_format):
"""
Type union/anyURI-float is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/union/anyURI-float/Schema+Instance/NISTSchema-SV-IV-union-anyURI-f... | 5,324,359 |
def get_forward_backward_walk_union_ops(forward_seed_ops,
backward_seed_ops,
forward_inclusive=True,
backward_inclusive=True,
within_ops=None,
... | 5,324,360 |
def init_model(engine):
"""
Call me before using any of the tables or classes in the model.
:param engine: SqlAlchemy engine to bind the session
:return:
"""
DBSession.remove()
DBSession.configure(bind=engine) | 5,324,361 |
def main(): # pragma: no cover
"""Executes model."""
import sys
try:
infile = sys.argv[1]
except IndexError:
print("Must include input file name on command line")
sys.exit(1)
sart = BasicRtSa.from_file(infile)
sart.run() | 5,324,362 |
def random_crop(*arrays, height, width=None):
"""Random crop.
Args:
*arrays: Input arrays that are to be cropped. None values accepted.
The shape of the first element is used as reference.
height: Output height.
width: Output width. Default is same as height.
Returns:
... | 5,324,363 |
def fetch_and_shift_spectra(n_spectra,
outfile,
primtarget=TARGET_GALAXY,
zlim=(0, 0.7),
loglam_start=3.5,
loglam_end=3.9,
Nlam=1000):
"""
This ... | 5,324,364 |
def block_amplitudes(name, block_spec, t, hrfs=(glover,),
convolution_padding=5.,
convolution_dt=0.02,
hrf_interval=(0.,30.)):
""" Design matrix at times `t` for blocks specification `block_spec`
Create design matrix for linear model from a block s... | 5,324,365 |
def main():
"""Assess FPS performance of webcam."""
#
# Open webcam device and set some capture properties
#
cap = cv2.VideoCapture(0)
#cap.set(cv.CV_CAP_PROP_FRAME_WIDTH, 320)
#cap.set(cv.CV_CAP_PROP_FRAME_HEIGHT, 240)
print 'CV_CAP_PROP_FPS ', cap.get(cv.CV_CAP_PROP_FPS)
prin... | 5,324,366 |
def get_embedding(param_list, meta):
"""
Get the USE embeddings of the input text. (non-qa USE)
Param 1 - either string or list of strings
Return - Embeddings
"""
data = {
'op': 'encode',
'text': param_list[0]
}
ret = USE_ENCODER_API.post(data)
return ret['encoded'] | 5,324,367 |
def ticket(request, key):
""" 提供查询接口,让客户拿到 result key 之后查询用户的信息
"""
wxuser = ResultTicket.fetch_user(key)
if not wxuser:
return HttpResponse(status=404)
return HttpResponse(json.dumps(wxuser.serialize())) | 5,324,368 |
def is_sequence(arg):
"""Check if an object is iterable (you can loop over it) and not a string."""
return not hasattr(arg, "strip") and hasattr(arg, "__iter__") | 5,324,369 |
def _save_passing_tests_num(stdout: str) -> None:
"""
Save a passing tests number to the `.env` file.
Parameters
----------
stdout : str
Test command stdout.
"""
passing_test_num: str = _get_passing_test_num_from_stdout(
stdout=stdout)
logger.info('Saving a do... | 5,324,370 |
def _sig_figs(x):
""" Wrapper around `utils.sigFig` (n=3, tex=True) requiring only
argument for the purpose of easily "apply"-ing it to a pandas
dataframe.
"""
return numutils.sigFigs(x, n=3, tex=True) | 5,324,371 |
def stackbar(
y: np.ndarray,
type_names: List[str],
title: str,
level_names: List[str],
figsize: Optional[Tuple[int, int]] = None,
dpi: Optional[int] = 100,
cmap: Optional[ListedColormap] = cm.tab20,
plot_legend: Optional[bool] = True,
) -> plt.Subplot:
... | 5,324,372 |
def get_mempool_transaction_ids():
"""
Request the full list of transactions IDs currently in the mempool,
as an array
:return list: a list of transaction IDs
"""
resource = 'mempool/txids'
return call_api(resource) | 5,324,373 |
def push_remote(c, exclude=None, dry_run=False):
"""push all repos from "central" to BitBucket with possibility to exclude
To exclude multiple repos you need to provide a string with escaped commas
e.g. binfab push_remote
binfab push remote:exclude=apropos
binfab push_remote:exclude="aprop... | 5,324,374 |
def zsplits(ds, flds=['density'], npts=21):
"""Return a lineout of a yt dataset, along z, through X=Y=0 but averaged over X,Y within a cube edge length
Splits region into a series of cubes and takes their averages
Expects multiple fields; returns dict of field grid vectors.
Also, outputs YT ar... | 5,324,375 |
def get_ma15(ticker):
"""15일 이동 평균선 조회"""
df = pyupbit.get_ohlcv(ticker, interval="day", count=15)
ma15 = df['close'].rolling(15).mean().iloc[-1]
return ma15 | 5,324,376 |
def server_lcd(cmd, data):
"""Changes the local directory
Usage: lcd /dir
"""
pass | 5,324,377 |
def bootstrap(config_env=None):
"""Build, configure, and return a WSGI application using default
settings from the avalon.settings module and optionally from the file
referenced by the environmental variable.
:return: Fully configured WSGI application
:rtype: flask.Flask
"""
# Note that we ... | 5,324,378 |
def plot_pmf(df, out_name, full=False):
"""Plot the pmf from the given dataframe."""
fig, ax = plt.subplots()
set_m()
x = df["Number of sampled connected neurons"]
y = df["Probability"]
ax.plot(x, y, "ko", ms=2.5)
y_vals_min = [0 for _ in x]
y_vals_max = y
colors = ["k" for _ in x]
... | 5,324,379 |
def _default_error_handler(msg, _):
"""Default error handler callback for libopenjp2."""
msg = "OpenJPEG library error: {0}".format(msg.decode('utf-8').rstrip())
opj2.set_error_message(msg) | 5,324,380 |
def get_vpc_router_output(filter: Optional[pulumi.Input[Optional[pulumi.InputType['GetVPCRouterFilterArgs']]]] = None,
zone: Optional[pulumi.Input[Optional[str]]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetVPCRouterResult]:
"""
Ge... | 5,324,381 |
def urls(self, key, value):
"""Translates urls field."""
sub_y = clean_val("y", value, str, default="")
sub_u = clean_val("u", value, str, req=True)
_migration = self["_migration"]
volume_info = extract_volume_info(sub_y) if sub_y else None
if volume_info:
# url for a specific volume
... | 5,324,382 |
def distance_at_t(points, t):
"""
Determine the sum of all the distances of the Points at time t using the easy-to-calculate Manhattan metric.
We could use the Euclidean metric but the extra computation is entirely unnecessary.
:param points: the list of Points
:param t: the time t
:return: the ... | 5,324,383 |
def fixed_from_persian(p_date):
"""Return fixed date of Astronomical Persian date, p_date."""
month = standard_month(p_date)
day = standard_day(p_date)
year = standard_year(p_date)
temp = (year - 1) if (0 < year) else year
new_year = persian_new_year_on_or_before(PERSIAN_EPOCH + 180 +
... | 5,324,384 |
def fix_stddev_function_name(self, compiler, connection):
"""
Fix function names to 'STDEV' or 'STDEVP' as used by mssql
"""
function = 'STDEV'
if self.function == 'STDDEV_POP':
function = 'STDEVP'
return self.as_sql(compiler, connection, function=function) | 5,324,385 |
def argdispatch(argument=None):
""" Type dispatch decorator that allows dispatching on a custom argument.
Parameters
----------
argument : str
The symbolic name of the argument to be considered for type dispatching.
Defaults to ``None``. When ``None``, the decorator acts exactly like th... | 5,324,386 |
def calc_intersections(cost, weights):
"""
---------------------------------------------------------------
|Function unused in this code but remains for debugging issues|
---------------------------------------------------------------
Calculates for which layer weights the cost function value is ... | 5,324,387 |
def yaepblur(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#yaepblur"""
return filter(stream, yaepblur.__name__, *args, **kwargs) | 5,324,388 |
def prepare_ml_span_inputs(model: transformers.EncoderDecoderModel, tokenizer: transformers.T5TokenizerFast,
encoder_input_attention: InputAndAttention, context: Tensor, chunk_size: int, device: int,
trim_context: int):
"""Prepare the inputs for calculating the ... | 5,324,389 |
def test_validation(payload, is_valid):
"""
Assert that validation is turned on for the things we care about
"""
assert is_valid == PaymentSerializer(data=payload).is_valid() | 5,324,390 |
def toolButton(pixmap='', orientation=0, size=None):
""" toolbutton function with image
:param pixmap: location of the image
:type pixmap: string
:param orientation: rotation in degrees clockwise
:type orientation: int
:param size: height and width of image in pixels
:type size: int... | 5,324,391 |
def process_hub_timeout(bit):
"""Return the HUB timeout."""
if bit == '1':
return '5 Seconds'
return '2 Seconds' | 5,324,392 |
def sen_loss(outputs, all_seq, dim_used, dct_n):
"""
:param outputs: N * (seq_len*dim_used_len)
:param all_seq: N * seq_len * dim_full_len
:param input_n:
:param dim_used:
:return:
"""
n, seq_len, dim_full_len = all_seq.data.shape
dim_used_len = len(dim_used)
dim_used = np.array... | 5,324,393 |
def test_update_sets_correct_time():
"""
Tests that the update method sets the current
time correctly.
"""
start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
new_dt = pd.Timestamp('2017-10-07 08:00:00', tz=pytz.UTC)
universe = StaticUniverse_MC(equity_assets, cash_assets)
exchan... | 5,324,394 |
def test_list_float_min_length_2_nistxml_sv_iv_list_float_min_length_3_4(mode, save_output, output_format):
"""
Type list/float is restricted by facet minLength with value 7.
"""
assert_bindings(
schema="nistData/list/float/Schema+Instance/NISTSchema-SV-IV-list-float-minLength-3.xsd",
in... | 5,324,395 |
def get_net_peer_count(endpoint=_default_endpoint, timeout=_default_timeout) -> str:
"""
Get peer number in the net
Parameters
----------
endpoint: :obj:`str`, optional
Endpoint to send request to
timeout: :obj:`int`, optional
Timeout in seconds
Returns
------
s... | 5,324,396 |
def logctx_extra_restore():
""" fixture which reverts LogCtxData.extra to old values after test end """
old_extra = LogCtxData.extra.copy()
yield LogCtxData.extra
LogCtxData.extra.clear()
LogCtxData.extra.update(old_extra) | 5,324,397 |
def get_cursor_column_number(widget: QTextEdit) -> int:
"""Get the cursor column number from the QTextEdit widget
Args:
widget (QTextEdit): _description_
Returns:
int: _description_
"""
assert isinstance(widget, QTextEdit)
pos = widget.textCursor().position()
text = widget.... | 5,324,398 |
def plot_singular_values_and_energy(sv: np.ndarray, k: int):
"""
Plot singular values and accumulated magnitude of singular values.
Arguments:
sv: vector containing singular values
k: index for threshold for magnitude of
Side Effects:
- Opens plotting window
"""
en_cum = sv.cumsum... | 5,324,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.