text string | label_name string | labels int64 |
|---|---|---|
from evals.metrics.mia.all_attacks import AllAttacks
from evals.metrics.mia.loss import LOSSAttack
from evals.metrics.mia.reference import ReferenceAttack
from evals.metrics.mia.zlib import ZLIBAttack
from evals.metrics.mia.min_k import MinKProbAttack
from evals.metrics.mia.min_k_plus_plus import MinKPlusPlusAttack
fro... | Python | 1 |
nativeAuthProgramName, 0o750)
except PermissionError:
print("WARNING: chmod(4550), chown(%s:%s) failed for Unix Authentication Program (%s) " % ("root", groupName, nativeAuthProgramName))
else:
print("WARNING: Unix Authentication Program (%s) is not available for setting chmod(4550),... | Python | 1 |
(
doc! {},
FindOneOptions::builder().projection(doc! {"network_name":1}).build(),
)
.await
}
/// Sets the name of the network.
pub async fn set_network_name(&self, network_name: String) -> Result<(), Error> {
self.0
.collection::<S... | Rust | 0 |
y"]
)
st.session_state["message_history"] = response.all_messages()
if isinstance(response.output, NeedMoreInfo):
with st.chat_message("assistant"):
st.write(response.output.message)
elif isinstance(response.output, CAAFEInputAdapter):
with st.cha... | Python | 1 |
#[derive(Debug, PartialEq)]
pub enum WalletCommand {
Address,
Airdrop(u64),
Balance(Pubkey),
Cancel(Pubkey),
Confirm(Signature),
// ConfigureStakingAccount(delegate_id, authorized_voter_id)
AuthorizeVoter(Pubkey),
CreateVoteAccount(Pubkey, Pubkey, u32, u64),
ShowVoteAccount(Pubkey),
... | Rust | 0 |
timeout = 3
enable = true
listen_port = "1337"
listen_ip = "0.0.0.0"
[ws_config]
panic_on_internal = true
fragments_grow = true
panic_on_protocol = false
enable = true
in_buffer_capacity = 2048
panic_on_queue = false
fragment_size = 65535
panic_on_timeout = false
method_strict = false
thread_number = 2
panic_on_capaci... | Rust | 0 |
rem) = parsers::header_item(rem, "app_name")?;
result.app_name = app_name;
let (proc_id, rem) = parsers::header_item(rem, "proc_id")?;
result.proc_id = proc_id;
let (message_id, mut rem) = parsers::header_item(rem, "message_id")?;
result.message_id = message_id;
... | Rust | 0 |
from typing import TYPE_CHECKING, Any
from aiogram.methods import TelegramMethod
from ..types import ChatIdUnion
class UnpinAllGeneralForumTopicMessages(TelegramMethod[bool]):
"""
Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for ... | Python | 1 |
:marker::Copy for ActivationMode {
}
impl ::std::default::Default for ActivationMode {
fn default() -> Self {
ActivationMode::kNone
}
}
impl ::protobuf::reflect::ProtobufValue for ActivationMode {
fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef {
::protobuf::reflect::ReflectValueR... | Rust | 0 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2024/11/20
# @Author : cyq
# @File : interfaceModel
# @Software: PyCharm
# @Desc:
from app.model.basic import BaseModel
from sqlalchemy import Column, String, INTEGER, ForeignKey, JSON, BOOLEAN, Text
class InterfaceModel(BaseModel):
"""
接口表
"""
_... | Python | 1 |
ength/2., dz )
q3 = RR_Z*Ef*self.J_to_eV # (fiss/cm3 s * eV/fiss * J/eV) = (W/cm3)
q3std = uRR_Z*Ef*self.J_to_eV
return q3, z, q3std, Area
# very important function :)
def normalisation_z(self, qty_to_norm, Qp):
H1 = self.J_to_eV * Qp # (J/source)
Vol = (s... | Python | 1 |
service");
}
}
pub fn run_service() -> Result<()> {
// Create a channel to be able to poll a stop event from the service worker loop.
let (shutdown_tx, shutdown_rx) = mpsc::channel();
// Define system service event handler that will be receiving service events.
let event_handler = move |... | Rust | 0 |
monics(&mnemonics).unwrap();
assert_eq!(entropy.as_ref(), entropy2.as_ref());
}
#[test]
fn mnemonic_7f() {
let entropy = Entropy::Entropy12([0x7f; 16]);
let mnemonics = entropy.to_mnemonics();
let entropy2 = Entropy::from_mnemonics(&mnemonics).unwrap();
assert_eq!(en... | Rust | 0 |
velength_case(BEAM, DETECTOR, CRYSTAL, SF_model, weights=weights)
SIM3 = SWC.modularized_exafel_api_for_GPU(params=params, argchk=False, gpu_background=True)
SIM3.to_cbf("test_unified_%s_003.cbf"%(params.context), intfile_scale=scale)
if "kokkos" in params.context:
print("\n# Use case 4 (%s). 3-Color"%params.... | Python | 1 |
findall(r'<LegacyDN>(.*?)</LegacyDN>', response.text)[0]
print("\033[32m[o] LegacyDN: {}\033[0m".format(LegacyDN))
vuln_url = '/mapi/emsmdb/'
headers = {
'X-Clientapplication': 'Outlook/15.0.4815.1002',
'X-Requestid': 'x',
'X-Requesttype': 'Connect',
'Cookie': 'X-BEResource=... | Python | 1 |
_cmdline();
get_serial_cmdline(&mut cmdline, serial_parameters, "mmio")
.map_err(Error::GetSerialCmdline)?;
for param in components.extra_kernel_params {
cmdline.insert_str(¶m).map_err(Error::Cmdline)?;
}
if let Some(ramoops_region) = ramoops_region {
... | Rust | 0 |
");
// let context_path2 = std::env::var("CONTEXT_PATH").unwrap();
if username.is_none() || password.is_none(){
println!("用户或密码为空:{:?}->{:?}",username,password);
return HttpResponse::Ok().json(ResultBuild::<&str>::fail_with_msg("用户或密码为空"));
}
// 从配置获取用户并检查
let password_cfg = std::e... | Rust | 0 |
e)/(np.power(clip_length, 2))
#### code for check error#####
# num_nonzero = torch.count_nonzero(layouts_s_frames)
# print("num_nonzero",num_nonzero)
# print("layouts_s_frames",layouts_s_frames.shape)
# print("layouts_s_frames",layouts_s_frames)
# ... | Python | 1 |
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
# Load the image
image_path = 'your_image.jpg' # Replace with your image path
image = cv2.imread(image_path)
if image is None:
raise FileNotFoundError(f"Image not found at path: {image_path}")
# Ensure the output directory exists and delete... | Python | 1 |
_embedding, train,
batch_first):
super().__init__()
self.rnn_type = rnn_type.lower()
self.bidirectional = bidirectional
self.hidden_dim = hidden_dim
self.n_layers = n_layers
word_embedding = pickle.load(Path(word_embedding).open('rb'))
self.embedd... | Python | 1 |
env::var(format!("{}_TRUSTED_PEER_{}_ID", prefix, i));
if trusted_peer_address.is_err() || trusted_peer_id.is_err() {
break;
}
trusted_peers.push(TrustedPeer {
address: trusted_peer_address
.expect("incorrect trusted peer address... | Rust | 0 |
ddAction(
'Argument', lambda: utils.copy_str_to_clipboard(argument.text()))
if _class.text():
context_sub_menu.addAction(
'Class', lambda: utils.copy_str_to_clipboard(_class.text()))
if value:
if value.text():
... | Python | 1 |
(
LightSystem::new(client, remote_blockchain, fetcher, pool),
));
io
}
<reponame>jamespharaoh/rust-btrfs
use std::fmt::Debug;
use std::fmt::Error as FmtError;
use std::fmt::Formatter;
use super::super::*;
#[ derive (Clone, Eq, Hash, PartialEq) ]
pub enum BtrfsNode <'a> {
Internal (BtrfsInternalNode ... | Rust | 0 |
is_add: true,
del_all: false,
sw_if_index: 0,
prefix: AddressWithPrefix {
address: Address {
af: AddressFamily::ADDRESS_IP4,
un: AddressUnion::new_Ip4Address([10, 10, 1, 2]),
},
len: 24,
... | Rust | 0 |
::from_iter([
Interval::UNISON,
Interval::MINOR_THIRD,
Interval::PERFECT_FOURTH,
Interval::TRITONE,
Interval::PERFECT_FIFTH,
Interval::MINOR_SEVENTH,
])
}
}
pub type DiatonicScale<T> = Scale<T, Diatonic<T, ScaleIntervals>>;
impl<T> Di... | Rust | 0 |
"io_uring", nif)]
#[cfg_attr(not(feature = "io_uring"), nif(schedule = "DirtyIo"))]
fn sled_insert<'a>(
env: Env<'a>,
tree: SledDbTree,
k: Binary,
v: Binary,
) -> Result<Option<Binary<'a>>, Error> {
result_to_binary(env, tree.insert(&k[..], &v[..]))
}
#[allow(clippy::needless_pass_by_value)]
#[cfg_... | Rust | 0 |
ackage")], dependency_map=dm)),
[(None, "package")])
# Easy expansion.
self.assertEqual(list(add_extra_dependencies([("b", None)], dependency_map=dm)),
[("b", None), ("c", None), ("d", None)])
# Expansion with two groups -- each group is handled ... | Python | 1 |
import json
import copy
def convert_ner_cluener_prompt(inputfile,outputfile):
data = []
entity_map = {'name':'人名',
'organization':'组织机构',
'scene':'景点',
'company':'企业',
'movie':'影视',
'book':'书籍',
'gover... | Python | 1 |
#!/usr/bin/env python3
#
# Copyright (c) 2018-2022 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Check the test suite naming conventions
"""
import re
import subprocess
import sys
def grep_boos... | Python | 1 |
n: &Section) {
for s in &self.sections {
if current_section == s {
println!("{}", format!("• {}", s.to_string()).bold().yellow())
} else {
println!("{}", format!("• {}", s.to_string()))
}
}
}
pub fn run_setup(&self) {
Self::clear_screen();
let mut user_config = UserConfig::default();
let... | Rust | 0 |
hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and ... | Rust | 0 |
ile, "
"the temporary files in the working directory will also be kept.",
action="store_true")
parser.add_argument("--grf_path", help="Path to GRF program (Optional)",
type=str, default=os.path.dirname(shutil.which("grf-ma... | Python | 1 |
from PIL import Image, ImageDraw, ImageFont
def generate_icon_with_text(template_path, output_path, text_to_add):
font_size = 120
text_color = (0,0,0) # Black color (R, G, B)
try:
# Open the image file
with Image.open(template_path) as img:
# Get the image dimensions
... | Python | 1 |
# create/update a view to associate case duration with features for a regression task
import functions_framework
from google.cloud import secretmanager
from google.cloud import storage
from google.cloud import aiplatform
import duckdb
import pandas as pd
import datetime
# settings
project_id = 'group2-ba882'
project_... | Python | 1 |
('writing train data')
gen(train_data, True)
logger.info('writing val data')
gen(val_data, False)
# =========== train lnet ================
def train(args):
'''train lnet using data prepare by `prepare()`
'''
def get_data_size(txt):
size = 0
with open(txt, 'r') as fin:
for line in fin.read... | Python | 1 |
import pickle
import os
import argparse
import numpy as np
def sequences_to_nhot(seqs, vocab_size):
"""
args:
seqs: list of list of word_ids
vocab_size: int
outputs:
labels: np.array of shape [batch_size, vocab_size]
"""
labels = np.zeros((len(seqs), vocab_size), dtype=np... | Python | 1 |
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::support::test_init;
#[test]
fn test_diagnostics() {
test_init();
let uri = Url::from_file_path(absolute_path("test_data/diag/diag_test.sv")).unwrap();
let expected = PublishDiagnosticsParams::new(
u... | Rust | 0 |
MMIO access size: {}", memory_access.AccessSize),
}*/
panic!("memory() ist currently unsupported");
//S_OK
}
fn get_virtual_processor_registers(
&mut self,
register_names: &[WHV_REGISTER_NAME],
register_values: &mut [WHV_REGISTER_VALUE],
) -> HRESULT {
self.vcpu
.get_registers(register_names, regi... | Rust | 0 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019-2024 CERN.
# Copyright (C) 2019-2022 Northwestern University.
# Copyright (C) 2022 TU Wien.
# Copyright (C) 2023-2024 Graz University of Technology.
#
# Invenio App RDM is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; se... | Python | 1 |
CLIENT_CA_CN.to_string())
.set_ca_key_usage_extension()
.build(ca_cert_key_pair, MessageDigest::null())
.x509();
let ca_cert_proto = x509_public_key_cert(&ca_cert);
let registry = TlsRegistry::new();
let server = Server::builder(SERVER_ID_1)
.add_... | Rust | 0 |
::new(Sphere {
center: Vec3::from_xyz(4.0, surface_y(4.0, 0.0, ground_radius + 1.0, ground_y), 0.0),
radius: 1.0,
material: Rc::new(Metal::new(Vec3::from_xyz(0.7, 0.6, 0.5), 0.0)),
}));
bvh::BVH::new(&mut rng, scene, 0.0, 1.0)
}
fn surface_y(x: f64, z: f64, combined_radius: f64, ground... | Rust | 0 |
luminance_min: Option<f64>,
}
impl<R: Read + Seek> ParsableElement<R> for MasteringMetadata {
type Output = Self;
fn new(_r: &mut R, fields: &[(ElementId, ElementData)]) -> Result<Self> {
let primary_r_chromaticity_x = try_find_float(fields, ElementId::PrimaryRChromaticityX)?;
let primary... | Rust | 0 |
in as_completed(futures):
algorithm = futures[future]
log_action(future.result(), algorithm.exchange.codename, algorithm.codename)
exchange_exists = False
for exchange in state_vars["exchanges"]:
if algorithm.exchange.codename == excha... | Python | 1 |
q = open_api_models.OpenApiRequest(
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListHotlineRecordDetail',
version='2019-10-15',
protocol='HTTPS',
pathname='/',
method='GET',
auth_type=... | Python | 1 |
recv_msg = Array(xp.zeros(self.args.n_bytes, dtype="u1"))
await ep.send(send_msg)
await ep.recv(recv_msg)
stop = monotonic()
if i >= self.args.n_warmup_iter:
times.append(stop - start)
if self.args.report_gil_contention:
knock... | Python | 1 |
root_key));
Ok(())
})
.unwrap()
}
use std::env;
use std::path::PathBuf;
use mlua::{Lua, Result};
#[test]
fn test_module() -> Result<()> {
let lua = make_lua()?;
lua.load(
r#"
local mod = require("rust_module")
assert(mod.sum(2,2) == 4)
"#,
)
.exec()
}
#[cfg... | Rust | 0 |
doc=documento_cliente,
docType=tipo_documento_cliente,
ivaType=condicion_iva_cliente,
copies=1)
else:
... | Python | 1 |
of the
//! available options that the user may have actually meant to use, to suggest to them when
//! reporting the error. There is nothing however stopping users of this library from running
//! unmatched options through a third-party library to obtain the suggestion to display.
//!
//! # Crate name origins
//!
//! ... | Rust | 0 |
024, 12, 24).date() in schedule.early_close_dates # Christmas Eve
def test_weekend_adjustments(self):
"""Test that fixed‑date holidays falling on weekends get observed on the correct weekday"""
# Independence Day 2026 falls on Saturday → observed Friday, July 3,2026
with freeze_time("2026... | Python | 1 |
g10(currency.rounding))) if rounding is None else rounding
result = split_fun(value, precision_digits=digits)
self.assertEqual(result, expected, 'Split error: got %s, expected %s' % (result, expected))
try_split(2.674, ('2', '67'), float_split_str)
try_split(2.675, ('2', '68'), ... | Python | 1 |
2,
rel_heading_envs=1.0,
heading_command=True,
heading_control_stiffness=0.5,
debug_vis=False, # True
ranges=mdp.UniformVelocityCommandCfg.Ranges(
lin_vel_x=(-1.0, 1.0), lin_vel_y=(-1.0, 1.0), ang_vel_z=(-1.0, 1.0), heading=(-math.pi, math.pi)
),
)
@confi... | Python | 1 |
, '\u{a67d}', '⨽', '\u{1fa51}', '𝈄', 'ꑞ', 'ꑝ', '⍏',
'𑄈', '૩', '❈', 'ቄ', '𖤓', '𓊃', '⟘', '𖢭', '⁈', '𐕐', 'ħ', 'ᯪ',
'𐛎', 'ē', '𝞃', '𛇒', '𑖂', '𞡇', 'ﱦ', 'ࢩ', 'ꂒ', '𛈲', '㬙', '悔',
'⻘', '\u{18c16}', '𔗚', 'ᧃ', '𐧶', '𛇛', '𑰙', '𔗢', '𒌣', '˨', '𛇖',
'𛃴', 'ꃤ', '𔒉', '\u{1920}', '🈰', '𐠱', 'ڦ', 'ꥩ',... | Rust | 0 |
to ensure _emit_ast is True when registering a stored procedure."
assert (
sproc._ast_id is not None
), "Need to assign an ID to the stored procedure."
sproc_expr = proto.Expr()
build_sproc_apply(sproc_expr, sproc._ast_id, statement_pa... | Python | 1 |
Direction::Y => write!(f, "Y"),
Direction::Z => write!(f, "Z"),
}
}
}
/// Rotate a set of coordinates around an axis.
pub fn rotate_coords(coords: &[Coord], axis: Direction) -> Vec<Coord> {
coords.iter().map(|&coord| coord.rotate(axis)).collect()
}
/// Rotate a set of coordinates from... | Rust | 0 |
t())
logger.info(f"Filtered Test Dataset length: {len(test_dataset)}")
test_sentences = test_dataset['query']
test_query_ids = test_dataset['query_id']
test_real_answers = test_dataset['answers']
test_data_points = []
for query_id, sentence, test_single_answers in zip(test_query_ids, test_... | Python | 1 |
, output: &mut [usize], element_index: usize) {
self.space.populate_element_nodes(output, element_index)
}
}
define_thread_local_workspace!(SOURCE_WORKSPACE);
struct SourceTermWorkspace<T, D, Data>
where
T: Scalar,
D: SmallDim,
DefaultAllocator: DimAllocator<T, D>,
{
quadrature_buffer: Qua... | Rust | 0 |
STDErrorCode};
/// Allocates a new memory block.
///
/// # Parameters
///
/// - `const NSTDUSize size` - Number of bytes to allocate.
///
/// # Returns
///
/// `NSTDAny ptr` - The new memory block.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_alloc_allocate(size: usize) -> NSTDAny {... | Rust | 0 |
/ ^ \ | | | | "#);
display_redln!(r#"| __| / /_\ \ | | | | "#);
display_redln!(r#"| | / _____ \ | | | `----."#);
display_redln!(r#"|__| /__/ \__\ |__| |_______|"#);
std::process::exit(1);
};
}
/// Exit the origen process with a failing exit... | Rust | 0 |
button,
pressed,
modifiers: Default::default(),
};
self.push_event(egui_event);
}
}
SystemInput::Wheel { delta, .. } => {
if let In::WheelScroll = pay... | Rust | 0 |
import numpy as np
import torch
np.random.seed(1)
x0 = np.array([1, 2, 3, 4, 5], dtype=np.float32)
y0 = np.zeros(3, dtype=np.float32)
w0 = np.random.randn(5, 3).astype(np.float32)
b0 = np.random.randn(3).astype(np.float32)
################################################################################
# PyTorch
x = ... | Python | 1 |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
import joblib
# Tải dữ liệu từ file CSV
data = pd.read_csv('hand_gesture_data.csv')
# Tách dữ liệu thành các đặc trưng (X) và nhãn (y)
X = data.drop('label', axis=1) # Các đ... | Python | 1 |
= api.parser()
# # dataset_files_info_parser.add_argument('search_path', type=str, location='args', required=False, default='/', help='조회할 경로')
# auto_labeling_parser = api.parser()
# auto_labeling_parser.add_argument('workspace_id', type=str, location='form', required=True, help='워크스페이스 아이디')
# auto_labeling_parser.a... | Python | 1 |
import os
import cv2
import shutil
import numpy as np
from tqdm import tqdm
globe_temp_dir = "globe_hand_temp"
prompt_points = {}
for file_path in tqdm(sorted(os.listdir(globe_temp_dir))):
sample_id = file_path.split("_")[0]
if "_Hand" in file_path:
image = cv2.imread("{}/{}".format(globe_temp_dir, f... | Python | 1 |
: AsyncRead + AsyncWrite> AsyncWrite for TlsStream<S> {
fn shutdown(&mut self) -> Poll<(), io::Error> {
try_nb!(self.inner.shutdown());
self.inner.get_mut().shutdown()
}
}
impl TlsConnectorExt for TlsConnector {
fn connect_async<S>(&self, domain: &str, stream: S) -> ConnectAsync<S>
... | Rust | 0 |
class Employee:
language = "Python"
salary = 100000000000
# dunder metnod it like start with __
# this is constructor it is atomatic call to create object
def __init__(self,name,salary,language):
print("I am creating an object") #Constructor
self.name = name # Assign value to obje... | Python | 1 |
# Generated by Django 3.0.5 on 2020-04-23 08:14
from django.conf import settings
from django.db import migrations
from django.utils.module_loading import import_string
def get_plugins():
plugins = []
for plugin_path in settings.PLUGINS:
plugins.append(import_string(plugin_path))
return {plugin.P... | Python | 1 |
# Copyright (c) 2024, Shanghai Iluvatar CoreX Semiconductor Co., Ltd.
# All Rights Reserved.
#
# 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/license... | Python | 1 |
g))
except ValueError:
spacing_spin.setValue(1.5)
# 按钮
button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
button_box.accepted.connect(dialog.accept)
button_box.rejected.connect(dialog.reject)
... | Python | 1 |
let value = BigUint::from_str(s).map_err(|e| e.to_string())?;
if value <= 0.to_biguint().unwrap() {
Err("Bad value for PositiveInteger".to_string())
} else {
Ok(PositiveInteger(value))
}
}
}
impl fmt::Display for PositiveInteger {
fn fmt(&self, f: &mut fmt::Forma... | Rust | 0 |
Q: Q as _,
Rd: Rd as _,
a: a as _,
b: b as _,
c: c as _,
cmode: cmode as _,
d: d as _,
e: e as _,
f: f as _,
g: g as _,
h: h as _,
});
}
if (v & 0xbff89c00) == 0x2f001400 {
re... | Rust | 0 |
t.most_common(10)
# ### 聚合数据以便后续使用, 一个user_id购买了多个item_id
# In[30]:
group_by_col, agg_col = 'user_id', 'item_id'
data_ = click_all.groupby(['user_id'])[['item_id', 'time']].agg(
{'item_id': lambda x: ','.join(list(x)), 'time': lambda x: ','.join(list(x))}).reset_index()
data_.head(5)
# In[31]:
data_.shape
#... | Python | 1 |
ream = Microphone::default();
///
/// // register as media element in the audio context
/// let background = context.create_media_stream_source(mic.stream());
/// // connect the node directly to the destination node (speakers)
/// background.connect(&context.destination());
///
/// // enjoy listening
/// std::thread::s... | Rust | 0 |
_from_sql_row_tuple!($($rest)*);
};
}
_from_sql_row_tuple!(A B C D E F G H I);
/// Implements [`FromSqlRow`] for just one [`FromTypeTagAndSqlValue`].
#[derive(Debug)]
pub struct Just<T: FromTypeTagAndSqlValue>(std::marker::PhantomData<T>);
impl<T: FromTypeTagAndSqlValue> Clone for Just<T> {
fn clone(... | Rust | 0 |
lot.clone()
};
}
pub fn average_distance_from_exits(lot: &ParkingLot) -> i32 {
let mut average_distance = 0;
let mut total_distance = 0;
let mut i = 0;
let new_lot = lot.clone();
for y in 0..lot.h {
for x in 0..lot.w {
if lot.position(x, y) == EXIT {
conti... | Rust | 0 |
(&b)))
}
_ => None,
}
}
}
impl Damage for Primitive {
fn damage(&self, other: &Primitive) -> Option<Vec<Rectangle>> {
if let (
Primitive::Cached { cache: lcache },
Primitive::Cached { cache: rcache },
) = (self, other)
{
... | Rust | 0 |
Blacksmith, sub_args: &ArgMatches) -> ! {
let renderer = sub_args.value_of("renderer").expect("Required argument");
let supported = pre.supports_renderer(&renderer);
// Signal whether the renderer is supported by exiting with 1 or 0.
if supported {
process::exit(0);
} else {
process... | Rust | 0 |
alEq]
);
impl IntoIterator for Metadata {
type Item = <MetadataInner as IntoIterator>::Item;
type IntoIter = <MetadataInner as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl CommitEncodeWithStrategy for Metadata {
type Strategy = commit_strateg... | Rust | 0 |
lied for FermionOperator.')
return QubitOperator(_math.ops.ternary_tree(self.operator, self.n_qubits))
def reversed_jordan_wigner(self):
"""
Apply reversed Jordan-Wigner transform.
Returns:
FermionOperator, fermion operator after reversed_jordan_wigner transformation.
... | Python | 1 |
COMMISSIONER"]
#[doc = ""]
#[doc = " Writing to this property allows user to generate PSKc from a given commissioning pass-phrase, network name,"]
#[doc = " extended PAN Id."]
#[doc = ""]
#[doc = " Written value format is:"]
#[doc = ""]
#[doc = " `U` : The commissioning pass-phrase."]
#[doc = " `U` : Network Name."... | Rust | 0 |
PacketLoss::Wireless
} else {
PacketLoss::Congestion
}
}
2 => {
if rott < self.rott_mean - self.rott_dev / 2.0 {
PacketLoss::Wireless
} else {
PacketLo... | Rust | 0 |
SendErrorKind::Overflow => match overflow(value) {
Ok(()) => {}
Err(err) => {
drop(tx.send_err(err));
}
},
},
... | Rust | 0 |
self.token
);
let limits = match self.token.kind {
token::DotDot => RangeLimits::HalfOpen,
_ => RangeLimits::Closed,
};
let op = AssocOp::from_token(&self.token);
// FIXME: `parse_prefix_range_expr` is called when the current
// token is `DotD... | Rust | 0 |
ACK(fake_revoke_and_ack_msg!()));
generate_handle_message_test!(handle_update_fee, Message::UpdateFee(fake_update_fee_msg!()));
generate_handle_message_test!(handle_channel_reestablish, Message::ChannelReestablish(fake_channel_reestablish_msg!()));
generate_handle_message_test!(handle_announcement_signatures, Messag... | Rust | 0 |
1. (main) 监听入站连接循环,接收到一个 `TcpStream` 对象之后,异步调用 `handle_connection` 函数处理之
/// 2. (connection_read_loop) `TcpStream` 读取循环,循环读取 `TcpStream`,使用接收到的数据构造 `ServerMessage` 发送给 3.
/// 3. (server_loop) RTMP 服务器循环,接收到 2. 发送过来的 `ServerMessage` 对象,并处理之,将服务器处理的结果构造为 `Response` 并发送给 4.
/// 4. (connection_write_loop) `TcpStream` 写入循环... | Rust | 0 |
_or_create_buffer(&self, name: &str) -> Arc<MessageManager> {
if let Some(buffer) = self.buffers.borrow().get(name) {
return Arc::clone(buffer);
}
if let Some(buffer) = self.weechat.buffer_search("weecord", name) {
let msg_manager = MessageManager::new(buffer);
... | Rust | 0 |
// empty cache
let mut cache_0 = init_cache();
let res_0 = cache_0.entry(1).or_insert(2);
let mut cache_1 = init_cache();
let res_1 = cache_1.entry(1).or_insert_with(|| 2);
assert_eq!(res_0, res_1);
// non-empty cache
let mut cache_0 = init_cache();
... | Rust | 0 |
print(f"\r{CYAN}=== Akun ke {line_number} | {first_name} ===", flush=True)
print(f"\r{GREEN}SD: {sd}", flush=True)
print(f"\r{YELLOW}Probe: {probe}", flush=True)
print(f"\r{YELLOW}Farming Time: {formatted_time}", flush=True) # Updated print statement
print(f"\r{CYAN}Farming SD: Claim in {forma... | Python | 1 |
bulb, idx);
copy_to_result!(result, dew_point, idx);
copy_to_result!(result, theta_e, idx);
copy_to_result!(result, wind, idx);
copy_to_result!(result, pvv, idx);
copy_to_result!(result, height, idx);
copy_to_result!(result, cloud_fraction, idx);
Some(result)
... | Rust | 0 |
> 0 and "labels" in batch_samples[0]:
# For now we don't support object detection
try:
num_items_in_batch = sum([(batch["labels"].ne(-100)).sum() for batch in batch_samples])
except (TypeError, AttributeError):
pass
if self.args.average_token... | Python | 1 |
ruct SnpGuestMsgHdr {
authtag: [u8; MAX_AUTHTAG_LEN],
msg_seqno: u64,
rsvd1: [u8; 8],
algo: u8,
hdr_version: u8,
hdr_sz: u16,
msg_type: u8,
msg_version: u8,
msg_sz: u16,
rsvd2: u32,
msg_vmpck: u8,
rsvd3: [u8; 35],
}
impl Default for SnpGuestMsgHdr {
fn default() -> S... | Rust | 0 |
let mut bob_iv = [0 as u8; 16];
OsRng.fill_bytes(&mut bob_iv);
let mut bob_response = crate::aes_cbc::encrypt_aes_128_cbc(
&alice_msg,
&crate::sha1::sha1(
&bob.session_key(A.clone()).to_bytes_le(),
None,
None,
None,
None,
... | Rust | 0 |
# check_elser_status.py
import os
from dotenv import load_dotenv
from elasticsearch import Elasticsearch
print("Loading environment variables...")
load_dotenv()
es_url = os.getenv("ELASTICSEARCH_URL")
if not es_url:
raise ValueError("ELASTICSEARCH_URL not set in .env file")
print("Connecting to Elasticsearch...... | Python | 1 |
w
'train_datasets':r'/root/autodl-tmp/UIEB/train',
'val_datasets':r'/root/autodl-tmp/UIEB/test',
#bs
'train_bs':100,
#'train_bs':4,
'val_bs':32,
'initlr':0.0004,
'weight_decay':0.01,
'crop_size':256,
'num_workers':4,
#Net
'model_blocks':5,
'chns':64
}
hpar... | Python | 1 |
}
))
} else {
Ok(Value::null())
}
}))
.insert(tremor_fn! (origin::scheme(context) {
if let Some(uri) = context.origin_uri() {
Ok(Value::String(uri.scheme().to_string().into()))
} else {
Ok(Va... | Rust | 0 |
.
map(lookahead(parse_literal), |i| {
StringFragment::Literal(i.fragment())
}),
alt2(
map(lookahead(parse_escaped_char), StringFragment::EscapedChar),
map(lookahead(parse_escaped_whitespace), |_| {
StringFragment::EscapedWS
}),
... | Rust | 0 |
(rename = "longitude")]
longitude: f32,
/// pin_id integer
#[serde(rename = "pin_id")]
pin_id: i64,
/// schematic_id integer
#[serde(rename = "schematic_id")]
schematic_id: Option<i32>,
/// type_id integer
#[serde(rename = "type_id")]
type_id: i32
}
impl GetCharactersCharacterIdPlanetsPlanetIdPin {... | Rust | 0 |
'''
Decisions at the Crossroad
Task 1: Code Correction
You are provided with a Python script that uses conditional statements to
tell if a number is positive, negative, or zero, but it has some errors.
Identify and fix them.
'''
# Buggy code:
# number = input("Enter a number: ")
# if number > 0:
# print("The... | Python | 1 |
e = feature.value
db_feature.is_active = feature.is_active
await db.commit()
await db.refresh(db_feature)
return db_feature
except HTTPException:
raise
except SQLAlchemyError as e:
await db.rollback()
print("DB Error (Update):", repr(e))
raise H... | Python | 1 |
fsdp_model=models.generator if self.config.use_fsdp else None)
return self.Optimizers(generator=optimizer)
def setup_schedulers(self, extras: Extras, models: Models, optimizers: TrainingCore.Optimizers) -> Schedulers:
scheduler = GradualWarmupScheduler(optimizers.generator, multiplier=1, total_ep... | Python | 1 |
timeline (0).
db_tx.execute("INSERT INTO timelined_transactions VALUES (?, ?, ?, ?, ?, ?, ?)", &[&268435457, &3, &1529971773701734_i64, &268435457, &1, &4, &0]).expect("inserted");
db_tx.execute("INSERT INTO timelined_transactions VALUES (?, ?, ?, ?, ?, ?, ?)", &[&65536, &1, &":person/name", &268435457... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.