text string | label_name string | labels int64 |
|---|---|---|
# ======================================================================= #
# Copyright (C) 2024 Dominik Willner <th33xitus@gmail.com> #
# #
# https://github.com/dw-0/simple-config-parser #
# ... | Python | 1 |
ok());
let s = settings.unwrap();
match s.provisioning() {
Provisioning::External(ref external) => {
assert_eq!(external.endpoint().as_str(), "http://localhost:9999/");
}
_ => unreachable!(),
};
}
#[test]
fn case_of_names_of_keys_i... | Rust | 0 |
uper::super::Foundation::PSTR, pst: *mut super::super::Foundation::SYSTEMTIME, dwreserved: u32) -> super::super::Foundation::BOOL;
#[doc = "*Required features: 'Win32_Networking_WinInet', 'Win32_Foundation'*"]
#[cfg(feature = "Win32_Foundation")]
pub fn InternetTimeToSystemTimeW(lpsztime: super::super::Foun... | Rust | 0 |
from __future__ import print_function, unicode_literals
import shutil
from invoke import task
@task
def docs(ctx, warn=False):
ctx.run("make -C docs/ html", warn=warn)
@task
def test(ctx, coverage=False, warn=False):
cmd = "py.test"
if coverage:
cmd += " --cov=spotify --cov-report=term-missing... | Python | 1 |
NAMESPACE_REGISTRY_PREFIX) + &bytes_to_hex_str(hash)[..64])
}
/// Returns a state address for a given contract registry
///
/// # Arguments
///
/// * `name` - the name of the contract registry
fn compute_contract_registry_address(name: &str) -> String {
let hash: &mut [u8] = &mut [0; 64];
let mut sha = Sha512... | Rust | 0 |
(context, code, e);
for _ in 0..pop_num {
code.push(sp(loc, B::Pop));
}
}
C::Jump(lbl) => code.push(sp(loc, B::Branch(label(lbl)))),
C::JumpIf {
cond,
if_true,
if_false,
} => {
exp_(context, code, con... | Rust | 0 |
fn new() -> Self {
/// Self { number: 10 }
/// }
/// }
///impl From<Box<TenService>> for Box<dyn NumberService> {
/// fn from(x: Box<TenService>) -> Self {
/// x
/// }
/// }
///
/// #[derive(Dependency)]
/// struct Controller {
/// number... | Rust | 0 |
std::io::{self, Read};
///
/// fn main() -> io::Result<()> {
/// // "test" string encoded.
/// let enc = vec![
/// 0x62, 0x76, 0x78, 0x2d, 0x04, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x62, 0x76,
/// 0x78, 0x24,
/// ];
/// let mut decoder = LzfseRingDecoder::default();
/// let mu... | Rust | 0 |
ward_grad=False,
supports_autograd=False,
),
OpInfo(
name="flex_attention",
variant_test_name="simple",
op=flex_attention,
sample_inputs_func=sample_inputs_flex_attention,
dtypes=custom_types(torch.float16, torch.float32),
supports_out=False,
check... | Python | 1 |
#!/usr/bin/env python
#
# This allows running the matplotlib tests from the command line: e.g.
#
# $ python tests.py -v -d
#
# The arguments are identical to the arguments accepted by nosetests.
#
# See https://nose.readthedocs.org/ for a detailed description of
# these options.
import sys
if __name__ == '__main__... | Python | 1 |
run() not called"),
Some(mutex) => mutex,
}
}
}
/// Start the usage tracker. This should only be called ONCE.
///
/// # Arguments:
///
/// * `kind` - Which usage tracker to start
/// * `cuboid_root_path` - Root of cached cuboids
pub fn run(kind: UsageTrackerType) {
if let UsageTrackerType:... | Rust | 0 |
#!/usr/bin/python3
for a in range(0, 9):
for b in range(a + 1, 10):
if (a == 8 and b == 9):
print("{:d}{:d}".format(a, b))
else:
print("{:d}{:d}".format(a, b), end=", ")
| Python | 1 |
Assign |
BitAndAssign |
BitXorAssign |
BitOrAssign => true,
_ => false
}
}
#[inline]
pub fn category(&self) -> OperatorCategory {
match self {
In |
New |
... | Rust | 0 |
Error::<T, I>::NonexistentCommodity
);
ensure!(
Self::total_for_account(dest_account) < T::UserCommodityLimit::get(),
Error::<T, I>::TooManyCommoditiesForAccount
);
let xfer_commodity = (*commodity_id, <T as Config<I>>::CommodityInfo::default());
... | Rust | 0 |
# Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation (FSF), either version 3 of the ... | Python | 1 |
mbling/searching/discovery/mod.rs<gh_stars>1-10
pub mod general_approach;
pub mod constraint_space;
pub use self::general_approach::{GraphExplorerBuilder, GraphExplorer, GraphDiscovery, GeneralDiscoveryNode, GeneralDiscoveryArgs, EmpiricalTripleAdviser};
pub use self::constraint_space::{IntTreeSearchNode, IntTreeSearc... | Rust | 0 |
Ok(Some(x.into_string()?)),
Err(_) => Ok(None),
}
}
fn lookup_is_log(tree: &nvpair::NvList) -> Option<bool> {
tree.lookup_uint64(sys::zpool_config_is_log())
.map(|x| x == 1)
.ok()
}
fn lookup_guid(tree: &nvpair::NvList) -> Option<u64> {
tree... | Rust | 0 |
env_streams = [
"humidity",
"barometer",
"ambient-light",
"ambient-noise",
]
motion_streams = [
"gyroscope",
"accelerometer",
]
fitbit_alt_streams = [
"steps",
"distance",
"heart_rate",
"sedentary_minutes",
"lightly_active_minutes",
"moderately_active_minutes",
"ver... | Python | 1 |
# -*- coding: utf-8 -*-
# @Time : 2019/4/18 20:47
# @Author : Alan
# @Email : xiezhengwen2013@163.com
# @File : load_dbdata.py
# @Software: PyCharm
import pymysql
import pandas as pd
from sqlalchemy import create_engine
def create_db():
connect = pymysql.connect( # 连接数据库服务器-*-*-
user="root",
... | Python | 1 |
ryption.encrypt(&message);
let pickle = decryption.pickle(PicklingMode::Unencrypted);
let decryption = OlmPkDecryption::unpickle(pickle, PicklingMode::Unencrypted).unwrap();
let plaintext = decryption.decrypt(encrypted_message).unwrap();
assert_eq!(message, plaintext);
}
#[te... | Rust | 0 |
4u32;
#[doc = "*Required features: `\"Win32_Devices_ImageAcquisition\"`*"]
pub const WIA_IPA_DEPTH_STR: &str = "Bits Per Pixel";
#[doc = "*Required features: `\"Win32_Devices_ImageAcquisition\"`*"]
pub const WIA_IPA_FILENAME_EXTENSION: u32 = 4123u32;
#[doc = "*Required features: `\"Win32_Devices_ImageAcquisition\"`*"]
... | Rust | 0 |
.pt',
motion_std_path='/CT/EgoMocap/work/EgoOmniMocap/projects/TLControl/demo/info_motion_std.pt',
# save_path='/CT/EgoMocap/work/EgoOmniMocap/work_dirs/test_imuposer_dataset_mask/results_save.pkl'
),
dict(type='AgrolMPJPE', mode='p-mpjpe',
motion_mean_path='/CT/EgoMocap/work/Ego... | Python | 1 |
ed_distances_indices] = 1
return mkp_gt
if __name__ == "__main__":
# Visualize the Kitti lidar dataset and its ground truth trajectory
dataset = KittiLidarOdomDataset(dataset_config.LIDAR_PATH, dataset_config.GT_PATH, include_sequences=[0])
velo_to_cam_trans = read_calib_file(os.path.join... | Python | 1 |
_ferris_pointer_exited(
&mut self,
_sender: &Object,
_e: &PointerRoutedEventArgs,
) -> Result<()> {
self.happy_ferris_image
.set_render_transform_origin(Point { x: 0f32, y: 1f32 })?;
self.happy_ferris_collapse_storyboard.begin()
}
fn set_link_item_click_h... | Rust | 0 |
oll_diff: 0.0,
text: vec![],
}
}
pub fn step(&mut self) {
self.mouse_actions = vec![];
self.key_actions = vec![];
self.scroll_diff = 0.0;
self.mouse_point_prev = self.mouse_point;
self.text.clear();
}
pub fn handle_event(&mut self, event: &Wi... | Rust | 0 |
2).powf(-7.0/2.0) * (ao_dp * (1.0 + (1.5 * n2) + (4.0 * e0 * n) + (e0 * n3)) + 1.5 * (k2 * xi)/(1.0 - n2) * (-0.5 + (1.5 * O2)) * (8.0 + (24.0 * n2) + (3.0 * n4)));
// C₁ = B*C₂
let C1 = Bstar * C2;
// (qₒ − s)⁴ξ⁵A₃₀ nₒ" aE sin iₒ
// C₃ = -----------------------------
// k₂eₒ
... | Rust | 0 |
# Copyright 2019-2020 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS"... | Python | 1 |
,
&["abc"],
"abcdefghijklmnopqrstuvwxyzabcdefghijk",
&[(0, 0, 3), (0, 26, 29)]
),
];
// Now define a test for each combination of things above that we want to run.
// Since there are a few different combinations for each collection of tests,
// we define a couple of macros to avoid repetiti... | Rust | 0 |
'] = position.y
Logger.log_params['stage_z'] = position.z
Logger.log_params['ion_beam_shift_x'] = Logger._ion.beam_shift_x
Logger.log_params['ion_beam_shift_y'] = Logger._ion.beam_shift_y
@staticmethod
def save_log(slice_number=None):
"""Save yaml dict log to file"""
log... | Python | 1 |
vg_origin_get(x: *mut c_double,
y: *mut c_double);
pub fn efl_vg_mask_set(m: *mut Efl_Vg);
pub fn efl_vg_mask_get() -> *mut Efl_Vg;
pub fn efl_vg_interpolate(from: *const Efl_Vg_Base,
to: *const Efl_Vg_Base,
pos_map: c_... | Rust | 0 |
writer.add_scalar("Policy/policy_loss", losses[1], count_steps)
writer.add_scalar("Policy/entropy_loss", losses[2], count_steps)
writer.add_scalar('Policy/learning_rate', lr_scheduler.get_lr()[0], count_steps)
# log stats
if update > 0 an... | Python | 1 |
ac7a90de8837d49708e76310767cbe
4af18594d
client_nonce: 46498f95ec7986f0602019b3fbb646db87a2fdbc12176d4f7ab74fa
5fadace60
server_keyshare: 022aa8746ab4329d591296652d44f6dfb04470103311bacd7ad5
1060ef5abac41b
client_keyshare: 02a9f857ad3eabe09047049e8b8cee72feea2acb7fc487777c0b
22d3add6a0e0c0
server_private_keyshare: 48a5... | Rust | 0 |
max_align_t ) , "::" , stringify ! ( __clang_max_align_nonce2 ) )) ;
}
# [repr ( C )] # [derive ( Debug , Copy , Clone )] pub struct ModelState {
_unused : [u8 ; 0] ,
}
# [repr ( C )] # [derive ( Debug , Copy , Clone )] pub struct StreamingState {
_unused : [u8 ; 0] ,
}
# [doc = " @brief Stores text of an individu... | Rust | 0 |
_code_2106<filename>rust/day_5/src/lib.rs<gh_stars>1-10
extern crate crypto;
use std::str::Chars;
use crypto::md5;
use crypto::digest::Digest;
#[derive(Debug)]
pub struct Door(pub String);
impl Door {
pub fn hash_id_with_iteration(&self, iteration: u32) -> String {
let mut tester: md5::Md5 = md5::Md5::... | Rust | 0 |
rator<'a, W, F>
where
W: Semiring,
F: Fst<W>,
{
type Item = StateId;
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(s) = self.state_iter.next() {
if unsafe { self.fst.is_final_unchecked(s) } {
return Some(s);
}
... | Rust | 0 |
gralBitfieldType::new(location, name).into())
}
}
pub fn build(self) -> Struct {
unimplemented!()
}
}
use crate::{
chmod_error, chown_error, link_error, Result, CHARSET, ENV_FORMATTER, FORMATTER_FULL,
FORMATTER_JSON, FORMATTER_PRETTY, ID_LEN,
};
use fslock::{LockFile, ToOsStr};
use ... | Rust | 0 |
import onnxruntime as ort
from transformers import CLIPTokenizer
from optimum.onnxruntime import ORTStableDiffusionPipeline
from diffusers.schedulers import PNDMScheduler
main_dir=r"C:\Users\K_ADMIN\Desktop\AMD GenAI\SD_FaceGen\FaceGen_ONNX"
vaip_config = "C:/Users/K_ADMIN/Desktop/AMD GenAI/GPT J/gpt-j-6B-int8-dynamic... | Python | 1 |
yaml_modifier.final_val
== serialized_modifier.final_val
== obj_modifier.final_val
)
assert (
yaml_modifier.start_epoch
== serialized_modifier.start_epoch
== obj_modifier.start_epoch
)
assert (
yaml_modifier.end_epoch
== serialized_modifier.end_e... | Python | 1 |
es.clone(), halves);
let mut bv = BitVec::from_elem(len, false);
bv.clone_from(&ones);
assert_eq!(bv, ones);
bv.clone_from(&zeros);
assert_eq!(bv, zeros);
bv.clone_from(&halves);
assert_eq!(bv, halves);
}
#[test]
fn len_is_empty() {
let len =... | Rust | 0 |
ERROR: type should be string, got " https://docs.rs/sauron/0/sauron/type.Node.html\n///\n/// Note: `node!` macro is used since it is not an html tag\n/// while most other framework uses `html!` macro, this prevents\n/// the library to have collision with the `html` tag, when used as tag macro\n#[proc_macro]\npub fn node(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n node::to_token_stream(input).into()\n}\nuse discrete::{DiscreteDist32};\nuse env::{Env, DiscreteEnv, EnvRepr, EnvConvert, Action, DiscreteAction, Response, Value, Episode, EpisodeStep};\n\nuse operator::prelude::*;\nuse operator::rw::{ReadBuffer, ReadAccumulateBuffer, WriteBuffer, AccumulateBuffer};\nuse rng::xorshift::{Xorshiftplus128Rng};\nuse sharedmem::{RwSlice};\n\nuse rand::{Rng};\nuse std::cell::{RefCell};\nuse std::cmp::{min};\nuse std::marker::{PhantomData};\nuse std::rc::{Rc};\n\npub struct EpisodeStepSample<E> where E: Env {\n //pub env: Rc<RefCell<E>>,\n pub env: Rc<E>,\n pub act_idx: Option<u32>,\n pub suffix_r: Option<E::Response>,\n pub baseline: Option<f32>,\n weight: Option<f32>,\n}\n\nimpl<E> EpisodeStepSample<E> where E: Env {\n pub fn new(env: Rc<E>, act_idx: Option<u32>, suffix_r: Option<E::Response>) -> EpisodeStepSample<E> {\n EpisodeStepSample{\n env: env,\n act_idx: act_idx,\n suffix_r: suffix_r,\n baseline: None,\n weight: None,\n }\n }\n\n pub fn set_baseline(&mut self, baseline: f32) {\n self.baseline = Some(baseline);\n }\n\n pub fn init_weight(&mut self) {\n self.weight = Some(self.suffix_r.map(|r| r.as_scalar()).unwrap() - self.baseline.unwrap_or(0.0));\n }\n}\n\nimpl<E> SampleDatum<[f32]> for EpisodeStepSample<E> where E: Env + EnvRepr<f32> {\n fn extract_input(&self, output: &mut [f32]) -> Result<(), ()> {\n self.env.extract_observable(output);\n Ok(())\n }\n}\n\nimpl<E> SampleLabel for EpisodeStepSample<E> where E: Env {\n fn class(&self) -> Option<u32> {\n self.act_idx\n }\n\n fn target(&self) -> Option<f32> {\n self.suffix_r.map(|r| r.as_scalar())\n }\n}\n\nimpl<E> SampleLossWeight<ClassLoss> for EpisodeStepSample<E> where E: Env {\n fn weight(&self) -> Option<f32> {\n self.weight\n }\n\n fn mix_weight(&mut self, w: f32) -> Result<(), ()> {\n self.weight = Some(self.weight.unwrap_or(1.0) * w);\n Ok(())\n }\n}\n\npub struct BasePgWorker<E, PolicyOp> where E: Env {\n batch_sz: usize,\n minibatch_sz: usize,\n max_horizon: usize,\n act_dist: DiscreteDist32,\n episodes: Vec<Episode<E>>,\n episode_ks: Vec<usize>,\n step_values: Vec<Vec<f32>>,\n final_values: Vec<Option<f32>>,\n _marker: PhantomData<(E, PolicyOp)>,\n}\n\nimpl<E, PolicyOp> BasePgWorker<E, PolicyOp>\nwhere E: Env + EnvRepr<f32> + Clone,\n E::Action: DiscreteAction,\n PolicyOp: DiffOperatorInput<f32, EpisodeStepSample<E>> + DiffOperatorOutput<f32, R" | Rust | 0 |
ow;
use std::fmt;
use std::mem::size_of;
use tract_linalg::align;
use tract_linalg::f16::f16;
#[cfg(feature = "serialize")]
use serde::ser::{Serialize, Serializer};
use std::sync::Arc;
use crate::datum::TryInto;
use crate::ops::prelude::*;
#[derive(Debug, Clone)]
pub struct SharedTensor(Arc<Tensor>);
impl SharedTe... | Rust | 0 |
{emoji}
</div>
<div class="emoji">
{emoji}
</div>
<div class="emoji">
{emoji}
</div>
<div class="emoji">
{emoji}
</div>
</div>
""",
unsafe_allow_html=True,
)
def example():
rain(
emoji="🎈",
... | Python | 1 |
possible to change the slot duration after the chain has started.
// Attempting to do so will brick block production.
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
// Time is measured by number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
pub const HOURS: Bloc... | Rust | 0 |
_eq!(cycle_length(7), Some(6));
assert_eq!(cycle_length(8), None);
assert_eq!(cycle_length(9), Some(1));
assert_eq!(cycle_length(10), None);
}
<gh_stars>1-10
// Copyright 2018 <NAME> <<EMAIL>>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compli... | Rust | 0 |
x S r SSKJrJrJrJrJrJrJrJ r J
r
JrJrJ
r
JrJrJrJrJrJrJrJrJrJrJrJrJrJr g)
This file is in the process of migration to `torch/ao/quantization`, and
is kept here for compatibility while the migration process is ongoing.
If you are a... | Python | 1 |
clone();
let eval = db
.run(move |client| student_eval(client, &id, &group_id, &cloned_cycle, &cloned_today))
.await
.wrap_err("student_eval error")
.map_err(|_err| Status::InternalServerError)?;
let cloned_cycle2 = cycle.clone();
let cloned_today2 = today.clone();
let co... | Rust | 0 |
tanhf(n: f32) -> f32;
}
}
pub mod process {
#[link(wasm_import_module = "/wasp/process")]
extern "C" {
#[link_name = "/wasp/process/yield__1"]
pub fn yield_();
#[link_name = "/wasp/process/nanosleep__1"]
pub fn nanosleep(duration: u64);
#[link_name = "/wasp/process/... | Rust | 0 |
refi1[REFP_0]) {
mv1_l0[0] = 0;
mv1_l0[1] = 0;
}
if !REFI_IS_VALID(refi1[REFP_1]) {
mv1_l1[0] = 0;
mv1_l1[1] = 0;
}
if (refi0[REFP_0] == refi1[REFP_0]) && (refi0[REFP_1] == refi1[REFP_1]) {
idx = if (mv0_l0[MV_X] - mv1_l0[MV_X... | Rust | 0 |
import os
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.preprocessing.image import ImageDataGenerator
nb_epoch = 50
result_dir = 'results'
if not os.path.exists(result_dir):
os.mkdir(result_dir)
def... | Python | 1 |
continue;
}
};
let send_result = match message {
InboundMessage::Data(d) => inbound_socket.send(d.as_bytes(), 0),
InboundMessage::Restart =>
inbound_socket.send(serde_json::to_string(&InboundMessage::Restart).unwrap().as_bytes(... | Rust | 0 |
class Apriori:
def __init__(self, dataSet, minSupport=.5, ruleSupport=.7, is_show_rule=False):
self.dataSet = dataSet
self.minSupport = minSupport
self.ruleSupport = ruleSupport
self.is_show_rule = is_show_rule
# 计算支持项,全部支持项与最小支持项
self.L, self.supportData = self.apr... | Python | 1 |
def sort_by_value(data, reverse=False):
"""
Sorts a dictionary by value in ascending or descending order.
Args:
data: A dictionary to be sorted.
reverse: Boolean flag to sort in descending order (default: False - ascending).
Returns:
A list of tuples containing the ... | Python | 1 |
temp_video_path,
cv2.VideoWriter_fourcc(*'mp4v'),
fps,
(width, height)
)
# 写入所有帧
for image in images:
frame = self.tensor_to_cv2(image)
writer.write(frame)
writer.release()
... | Python | 1 |
_position_ids": decoder_position_ids,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
"use_cache": use_cache, # change this to avoid caching (presumably for debugging)
}
def build(self, input_shap... | Python | 1 |
import requests
import json
from . import Common
class SendHttp:
def sent_get(self,url, paraData=None):
res = requests.get(Common.baseUrl()+url, params=paraData)
return res.json()
def sent_get_bycookies(self,url,cookies):
res = requests.get(Common.baseUrl()+url, cookies=cookies)
... | Python | 1 |
}
pub type __compar_fn_t = ::std::option::Option<
unsafe extern "C" fn(
arg1: *const ::std::os::raw::c_void,
arg2: *const ::std::os::raw::c_void,
) -> ::std::os::raw::c_int,
>;
extern "C" {
pub fn bsearch(
__key: *const ::std::os::raw::c_void,
__base: *const ::std::os::raw::c... | Rust | 0 |
import uuid
SATOSHIS_IN_ONE_BITCOIN = 100000000
TRANSACTION_FEE = 0.015
BTC_STARTING_BALANCE = 1
ADMIN_API_KEY = "admin_api_key"
DEFAULT_WALLET_PREFIX = "default_wallet_"
DEFAULT_WALLET_BALANCE = 0
SAME_OWNERS_TRANSACTION_FEE = 0
MINIMUM_TRANSACTION_FEE = 1
MAX_WALLETS = 3
TEST_UUID = uuid.uuid4()
| Python | 1 |
from pathlib import Path
import os
import argparse
import random
import numpy as np
from sklearn.utils import shuffle
if __name__ == "__main__":
"""
this is a standalone script to process a km file
specifically, to dedup or remove tokens that repeat less
than k times in a row
"""
parser = argp... | Python | 1 |
embed=error_embed, ephemeral=True)
else:
await interaction.response.send_message(embed=error_embed, ephemeral=True)
except:
pass
@discord.ui.button(
label="📧 Já Estou Inscrito",
style=discord.ButtonStyle.secondary,
custom_id="... | Python | 1 |
unwrap();
Ok(rc)
})
}
pub fn set<T: Any>(hwnd: HWND, value: T) -> Result<Option<impl Deref<Target = T>>, Error> {
let rc = Rc::new(value);
ThreadLocal::with(|tl|{
let mut windows = tl.windows.borrow_mut();
let window = windows.get_mut(&hwnd).ok_or(Error::new("kakistocracy::windows::... | Rust | 0 |
**kwargs)
return loss
def get_acc(self, scores, labels, valid_mode):
"""get acc"""
top1 = paddle.metric.accuracy(input=scores, label=labels, k=1)
top5 = paddle.metric.accuracy(input=scores, label=labels, k=5)
_, world_size = get_dist_info()
#NOTE(shipping): deal with... | Python | 1 |
# This file was generated by 'versioneer.py' (0.23) from
# revision-control system data, or from the parent directory name of an
# unpacked source archive. Distribution tarballs contain a pre-generated copy
# of this file.
import json
version_json = '''
{
"date": "2025-08-05T11:08:32-0700",
"dirty": false,
"error... | Python | 1 |
zer in optimizers:
with ops.Graph().as_default() as g, self.session(graph=g) as session:
x, var, loss, global_step = _setup_model()
update_var = variable_scope.get_variable(
"update", [], initializer=init_ops.constant_initializer(10))
update_op = state_ops.assign(update_var, 20... | Python | 1 |
cenario_files[i] for i in [0,1,2,3,5,6,8,9,10,11]]
# 逐个加载模型并处理所有场景
models = [
(Llama3_llava_next_8b_hf_text_only, "Llama3_llava_next_8b_hf_text_only"),
]
# 对每个模型分别进行推理
for model_class, model_name in models:
print(f"Processing with model: {model_name}")
if not os.pat... | Python | 1 |
import os
import csv
import shutil
import urllib.request
def get_score(model_name=None, dataset_name=None,
dataset_res=None, dataset_split=None, task_name=None):
# download the csv file from server
url = "https://www.cs.cmu.edu/~clean-fid/files/leaderboard.csv"
local_path = "/tmp/leaderboard.csv"
... | Python | 1 |
# Write part file
part_file = export_dir / f"part-{i:05d}.parquet"
chunk_df.to_parquet(part_file, compression='snappy', index=False)
print(f"Created: {part_file}")
# Create manifest.json
manifest = self._create_manifest(date_range, run_id, num_parts, len(rec... | Python | 1 |
targets = torch.tensor(targets)
# 返回填充后的输入序列和目标输出的张量
return padded_contexts, targets
def train(model, dataloader, num_epochs=100, learning_rate=0.001):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device) # 将模型移动到GPU
# 初始化损失函数,并忽略索引为0的输出(通常用于padding),然后将损失函数移动到选定... | Python | 1 |
{
assert!(maybe_mode.is_none());
Some(app.primary.clear_sim())
} else {
None
};
// Just apply this here, don't plumb to SimFlags or anything else. We recreate things using
// these flags later, but we don't want to keep applying the same edits.
if let Some(edits_name) = ... | Rust | 0 |
#[test]
fn test_render_config_validation() {
let render_config = RenderConfig {
vertical_scale: 0.0, // invalid
tile_lens: TileLens::Surface, // valid
show_features: false, // valid
max_runoff: Meter3(5.0), // valid (can't validate Meter3 atm)
max_... | Rust | 0 |
}
ret
}
pub(crate) fn ray_pow(x: &U256, y: u32) -> U256 {
let mut z = RayMath::ray().clone();
for _ in 0..y {
z = RayMath::ray_mul(&z, x)
}
z
}
pub fn fac(u: u64) -> u64 {
let mut r: u64 = 1;
for i in 1..=u {
r = r * i
}
r
}
// // 泰勒展开式 sinx = x - ... | Rust | 0 |
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional
from datetime import datetime, timedelta
from ..services.scheduler_service import scheduler_service
from ..services.task_service import TaskService
from ..schemas.sched... | Python | 1 |
-bit`
Rol_rm32_1 = 435,
/// `ROL r/m64, 1`
///
/// `o64 D1 /0`
///
/// `X64`
///
/// `64-bit`
Rol_rm64_1 = 436,
/// `ROR r/m16, 1`
///
/// `o16 D1 /1`
///
/// `8086+`
///
/// `16/32/64-bit`
Ror_rm16_1 = 437,
/// `ROR r/m32, 1`
///
/// `o32 D1 /1`
///
/// `386+`
///
/// `16/32/64-bit`
Ror_rm32_1... | Rust | 0 |
255.) as u8,
(rgb_color.blue * 255.) as u8,
255,
]
}
}
}
}
//! Transformation passes used for testing parts of the system.
use syntax::ast::Crate;
use api::*;
use command::{CommandState, Registry};
use driver;
use transform::Transform;
... | Rust | 0 |
from openpyxl import load_workbook
from openpyxl.chart import BarChart, Reference
# Read workbook and select sheet
wb = load_workbook('pivot_table.xlsx') ##charts are made on pivot_table, so we load it as the wb(workbook)
sheet = wb['Report'] ##report sheet of wb is to be used
min... | Python | 1 |
) -> Poll<Option<Result<usize, crate::proto::h2::Error>>> {
self.inner
.poll_capacity(cx)
.map_ok_(|w| w as usize)
.map_err_(Into::into)
}
pub fn send_data(
&mut self,
data: B,
end_of_stream: bool,
) -> Result<(), crate::proto::h2::Er... | Rust | 0 |
p_count
/// [`opRegister`]: #method.op_register
/// [`Register.None`]: enum.Register.html#variant.None
/// [`OpKind.Register`]: enum.OpKind.html#variant.Register
#[wasm_bindgen(getter)]
#[wasm_bindgen(js_name = "op2Register")]
pub fn op2_register(&self) -> Register {
iced_to_register(self.0.op2_register())
}
... | Rust | 0 |
from controllers.modules import *
__PERM__UPLOADS__ = "uploads/permanent/"
__TEMP__UPLOADS__ = "uploads/temp/"
class UploadHandler(RequestHandler):
def set_default_headers(self):
print("setting headers!!!")
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "Ac... | Python | 1 |
: bool,
pub cmd_submitEthBlock: bool,
pub cmd_submitEvmBlock: bool,
pub cmd_getEnclaveState: bool,
pub cmd_debugResetEthChain: bool,
pub cmd_debugResetEvmChain: bool,
pub cmd_getLatestBlockNumbers: bool,
pub cmd_debugSetFeeBasisPoints: bool,
pub cmd_addVaultContractAddress: bool,
pub... | Rust | 0 |
Short,
/// Target GATT characteristic.
#[clap(long, short, default_value = "02091984-ecf2-4b12-8135-59f4b1d1904b")]
characteristic: UuidOrShort,
/// Public Bluetooth address of target device.
address: Address,
}
impl ConnectOpts {
pub async fn perform(self) -> Result<()> {
let (_session... | Rust | 0 |
Arg::new("exe")
.long("exe")
.short('e')
.value_hint(ValueHint::ExecutablePath),
)
.arg(
Arg::new("cmd_name")
.long("cmd-name")
.value_hint(ValueHint::CommandName),
)
.arg(
... | Rust | 0 |
import random
import string
chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()
random.shuffle(key)
#print(f"Chars: {chars}\n")
#print(f"Keys: {key}")
#ENCRYPT
plain_text = input("Enter a message to encrypt: ")
cipher_text = ""
for letter in plain_text:
... | Python | 1 |
err == K_ERR_NONE) {
rust_print_num(test_pend as u32);
}
if(err == K_ERR_PEND_TIMEOUT){
rust_print("pend mail_q: K_ERR_PEND_TIMEOUT\r\n\0".as_ptr());
return ;
}
}
}
pub fn rust_test_tos_mail_queue_pend_timed(){
unsafe{
let mut test_mail_q_00... | Rust | 0 |
#output_enum
impl proconio::source::Readable for #enum_ident {
type Output = Self;
fn read<R: std::io::BufRead, S: proconio::source::Source<R>>(source: &mut S) -> Self::Output {
let t = source.next_token_unwrap().parse::<isize>().expect("query number parse error"... | Rust | 0 |
Err(e)) => Err(Error::Io("Inotify stream error".into(), e)),
None => unreachable!("Inotify closed"),
}
}
#[cfg(test)]
mod tests {
use super::wait_file_deleted;
use std::{path::Path, time::Duration};
use tokio::{fs, task};
#[tokio::test]
async fn wait_for_non_existing_file() {
a... | Rust | 0 |
led=self.boards[board_name]['LED_BUILTIN']
if 'flash_size' in self.boards[board_name]:
flash_size_value=self.boards[board_name]['flash_size']
flash_size=f"[{';'.join(flash_size_value)}]"
else:
flash_size='[N/A]'
... | Python | 1 |
.send_message(event.channel(), "Please specify exactly one argument.");
return;
}
let max = match event.args[0].parse::<u64>() {
Ok(v) => v,
Err(_) => {
event.client.send_message(event.channel(),
format!("Invalid number '{}'", event.arg... | Rust | 0 |
import tensorflow as tf
import random
import numpy as np
from tqdm import tqdm
import pandas as pd
from charformer_model import make_charformer
import json
unk_char = "🫃"# unk token. pregnant man emoji :3
eof_char = "🫄"# eof token. pregnant person emoji :3
text = """"""
tparq = pd.read_parquet('2013.parquet', engine=... | Python | 1 |
self, resp: OW) -> Result<TwoWay> {
Ok(match resp.msg {
Msg::Devstatus(s) => match
s.addr
.rsplit('_')
.nth(0)
.unwrap()
.parse()
.map_err(|e| super::E... | Rust | 0 |
, 129, 130, 131, 132, 133, 6, 135, 8, 137, 10, 11, 140, 141, 142, 143,
16, 17, 146, 147, 148, 149, 150, 151, 152, 153, 26, 27, 28, 29, 30, 159,
160, 161, 162, 163, 36, 165, 166, 167,
// state 81: SP+ RI
128, 129, 130, 131, 132, 133, 6, 135, 8, 137, 10, 11, 140, 141, 142, 143,
16, 17, 146, 147, 148, ... | Rust | 0 |
wn_player.system()))
// .add_system(player_jumps.system())
// .add_system(player_movement.system())
// .add_system(jump_reset.system())
app.add_system_set(
SystemSet::on_enter(AppState::InGame).with_system(spawn_player.system()),
)
//.add_system_set(
... | Rust | 0 |
# Έστω ακολουθία από n νομίσματα με μη αρνητικές αλλά όχι απαραίτητα διαφορετικές αξίες. Να αναπτυχθεί αλγόριθμος σε
# δυναμικό προγραμματισμό ο οποίος θα υπολογίζει το μέγιστο χρηματικό ποσό το οποίο και μπορούμε να μαζέψουμε με τη
# προϋπόθεση πως δεν μπορούμε να πάρουμε 2 γειτονικά νομίσματα.
# Αρχική αναδρομή με ba... | Python | 1 |
"""
if not hasattr(self, "unet"):
raise ValueError("The pipeline must have `unet` for using FreeU.")
self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
def disable_freeu(self):
"""Disables the FreeU mechanism if enabled."""
self.unet.disable_freeu()
def fuse... | Python | 1 |
t(length)
stats.at[i, "results"] = bootstrap_elo_lu[model].tolist()
if not args.show_elo:
stats.sort_values(by="model", inplace=True)
stats["score"] = get_win_rate_column(stats, "score", args.baseline).tolist()
stats["lower"] = get_win_rate_column(stats, "lower", args.baseline).... | Python | 1 |
import pytest
from testpath import modified_env
from jeepney import bus
def test_get_connectable_addresses():
a = list(bus.get_connectable_addresses('unix:path=/run/user/1000/bus'))
assert a == ['/run/user/1000/bus']
a = list(bus.get_connectable_addresses('unix:abstract=/tmp/foo'))
assert a == ['\0/t... | Python | 1 |
ER: &str = include_str!("balances/balance_compound_ether.json");
pub const TX_DETAILS_WITH_ORIGIN: &str = include_str!("results/tx_details_with_origin.json");
pub const CHAIN_INFO_RINKEBY: &str = include_str!("chains/rinkeby.json");
pub const CHAIN_INFO_MOONBASE: &str = include_str!("chains/moonbase.json");
pub const... | Rust | 0 |
{
send.send(cmd).ok();
}
}
<reponame>simpago/nano-node
use std::convert::TryFrom;
use crate::{ffi::NetworkConstantsDto, NetworkConstants, NodeConstants};
#[repr(C)]
pub struct NodeConstantsDto {
pub backup_interval_m: i64,
pub search_pending_interval_s: i64,
pub unchecked_cleaning_interval_m: ... | Rust | 0 |
.margin_start(6)
.margin_end(6)
.margin_top(6)
.margin_bottom(6)
.halign(gtk::Align::Center)
.valign(gtk::Align::Center)
.row_spacing(6)
.column_spacing(6)
.build();
let clockwise = gtk::Button::with_label("Rotate clockwise");
let counter_... | Rust | 0 |
t fluid_audio_driver_t,
}
impl AudioDriver {
pub fn new(settings: &mut Settings, synth: &mut Synth) -> AudioDriver {
unsafe {
AudioDriver {
c_fluid_audio_driver: new_fluid_audio_driver(settings.to_raw(), synth.to_raw())
}
}
}
// TODO
/*pub fn new... | Rust | 0 |
sled.rs/) key-value store.
//! It requires the `"sled"` feature to be activated.
//! Sled is much faster to build than RockDB and does not require a C++ compiler.
//! However, Sled is still in developpment, less tested and data load seems much slower than RocksDB.
//!
//! Oxigraph is in heavy development and SPAR... | Rust | 0 |
then {
let mut applicability = Applicability::MachineApplicable;
let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0][0]).peel_refs();
if *self_ty.kind() != ty::Str {
return false;
}
span_lint_and_sugg(
cx,
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.