text string | label_name string | labels int64 |
|---|---|---|
, Y values.
"""
ax, ay = self._axes_mapping['right_thumbstick']
ax_val = self._clip_range(self.getAxis(ax))
ay_val = self._clip_range(self.getAxis(ay))
return ax_val, ay_val
@property
def trigger_axis(self):
return self.get_trigger_axis()
def get_trigger_a... | Python | 1 |
odel(x)
# Just add some random function of the residual
out_pt = out_pt + F.gelu(x_pt)
out = out + F.gelu(x_copy)
assert torch.allclose(out, out_pt, rtol=rtol, atol=atol)
# If we don't divide by batch_size, the gradient gets a bit too large.
g = torch.randn_like(out) / 32
out_pt... | Python | 1 |
import os
import platform
import sys
from pathlib import Path
from dotenv import load_dotenv
from utils.network import is_china_network
PROJECT_ROOT = Path(__file__).parent.parent
EXTERNAL_ARGO_PATH = os.getenv("EXTERNAL_ARGO_PATH", "")
ARGO_STORAGE_PATH = os.getenv("ARGO_STORAGE_PATH", os.path.join(os.path.expand... | Python | 1 |
id_x, mid_y) = self.center();
let x = (HILBERT_MAX * (mid_x - extent.min_x) / extent.width()).floor() as u32;
let y = (HILBERT_MAX * (mid_y - extent.min_y) / extent.height()).floor() as u32;
hilbert(x, y)
}
}
fn feat_coord(f: &geojson::Feature) -> (f64, f64) {
f.geometry.as_ref().map(|g... | Rust | 0 |
-> Vec3 {
self.clone() * (1.0 / self.length())
}
#[allow(dead_code)]
pub fn to_string(&self, samples_per_pixel: usize) -> String {
let scale = 1.0 / samples_per_pixel as f64;
let r = (256.0 * clamp((self.x * scale).sqrt(), 0.0, 0.999)) as u8;
let g = (256.0 * clamp((self.y *... | Rust | 0 |
# load the raw action
if os.path.exists(os.path.join(instance_folder, 'raw_action.jsonl')):
# raw_actions = []
raw_actions = [" " for _ in frames]
with open(os.path.join(instance_folder, 'raw_action.jsonl'), 'r') as f:
# for line in f:
for... | Python | 1 |
ter) is int and (count > self.stop_after):
break
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def upda... | Python | 1 |
}
}
impl From<bincode::Error> for LogError {
fn from(error: bincode::Error) -> LogError {
LogError::SerializationError(error)
}
}
impl From<mpsc::RecvError> for LogError {
fn from(error: mpsc::RecvError) -> LogError {
LogError::RecvError(error)
}
}
pub fn log<E: Send + Serialize>(... | Rust | 0 |
ul = 0
pls_wait = await message.reply("<i>Broadcasting Message.. This will Take Some Time</i>")
for chat_id in query:
try:
await broadcast_msg.copy(chat_id)
successful += 1
except FloodWait as e:
await asyncio.sleep(e.x)
... | Python | 1 |
Space;
let header = sys::LV2_Atom_Sequence_Body {
unit: match unit {
TimeStampURID::BeatsPerMinute(urid) => urid.get(),
TimeStampURID::Frames(urid) => urid.get(),
},
pad: 0,
};
frame.write(&header... | Rust | 0 |
::new(seconds2[1], nanos[1]),
Duration::new(seconds2[0], nanos[0]),
];
let expected_seconds: Vec<_> = lhs_durations
.into_iter()
.zip(rhs_durations)
.map(|(lhs, rhs)| lhs.checked_add(r... | Rust | 0 |
: u32,
pub flags: u32,
pub op: u32,
pub __bindgen_anon_1: vfio_eeh_pe_op__bindgen_ty_1,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union vfio_eeh_pe_op__bindgen_ty_1 {
pub err: vfio_eeh_pe_err,
}
impl Default for vfio_eeh_pe_op__bindgen_ty_1 {
fn default() -> Self {
let mut s = ::std::mem::Mayb... | Rust | 0 |
=> None,
"Eisu" => None,
"Hankaku" => None,
"Hiragana" => None,
"HiraganaKatakana" => None,
"KanaMode" => Some(VirtualKeyCode::Kana),
"KanjiMode" => Some(VirtualKeyCode::Kanji),
"Romaji" => None,
"Zenkaku" => None,
"ZenkakuHanaku" => None,
... | Rust | 0 |
; $count_x]; $count_y] = [$(<[$inner_ty; $count_x]>::from(other.inner[$idx])),*];
unsafe { core::mem::transmute(d2) }
}
}
impl From<$name> for [[$inner_ty; $count_x]; $count_y] {
#[inline(always)]
fn from(other: $name) -> Self {
[$(<[$... | Rust | 0 |
enter the correct API key for the selected provider.")
else:
try:
with st.spinner("🔄 Loading and summarizing..."):
docs = load_content(generic_url)
if not docs:
st.stop()
trimmed_text = docs[0].page_content[:12000]
... | Python | 1 |
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
import argparse
import time
import sys
import os
from blobbackup.q_single_application import QSingleApplication
from blobbackup.main_window import MainWindow
from blobbackup.models import get_resource_path
from blobbackup.schedul... | Python | 1 |
rip():
print(f" 片段 {j+1}: {repr(text)} -> 格式已应用")
clean_text = parser.strip_ansi(test_text)
print(f"清理后文本: {repr(clean_text)}")
except Exception as e:
print(f"解析错误: {e}")
print("-" * 40)
print(f"\n测试完成。... | Python | 1 |
ic_nns_governance::pb::v1::manage_neuron_response::Command::Error;
use ic_nns_governance::pb::v1::{
manage_neuron::configure::Operation,
manage_neuron::Command,
manage_neuron::Configure,
manage_neuron::IncreaseDissolveDelay,
manage_neuron::{StartDissolving, StopDissolving},
ManageNeuron, Manage... | Rust | 0 |
letion = await self.chat_completion_handler.create_chat_completion(request)
self.assertEqual("hello", chat_completion["chat_template"])
@patch("fastdeploy.entrypoints.llm.LLM.__init__")
def test_llm(self, mock_class):
mock_class.return_value = None
llm = LLM()
llm.llm_engine = M... | Python | 1 |
for b in range(min(target_original_images.shape[0], 4)):
torchvision.utils.save_image(target_original_images[b], os.path.join(save_dir, f"sample_{b}_original_img_target.jpg"))
torchvision.utils.save_image(target_depthmaps[b, :, None, ...], os.path.join(save_dir, f"sample_{b}_depthmap_target.jpg"), n... | Python | 1 |
TCP回调函数发生异常! %s " % tcpStr)
# lock.release()
serviceThreadDict[serviceConfKey][taskId] = {}
# serviceThreadDict[serviceConfKey][taskId]['thread'] = tmpThread
serviceThreadDict[serviceConfKey][taskId]['taskExecuteId'] = taskExecId
logging.... | Python | 1 |
#! /usr/bin/env python3
""" module: alpha """
def funA():
return "ALPHA"
if __name__ == "__main__":
print("I prefer to be a module.")
| Python | 1 |
# Copyright 2013 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and t... | Python | 1 |
pub fn set_decider(&mut self, decider: Decider<T::Item>) -> &mut Self {
self.decider = decider;
self
}
pub fn set_trail(&mut self, trail: usize) -> &mut Self {
self.trail = trail;
self
}
fn prefer_left(left: T::Item, _: T::Item) -> T::Item { left }
fn prefer_r... | Rust | 0 |
ned(), self.value);
}
None => {}
}
}
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct Transition<A, S, C> {
/// The state to transition to
pub on: Option<fn(context: C, action: A, state: S) -> S>,
/// Method to run when ... | Rust | 0 |
"""Add AIRTABLE_CONNECTOR to enums
Revision ID: 19
Revises: 18
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "19"
down_revision = "18"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""Upgrade schema - add AIRTABLE_CONNECTOR to enums."""
# Add to searchsource... | Python | 1 |
, funct3)).cloned())
.flatten()
})
}
fn r_kind_get<B: Base>(opcode: u8, funct3: u8, funct7: u8) -> Option<Kind> {
static RV32_TABLE: SyncLazy<HashMap<(u8, u8, u8), Kind>> = kind_table! {
(0b011_0011, 0b000, 0b000_0000) => ADD,
(0b011_0011, 0b000, 0b010_0000) => SUB,
(0b011_0... | Rust | 0 |
(-1.0));
assert_ok!(read_float(b".0|"), LitFloat(0.0));
assert_ok!(read_float(b"-.0|"), LitFloat(0.0));
assert_ok!(read_float(b"1.2|"), LitFloat(1.2));
assert_ok!(read_float(b"99999.0|"), LitFloat(99999.0));
assert_ok!(read_float(b"-1234.0|"), LitFloat(-1234.0));
}
#[tes... | Rust | 0 |
= "rust1", since = "1.0.0")]
#[rustc_deprecated(
since = "1.34.0",
reason = "the `new` function is now preferred",
suggestion = "AtomicBool::new(false)"
)]
pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool::new(false);
#[cfg(target_has_atomic_load_store = "8")]
impl AtomicBool {
/// Creates a new `A... | Rust | 0 |
ic::Metric;
use crate::update::Updatable;
use crate::widget::cpu::Cpu;
pub struct CpuSys<'a> {
cpu_sys: VecDeque<(f64, f64)>,
last_delta_cpu_sys: f64,
theme: &'a Theme,
max_elements: usize,
update_count: u64,
}
impl<'a> CpuSys<'a> {
pub fn new(theme: &'a Theme, max_elements: usize) -> Self {
... | Rust | 0 |
Change))
} else if self.bin_files.len() > loc.bin_file_no + 1 {
loc.bin_file_no += 1;
loc.track_in_bin = 0;
loc.bin_local_lba = 0;
Ok(Some(Event::TrackChange))
} else {
Ok(Some(Event::EndO... | Rust | 0 |
uery_feature = query_feature / np.linalg.norm(query_feature) if np.linalg.norm(query_feature) > 0 else query_feature
self.search_similar_vectors(query_feature, 5)
'''for name, distance in self.matched_face.items():
if distance > 0.4... | Python | 1 |
unwrap()),
"\u{feff}\u{fffd}\u{fffd}\0\0\u{62}\0\u{18}"
);
assert_eq!(
host_c_str_to_str(CStr::from_bytes_with_nul(b"\xf0\x9f\0").unwrap()),
"\u{feff}\u{fffd}\u{fffd}\0\0\u{70}\0\u{1f}"
);
assert_eq!(
host_c_str_to_str(CStr::from_bytes_with_nul(b"\xf0\x9f\x92\0").unwrap()... | Rust | 0 |
# Import the necessary libraries
import streamlit as st
# Set the page configuration to adjust the layout width
st.set_page_config(
page_title="Simple Streamlit App",
layout="wide", # Use 'wide' to increase the app's width
)
st.sidebar.image: st.sidebar.image("image_circle.png", use_container_width=Tr... | Python | 1 |
certificates(1, 9, &genesis, &keys);
// Spawn the consensus engine and sink the primary channel.
let (tx_waiter, rx_waiter) = channel(1);
let (tx_primary, mut rx_primary) = channel(1);
let (tx_output, mut rx_output) = channel(1);
Consensus::spawn(
mock_committee(),
/* gc_depth */ 50... | Rust | 0 |
_string());
// Get a handle to the cluster
let client: mongodb::Client = Client::with_options(client_options)?;
info!("Attemp db connect.");
// Ping the server to see if you can connect to the cluster
client
.database("redmob")
.run_command(doc! {"ping": 1}, None)
.await?;
... | Rust | 0 |
<reponame>Metaswitch/iobuffer
//! IoBuffer library
//!
//! Copyright 2020 Metaswitch Networks
//!
//! Memory-based buffer which implements Write and Read traits.
use std::cmp;
use std::default::Default;
use std::io;
use std::result::Result::Ok;
use std::sync::{Arc, Mutex};
/// Simple object which implements both `st... | Rust | 0 |
::Rc};
use actix_session::UserSession;
use actix_utils::future::{ok, Ready};
use actix_web::{
body::EitherBody,
cookie::Cookie,
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
http::{header::COOKIE, StatusCode},
web, Error, HttpResponse,
};
use crate::Limiter;
/// Rate ... | Rust | 0 |
for query in &*PRIVILEGED_QUERIES {
guard
.guard(query)
.expect_err("Failed to reject privileged query");
}
}
#[test]
fn parses_complex_queries() {
// set up guard that does some query parsing
let guard = Guard::new(
AllowedStatements::List(vec![
Command:... | Rust | 0 |
rface.set_colormap_name("seismic")
/// .set_with_colorbar(true)
/// .set_with_wireframe(true)
/// .set_line_width(0.3);
///
/// // draw surface + wireframe
/// surface.draw(&x, &y, &z);
///
/// // add surface to plot
/// let mut plot = Plot::new();
/// plot.add(&surface)
/// .set_title("horse saddle equ... | Rust | 0 |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems Inc.
# 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
#... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.utils.data_helpers.data_dispatcher import ContainerTypes
from openvino.utils.data_helpers.data_dispatcher import ScalarTypes
from openvino.utils.data_helpers.data_dispatcher import ValidKeys
from o... | Python | 1 |
INTER", Some("1"))
.define("STDC_HEADERS", Some("1"))
.define("HAVE_SYS_TYPES_H", Some("1"))
.define("HAVE_SYS_STAT_H", Some("1"))
.define("HAVE_STDLIB_H", Some("1"))
.define("HAVE_STRING_H", Some("1"))
.define("HAVE_MEMORY_... | Rust | 0 |
>> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - Write Protect HW Status"]
#[inline(always)]
pub fn wphws4(&self) -> WPHWS4_R {
WPHWS4_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - Write Protect HW Status"]
#[inline(always)]
pub fn wphws5(&self) -> WPHWS5_R {
WPHWS... | Rust | 0 |
ilis: f32) {
self.position += self.linear_velocity.multiply_by(milis / 1000.0);
}
pub fn set_position(&mut self, position: Vector3<f32>) {
self.position = position;
}
}
<filename>src/file.rs<gh_stars>0
use std::io::{self, Read};
use {image, nt, parse, traits};
pub struct File<R> {
read... | Rust | 0 |
from typing import List
def joinNumbers(numbers: List[int], char: str) -> str:
return char.join(str(i) for i in numbers)
numbers = []
for i in range(1, 6):
num = int(input(f"Enter number {i} = "))
numbers.append(num)
c = input("Enter a character = ")
result = joinNumbers(numbers, c)
print(result)
| Python | 1 |
ording to the terms contained in the COPYRIGHT file.
// Copyright © 2016 The developers of rdma-core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT.
include!("structs/__BindgenUnionField.rs");
include!("structs/_bin... | Rust | 0 |
"other".to_string(),
title: "other app".to_string(),
..Default::default()
},
],
tls_key: Some(TLS_KEY.to_string()),
tls_cert: Some(TLS_CERT.to_string()),
..Default::default()
... | Rust | 0 |
p.nan, -np.inf]
for value in values:
input = torch.randn(8, dtype=torch.float32)
input_mlu = copy.deepcopy(input).mlu()
input.requires_grad = True
input_mlu.requires_grad = True
grad = torch.randn(8, dtype=torch.float32)
grad[7] = value
... | Python | 1 |
ash(state);
user_id.hash(state);
}
}
}
}
struct DispatcherKey;
impl TypeMapKey for DispatcherKey {
type Value = Arc<RwLock<Dispatcher<DispatchEvent>>>;
}
struct SchedulerKey;
impl TypeMapKey for SchedulerKey {
type Value = Arc<RwLock<Scheduler>>;
}
struct Handler;
impl... | Rust | 0 |
ble_name};"
if sql:
logger.info(f'执行重置索引的SQL:{sql}')
db.execute(sql)
db.commit()
db.close()
return respSuccessJson()
@router.delete(api_url + '/{_ids}', summary="通过ID删除配置")
async def delRecordByID(*,
db: Session = Depends(deps.get_db),
... | Python | 1 |
# pylint: disable=wrong-or-nonexistent-copyright-notice
"""Creates and simulates a circuit for Quantum Fourier Transform(QFT) on 4 qubits.
In this example we demonstrate Fourier Transform on
(1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) vector. To do the same, we prepare the input state of the
qubits as |0000>.
=== EXAMPLE OUTPUT... | Python | 1 |
pth1].get('Key'))
if Tags[depth1].get('Value') is not None:
self.add_query_param('Tags.' + str(depth1 + 1) + '.Value', Tags[depth1].get('Value'))
def get_MaxResults(self): # Integer
return self.get_query_params().get('MaxResults')
def set_MaxResults(self, MaxResults): # Integer
self.add_query_param('MaxR... | Python | 1 |
}
}
}
// Step 2: For each field and each branch, check if it needs to be
// added, and if so, do so.
for f in &all_new {
for j in 0..es.len() {
if !contains_ident(&fo... | Rust | 0 |
n
last_idx = start_idx + packets_per_scan - 1
first_pkt_ts = lidar_timestamps[start_idx]
last_pkt_ts = lidar_timestamps[last_idx]
mid_ts = (first_pkt_ts + last_pkt_ts) // 2
scan_timestamps.append(mid_ts) # Keep timestamp in nanoseconds
# 4a) Convert ranges → XYZ and fl... | Python | 1 |
y_range.len() == 1 {
Box::new(
x_range
.into_iter()
.zip(std::iter::repeat(y_range[0]))
.map(Point::from),
)
} else {
unreachable!();
}
}
fn horizontal(&self) -> bool {
self.... | Rust | 0 |
check_hover(mouse_pos)
if pause_button.is_clicked(mouse_pos, click):
game_paused = not game_paused
if settings_button.is_clicked(mouse_pos, click):
settings_open = not settings_open
# Керування слайдером в налаштуваннях
if settings_o... | Python | 1 |
from tkinter import *
window = Tk()
window.title("Event Handler")
window.geometry("100x100")
def handle_keypress(event):
"""Print the character associated to the key pressed"""
print(event.char)
window.bind("<Key>", handle_keypress)
def handle_click(event):
print("The button was clicked!")
button = Bu... | Python | 1 |
turn client.MakeRequests([(service, 'Patch', request)])
Delete.detailed_help = {
'brief':
'Delete values defined in the all-instances configuration of a managed '
'instance group.',
'DESCRIPTION':
"""\
*{command}* deletes one or more values defined in the all-instances
... | Python | 1 |
employees(self):
employees = backend.get_all_employees()
for row in employees:
self.tree.insert('', 'end', values=(
row['EmployeeID'], row['Name'], row['Gender'], row['PhoneNumber'],
row['IDCardNumber'], row['Position']
))
def show(self):
... | Python | 1 |
import platform
sistema_operacional = platform.system()
if sistema_operacional == "Windows":
print("Você está usando o Windows.")
versionador = '\\'
elif sistema_operacional == "Linux":
print("Você está usando o Linux.")
versionador = '/'
elif sistema_operacional == "Darwin":
print("Você está us... | Python | 1 |
_to_bytes(self.ehfrm.offset),
),
Splice(
self.sym.EH_FRM_HDR_SIZE.value(),
u64_to_bytes(self.ehfrm.size),
),
Splice(self.sym.TEXT_BASE.value(), u64_to_bytes(self.text.offset)),
Splice(self.sym.TEXT_SIZE.value(), u64_to_bytes(sel... | Rust | 0 |
n + v.len() as u64;
let end_position: u64 = end_position - 2;
let index_info = IndexInfo {
file_id: self.get_file_id(),
start_position,
end_position,
time_stamp: data.time_stamp,
};
// add total index number
if !index.contains_key... | Rust | 0 |
c_call is not None:
# ! only be called in runing MKINI, LULCC will be executed later
VTV.WRITE_TimeVariables(idate, lc_year, casename, dir_restart)
# Barrier synchronization for MPI
if nl_colm['USEMPI']:
pass
if mpi.p_is_master:
print('Successfully Initialize the Land Time-... | Python | 1 |
# -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata module.**
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Sof... | Python | 1 |
"""
Ultralytics YOLOv8*-cls model training script
for generating confidence-based noise labels for a dataset.
| Copyright 2017-2024, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
Requires `ultralytics` and `fiftyone>=0.25.0` to be installed.
"""
import argparse
import os
import tempfile
import torch
from ul... | Python | 1 |
fe\x99\xfbfQ\xff\x93\x01\
\xd8\x02\xbfOt~\xb0},\xd2\x04\xd7\xee\xbaK\xfc\
W\x0b\x85V\xe0@\xf7\x1a\xa5LJ\xbf\x04\x14oO\
*\xb9R<\xfe\x94\xc0\x9d\x7fHd\x10\x00-\x11\xf1\
\xfaE\xe4t\xdf\xa53\xb3\x7f\x85,)H?kw\
\xfc\xeeE\xbb\x17u\xe7\x22?-\x99H\x8d\xa9\xf0\xeb\
\x9d\xff\xf4\xda\x14\x0f\xd6%EiB\x02\xe4J\xe6\xaa\
[\x0c`D\xa9-... | Python | 1 |
This register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcoir_fcal_rsel5](dcoir_fcal_rsel5) module"]
pub type DCOIR_FCAL_RSEL5 = crate::Reg<u32, _DCOIR_FCAL_RSEL5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub s... | Rust | 0 |
from model.abstractUsuario import AbstractUsuario
class Professor(AbstractUsuario):
def __init__(self,
nome: str,
email: str,
telefone: int,
cpf: int,
cidade: str,
sigla_estado: str,
rua:... | Python | 1 |
0x97c88939cbce8317,
0x001752ce51d19c97,
);
let r = n.invmod(&m).unwrap();
assert_eq!(i, r);
}
#[test]
fn test_mulmod() {
let a = U256::from_limbs(
0xb7eb3137d7271553,
0xf44101622499c849,
0x6364b9150f381299,
... | Rust | 0 |
# value[i] = value[i].lower() == "true"
# else:
# value[i] = ast.float(value[i])
# if len(value) == 1:
# value = value[0]
# else:
# value = tuple(value)
optimizer_kwargs[key] = value
# logger.info... | Python | 1 |
{
unsafe extern "C" fn notify_v_align_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableRowElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableRowElement>,
{
... | Rust | 0 |
from msalde.simulator import DESimulator
from msalde.container import ALDEContainer
import cProfile
def test_run_simulations():
container = ALDEContainer(config_file="./config/msalde.yaml")
de_simulator: DESimulator = container.simulator
de_simulator.run_simulations(
name="test_run",
num_... | Python | 1 |
from .dpo_trainer import DPOTrainer
from .kd_trainer import KDTrainer
from .kto_trainer import KTOTrainer
from .ppo_trainer import PPOTrainer
from .prm_trainer import ProcessRewardModelTrainer
from .rm_trainer import RewardModelTrainer
from .sft_trainer import SFTTrainer
from .dpo_trainer_my import DPOTrainerMy | Python | 1 |
}
}
pub fn max_chroma_prop_for_current_sum(&self) -> Prop {
if let Some(hue) = self.hue {
if let Some(max_c_prop) = hue.max_chroma_prop_for_sum(self.sum) {
max_c_prop
} else {
Prop::ZERO
}
} else {
Prop::ZERO
... | Rust | 0 |
config::Config,
layer::Layer,
manifest::Manifest,
manifest_index::{ManifestIndex, Platform},
},
};
use super::storage::{
Storage, StorageEngine, BLOBS_STORAGE_KEY, IMAGES_INDEX_STORAGE_KEY,
};
/// Represents layer download update.
#[derive(Clone, Debug)]
pub enum LayerDownload... | Rust | 0 |
fn update(self, u: &Uniform<Self>) {
unsafe { gl::Uniform4fv(u.index, 1, &self as *const f32) }
}
fn ty() -> Type {
Type::Vec4
}
}
unsafe impl<'a> Uniformable for &'a [f32] {
fn update(self, u: &Uniform<Self>) {
unsafe { gl::Uniform1fv(u.index, self.len() as GLsizei, self.as_ptr() as *const f32) }... | Rust | 0 |
ength()` 获取响应体具体尺寸,
/// 当尺寸大小可以接受全部被载入内存时,才调用该函数
/// @param[in] response HTTP 响应实例
/// @param[in] max_body_size 缓冲区最大尺寸,单位为字节
/// @param[out] body_ptr 缓冲区地址
/// @param[out] body_size 最终获取的响应体尺寸,单位为字节
/// @param[out] err 用于返回错误,如果传入 `NULL` 表示不获取 `err`。但如果运行发生错误,返回值将依然是 `false`
/// @retval bool 是否运行正常,如果返回 `true`,则表示... | Rust | 0 |
cription],
base_version: Optional[str],
next_version: Optional[str],
params: dict[str, Any],
) -> dict[str, Any]:
"""Implements the ``"basic"`` ``template-fields`` method"""
params = deepcopy(params)
vtuple_params = params.pop("version-tuple", {})
SUBTABLE = "template-fields.version-tuple"
... | Python | 1 |
class Solution:
def missingInteger(self, nums: List[int]) -> int:
seq_sum = nums[0]
for i in range(1, len(nums)):
if nums[i] == nums[i - 1] + 1:
seq_sum += nums[i]
else:
break
num_set = set(nums)
while ... | Python | 1 |
smallvec::SmallVec;
use std::u32;
fn small_grid(w: usize, h: usize) -> SmallRectangularGrid {
small_rect_grid(RowLength(w), ColumnLength(h))
.expect("grid dimensions too large for small grid")
}
// Compare a smallvec to e.g. a vec! or &[T].
// SmallVec really ruins the syntax ... | Rust | 0 |
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
import os.path
import sys
from docutils.nodes import Element
from sphinx.writers.html5 import HTML5Translator
sys.p... | Python | 1 |
metrics({
"val_accuracy" : val_acc,
"val_auroc" : val_auc_m.compute().item(),
"val_pr_auc" : val_pr_m.compute().item(),
"val_best_macro_f1" : f1_star,
"val_best_threshold": t_star,
}, step=epoch)
print(f"[Ep {epoch}] val_ac... | Python | 1 |
def fix_bn(module):
"""Fix the batch normalization layers."""
for m in module.modules():
classname = m.__class__.__name__
if classname.find('BatchNorm') != -1:
m.eval()
return module
| Python | 1 |
tive numbers were entered.")
break
else:
total += num
count += 1
# Call the method to execute the functionality
printAverage()
#14
def printAverage():
total = 0.0
count = 0
while True:
num = float(input("Type a number: "))
if num < 0:
... | Python | 1 |
_create_java_service_runtime(config: Config) -> JavaServiceRuntime {
// Initialize runtime if it wasn't created before.
JAVA_SERVICE_RUNTIME_INIT.call_once(|| {
Self::create_runtime(config);
});
unsafe { JAVA_SERVICE_RUNTIME.clone() }
.expect("Trying to return ru... | Rust | 0 |
a=(5,2,3,1,4)
print("a=",a)
print(type(a))
| Python | 1 |
ture_crate_model_sidewalk_event_notification_configurations(&mut object_241, var_240)?;
object_241.finish();
}
Ok(())
}
pub fn serialize_structure_crate_model_lo_ra_wan_update_device(
object: &mut aws_smithy_json::serialize::JsonObjectWriter,
input: &crate::model::LoRaWanUpdateDevice,
) -> Resu... | Rust | 0 |
=> true,
Err(_) => false
}
}
}
impl<'a, U : Send> Publisher<'a> for NetStreamer<'a, U>
{
type Output = ProtoMsg<U>;
//fn subscribe(&mut self, s: Box<Subscriber<Input=<Self as Publisher<'a>>::Output > + 'a>) {
fn subscribe(&mut self, s: Box<Subscriber<Input=ProtoMsg<U>> + 'a>) {
... | Rust | 0 |
from odoo import models, fields
class Owner(models.Model):
_name = "owner"
name = fields.Char(string="Owner", required=True)
phone = fields.Char(string="Phone", required=True)
address = fields.Char(string="Address")
property_ids = fields.One2many('property', 'owner_id')
| Python | 1 |
et)
self.additional_target = split_arg(self.additional_target)
self.galore_target = split_arg(self.galore_target)
assert self.finetuning_type in [
"lora",
"freeze",
"full",
], "Invalid fine-tuning method."
assert self.ref_model_quantization_bi... | Python | 1 |
sName => &"AlarmClassName",
StringCriterion::AlarmName => &"Name",
}
}
}
#[derive(Debug, Clone)]
pub enum IntCriterion {
Id,
InstanceId,
Priority,
AlarmState,
}
impl IntCriterion {
pub fn evaluate(&self, alarm: &AlarmData) -> i32 {
match self {
IntCriter... | Rust | 0 |
pth)
}
}
#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for Rgba {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
use crate::math::arbitrary_notnan;
Ok(Rgba::new_nn(
arbitrary_notnan(u)?,
arbitrary_notnan(u)?,
a... | Rust | 0 |
).map(|i| Celsius(i as f64)).collect();
c.bench_function("mixing_ratio", |b| {
b.iter(|| {
for p in &pressures {
for t in &temperatures {
mixing_ratio(black_box(*t), black_box(*p));
}
}
})
});
}
fn rh_bench(c: &mut Cri... | Rust | 0 |
roup_by_clause(i: &[u8]) -> IResult<&[u8], GroupByClause> {
let (remaining_input, (_, _, _, columns, having)) = tuple((
multispace0,
tag_no_case("group by"),
multispace1,
field_list,
opt(having_clause),
))(i)?;
Ok((remaining_input, GroupByClause { columns, having }))... | Rust | 0 |
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from app.models import Product
from app.permissions import IsPostEditorOrReadOnly
from app.serializers import ProductSerializer
# Create your views here.
class ProductViewSet(viewsets.ModelV... | Python | 1 |
velli::sequence_cards::*;
///
/// let mut table1 = Table::new();
/// table1.add(Sequence::from_cards(&[
/// RegularCard(Diamond, 4),
/// RegularCard(Diamond, 5),
/// RegularCard(Diamond, 6),
/// ]));
/// table1.add(Sequence::from_cards(&[
/// RegularCard(Heart, 11)... | Rust | 0 |
x + 1 // this is also an EXPRESSION
}
fn another_function(x: i32) {
println!("Another function.");
println!("valur for x is:{}", x);
}
<filename>2021/14/src/lib.rs
use std::collections::HashMap;
fn get_rules(input: &str) -> HashMap<(char, char), char> {
input
.trim()
.lines()
.... | Rust | 0 |
def histogram(x):
for i in x:
print("*" * i)
x = list(map(int, input().split()))
histogram(x) | Python | 1 |
dp -= 1;
trace_op!(trace, 2);
},
Op::Right => {
dp += 1;
trace_op!(trace, 3);
},
Op::Read => {
let c = input.next();
let c = c.expect("end of stream");
let c = c.unwra... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.