text string | label_name string | labels int64 |
|---|---|---|
ftmax_sample(&self, node: usize, temperature: f32) -> Move {
let mut sum: f32 = 0.0;
for child in &self.game_tree[node].children {
sum += (self.game_tree[*child].n as f32).powf(1.0 / temperature);
}
let mut rng = rand::thread_rng();
let r: f32 = rng.gen();
... | Rust | 0 |
=> key,
Op::Append { key, .. } => key,
_ => unreachable!(),
};
let shard = key2shard(key);
if !self.cores.borrow().contains_key(&shard) {
self.renew_cores().await;
}
self.cores.borrow().get(&shard).unwrap().call(args).await
}
async fn... | Rust | 0 |
{
pub indptrType: Option<flatbuffers::WIPOffset<Int<'a>>>,
pub indptrBuffers: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Buffer>>>,
pub indicesType: Option<flatbuffers::WIPOffset<Int<'a>>>,
pub indicesBuffers: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Buffer>>>,
pub axisOrder... | Rust | 0 |
ra_reader: &'a Box<dyn RAReader + 'a>,
saligned_dim_index: Vec<usize>,
saligned_dims: Vec<AlignedRangeStep>,
maligned_dims: Vec<MAlignedDimension>,
// for stream ref index iterator
unfrozen_dims: Vec<usize>,
unknown_upperbounds: Vec<bool>,
lowerbounds: Vec<usize>,
upperbounds: Vec<usize>,
neg_up... | Rust | 0 |
mu_hat_top_values, mu_hat_top_indices = torch.topk(mu_hat.view(-1), k=t_bar_emb.size(0), largest=True)
choose_movie_shot = m_shot_emb[mu_hat_top_indices]
# emperical matrix: partial_pi
partial_pi = torch.zeros((choose_movie_shot.size(0), t_bar_emb.size(0))).to(device)
f... | Python | 1 |
train: bool) -> Callable[
[Collection[Tuple[str, Dict[str, np.ndarray]]]],
Tuple[List[str], Dict[str, torch.Tensor]],
]:
# NOTE(kamo): int value = 0 is reserved by CTC-blank symbol
return CommonCollateFn(float_pad_value=0.0, int_pad_value=-1)
@classmethod
@typechecked
de... | Python | 1 |
).ulCodePageRange1 = tt_get_unsigned_quad((*sfont).handle);
(*table).ulCodePageRange2 = tt_get_unsigned_quad((*sfont).handle);
if (*table).version as i32 > 1i32 {
/* and formats 2 and 3 (current) include 5 more.... these share the
same fields, only... | Rust | 0 |
# Copyright (c) 2022, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | Python | 1 |
"""
终极贪吃蛇 - 优化版
功能特性:
1. 多食物系统(最多20个)
2. 动态障碍物系统(每40秒刷新位置)
3. 自适应难度(吃食物加速)
4. 碰撞安全距离保护
5. 高分存档功能
6. 优化渲染性能
"""
import random
import math
import pygame
import json
from pathlib import Path
# 初始化Pygame引擎
pygame.init()
# 游戏配置常量
class Config:
SCREEN_WIDTH = 1500
SCREEN_HEIGHT = 900
SNAKE_SIZE = 10
INIT_S... | Python | 1 |
,
name=args.exp_name,
config=args)
wandb.run.summary["best_acc"] = best_acc
wandb.run.summary["best_eval_name"] = best_eval_name
wandb.run.summary["best_epoch"] = 0
for epoch in range(start_epoch, args.max_epochs):
"""
Train
"""... | Python | 1 |
.0-extensions/html/vkspec.html#VkBlendFactor)
const VK_BLEND_FACTOR_CONSTANT_COLOR = 10,
/// See [`VkBlendFactor`](https://www.khronos.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#VkBlendFactor)
const VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR = 11,
/// See [`VkBlendFactor`](https://www.khr... | Rust | 0 |
s in chunked_transcripts.items():
print(f"\n📞 Call {call_id}:")
print(f" - Number of chunks: {len(chunks)}")
# Show first chunk as example
if chunks:
first_chunk = chunks[0]
print(f" - First chunk segments: {first_chunk['sta... | Python | 1 |
# In buffers are passed as void *
([("void", "*", "OutMode"), ("ByteCount", "*", "InMode")],
[("MlteInBuffer", "*", "InMode")]),
# The AdjustCursor region handle is optional
([("RgnHandle", "ioCursorRgn", "InMode")],
[("OptRgnH... | Python | 1 |
conn: &PgConnection) -> bool {
schema::users::table
.filter(schema::users::dsl::email.eq(email_addr))
.select(schema::users::dsl::email_verified)
.first(conn)
.unwrap_or(false)
}
/// Mark the email address as verified
pub fn set_verified_email(email_addr: &str, conn: &PgConnection)... | Rust | 0 |
return {"models": models}
@app.post("/get_worker_address")
async def get_worker_address(request: Request):
data = await request.json()
addr = controller.get_worker_address(data["model"])
return {"address": addr}
@app.post("/receive_heart_beat")
async def receive_heart_beat(request: Request):
dat... | Python | 1 |
y_op=tf.nn.softmax(classifier(x_in, getter=ema_getter, training=False)))
def main(argv):
utils.setup_main()
del argv # Unused.
dataset = PAIR_DATASETS()[FLAGS.dataset]()
log_width = utils.ilog2(dataset.width)
model = UDA(
os.path.join(FLAGS.train_dir, dataset.name),
dataset,
... | Python | 1 |
olve::result::{EvolveResult, Stats};
use crate::gen::member::Member;
use crate::gen::unevaluated::UnevaluatedGen;
use crate::ops::util::rand_vec;
pub trait CreateEvolverFn<E: Evaluator> =
Fn(EvolveCfg) -> Evolver<E> + Sync + Send + Clone + 'static;
pub trait RandState<S: State> = FnMut() -> S + Send;
/// Runs ite... | Rust | 0 |
<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub parents: Option<Vec<Parent>>,
}
<reponame>mattwparas/fluvio
#![allow(clippy::assign_op_pattern)]
use dataplane::derive::{Decode, Encode};
use dataplane::api::Request;
use dataplane::Offset;
use fluvio_controlplane_metadata::partition::ReplicaKey;
... | Rust | 0 |
mpl OUTLINK_START_CH0_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
OUTLINK_START_CH0_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for OUTLINK_START_CH0_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
... | Rust | 0 |
OB}} \right\}"#,
r#"p \perp q \; \text{and} \; r \perp q \ \Rightarrow \ p \parallel r"#,
r#"f' ( x ) = \lim_{h \to 0} \frac{ f ( x + h ) - f ( x ) }{ h }"#,
r#"\erf ( x ) = \frac{ 2 }{ \sqrt{ \pi } } \int_0^x e^{- t^2} \, dt"#,
r#"\sum_{n = 1}^\infty \frac{ 1 }{ n^2 } = \frac{ \pi^2 }{ ... | Rust | 0 |
C23_0326, 0xEA15_AEE2),
(r"meshes\f\terrain_rock_rm_14.nif", 0x7C23_0326, 0xEA15_AEE6),
(r"meshes\f\terrain_rock_rm_24.nif", 0x7C23_0326, 0xEA15_AEEA),
(r"meshes\f\terrain_rock_rm_03.nif", 0x7C23_0326, 0xEA15_B2E2),
(r"meshes\f\terrain_rock_rm_13.nif", 0x7C23_0326, 0xEA15_B2E6),
(r"meshes\f\ter... | Rust | 0 |
print("计算完成!坐标为", X_middlePilePoint, Y_middlePilePoint)
else:
print("主点里程计算错误")
def relief_circularCurve_principalPointMileage(self, circularR, steerAngle_alpha, Ls, K_JD):
"""
带有缓和曲线的圆曲线主点里程计算
:param circularR: 圆曲线半径R:m
:param steerAngle_alpha: 线路转向角(弧度)
... | Python | 1 |
12345678");
// simulate deal with an address that isn't registered
crate::DealOrders::<Test>::mutate(
&deal_order_id.expiration(),
&deal_order_id.hash(),
|deal_order_storage| {
let blockchain = Blockchain::Rinkeby;
deal_order_storage.as_mut().unwrap().lender_address_id =
AddressId::new::<Tes... | Rust | 0 |
like a video.
*/
pub async fn rate(
&self,
auth: &crate::data::Token,
id: &str,
rate: crate::param::Rating,
) -> crate::Result<()> {
let params = crate::param::Ratings {
rating: Some(rate),
..Default::default()
};
let request... | Rust | 0 |
der);
declare_async_mmap_file_mut_ext!(AsyncMmapFileWriter);
declare_and_impl_inners!();
declare_and_impl_async_mmap_file!("tokio_async", "tokio_test", "tokio");
delcare_and_impl_async_mmap_file_mut!("tokio_async", "tokio_test", "tokio");
impl_async_tests!("tokio_async", tokio::test, tokio, AsyncMmapFile, AsyncMma... | Rust | 0 |
rs) =
windows::utils::optional_slice_to_num_ptr_pair(Some(&self.parameters));
let (num_static_samplers, p_static_samplers) =
windows::utils::optional_slice_to_num_ptr_pair(Some(self.static_samplers));
RootSignatureDesc {
inner: D3D12_ROOT_SIGNATURE_DESC {
... | Rust | 0 |
# files go into the api/ directory. Note that some apidoc options may not work
# the same because we aren't using their values in the custom templates
apidoc.main([
'--force', # overwrite any files from previous run
'-o', os.path.join(DOCS_SOURCE_DIR, 'api'), # output to api/
'--templatedir', os.path.join... | Python | 1 |
"Mean CPU usage per frame: {:.2} ms / frame",
1e3 * self.frame_times.average().unwrap_or_default()
))
.on_hover_text(
"Includes Egui layout and tesselation time.\n\
Does not include GPU usage, nor overhead for sending data to GPU.",
);
crate::demo... | Rust | 0 |
e or subdirectory in the given subdirectory
"""
if subdirectory is None:
subdirectory = []
full_subdir_path = self._safe_join(subdirectory)
try:
subdir_items = sorted(os.listdir(full_subdir_path))
except FileNotFoundError:
return []
... | Python | 1 |
"""
try:
service = TextbookService(db)
result = service.create_textbook_pages(book_id, pages)
return ApiResponse.success(result)
except Exception as e:
return ApiResponse.system_error(str(e))
@router.post("/textbook/{book_id}/chapters", response_model=ApiResponse)
def ... | Python | 1 |
`"]
#[doc = "* **Groups:** SamplerParameterI, TextureParameterName"]
pub const GL_TEXTURE_COMPARE_MODE: GLenum = 0x884C;
#[doc = "`GL_TEXTURE_CUBE_MAP: GLenum = 0x8513`"]
#[doc = "* **Groups:** CopyImageSubDataTarget, TextureTarget"]
pub const GL_TEXTURE_CUBE_MAP: GLenum = 0x8513;
#[doc = "`GL_TEXTURE_CUBE_... | Rust | 0 |
import torch
from torch import nn
from .. import utils
class MLP(nn.Module):
"""
A multilayer perceptron with Leaky ReLU nonlinearities
"""
def __init__(
self,
layers,
dropout_rate=None,
init=False,
layernorm=False
):
"""
layers: list of laye... | Python | 1 |
();
if let Err(e) = controller_data.storage.store(CertificateEntry {
name: subject_name.clone(),
cert: der,
key_identifier: ski,
key: None,
}) {
log::error!("insertion failed for leaf {}: {}", subject_name, e);
} else {
res.status(StatusCode::OK);
}
}
fn... | Rust | 0 |
nge, record not found %s",
message._thread_id,
)
return None
cred_ex_record.state = V10CredentialExchange.STATE_ABANDONED
code = message.description.get(
"code",
ProblemReportReason.ISSUANCE_ABANDONED.value,
... | Python | 1 |
pub async fn run<S>(self, socket: S)
where S: AsyncRead + AsyncWrite + Unpin {
let peer = &self.peer;
metrics::num_sessions().inc();
debug!(
target: LOG_TARGET,
"Starting inbound messaging protocol for peer '{}'",
peer.short_str()
);
l... | Rust | 0 |
;
#[derive(StructOpt, Debug)]
#[structopt(name = "ping3", version = "0.1.0")]
/// Sends ICMP echo requests to a host and displays relies.
///
/// If ping3 does not receive any reply packets at all, it will exit with code 1. If `count` and
/// `deadline` are both specified, and fewer than `count` replies are received b... | Rust | 0 |
www.unicode.org/reports/tr53/.
fn reorder_marks(glyphs: &mut Vec<ArabicGlyph>) {
for gs in glyphs.split_mut(|g| g.canonical_combining_class() == CanonicalCombiningClass::CCC000)
{
reorder_marks_nfd(gs);
reorder_marks_shadda(gs);
reorder_marks_other_combining(gs, CanonicalCombiningClass::... | Rust | 0 |
#!./env/bin/python
import pandas as pd
import numpy as np
import os
# ember
import ember
from ember.features import PEFeatureExtractor
from modified_ember import PEFeatureExtractorPFG
def extract_ember_features(folder):
out = []
print("Extract from", folder)
for _, f in enumerate(os.listdir(folder)):
... | Python | 1 |
of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ... | Rust | 0 |
label: s.label,
enabled: true,
draw: batch.upload(ctx),
});
}
let plot = ScatterPlotV2 {
series: series_state,
draw_grid: ctx.upload(grid_batch),
top_left: ScreenPt::new(0.0, 0.0),
dims: ScreenDi... | Rust | 0 |
(name in coord_names for name in ['theta', 'psi', 'φ', 'phi'])
has_phi = any(name in coord_names for name in ['phi', 'φ', 'ϕ'])
if not (has_r and has_theta):
return False
# Check the diagonal structure
for i in range(n):
for j in range(n):
... | Python | 1 |
import gymnasium as gym
from policyiteration import PolicyIteration
# policy iteration 1번,policy improvement 1번을 10번 반복
print("======iter:1======")
N = 10
# environment 생성
env = gym.make('Taxi-v3', render_mode="ansi")
# policy iteration 생성 및 설정
policyIteration = PolicyIteration(env=env, discount_factor=0.95)
for n in ... | Python | 1 |
f_v0.6.1.pkl");
let model_def_other = release_dir.join("vmaf_v0.6.1.pkl.model");
let model_4k = release_dir.join("vmaf_4k_v0.6.1.pkl");
let model_4k_other = release_dir.join("vmaf_4k_v0.6.1.pkl.model");
let header_file = release_dir.join("libvmaf.h");
// CHECKS
if is_debug_mode() {
// Le... | Rust | 0 |
09E667u32 as i32, 0xBB67AE85u32 as i32, 0x3C6EF372u32 as i32, 0xA54FF53Au32 as i32);
let mut vb = _mm_setr_epi32(0x510E527Fu32 as i32, 0x9B05688Cu32 as i32, 0x1F83D9ABu32 as i32, 0x5BE0CD19u32 as i32);
let mut vc = va.clone();
let mut vd = _mm_setr_epi32(t0, t1, blen, flags as i32);
let w = _mm256_load... | Rust | 0 |
ngs.values() if m.get('enabled'))
st.toast(f"✅ 端口验证通过!所有 {enabled_count} 个端口均无冲突")
logger.info(f"端口映射确认成功: 所有 {enabled_count} 个端口均无冲突")
def auto_fix_port_conflicts():
"""
自动修正所有端口冲突
从起始端口开始,为所有启用的节点重新分配不冲突的端口
"""
if 'node_mappings' not in st.session_state:
return
start_... | Python | 1 |
#[test]
fn test_final_approach_by_a_step() {
let constraint: Box<dyn SinglePartConstraint> = Box::new(FinalApprochedByAStep);
run_scale_free_test(&constraint, &[0, 1, 2, 1], 4, true);
run_scale_free_test(&constraint, &[0, 1, 3, 1], 4, false);
run_scale_free_test(&constraint, &[0, 1, ... | Rust | 0 |
}
}
type Dense = usize;
type Sparse = usize;
struct DenseCollection {
dense: Vec<Sparse>,
dense_rev: Vec<Dense>,
}
impl DenseCollection {
fn new() -> DenseCollection {
DenseCollection {
dense: Vec::new(),
dense_rev: Vec::new(),
}
}
fn push(&mut self, elt: Sparse) {
let idx = self... | Rust | 0 |
(msg)
msg = "{}You do so by using the `{}gamble [amount in multiple of 10]` command.\n".format(msg, ctx.prefix)
msg = "{}This pulls from your *xp reserve* - and if you win, adds to your *xp*.\n\n".format(msg)
msg = "{}You can also *feed* me.\n".format(msg)
msg = "{}This is done with the `{}feed [amount]` comma... | Python | 1 |
",
match_reference.game_id, summoner_id, match_reference.role, match_reference.platform_id, match_reference.champion.identifier(), match_reference.lane, queue, match_reference.timestamp).fetch_one(conn).await
}
pub async fn get_match_details(conn: &PgPool, game_id: i64) -> Result<Match, Error> {
query_as!(Match, "... | Rust | 0 |
#Aritmetiksel Operatörler
sayi1 = 10
sayi2 = 3
print("Toplam: ", sayi1 + sayi2)
print("Çıkar: ", sayi1 - sayi2)
print("Çarp: ", sayi1 * sayi2)
print("Böl: ", sayi1 / sayi2)
print("Böl: ", sayi1 // sayi2)
print("Üs: ", sayi1 ** sayi2)
print("Mod: ", sayi1 % sayi2)
#Karşılaştırma Operatörleri
print(sayi1 < sayi2)
pri... | Python | 1 |
ageGroupArray = self.post_data::<StorageGroupArray, Value>(
"performance/StorageGroup/keys/",
&vmaxstoragegroups,
)?;
let ids: Vec<String> = sgmet
.storage_group_info
.iter()
.map(|f| f.storage_group_id.clone())
.collect();
... | Rust | 0 |
# Generated by Django 4.2.7 on 2023-11-12 16:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventory', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='item',
name='in_stock',
f... | Python | 1 |
class Solution:
def maximumSwap(self, num: int) -> int:
li = []
while num > 0:
mod = num % 10
li.append(mod)
num //=10
li.reverse()
for i in range(len(li) - 1):
ind = 0
mx = max(li[i:])
if li[i] != mx:
... | Python | 1 |
cursor.write_f32::<LittleEndian>(slice[1])?;
cursor.write_f32::<LittleEndian>(slice[2])?;
cursor.write_f32::<LittleEndian>(slice[3])?;
Ok(())
}
fn write_matrix(mat: &glm::Mat4, buffer: &mut Vec<u8>) -> ParserResult<()> {
let mut cursor = Cursor::new(buffer);
cursor.seek(SeekFrom::End(0)).unwrap()... | Rust | 0 |
return false;
}
}
Bound::Ex(inner) => {
if collator.compare(inner, outer) == Greater {
return false;
}
}
},
}
true
}
/// Retu... | Rust | 0 |
_pan_end(evt: Event),
on_accept_button(evt: Event),
on_reject_button(evt: Event),
on_anim(t: f64),
on_send_chat(),
on_chat(from: &str, msg: &str),
on_information(msg: &str),
on_new_player(name: &str),
on_player_disconnected(... | Rust | 0 |
rs` and a configuration of
/// `WithSource("regressions")`, the resulting path would be
/// `/home/jsmith/code/project/src/foo/bar.regressions`.
WithSource(&'static str),
/// The string given in this option is directly used as a file path without
/// any further processing.
Direct(&'static str),... | Rust | 0 |
software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Implementation of trait `StorageInfoTrait` on module st... | Rust | 0 |
log2_cuh: usize) {
let shift1 = evc_get_transform_shift(log2_cuw, 0);
let shift2 = evc_get_transform_shift(log2_cuh, 1);
let mut tb = [0i32; MAX_TR_DIM]; /* temp buffer */
tbl_txb0[log2_cuw - 1](coef, &mut tb, log2_cuh);
tbl_txb1[log2_cuh - 1](&tb, coef, (shift1 + shift2), log2_cuw);
}
fn get_ic_r... | Rust | 0 |
ring,
pub result: String,
}
impl arg::AppendAll for OrgFreedesktopSystemd1ManagerJobRemoved {
fn append(&self, i: &mut arg::IterAppend) {
arg::RefArg::append(&self.id, i);
arg::RefArg::append(&self.job, i);
arg::RefArg::append(&self.unit, i);
arg::RefArg::append(&self.result, i)... | Rust | 0 |
pability::Backward, res2_2, 0, stream.clone());
let res2_4 = DeviceResidualConv2dOperator::new(res2_cfg, OpCapability::Backward, res2_3, 0, stream.clone());
let res2_5 = DeviceResidualConv2dOperator::new(res2_cfg, OpCapability::Backward, res2_4, 0, stream.clone());
let res2_6 = DeviceResidualConv2dOperator::new(r... | Rust | 0 |
import operator
import numpy as np
from qecsim import paulitools as pt
from qecsim.model import Decoder, cli_description
@cli_description('Naive ([max_qubits] INT)')
class NaiveDecoder(Decoder):
"""
Implements a naive decoder.
Decoding algorithm:
* Naively iterate through all possible errors, in a... | Python | 1 |
(0, 3);
print!("{:?}", p);
println!("End Dijkstra")
}
use crate::Progress;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct WindowConfig {
pub title: String,
pub label: String,
pub progress: Arc<Progress>,
}
impl WindowConfig {
pub fn new(title: String, label: String, progress: Arc<Prog... | Rust | 0 |
#!/usr/bin/python
#############################################################################
##
## Copyright (C) 2013 Canonical Ltd.
## Contact: http://www.qt.io/licensing/
##
## This file is part of the test suite of the Qt Toolkit.
##
## $QT_BEGIN_LICENSE:LGPL21$
## Commercial License Usage
## Licensees holding va... | Python | 1 |
g, global_step)
if fp16:
msg = (
"Speed %.2f samples/sec Loss %.4f LearningRate %.4f Epoch: %d Global Step: %d "
"Fp16 Grad Scale: %2.f Required: %1.f hours"
% (
speed_tota... | Python | 1 |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.common.config.config import settings
# Create engine with stringified URL
engine = create_engine(str(settings.database_url))
# Session factory
SessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=engine,
... | Python | 1 |
# -*- coding: utf-8 -*-
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class GumroadAccount(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get("url")
def to_str(self):
dfl... | Python | 1 |
import sys
import io
from PIL import Image
from image_segmentation.model import image_segmentation
from edge_detection.model import edge_detection
from edge_smoothing.model import edge_smoothing
from convert_svg.model import convert_svg
import tempfile
import base64
def bytes_to_base64(byte_data):
# Encode bytes ... | Python | 1 |
Boundary::new(BoundaryKind::Start, span)),
map(Token::BEnd, |(_, span)| Boundary::new(BoundaryKind::End, span)),
map(Token::BWord, |(_, span)| Boundary::new(BoundaryKind::Word, span)),
map(pair(Token::Not, Token::BWord), |((_, span1), (_, span2))| {
Boundary::new(Boun... | Rust | 0 |
eturn ShutdownMethod::AlreadyExited;
}
let stop_time = SteadyTime::now() + Duration::seconds(8);
loop {
if let Ok(Some(_status)) = self.try_wait() {
return ShutdownMethod::GracefulTermination;
}
if SteadyTime::now() < stop_time {
... | Rust | 0 |
inner: value,
loaded_contexts: MaybeOwned::Owned(FrozenMap::new())
}
}
}
pub async fn compact<'a, T, F>(input: JsonLdInput<'_, T>, ctx: Option<Cow<'a, T>>, options: &'a JsonLdOptions<'a, T, F>) -> Result<T::Object>
where
T: ForeignMutableJson + BuildableJson,
F: for<'b> Fn(&'b str, &'b Option<LoadDocumentOpti... | Rust | 0 |
hader.uniform(b"color\0");
let position = shader.vertex_data(b"position\0");
let texpos = shader.vertex_data(b"texpos\0");
let acolor = shader.vertex_data(b"acolor\0");
Style {
shader, matrix_uniform, has_camera, camera_uniform, fog,
range, position, texpos, alpha, has_fog, color, acolor,
}
}
}
struc... | Rust | 0 |
class AccessStrategy:
"""Clase base para estrategias de acceso."""
def has_access(self, user_role):
raise NotImplementedError
class AdminAccess(AccessStrategy):
"""Acceso para administradores."""
def has_access(self, user_role):
return user_role == "admin"
class EditorAccess(AccessStra... | Python | 1 |
ion_lengths[1], num_features)`
self.condition_lengths = [77, 257]
# Which transformer to use to encode which condition.
# E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])`
self.transformer_index_for_condition = [1, 0]
def forwa... | Python | 1 |
push(t);
}
idx_vec
}
}
pub struct IdxVecIterator<I, T> {
next_idx: usize,
iter: <Vec<T> as IntoIterator>::IntoIter,
_phantom: PhantomData<fn(&I)>,
}
impl<I, T> Iterator for IdxVecIterator<I, T>
where
I: Idx,
{
type Item = (I, T);
#[inline]
fn next(&mut self) -> Option<... | Rust | 0 |
the grid of position embeddings when loading from state_dict. Adapted from
# https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224
#print('Resized position embedding: %s to %s', posemb.shape, posemb_new.shape)# 修改
ntok_new = posemb_n... | Python | 1 |
(MCLK::DIV::DIV1_0)
///
/// Double Speed (ADCCTL::FM::DOUBLE_SPEED_50_100_KHZ)
/// --------------------------------------------------
/// 64kHz, 192x, 1.5 (MCLK::DIV::DIV1_5)
/// 96kHz, 128x, 1.0 (MCLK::DIV::DIV1_0)
///
/// Quad Speed (ADCCTL::FM::QUAD_SPEED_100_200_KHZ)
/// ---------------------------------------... | Rust | 0 |
ing blobs in a specific stage."""
storage = get_storage()
test_uuid = "test-uuid-list"
test_data = b"test data for listing"
# Upload a blob to OCR_RAW stage
storage.upload_blob(test_uuid, Stage.OCR_RAW, ".json", test_data)
# List blobs in OCR_RAW stage
... | Python | 1 |
::Error> {
// Open the file
let f = File::open(path)?;
let mut file = BufReader::new(f);
// Read the first line of the file
let mut buffer = String::new();
file.read_line(&mut buffer)?;
// Read the tags, remove empty ones
let mut t: Vec<&str> = buffer.as_str().split(',').map(|s| s.trim... | Rust | 0 |
#[cfg(feature = "vmrun")]
pub use vmrun::*;
fn get_key_value(s: &str) -> Option<(&str, &str)> {
let kv: Vec<&str> = s.splitn(2, '=').collect();
if kv.len() < 2 {
return None;
}
let (key, mut value) = (kv[0].trim(), kv[1].trim());
if value.starts_with('"') && value.ends_with('"') {... | Rust | 0 |
ain_config.train_distribute = 0
pipeline_config.train_config.num_gpus_per_worker = 1
pipeline_config.train_config.sync_replicas = False
config_util.save_pipeline_config(pipeline_config, self._test_dir)
test_pipeline_config_path = os.path.join(self._test_dir, 'pipeline.config')
hyperparam_str = ''
... | Python | 1 |
M=M,
D=D,
stride_batch=K.stride(0),
stride_head=K.stride(1),
stride_seq=K.stride(2),
stride_dim=K.stride(3),
NUM_HEADS=NUM_HEADS,
SEQ_LEN=SEQ_LEN,
BLOCK_Q=BLOCK_SIZE_MACRO,
BLOCK_KV=BLOCK_SIZE_MICRO,... | Python | 1 |
"""
This moddule provides utilities for graph-based image processing.
This includes creating adjacency graphs of pixels in an image, finding the
central pixel in an image, finding (minimum-cost) paths across pixels, merging
and cutting of graphs, etc.
"""
import lazy_loader as lazy
__getattr__, __dir__, __all__ = l... | Python | 1 |
32> {
self.bid.as_ref()
}
pub fn reset_bid(&mut self) {
self.bid = None;
}
pub fn set_bid_size(&mut self, bid_size: f32) {
self.bid_size = Some(bid_size);
}
pub fn with_bid_size(mut self, bid_size: f32) -> MarketData {
self.bid_size = Some(bid_size);
self
}
pub fn bid_size(&self)... | Rust | 0 |
# ternary operator in python
# syntax
[on_true] if [expression] else [on_false]
i=1
print("positive") if(i>0) else print("negative")
| Python | 1 |
endPacket(i32),
#[error("Error draining decoder: {0}")]
DrainDecoder(i32),
#[error("Error receiving frame: {0}")]
ReceiveFrame(i32),
#[error("Failed to initialize swr context")]
InitializeSwr,
}
use rand::{seq::SliceRandom, thread_rng, Rng};
use std::cmp::{PartialEq, PartialOrd};
use std::fmt;
... | Rust | 0 |
_variable].attrs['flag_meanings'][1]
== 'Shift in data detected with CUSUM algorithm: k=1.0'
)
assert ds[qc_variable].attrs['flag_assessments'][1] == 'Indeterminate'
ds.qcfilter.add_step_change_test(variable, k=4, prepend_text='ARM')
index = ds.qcfilter.get_qc_test_mask(var_name=variable, test_... | Python | 1 |
utils.create_tensorboard_writer(opt)
print('[training]')
n_iter = 0
for i in range(200):
t0 = time.time()
train_loss = train(opt.epoch_size, opt.npred)
valid_loss = test(int(opt.epoch_size / 2), opt.npred)
n_iter += opt.epoch_size
model.intype('cpu')
torch.save({'model': cost,
... | Python | 1 |
match args.next() {
Some(key) => Key::new(&key),
None => {
eprintln!("Expected key");
return;
}
}
};
kademlia.start_providing(key).expect("Failed to start providing k... | Rust | 0 |
#!/usr/bin/env python3
import json
import os
from pathlib import Path
def run(input_path, apps_path, out_path):
default_command_flags = [
"--host",
"${host}",
"--port",
"${port}",
"--authKey",
"${secret}",
"--server",
]
default_ready_line = "App run... | Python | 1 |
nt_steps = opts.print_steps
c.tensorboard_steps = opts.tb_steps
c.image_snapshot_steps = opts.img_snshot_steps
c.network_snapshot_steps = opts.net_snshot_steps
c.learning_rate = opts.lr
c.l2_lambda = opts.l2_lambda
c.lpips_lambda = opts.lpips_lambda
c.id_lambda = opts.id_lambda
c.reg_la... | Python | 1 |
essages: Vec<CosmosMsg> = vec![CosmosMsg::Wasm(WasmMsg::Instantiate {
code_id: config.pair_code_id,
send: vec![],
label: format!(
"{}-{}-pair-{}-{}",
asset_infos[0],
asset_infos[1],
env.contract.address.clone(),
config.pair_code_id
... | Rust | 0 |
readPointsFromFile(pointSetPath1)
pointSet2 = self.evaluation.readPointsFromFile(pointSetPath2)
normalizedPointSet1 = self.evaluation.normalizePoints(pointSet1, self.spacings[f"copd{imageNumber}"])
normalizedPointSet2 = self.evaluation.normalizePoints(pointSet2, self.spa... | Python | 1 |
from typing import Dict, List, Tuple
if 'custom' not in globals():
from mage_ai.data_preparation.decorators import custom
@custom
def models(*args, **kwargs) -> Tuple[List[str], List[Dict[str, str]]]:
"""
models: comma separated strings
linear_model.Lasso
linear_model.LinearRegression
... | Python | 1 |
legacy: LegacyConfig::default(),
remote: (),
_marker: std::marker::PhantomData,
}
}
}
impl<C> NoiseConfig<IK, C, (PublicKey<C>, identity::PublicKey)>
where
C: Protocol<C> + Zeroize,
{
/// Create a new `NoiseConfig` for the `IK` handshake pattern (initiator side)... | Rust | 0 |
];
assert!(!entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
assert_eq!(tick_hash_count, hashes_per_tick + 1);
tick_hash_count = 0;
// full tx entry without tick entry should fail
entries = vec![full_tx_entry];
assert!(!entries.verify_tick_hash_cou... | Rust | 0 |
struct Arguments {
pub input_file_path: String,
pub output_rules_path: String,
pub min_support: f64,
pub min_confidence: f64,
pub min_lift: Option<f64>,
}
pub fn parse_args_or_exit() -> Arguments {
let mut args: Arguments = Arguments {
input_file_path: String::new(),
output_rul... | Rust | 0 |
Args:
base_sleep: Base sleep duration in seconds
"""
if self.current_cpu_usage > 90:
sleep_time = base_sleep * 3
elif self.current_cpu_usage > 80:
sleep_time = base_sleep * 2
elif self.current_cpu_usage > 70:
sleep_time = base_slee... | Python | 1 |
n frequencies if 50 <= f < 100):,}")
print(f" Very common (≥100 proteins): {sum(1 for f in frequencies if f >= 100):,}")
# Top terms
print(f"\nTop 10 most frequent terms:")
for i, (term, count) in enumerate(stats['term_counts'].most_common(10), 1):
print(f" {i:2d}.... | Python | 1 |
e(frame_notebook2)
frame_busqueda.pack(anchor="n")
label_busqueda = ttk.Label(frame_busqueda, text="Codigo:")
label_busqueda.pack(anchor="ne", side="left", padx=10, pady=10)
entry_busqueda_codigo = ttk.Entry(frame_busqueda)
entry_busqueda_codigo.pack(anchor="ne", side="left", padx=10, pady=10)
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.